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?
answer
- paths resolve at the call
- whose crate root is crate::?
- a metavariable naming the defining crate
- privacy still applies
- where #[macro_export] puts it
basics
~20 sPaths 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 sHygiene 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// 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
Recall that #[macro_export] makes a macro usable from other crates and that exported macros reach their own crate's items through $crate.
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.
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.
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.