Sub topic 8
Hygiene: which names a macro can see
This chapter assumes you can write a macro_rules! macro with expr and ident fragments and read a transcriber. The goal is to predict which names a macro can see and which names it can't. You will also learn how to make a macro introduce a binding that the caller can use.
The problem hygiene solves
Suppose macros worked like text substitution, as in C. A macro that declares a temporary variable could silently capture a variable of the same name in the caller's code. Rust avoids this class of bug with hygiene. Hygiene means that each identifier remembers where it came from, in addition to its spelling. Two identifiers with the same text can still be different names.
For local variables and labels, macro_rules! tracks a syntax context for each identifier:
- An identifier written inside the macro definition belongs to the macro.
- An identifier passed in by the caller belongs to the caller.
The compiler resolves a local name only against bindings from the same origin.
Local variables: the macro's `x` is not your `x`
This macro declares its own x and then adds it to a caller-supplied expression.
macro_rules! shadow {
($e:expr) => {{
let x = 100;
$e + x
}};
}
fn main() {
let x = 1;
println!("{}", shadow!(x));
}The program prints 101. The expansion looks like let x = 100; x + x, but the two x tokens differ. The x inside $e came from the caller and still refers to the caller's let x = 1. The x written in the macro body refers to the macro's let x = 100. Without hygiene, the result would be 200.
Here is a second case where the macro's temporary would otherwise swallow the caller's variable:
macro_rules! push_one {
($e:expr) => {{
let mut v = Vec::new();
v.push($e);
v
}};
}
fn main() {
let v = 10;
let result = push_one!(v);
println!("{:?}", result);
}This prints [10]. The caller's v is passed in as $e, and the macro's v is a separate binding.
The reverse direction: the macro can't see your locals
Hygiene works both ways. A macro body can't use a caller's local variable just because the name matches. This code fails to compile:
macro_rules! add_x {
($e:expr) => {
$e + x
};
}
fn main() {
let x = 1;
println!("{}", add_x!(2));
}The compiler reports cannot find value 'x' in this scope. The x in the macro body has the macro's origin. No binding with that origin exists at the expansion site, so resolution fails. The fix is to pass the name in, either as an ident fragment or as an expr fragment.
Passing an identifier makes it visible
An identifier supplied by the caller carries the caller's context. If the macro uses it in a let, the binding is visible to the caller's later code:
macro_rules! make_var {
($name:ident, $val:expr) => {
let $name = $val;
};
}
fn main() {
make_var!(answer, 42);
println!("{}", answer);
}This prints 42. The caller wrote answer at the invocation site, so both the let and the later println! use the same origin.
Compare this with a macro that writes the name itself:
macro_rules! make_hidden {
($val:expr) => {
let hidden = $val;
};
}
fn main() {
make_hidden!(5);
// println!("{}", hidden); // error: cannot find value `hidden`
}The binding hidden exists, but only code that comes from the macro can name it.
A hygiene-based swap
Because of hygiene, a macro's helper variable can't collide with the arguments:
macro_rules! swap {
($a:ident, $b:ident) => {
let tmp = $a;
$a = $b;
$b = tmp;
};
}
fn main() {
let mut tmp = 1;
let mut y = 2;
swap!(tmp, y);
println!("{} {}", tmp, y);
}This prints 2 1. The caller's variable is itself called tmp, yet the swap works. The macro's tmp and the caller's tmp are different names.
What is hygienic and what is not
Hygiene in macro_rules! applies to a narrow set of names. Everything else is resolved as if the macro's tokens had been typed at the call site.
| Kind of name | Hygienic? | Consequence |
|---|---|---|
| Local variables (`let` bindings, closure and function parameters, pattern bindings) | Yes | Macro locals and caller locals never clash. |
| Loop labels (`'outer:`) | Yes | A label inside a macro can't be targeted by a caller's `break 'outer`. |
| `$crate` | Special | Always refers to the crate that defined the macro. |
| Functions, structs, enums, traits, modules, statics, constants | No | Names resolve at the expansion site. |
| Types, generic parameters, lifetimes other than labels | No | Resolved at the expansion site. |
| Macro names | No | Resolved by macro scoping rules, covered in a later chapter. |
Items defined by a macro are visible to the caller, even when the macro wrote the name:
macro_rules! define_helper {
() => {
fn helper() -> i32 {
7
}
};
}
define_helper!();
fn main() {
println!("{}", helper());
}This prints 7. It also means a macro that refers to a function by plain name depends on that function existing where the macro is expanded:
macro_rules! call_double {
($e:expr) => {
double($e)
};
}
fn double(n: i32) -> i32 {
n * 2
}
fn main() {
println!("{}", call_double!(4));
}This prints 8. If the caller has no double in scope, or has a different double, the macro uses whatever it finds. For macros that other crates will use, this is fragile, and $crate is the remedy (see below).
An edge case: macros defined after a local
A macro defined inside a function can see locals declared before the macro definition. This is because the identifier in the macro body gets the context of the definition site, and the let is in scope there.
fn main() {
let x = 1;
macro_rules! show_x {
() => {
println!("{}", x)
};
}
show_x!();
}This prints 1. It works because the macro's x and the let x were both written in the same place, at the definition site. Moving the macro_rules! above let x would make it fail. The rule is the same as before: names resolve according to where they were written.
Using `$crate` to avoid depending on the caller
Because items aren't hygienic, an exported macro that calls a helper by bare name resolves at the user's call site. The user may not have the helper, or may have a different one. $crate always expands to the defining crate's root, so paths that start with it resolve the same way everywhere:
#[macro_export]
macro_rules! call_helper {
($x:expr) => {
$crate::helper($x)
};
}
pub fn helper(x: i32) -> i32 {
x + 1
}For the same reason, use absolute paths like ::std::collections::HashMap in exported macros. A caller might have their own module named std or a type named HashMap in scope. The leading :: rules that out.
Practical rules
- If the macro needs a temporary, name it freely. It can't collide with caller locals.
- If the caller must be able to use a binding the macro creates, take the name as an
identfragment. - If the macro must read a caller variable, take it as an
exproridentargument. Don't write its name in the body. - In exported macros, reach into your crate with
$crate::and into the standard library with::std::.
Common errors
- "cannot find value
xin this scope" inside a macro. The macro body mentions a caller's local by name. Pass it as an argument. - "cannot find value
name" after invoking a macro that declareslet name. The name was written inside the macro, so the caller can't see it. Take the name as$name:ident. - A helper function resolves to the wrong item or isn't found. Items aren't hygienic. Use
$crate::for your own items and::std::for the standard library. break 'labelfails inside a macro argument. Labels are hygienic. A label defined by the caller can be used in code the caller passed in, but a label defined inside the macro can't be targeted by the caller's tokens.
Exercise
What does this program print, and why? macro_rules! twice { ($e:expr) => {{ let n = 10; $e * 2 + n }}; } fn main() { let n = 3; println!("{}", twice!(n)); }
Show answer
It prints 16. The expression n passed by the caller refers to the caller's n = 3, so $e * 2 is 6. The n written in the macro body refers to the macro's own n = 10. The sum is 6 + 10 = 16. Without hygiene, both would be 10 and the result would be 30.
Exercise
You want a macro declare!(count, 0) that lets the caller write println!("{}", count); on the next line. What fragment type must the macro use for the name, and what goes wrong if the macro body writes let count = $val; directly instead?
Show answer
Use $name:ident and expand to let $name = $val;. If the body writes let count = $val;, the binding belongs to the macro, so the caller's later reference to count fails with "cannot find value count in this scope".