Is there a way to have a public trait in a proc-macro crate?

前端 未结 1 2029
萌比男神i
萌比男神i 2021-01-23 08:45

I have a proc-macro crate with a macro that, when expanded, needs to use custom trait implementations for Rust built-in types. I tried to define the trait in the same crate, but

1条回答
  •  广开言路
    2021-01-23 08:59

    The way this is usually dealt with is to not have users depend on your proc-macro crate at all.

    Your problem can be solved with 3 crates:

    • "internal" crate containing type and trait definitions that are used by the proc-macro
    • proc-macro crate:
      • Depends on the internal crate, so it can use its types and traits
    • "public" crate:
      • Depends on both the internal and proc-macro crates
      • Re-exports all types, traits and macros that you want your users to use

    Whenever your macro mentions the shared types in its generated code, you need to use the fully-qualified names so that users don't also need to import them.


    Some popular examples of this pattern in the wild:

    • thiserror depends on thiserror-impl which contains the actual macros
    • pin-project depends on pin-project-internal which again contains the macros
    • darling depends on darling-core and darling-macro, which itself also depends on darling-core

    0 讨论(0)
提交回复
热议问题