Macro Design · 18 min · free lesson

Macro Hygiene

Resolve generated names without accidental capture.

Core idea

Rust macros track syntax context so identifiers introduced by a macro do not casually collide with names at the call site.

Diagram for Macro Hygiene: a Rust code example flows to the lesson rule and the key observation.
$crate::value keeps pointing at the defining crate wherever the macro is expanded.

Understand it

Rust macros track syntax context so identifiers introduced by a macro do not casually collide with names at the call site. Use explicit paths such as $crate for helper items exported with a macro.

A macro can introduce identifiers in the caller's scope, and those names must resolve predictably. Rust's syntax contexts protect many identifiers introduced by a declarative macro from accidentally capturing a similarly named local value. This is hygiene, but it is not a reason to ignore names entirely: exported macros still need a stable way to refer to helper items from their defining crate. $crate::helper points to that crate even when a caller renames its dependency. A plain unqualified helper name may accidentally resolve in the caller's scope or fail there.

Try exporting a macro that calls an internal helper and invoke it from a separate crate. First use an unqualified helper name and observe the failure. Then use $crate::helper and ensure the helper is reachable in the way the expansion needs. If the macro creates a local temporary, choose a small scope and test with a caller variable of the same spelling. Also test the macro when the dependency is renamed in Cargo.toml. Inspect expanded code when a diagnostic seems to point at an unfamiliar name. Hygiene reduces accidental capture, while explicit paths and careful API tests make an exported macro dependable across crate boundaries.

When a macro is exported, run a small downstream consumer test rather than invoking it only inside its defining crate. The consumer catches path assumptions that local tests hide. Give public helper items namespaced paths and avoid relying on imports that happen to be present in one caller. This keeps the macro usable as the crate evolves.

Read the code

#[macro_export]
macro_rules! answer {
    () => { $crate::value() };
}

$crate::value keeps pointing at the defining crate wherever the macro is expanded.

Practice starter

// my_macros/src/lib.rs
pub fn value() -> u32 { 42 }

#[macro_export]
macro_rules! answer {
    () => { $crate::value() };
}

// app/src/main.rs, with my_macros renamed to helpers
fn value() -> u32 { 0 }

fn main() {
    println!("{}", helpers::answer!());
}

Practise this code in Playground ↗

Try it

Predict what app prints. Then change $crate::value() to plain value() in the macro, and predict again.

What success looks like: You can say why the unqualified call picks the caller's value and why $crate does not.

Check your understanding

What does $crate resolve to at the call site?

Reveal the answer
  1. The defining crate
  2. The caller variable
  3. Cargo.lock

$crate names the crate that defined the macro, even when the caller renamed it, so this prints 42 rather than using the caller's value.

Go deeper

Common misconception: “Because macros are hygienic, every name in an exported macro resolves in the defining crate.”

Hygiene protects local names such as temporaries, not item paths. An exported macro reaches its helpers through $crate.

  1. Export the macro: #[macro_export] places answer! at the root of the defining crate, so other crates can name it.
  2. Expand the call: A call of answer!() expands to $crate::value(), which names a value function at the defining crate's root.
  3. Check the helper: value must be pub, because the expansion runs in the caller's crate. A private helper fails there, even though $crate finds the right crate.

Transfer challenge: Add a temporary named tmp inside answer! and a let tmp in the caller. Predict which value each use sees, then explain why that protection did not help the unqualified value().

Connections

  • Rust Idioms: Newtype, builder, and typestate
  • Token Trees: Match Rust syntax as nested tokens, not raw text
Learn this lesson with AI

Paste this into Claude, Codex, Cursor or another agent connected to Crabrix Academy. It contains only this lesson’s public details.

I'm learning Rust with Crabrix Academy. Teach me this lesson with the Crabrix Academy tools.
Lesson: Macro Hygiene (courseId "systems", lessonId "macro-hygiene")
Link: https://crabrix.com/learn/systems/macro-hygiene/
Goal: Rust macros track syntax context so identifiers introduced by a macro do not casually collide with names at the call site.
Practice: open the starter in the Crabrix Playground (https://crabrix.com/playground/?lesson=systems/macro-hygiene) and I will write the code there.
Explain it step by step for my level, let me write the code myself, give hints before any solution, and do not mark anything as passed: only Crabrix checks do that.

In Claude Code, Codex or Cursor, paste it into a chat with Crabrix Academy connected. On a phone, the Claude and ChatGPT apps open the same links.