In Rust, why must a `macro_rules!` macro be defined above its first use in a file, when a function can be defined anywhere?
answer
- two different kinds of scope
- source order, like let bindings
- items resolve by path, in any order
- recursion still works inside it
basics
~20 sA 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.
solid answer
~40 sBy default a `macro_rules!` macro is **textually scoped**: its name enters scope right after the definition and stays until the enclosing module or block closes, much like a `let` binding, except that it also works at module level and flows into child modules declared after it. A call written above the definition fails with ``cannot find macro `greet` in this scope``, and rustc adds a note that a macro with that name appears later. Functions, structs and other items have **path-based scope**, so their whole module sees them whatever the order. Recursion still works, because the names in an expansion are looked up at each invocation, where the macro is already in scope. The fix is to move the definition up, or give the macro a path with `pub(crate) use greet;` after it.
code
rust · 7 linesfn main() {
greet!();
}
macro_rules! greet {
() => { println!("hi") };
}go deeper
Recall that macro_rules! macros are scoped by source order, unlike functions, and recognise the cannot find macro error you get when a call sits above the definition.
Explain textual versus path-based scope, that a textually scoped macro flows into child modules declared after it, and why recursion works anyway.
Lay out a crate so macro order never bites: give internal macros a path with pub(crate) use, or keep a macros module declared before everything that uses it.
Treat macro placement as a crate convention, so contributors never have to know which file is declared first for the build to work.
## Two kinds of scope for one name Rust gives names two quite different scoping rules, and `macro_rules!` macros use the unusual one. - **Path-based scope** is what items get. A `fn`, `struct`, `enum`, `static` or `mod` belongs to a module, and any code in that module can name it, above or below the definition. That is why `main` can call a function written at the bottom of the file. - **Textual scope** follows the order of the source. A `macro_rules!` definition makes its name available *from that point on*, until the module or block that contains it closes. The Reference compares it to the scope of a local variable declared with `let`, except that it also applies at the module level. By default a macro by example has **only** textual scope. It has no path at all, so even `self::greet!()` or `crate::greet!()` fails unless something gives it one. ## What textual scope means in practice 1. A call above the definition does not compile. rustc 1.99.1 prints ``cannot find macro `greet` in this scope`` and a note pointing at the definition that "appears later". The error has no E-code. 2. The scope runs to the end of the enclosing module or block. A macro defined inside `fn foo` is usable only in `foo`, after its definition; a macro defined in `mod util { ... }` is gone once that module's closing brace is reached, unless the module carries `#[macro_use]`. 3. The scope **flows into child modules** declared after the definition, even when the child lives in another file. If `lib.rs` defines a macro and then says `mod parser;`, code in `parser.rs` can call it. 4. Redefining a name is allowed. A second `macro_rules! greet` shadows the first from that point on; a call between the two uses the first. Two `fn greet` items in one module, by contrast, are an `E0428` error. 5. Recursion works. The body of a macro is not resolved when the definition is read; names in an expansion are looked up at the invocation, and every recursive invocation happens where the macro is already in scope. ## Why macros work this way The Reference says plainly that macro scoping does not work entirely like items "for historical reasons". Textual scope is the original rule for `macro_rules!`. Path-based imports of macros, `use` for macros and `$crate` only arrived in Rust 1.30, shortly before the 2018 edition, and they were added on top of textual scope rather than replacing it. So today a macro can have both kinds of scope, and an unqualified call such as `greet!()` checks textual scope first, then path-based scope. ## The fixes, side by side | Fix | What changes | When to use it | |---|---|---| | Move the definition above the first call | The call is inside the textual scope | One file, a few small macros | | `#[macro_use]` on the module that defines it | Textual scope extends past that module, still in source order | Older code with a `macros` module declared first | | `pub(crate) use greet;` after the definition | The macro gets a path; other code imports it like a function | Internal macros shared across modules | | `#[macro_export]` | The macro gets a path at the crate root and is public | Macros meant for other crates | ## Where you meet this in real code - **Test modules.** A helper macro defined at the bottom of `lib.rs` is not visible inside a `#[cfg(test)] mod tests` written above it; the test build fails with the same cannot-find-macro error until the macro moves up or the test module moves down. - **Shared helpers across files.** A macro written in one module file is not visible in a sibling module, because textual scope ends with the module that contains it; giving it a path is the clean fix. - **Standard macros.** `println!`, `vec!` and `assert!` never hit this, because they come from the standard library, which every crate imports implicitly, rather than from a definition in your file. - **Macros inside functions.** A local `macro_rules!` is a handy way to cut repetition inside one long function, and textual scope guarantees it leaks nowhere else. ## A worked check The snippet in the code example fails exactly as described: `main` calls `greet!()` on line 2, the definition follows it, and rustc reports the missing macro plus an `unused_macros` warning on the definition it could not reach. Moving the four lines of the definition above `fn main` is the whole fix. Things to remember: - Order of definitions matters for macros and does not matter for items. - "cannot find macro" with a note that the name "appears later" is the signature of a textual-scope problem. - When order becomes awkward, give the macro a path instead of shuffling files.
- Can a macro_rules! macro call itself recursively when its scope only starts after the definition?Yes. The body is not resolved when the definition is read. Names in an expansion are looked up at the invocation, and each recursive invocation sits inside an expansion of the macro, which is already in its own scope by then. The Reference states this explicitly in its textual-scope rules, which is why tt munchers and other recursive macros need nothing special.
- What happens if one file defines the same macro_rules! name twice?It compiles. The later definition shadows the earlier one from its position onward, and calls between the two still use the first. This is another place where macros behave like let bindings rather than items: two fn items with one name in one module are E0428, the name is defined multiple times.
- Macros are expanded before name lookup, so their definition order cannot matter.
- A macro defined anywhere in a module is visible to the whole module, like a function.
- A macro_rules! macro cannot call itself, because it is not in scope inside its own body.
- Defining the same macro_rules! name twice in one file is a duplicate-definition error.
- Every macro_rules! macro can be called by path, as crate::name!, without any extra step.