有没有办法在 proc-macro crate 中拥有公共特征? [英] Is there a way to have a public trait in a proc-macro crate?

查看:46
本文介绍了有没有办法在 proc-macro crate 中拥有公共特征?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有宏的 proc-macro crate,当扩展时,需要为 Rust 内置类型使用自定义特征实现.我试图在同一个 crate 中定义 trait,但 Rust 告诉我 proc-macro crate 只能有公共宏(用 #[proc_macro] 注释的函数),其他任何东西都不能是公共的.所以我把这个 trait 放在另一个 crate 中,并在 proc-macro crate 中将它作为依赖项包含在内.但这意味着任何想要使用我的 proc-macro crate 的人也必须依赖其他 trait crate.

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 Rust tells me that a proc-macro crate can only have public macros (the functions annotated with #[proc_macro]) and nothing else can be public. So I put the trait in another crate and in the proc-macro crate included it as a dependency. But this means that anyone that wants to use my proc-macro crate has to depend on the other trait crate too.

所以我想知道 是否有一种方法可以将公共特征添加到 proc-macro crate 中,或者以其他方式使 proc-macro 和 trait crate 以某种方式链接,以便最终用户可以不要尝试在没有另一个的情况下使用一个?如果两者都不可能,唯一的解决方案就是记录依赖项,这有点脆弱.

So I wonder if there is a way to add a public trait to the proc-macro crate, or otherwise to make the proc-macro and trait crates linked in some way so the end user can't try to use one without the other? If neither is possible, the only solution is documenting the dependency, which is kind of fragile.

推荐答案

通常处理这种情况的方法是让用户完全不依赖您的 proc-macro crate.

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

你的问题可以用 3 个板条箱解决:

Your problem can be solved with 3 crates:

  • 内部"包含 proc 宏使用的类型和特征定义的 crate
  • proc-宏板条箱:
    • 依赖于内部 crate,所以它可以使用它的类型和特征
    • 取决于内部和 proc 宏包
    • 重新导出您希望用户使用的所有类型、特征和宏

    每当您的宏在其生成的代码中提及共享类型时,您都需要使用完全限定的名称,这样用户就不需要导入它们.

    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 依赖于 thiserror-impl 包含实际的宏
    • pin-project 取决于 pin-project-internal 再次包含宏
    • darling 依赖于 darling-coredarling-macro,它本身也依赖于 darling-core
    • 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

    这篇关于有没有办法在 proc-macro crate 中拥有公共特征?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆