How to use macro inside another macro?


#1

I’ve defined a macro in a crate, and that macro uses lazy_static internally. Unfortunately, when I use this macro from another crate, I get the error “cannot find macro lazy_static! in this scope.”

This is finally fixed when I do #[macro_use] extern crate lazy_static in the crate in which I’m using the macro, but this seems sketchy to me for two reasons:

  • This requires the user to know about this dependency
  • I could probably instead do #[macro_use] extern crate lazy_static in the macro definition itself, but then that would preclude the macro from being used anywhere other than a crate root (since doing #[macro_use] on an extern crate declaration is disallowed outside of the crate root).

Is there a clean way around this issue that I’m missing?


#2

Well, I think there’s a trick, but use it on your own risk. In the recent versions of Rust, use foo::* exports macros (this is not yet documented, because it sort of not entirely stable yet). So, before the definition of your macro, you could use lazy_static::*;. I’ve use this trick here: https://github.com/matklad/fall/blob/527ab331f82b8394949041bab668742868c0c282/fall/parse/src/lib.rs#L291 (runtime is a module used by generated code, which is like a macro in some sence) .


#3

I had to use pub use rather than juse use, but it worked! Thanks!