Generate code once in proc_macro

I'm creating some helper functions/enums for a derive macro. I annotate many structs/enums with this derive macro. But for each annotation I end up generating duplicates of those helpers. How do I limit certain code generation to once?

the name 'SomeHelper' is defined multiple times

You shouldn't generate helpers from a derive macro. Put them in a separate crate and refer to them using their fully-qualified path instead.

4 Likes

The derive macro mainly wraps a data structure's fields in a new type

#[derive(MyDerive)]
struct Thing { a: u8, b: u32 }

Turns it into this

struct Thing { a: Setting<u8>, b: Setting<u32> }

Setting is only relevant for the macro's usage. Are you saying I shouldn't generate Setting and put that struct in a whole separate crate?

Yes.

1 Like

Almost all proc macro libraries come as two crates: one that provides runtime support facilities and another that implements the compile-time code generation. Usually, the runtime crate will list the compile-time crate as a dependency and re-export the proc macro. This lets downstream users have access to the entire library by including only the runtime crate in Cargo.toml.

4 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.