How to put proc macro into prelude?

I implemented proc macro and I want to avoid importing it everywhere I want to use it within #[derive(...)]. So I declared it in main.rs using extern crate packet. But I still need to import it directly.

This is how I declared the macro:

#[proc_macro_derive(Packet, attributes(options, dynamic_field))]
pub fn derive_packet(input: TokenStream) -> TokenStream {
    // ...
}

and my Cargo.toml inside root of macro dir:

[package]
name = "packet"
version = "0.1.0"
edition = "2021"

[lib]
name = "packet"
path = "src/lib.rs"
proc-macro = true

[dependencies]
...

Could somebody explain if it possible to make proc macro be imported by default so I can omit importing it directly ?

In a crate that wants to use the macro, you can do

#[macro_use]
extern crate packet;

in the top-level module to avoid the need for adding

use packet::Packet;

in every module.

2 Likes

Thank you ! This works

On the other hand (or maybe additionally), it might also be sufficiently convenient to re-export (pub use packed::Packed) the derive macro in the same module where the trait is defined, assuming this is about a trait named Packed. (If it isn’t, then this remark does not apply.) Then the derive-macro will be usable unqualified whenever the trait is in scope, too.[1] This assumes that the crate that defines Packed does (at least conditionally, e.g. with a “derive” feature flag) depend on the crate that defines the proc-macro.


  1. For context, macros and other items like functions or types can be in scope or even exported at the same time under the same name without conflict, and a like use crate_name::Packet statement would then bring both into scope at the same time. ↩︎

2 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.