Sub topic 10
Scoping, #[macro_export], and $crate
This chapter covers where a macro_rules! macro can be called, how to share it across modules and crates, and how an exported macro refers to its own crate's items. It assumes you can write a basic macro_rules! macro with matchers and transcribers, and that you know Rust modules, pub, and how a Cargo workspace or a library crate with a dependent binary is laid out.
Two kinds of macro scope
Functions and types are found by path. macro_rules! macros were designed before that system covered macros, so they have two separate lookup mechanisms:
- Textual scope. A macro is visible from the line after its definition to the end of the enclosing block or module. Lookup depends on source order.
- Path-based scope. A macro is visible through a path such as
crate::name!,mycrate::name!, or a name brought in withuse. Lookup depends on module structure and works like any other item.
A bare invocation like name!() is resolved first against textual scope and then against path-based scope. That is why the same macro can be reachable in one place and invisible in another.
Textual scope
A macro must be defined before the code that calls it, in file order. The scope ends when the enclosing module or block ends.
mod first {
macro_rules! greet {
() => {
println!("hello")
};
}
pub fn run() {
greet!(); // fine: defined above, same module
}
}
fn main() {
first::run();
// greet!(); // error: cannot find macro `greet` in this scope
}Two consequences follow:
- Order of
moddeclarations matters. Ifmod macros;comes aftermod users;inmain.rs, code inuserscannot see macros defined inmacros. - A macro defined inside a function body is visible only in the rest of that block.
A later definition with the same name shadows an earlier one for the rest of the scope. This is legal and sometimes intentional, but it can surprise you when two files define macro_rules! log.
Extending scope with #[macro_use] on a module
By default a macro does not escape its module. Putting #[macro_use] on the module extends the scope past the closing brace, to the end of the parent.
#[macro_use]
mod macros {
macro_rules! twice {
($e:expr) => {
($e, $e)
};
}
}
fn main() {
let t = twice!(1 + 1);
println!("{:?}", t);
}This prints (2, 2). The attribute only widens textual scope inside the current crate. It does not make the macro available to other crates. For a module in a separate file, the order still matters: declare #[macro_use] mod macros; before any module that needs it.
Older code also writes #[macro_use] extern crate somecrate; to import all of a dependency's exported macros. In the 2018 edition and later you import them by path instead, as shown below.
Path-based scope with #[macro_export]
Adding #[macro_export] changes how the macro is named:
- The macro is placed at the crate root, no matter which module defines it.
- It becomes
pub, so other crates can import it. - It is reachable by path, so definition order no longer matters for path-based uses.
Here is a library crate named mini:
// src/lib.rs of the crate `mini`
pub mod util {
#[macro_export]
macro_rules! square_plus_one {
($x:expr) => {
$crate::util::add_one($x * $x)
};
}
pub fn add_one(x: i32) -> i32 {
x + 1
}
}A binary crate that depends on mini imports the macro from the crate root:
// src/main.rs of a crate that depends on `mini`
use mini::square_plus_one;
fn main() {
println!("{}", square_plus_one!(3));
}This prints 10. Note the path: the macro lives at mini::square_plus_one, not mini::util::square_plus_one, even though it was written inside util. This is the most common surprise with #[macro_export]. The module only affects where the definition sits in the source, not its public path.
Inside the defining crate you can also write crate::square_plus_one!(2).
Keeping a macro crate-private but path-addressable
If you want path-based lookup without exporting the macro, re-export it with a use declaration:
mod macros {
macro_rules! shout {
($s:expr) => {
println!("{}!", $s)
};
}
pub(crate) use shout;
}
use macros::shout;
fn main() {
shout!("hey");
}This prints hey!. The pub(crate) use turns the textually scoped macro into a normal item with crate visibility. You can now import it from any module, and call order no longer matters.
Why $crate exists
A macro body is pasted into the caller's code. Any path you write in it is resolved where the macro is used, not where it was defined. Suppose the caller's crate has its own util module, or no util at all. Writing util::add_one(...) in the transcriber would then break or, worse, call a different function.
$crate solves this. It is a special metavariable that always expands to the crate that defined the macro:
- Inside the defining crate it acts like
crate. - In a downstream crate it becomes a path to the defining crate, whatever the user renamed it to in
Cargo.toml.
#[macro_export]
macro_rules! hashmap {
($($k:expr => $v:expr),* $(,)?) => {{
let mut map = ::std::collections::HashMap::new();
$( map.insert($k, $v); )*
map
}};
}
#[macro_export]
macro_rules! call_helper {
($x:expr) => {
$crate::helper($x)
};
}
pub fn helper(x: i32) -> i32 {
x + 1
}Two habits in this example are worth copying:
- Use
$crate::for anything from your own crate. - Use a leading
::std::(or::core::) for the standard library. A plainstd::collections::HashMapfails if the caller has a local module or crate namedstd. This is rare but easy to avoid.
Everything $crate points at must be public
The expansion lands in someone else's crate, so the path must be valid from there. A private fn helper would fail with a privacy error in the downstream crate. Helpers that only exist for your macros are usually made pub and hidden from the docs:
#[doc(hidden)]
pub fn __helper(x: i32) -> i32 {
x + 1
}The double-underscore prefix and #[doc(hidden)] signal "not part of the public API", although the item is technically public and cannot change without risk.
Calling other macros from a macro
The same rule applies to macros that call macros. If hashmap! is exported and another exported macro wants to use it, write $crate::hashmap!. A bare hashmap! would require the user to have imported it. Writing $crate::name! works on any supported edition and makes the macro self-contained.
How a bare invocation is resolved
The diagram shows the lookup for name!() in the order the compiler tries it.
Common errors and their causes
| Symptom | Likely cause | Fix |
|---|---|---|
| `cannot find macro` in a sibling module | Macro defined in a module that closed, or declared after the caller | Add `#[macro_use]` to the module and put it first, or use `pub(crate) use` |
| `unresolved import mini::util::square_plus_one` | `#[macro_export]` places the macro at the crate root | Import `mini::square_plus_one` |
| `failed to resolve: use of undeclared crate or module` in a downstream crate | The transcriber used a plain path instead of `$crate::` | Replace with `$crate::path` |
| `function helper is private` in a downstream crate | `$crate::helper` is not `pub` | Make it `pub` and add `#[doc(hidden)]` |
| Macro works in one file but not another | Textual scope depends on `mod` order | Prefer path-based imports for shared macros |
Choosing an approach
- Macro used in one module only: define it there, with no attributes.
- Macro shared inside one crate: use
pub(crate) use name;and import it normally. This avoids order problems and keeps the macro private. - Macro shared with other crates: use
#[macro_export],$crate::for your items, and::std::for the standard library. - A tiny legacy codebase with many macros:
#[macro_use] modworks, but it hides where names come from.
Exercise
A library crate named shapes defines this inside pub mod area { ... }: #[macro_export] macro_rules! circle_area { ($r:expr) => { area::pi() * $r * $r }; }, where pi() is a pub fn in that same module. A downstream crate writes use shapes::area::circle_area; and fails to compile. Name the two mistakes (one on each side) and give the corrected import and the corrected transcriber path.
Show answer
First mistake: #[macro_export] puts the macro at the crate root, so the import must be use shapes::circle_area;. Second mistake: the transcriber uses area::pi(), which is resolved in the caller's crate where no area module exists. It should be $crate::area::pi() * $r * $r. The function pi must also be pub, which it already is.
Exercise
You have a macro log_line! that only one crate uses, defined in mod macros in src/macros.rs. Modules net and db both call it, and mod net; appears before mod macros; in main.rs, so net fails with "cannot find macro". Give a fix that does not depend on module order and does not export the macro from the crate.
Show answer
Add pub(crate) use log_line; after the macro_rules! definition in macros.rs, then write use crate::macros::log_line; in net and db. The macro is then found by path, so the order of mod declarations no longer matters, and it stays private to the crate.