【问题标题】:Using $crate in Rust's procedural macros?在 Rust 的过程宏中使用 $crate?
【发布时间】:2017-12-10 13:25:35
【问题描述】:

我知道$crate 变量是什么,但据我所知,它不能在过程宏中使用。有没有其他方法可以达到类似的效果?

我有一个示例,大致要求我使用 quote 和 nightly Rust 编写类似的东西

quote!(
     struct Foo {
        bar: [SomeTrait;#len]
     }
)

我需要确保SomeTrait 在范围内(#len 引用的是 sn-p 范围之外的整数)。

我在夜间使用过程宏 2.0 时使用 quote 和 syn,因为 proc-macro-hack 对我不起作用。 This is the example 我正在尝试概括。

【问题讨论】:

  • 1.您的程序宏真的生成结构而不是 impl 块吗?出于愚蠢的原因,与生成 impl 的宏相比,生成结构的宏最可靠的方法要复杂得多。
  • 2.这是针对 proc_macro_derive 宏还是其他类型的程序宏?
  • 3. [SomeTrait; #len] 不是你能做的,因为[T; n] 需要T: Sized。见play.rust-lang.org/?gist=bb33e5ba42a7e64af998b014483329f0。你能澄清一下预期的结果吗?
  • @dtolnay: 1. 它正在生成一个结构和一个 impl 块。 2. 这是针对 Nightly Macros 2.0 的; 3. play.rust-lang.org/… 之类的东西(我需要过程宏,因为我想以特定方式解析第一个参数)
  • @dtolnay 更新了问题并进行了澄清。

标签: macros rust


【解决方案1】:

根据https://github.com/rust-lang/rust/issues/38356#issuecomment-412920528 的回复,看起来没有办法做到这一点(截至 2018-08 年),既不能引用 proc-macro crate,也不能明确引用任何其他 crate。

【讨论】:

    【解决方案2】:

    在 2015 版(经典 Rust)中,您可以这样做(但它很老套):

    • 在宏中使用::defining_crate::SomeTrait
    • 在取决于defining_crate 的第三方板条箱中,上述工作正常
    • defining_crate自身内,在根目录下添加一个模块:

      mod defining_crate { pub use super::*; }

    在 2018 版中,需要更多的 hacky 解决方案(请参阅 this issue),尽管 #55275 可能会给我们一个简单的解决方法。

    【讨论】:

      【解决方案3】:

      从 Rust 1.34 开始,您可以使用 extern crate self as my_crate,并使用 my_crate::Foo 代替 $crate::Foo

      https://github.com/rust-lang/rust/issues/54647

      https://github.com/rust-lang/rust/pull/57407

      (来源:Neptunepink ##rust irc.freenode.net)

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多