Title says it all. It came to me as a real surprise, that this is working "the old fashioned way", unlike everything else in rust with regards to definitions. For example the definition of fn may be at the end of file and yet we can call it from the definition of another function that is at the very beginning of the file.
What are the reasons, that this behavior doesn't work for macros?
Declarative macros are textually scoped, unlike other (proper) items, which have path-based scopes. As to why, the Reference puts that down to historical reasons. Macros 2.0 is a proposal to supersede current declarative macros with macros that are proper items with path-based scoping.
For macros inside the same crate, you can give them path-based scope with a use
:
foo::bar!();
mod foo {
macro_rules! bar {
() => {};
}
pub(crate) use bar;
}
Outside the crate you have to get a little weirder because you have to also use #[macro_export]
, which will always add the macro to the crate root:
foo::bar!();
pub mod foo {
#[doc(hidden)]
#[macro_export]
macro_rules! bar_will_be_exported_at_crate_root_please_ignore_this {
() => {};
}
pub use bar_will_be_exported_at_crate_root_please_ignore_this as bar;
}
Note that the re-export trick may not play well with your docs.
I don't recall if it is necessary, but documentation will definitely appear if you put it on the pub use
.
Thank you for your reply.
Of course I do appreciate the effort you've put into the answer but that only reaffirms the feeling in me that macros are messed up.
In my simple case I just took the macro def and moved it up in the file, but why did I have to do it? Why doesn't it work as fn do? Weird and surprising...
Once again, thank you for your time and help.