How to devide proc_macro into multiple modules?

I have multiple proc macros for my project, since them working in different categories, I decide to divide them. But the compiler complains that

`proc-macro` crate types currently cannot export any items other than functions tagged with `#[proc_macro]`, `#[proc_macro_derive]`, or `#[proc_macro_attribute]`

I tried to make the submodule private and only pub use the proc macro only, but it cannot work either.

You can have regular functions with the proc macro implementations in submodules and then at the root for each proc macro just the #[proc_macro] function which only calls this implementation. So for example:

use proc_macro::TokenStream;

mod foo_impl {
    use proc_macro::TokenStream;
    fn foo(ts: TokenStream) -> TokenStream { todo!(); }
}

#[proc_macro]
fn foo(ts: TokenStream) -> TokenStream { foo_impl::foo(ts) }

This is what for example rustc itself and serde_derive do.

1 Like