skip to content

Macro Hygiene and Scope

Rust macros are partly hygienic: local variables cannot leak in or out, but items can. Interviewers ask why exported macros use $crate and how macro scoping differs from items.

on this pageshow

questions

6

A Rust utility crate exports `log_once!`, which calls the crate's own helper function; why must the macro write `$crate::` instead of `crate::` or a bare name?

level: middleimportance: must knowfreq 50%

answer

  1. paths resolve at the call
  2. whose crate root is crate::?
  3. a metavariable naming the defining crate
  4. privacy still applies
  5. where #[macro_export] puts it

basics

~20 s

Paths in a macro_rules! body resolve where the macro is invoked, so a bare helper name or crate:: points into the caller's crate and fails with E0425. $crate always means the defining crate, though the helper must still be pub.

solid answer

~40 s

Hygiene in `macro_rules!` covers only locals and labels; every path in the body is resolved at the invocation site. Inside the utility crate's own tests a bare `__emit(...)` or `crate::__emit(...)` can work, because there the caller *is* the defining crate. In a downstream crate the bare name fails with ``cannot find function `__emit` in this scope`` and the `crate::` form with ``not found in the crate root``, both `E0425`. `$crate` is a special metavariable that refers to the crate defining the macro, whatever name the dependency has at the call site. It does not bypass privacy, so the helper must be `pub`, conventionally `#[doc(hidden)]`, or the caller gets `E0603`. `#[macro_export]` is what lets other crates call the macro at all, as `logutil::log_once!`, from the crate root.

code

rust · 24 lines
rust
// logutil/src/lib.rs
use std::fmt;
use std::sync::atomic::{AtomicUsize, Ordering};

#[doc(hidden)]
pub static EMITTED: AtomicUsize = AtomicUsize::new(0);

#[doc(hidden)]
pub fn __emit(args: fmt::Arguments<'_>) {
    EMITTED.fetch_add(1, Ordering::Relaxed);
    eprintln!("[once] {args}");
}

pub fn emitted() -> usize {
    EMITTED.load(Ordering::Relaxed)
}

#[macro_export]
macro_rules! log_once {
    ($($arg:tt)*) => {{
        static ONCE: ::std::sync::Once = ::std::sync::Once::new();
        ONCE.call_once(|| $crate::__emit(::std::format_args!($($arg)*)));
    }};
}

go deeper

for a junior

Recall that #[macro_export] makes a macro usable from other crates and that exported macros reach their own crate's items through $crate.

for a middle

Explain why paths in a macro body resolve at the call site, what $crate expands to, why the helper must still be pub, and where #[macro_export] places the macro.

for a senior

Recognise the bug that passes the crate's own tests and fails downstream, and build exported macros with $crate paths, hidden pub helpers, ::std paths and a cross-crate test.

for a principal

Treat an exported macro's expansion as public API: the hidden helpers it calls are compiled into users' crates, so changing them needs the same care as a public function.

## The scenario A small utility crate, `logutil`, offers `log_once!`: each call site prints its message the first time it runs and stays silent afterwards, and the crate counts how many messages it has emitted. The expansion needs three things from outside itself: a per-call-site `std::sync::Once`, the crate's helper function `__emit`, and the crate's `static EMITTED` counter that `__emit` updates. Getting the paths to those right is the whole job of `$crate`. ## Where each path in the body resolves Macros by example are only partly hygienic. Locals and labels resolve at the definition site; **every other name, including every path, resolves at the invocation site**, as if the expansion had been typed there. | Written in the transcriber | Called inside `logutil` | Called from another crate | |---|---|---| | `__emit(...)` | Works if `__emit` is in scope there | `E0425`: cannot find function `__emit` in this scope | | `crate::__emit(...)` | Works | `E0425`: not found in the crate root (the caller's root) | | `$crate::__emit(...)` | Works | Works | | `Once::new()` | Only where `Once` is imported | Only if the caller imported `std::sync::Once` | | `::std::sync::Once::new()` | Works | Works | The second row is the trap. `crate` is an ordinary path keyword meaning "the root of the crate being compiled", and the expansion is compiled as part of the caller's crate. Because the utility crate's unit tests invoke the macro from inside the defining crate, both broken forms pass those tests and fail only for users. ## What `$crate` is `$crate` is a special metavariable: a macro can use it at the start of a path, and rustc replaces it with a reference to **the crate that defined the macro**. It works even if the user renamed the dependency in their manifest, and it is the one spelling that works reliably both inside and outside the crate. Two consequences follow: - Non-macro items need their full module path: `$crate::inner::foo()`, not `$crate::foo()` when `foo` lives in `inner`. - Helper macros are reached the same way, `$crate::helper!()`, and must themselves be `#[macro_export]`. The older `#[macro_export(local_inner_macros)]` form adds an implicit `$crate::` to single-segment macro calls in the body; the Reference describes it as a migration aid for code from before `$crate` and discourages it in new code. ## `$crate` does not grant access Privacy is checked against the invocation site. If the expansion calls `$crate::private_count()` and that function is private, a downstream caller gets `E0603`, ``function `private_count` is private``. The usual pattern is to make helpers `pub` and mark them `#[doc(hidden)]`, often with a leading double underscore, so they are reachable but kept out of the documentation. That applies to statics too: the counter the helper updates, `EMITTED`, is `pub` because a macro could name it directly. ## Two kinds of static in one macro The expansion of `log_once!` involves two statics with different jobs: - `static ONCE` is written **in the transcriber**, inside a block expression, so every call site gets its own `Once`. That is what makes each message print once per call site rather than once per program. - `EMITTED` lives **in the crate** and is reached only through `$crate::__emit`, so every call site in every downstream crate updates the same counter, which `logutil::emitted()` reads. Writing the counter in the transcriber would give each call site a private counter; writing the `Once` in the crate would silence every call site after the first one. Where each static lives is the design. ## What `#[macro_export]` does 1. It makes the macro usable from other crates. 2. It gives the macro `pub` visibility instead of the implicit `pub(crate)`. 3. It places the macro at the **crate root** for path-based resolution, regardless of the module it was written in: a `#[macro_export]` macro written inside `pub mod inner` is `logutil::nested_m!`, and `logutil::inner::nested_m!` is `E0433`, could not find `nested_m` in `inner`. ## Paths to the standard library A bare `Once` or `format_args!` also resolves at the call site, so it depends on the caller's imports. A path starting with `::` names an external crate directly, which is why the transcriber writes `::std::sync::Once` and `::std::format_args!`. A macro meant for `no_std` users would use `::core` paths where the item lives in `core`. Checklist for an exported macro: - Every crate-local item through `$crate::path::to::item`. - Every helper `pub`, usually `#[doc(hidden)]`. - Every std item through `::std::` or `::core::`. - At least one test that calls the macro from a separate crate, such as an integration test under `tests/`.

  • Why do the utility crate's own unit tests not catch a bare helper name?
    Inside the defining crate the call site and the definition site are the same crate, so crate::__emit, or a bare __emit where the helper is in scope, resolves to the real helper. The bug appears only when another crate expands the macro. An integration test under tests/ or an example catches it, because each is compiled as a separate crate that uses the library the way a dependent does.
  • How should an exported macro call another macro from the same crate?
    Write $crate::helper!() and mark helper with #[macro_export] as well, since the path still has to reach an exported macro. The older #[macro_export(local_inner_macros)] adds an implicit $crate:: to single-segment macro calls in the body; the Reference calls it a migration aid and discourages it in new code.
  • Why does the transcriber spell ::std::sync::Once instead of Once?
    A bare Once resolves at the call site, which may not import it or may import std::iter::Once instead. A path starting with :: names an external crate directly, so it does not depend on the caller's use declarations. A macro aimed at no_std users writes ::core paths where the item lives in core.

  • crate:: inside a macro body always means the crate that defined the macro.
  • $crate lets an exported macro call private functions of its own crate.
  • A #[macro_export] macro is reached through the module it was written in.
  • use declarations at the top of the macro's file are in scope inside its expansion.
  • Hygiene keeps a bare helper name pointing at the macro's own crate.
open as a page

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%

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.

open as a page

In Rust, why must a `macro_rules!` macro be defined above its first use in a file, when a function can be defined anywhere?

level: juniorimportance: should knowfreq 40%

basics

~20 s

A macro_rules! macro has textual scope: it exists from its definition to the end of the enclosing module or block, so a call above it fails to resolve. A function is an item with path-based scope, visible anywhere in its module.

open as a page

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?

level: seniorimportance: should knowfreq 25%

basics

~20 s

macro_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.

open as a page

In a Rust crate, a `macro_rules!` macro in `src/macros.rs` cannot be found from `src/report.rs`; which fixes work, and how do they differ?

level: seniorimportance: should knowfreq 35%

basics

~20 s

Textual scope ends when the macros module closes. #[macro_use] on mod macros extends it to code declared after that line; pub(crate) use name; gives the macro an ordinary path to import; #[macro_export] moves it to the crate root and exports it to other crates.

open as a page

A Rust 2021 crate exports a macro that writes `let gen = $e;` and a plain `extern "C"` block; why does it compile when a 2024 crate invokes it?

level: seniorimportance: nice to knowfreq 15%

basics

~20 s

Edition hygiene: every token remembers the edition of the crate it was written in, and rustc parses it under that edition wherever it is expanded. The macro's own tokens follow 2021 rules, where gen is an identifier and extern blocks need no unsafe.

open as a page