skip to content

In Rust, why can code after a `macro_rules!` call not read a variable the expansion declared with `let`, and how do you hand one out?

level: middleimportance: must knowfreq 45%

answer

  1. mixed-site, not fully hygienic
  2. where each name is looked up
  3. locals and labels are special
  4. let the caller supply the name

basics

~20 s

macro_rules! hygiene resolves local variables and labels where the macro was defined, so a let inside an expansion is invisible to the caller (E0425) and never captures the caller's variables. To hand one out, take its name as a $name:ident fragment.

solid answer

~50 s

Macros by example have **mixed-site hygiene**: local variables, loop labels and block labels are looked up at the definition site, while other names are looked up at the invocation site. Each expansion's `let tmp` lives in its own syntax context, so code after the call that names it gets `E0425`, and rustc adds a help line saying the identifier exists but is "not accessible due to macro hygiene". It also protects the caller: a `tmp` the caller passes in through `$e` is not captured by the macro's own `tmp`. It works the other way too: the body cannot read the caller's locals unless they arrive as arguments or were already in scope where the macro was defined, and `break 'outer` aimed at a caller's label is `E0426`. To give the caller a binding, make the name an input, `($name:ident) => { let $name = 10; }`, because that identifier token comes from the caller.

code

rust · 20 lines
rust
macro_rules! square {
    ($e:expr) => {{
        let tmp = $e;
        tmp * tmp
    }};
}

macro_rules! define_named {
    ($name:ident) => {
        let $name = 10;
    };
}

fn main() {
    let tmp = 3;
    let r = square!(tmp + 1); // the macro's tmp does not capture ours
    println!("{r} {tmp}"); // 16 3
    define_named!(y); // the caller supplied the name, so y is visible
    println!("{y}"); // 10
}

go deeper

for a junior

Know that a variable declared inside a macro_rules! expansion is not visible after the call, and that trying to use it gives E0425.

for a middle

Explain mixed-site hygiene: locals and labels resolve at the definition site, other names at the call site, and how an $name:ident input hands a binding to the caller.

for a senior

Read rustc's not accessible due to macro hygiene help line quickly, and choose between an ident input, a block expression that returns a value, or a lifetime input for labels.

for a principal

Favour macros whose expansions are block expressions returning values, keeping caller-named bindings for the few APIs that document them clearly.

## Mixed-site hygiene in one table **Hygiene** is the rule that decides which scope an identifier written inside a macro is resolved in. The Reference says macros by example have **mixed-site hygiene**: some names are looked up where the macro was *defined*, the rest where it is *invoked*. | Kind of name written in the transcriber | Looked up at | |---|---| | Local variables (`let` bindings) | Definition site | | Loop labels and block labels (`'outer`) | Definition site | | `$crate` | The crate that defines the macro | | Functions, statics, types, modules, other macros | Invocation site | So locals and labels are the protected group. Everything else behaves as if it had been typed at the call. ## Hygiene works in both directions - **Out of the macro.** A `let x = 10;` in a transcriber does not become a variable the caller can use. Code after `define_x!()` that prints `x` fails with `E0425`, ``cannot find value `x` in this scope``, and rustc 1.99.1 adds "an identifier with the same name is defined here, but is not accessible due to macro hygiene", pointing into the macro. - **Into the macro.** A transcriber that names `total` does not see the caller's `let total = 5;`. Unless `total` was in scope where the macro was defined, the expansion fails with `E0425` and the same kind of help line. - **Between invocations.** Locals are not shared across expansions either: `m!(define)` declaring `x` and a later `m!(refer)` reading `x` does not compile; the Reference uses exactly this example. - **Labels.** A transcriber containing `break 'outer` cannot target an `'outer: loop` written around the call; rustc reports `E0426`, ``use of undeclared label `'outer` ``. The protection matters most for helpers like `square!`, whose expansion is `{ let tmp = $e; tmp * tmp }`. Called as `square!(tmp + 1)` with the caller's `tmp` equal to 3, the result is 16 and the caller's `tmp` is still 3, because the macro's `tmp` and the caller's `tmp` are different bindings even though they are spelled the same. ## Definition site really means definition site A macro defined inside a function sees the locals in scope *at its definition*, not at its call: ```rust fn main() { let total = 5; macro_rules! show_total { () => { println!("{}", total); }; } { let total = 99; show_total!(); // prints 5 println!("{total}"); // prints 99 } } ``` The inner `total` shadows the outer one for code written in that block, but the macro's `total` token was resolved against the definition, where only the binding to 5 exists. ## Handing a binding out deliberately When the caller should end up with a variable, the caller has to name it: 1. Take the name as an input: `($name:ident) => { let $name = 10; }`. 2. Call it as `define_named!(y);` and then use `y` freely. This works because hygiene follows the **token**, not the spelling. The `y` token was written by the caller, so it carries the caller's context, and the binding it introduces is visible there. The same trick hands a label in: a `$l:lifetime` input lets `break $l` leave the caller's loop. An `expr` fragment does not work for this: `let $n = 0;` with `$n:expr` is rejected, because an expression fragment cannot stand in for a pattern. ## Reading the diagnostic When hygiene is the cause, rustc says so. Both directions produce `E0425` with a help line pointing at the binding that could not be reached: - For a binding declared inside the macro and used after the call, the help says an identifier with the same name "is defined here, but is not accessible due to macro hygiene" and points into the transcriber. An `unused_variables` warning usually fires on that binding as well, because nothing in the macro's context reads it. - For a caller variable that the transcriber tried to use, the help says an identifier with the same name "exists, but is not accessible due to macro hygiene" and points at the caller's `let`. Either way the repair starts with one question: who should name this binding? If the caller should, pass the name in; if nobody outside needs it, return a value from a block expression instead. ## What hygiene does not cover Only locals and labels get this protection. A `fn`, `static` or `struct` that a macro emits is visible to the caller and can collide with the caller's items, and a function name in the body resolves at the call site. Those leaks are a separate topic; for local variables, the rules above are the whole story. Points to carry into an interview: - E0425 with "not accessible due to macro hygiene" is the symptom. - The caller supplies names it wants to use; the macro returns values through a block expression.

  • A macro is defined inside fn main after let total = 5 and called in an inner block that declares let total = 99; what does it print?
    5. Local variables in a macro body are looked up at the definition site, and the only total in scope where the macro was defined is the one bound to 5. The inner block's total is a different binding; code typed in that block sees 99, but the macro's total token never does.
  • Do loop labels follow the same rule as local variables?
    Yes. Loop and block labels are hygienic, so break 'outer inside a transcriber cannot reach an 'outer: loop written around the call; rustc reports E0426, use of undeclared label. If the macro really must leave the caller's loop, take the label as a $l:lifetime input and write break $l.

  • A let inside a macro expansion is visible to the code that follows the call.
  • A macro body can read any local variable in scope where it is invoked.
  • Hygiene renames everything a macro emits, functions and statics included.
  • Taking the name as $name:ident still keeps the binding hidden from the caller.
  • Two calls of the same macro share the locals the first call declared.