A Rust `macro_rules!` macro emits `static ONCE` at statement level, and two calls in one function fail with E0428; why, and what fixes it?
answer
- hygiene is narrow
- items keep their literal names
- one block, one value namespace
- an extra pair of braces
basics
~20 smacro_rules! hygiene covers only local variables and labels; statics, functions and other items are named as if written at the call site, so two expansions put ONCE into one block twice (E0428). Wrap the expansion in its own block, or take the name as an ident.
solid answer
~50 sMixed-site hygiene protects nothing but local variables and labels. A `static`, `fn`, `struct`, `const` or `mod` that a macro emits lands in the caller's scope under its literal name, visible to the caller and free to collide. Two `once_flat!()` calls in one function each put `static ONCE` into the same block, so rustc reports `E0428`, ``the name `ONCE` is defined multiple times``, noting it ``must be defined only once in the value namespace of this block``. The usual fix is a second pair of braces in the transcriber, `{{ static ONCE: ...; ... }}`, so each expansion is a block expression whose items are private to it; that also gives every call site its own `Once`. When the item must be visible, take its name as a `$name:ident` input so the caller chooses it. The same rule makes function names and paths in the body resolve at the call site.
code
rust · 11 linesmacro_rules! once_flat {
() => {
static ONCE: std::sync::Once = std::sync::Once::new();
ONCE.call_once(|| println!("first"));
};
}
fn main() {
once_flat!();
once_flat!();
}go deeper
Know that a fn or static generated by a macro_rules! macro is visible to the calling code, unlike a let binding generated the same way.
Explain that only locals and labels are hygienic, why two expansions defining one item collide with E0428, and how an inner block in the transcriber scopes them.
Debug leaks in both directions, items escaping into the caller and caller names or missing imports captured by the body, and fix them with blocks, ident inputs, $crate and full paths.
Set a review rule for macros in the codebase: expansions are block expressions, generated public items take caller-supplied names, and paths in transcribers are absolute.
## Hygiene is narrow by design Macros by example have **mixed-site hygiene**. The Reference spells out the protected group: loop labels, block labels and local variables are looked up at the definition site; **all other symbols are looked up at the invocation site**. In practice: | Introduced or used by the transcriber | Hygienic? | Effect at the call site | |---|---|---| | `let` bindings | Yes | Invisible to the caller, cannot capture caller variables | | Loop and block labels | Yes | `break 'outer` cannot reach a caller's label | | `fn`, `static`, `const`, `struct`, `enum`, `mod`, `impl` | No | Visible under the literal name, can collide | | Function calls, type names, paths | No | Resolved among the caller's names | | Field and method names | No | `$s.count` reaches the caller's struct field | Leaving items unhygienic is what lets a macro generate a struct, a function or an `impl` that the caller then uses by name. ## How items leak out When a macro is expanded at statement level, its items are placed in the surrounding block or module exactly as if the user had typed them there. - A generated `fn helper()` is callable by the code after the call, even though the caller never wrote it. - Two expansions in one module both define `fn helper`, and rustc reports `E0428`, ``the name `helper` is defined multiple times``. - The same happens one level down. Inside a function, two `once_flat!()` calls that each emit `static ONCE` put both statics into the function's block, and the note says `ONCE` ``must be defined only once in the value namespace of this block``. ## How names leak in The other direction catches people as often: - A function call such as `helper()` in the body resolves among the caller's names. If the calling block defines its own `fn helper`, that one runs; if no `helper` is in scope there, the call is `E0425`. The Reference demonstrates this with a `func` defined in the calling block. - **Imports do not travel.** A `use std::sync::Once;` at the top of the macro's own module is not in scope where the expansion lands. Called from another module, a transcriber that writes `Once::new()` fails; rustc 1.99.1 prints ``error[E0425]: cannot find type `Once` in this scope`` and suggests imports. ## Fixes 1. **Scope the items in a block.** Write the transcriber with doubled braces: the outer pair delimits the transcriber and is not part of the output, the inner pair becomes a block expression. Items declared inside it are local to that block, so every expansion has its own `ONCE`, and two calls side by side no longer collide. This is the standard shape for per-call-site statics. 2. **Let the caller name public items.** A macro that generates a function or type the caller is meant to use should take the name as `$name:ident`; then the caller controls collisions. 3. **Define shared helpers once.** Instead of emitting a `fn helper` per call, put it in the macro's crate and call it as `$crate::helper()` from the expansion. 4. **Write full paths.** Use `::std::sync::Once` rather than relying on an import the caller may not have. ## A note on fields Field and method names are not hygienic either. A macro written as `($s:expr) => { $s.count += 1 }` compiles against the caller's struct even though the `count` token came from the macro. That is usually what you want, and it means a macro can depend on the caller's types having particular field names, which is worth stating in its documentation. ## Testing for leaks Two cheap compile-only tests catch most leaks before users do: 1. Invoke the macro **twice in the same block** and twice in the same module. If it emits named items at statement or module level, the second call reveals the `E0428`. 2. Invoke it from a module with **no imports**, and from a separate crate if it is exported. Any name the transcriber relied on from its own file shows up as `E0425`. Together they cover both directions in which non-hygienic names cross the macro boundary. ## Diagnosing a leak - `E0428` pointing into a macro means two expansions emitted the same item into one namespace. - `E0425` on a name you can see imported in the macro's file means the import did not travel. - An unexpected function running means a call in the body resolved to the caller's item.
- A macro body calls helper(), and both the macro's module and the calling block define a fn helper; which one runs?The calling block's helper. Function names are not hygienic, so a call in the expansion resolves at the invocation site, where the caller's helper is in scope. If the caller had none in scope, the call would be E0425. An exported macro avoids the whole question with $crate::helper().
- Why does a macro need doubled braces at all, rather than one pair?The outermost delimiters of a transcriber only mark where the transcriber starts and ends; they are not part of the expansion. A single pair therefore emits the statements bare into the caller's block. The second pair survives into the output and becomes a block expression, which scopes items and locals and lets the macro yield a value.
- Hygiene renames every identifier a macro introduces, statics and functions included.
- Two calls emitting the same static name each get a private copy automatically.
- A function that a macro defines is invisible to the code that invoked it.
- use declarations in the macro's module are in scope inside its expansion.
- The doubled braces in a transcriber are only a style choice and change nothing.