Sub topic 10
Scoping, #[macro_export], and $crate
This chapter assumes you can write a basic macro_rules! macro and understand Rust modules and pub. It covers where a macro can be called, how to share one across files and crates, and how to keep it working when other crates call it.
Textual scope
A macro_rules! macro is not an item in a module namespace. It follows textual scope. You can call it only in code that comes after its definition in the source, inside the block or module that contains it. A call placed before the definition fails with "cannot find macro".
Child modules declared after the definition can see the macro. A macro defined inside a module is not visible once that module closes, unless you put #[macro_use] on the module.
#[macro_use]
mod macros {
macro_rules! shout {
($s:expr) => {
println!("{}!", $s)
};
}
}
fn main() {
shout!("hello");
}Without #[macro_use], the call in main fails because shout! goes out of scope at the end of mod macros. The module must also appear before the code that uses it. In a multi-file project, declare the macros module first in main.rs or lib.rs.
Path-based scope with #[macro_export]
#[macro_export] makes a macro an ordinary public item at the root of its crate. It then follows path-based scope, and the order of definitions no longer matters. The attribute works wherever the macro is defined, even inside a nested module. The macro is still placed at the crate root.
Other crates can import the macro with use:
use my_crate::hashmap;They can also call it by full path:
let m = my_crate::hashmap!{ "a" => 1 };Inside the same crate, you can write crate::hashmap!.
| Mechanism | Visible where | Order matters |
|---|---|---|
| Plain `macro_rules!` | After the definition, in the same module and its children | Yes |
| `#[macro_use]` on a module | After the module, in the parent | Yes |
| `#[macro_export]` | Crate root, and other crates by path | No |
Making exported macros robust with $crate
An exported macro expands in someone else's crate. Any path you write in the transcriber is resolved at the call site, so it can break. Two habits prevent this:
- Use
$crate::to refer to items in the macro's own crate.$cratealways resolves to the defining crate, however the caller imported the macro. - Use absolute paths such as
::std::collections::HashMapfor standard library items. The caller might have their ownHashMapor a module namedstd.
Items reached through $crate:: must be pub, because the expansion happens outside your crate.
#[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
}A user of this crate can call call_helper!(1) without importing helper. The expansion becomes my_crate::helper(1), which resolves correctly.
Common errors
- "cannot find macro" in the same crate. The call comes before the definition, or the defining module lacks
#[macro_use]. Move the definition earlier, or add#[macro_export]and call it by path. - "function is private" at the call site. A macro used
$crate::helper, buthelperis notpub. - Name clashes at the crate root. Every exported macro shares one flat namespace, so give exported macros distinctive names.
Exercise
A library crate defines #[macro_export] macro_rules! double { ($x:expr) => { util::twice($x) }; }, where util is a private module with pub fn twice. The macro compiles in the library but fails when another crate calls it. What is wrong, and how do you fix it?
Show answer
The path util::twice is resolved at the call site, where no util module exists, and a private module could not be reached anyway. Write $crate::util::twice($x) and make util a pub mod (or re-export twice publicly) so the expansion can reach it from outside the crate.