简体   繁体   English

在宏扩展中引用一个 extern crate

[英]Refer to an extern crate in macro expansion

I'm trying to write some macros that work in nostd environment as well as in std environment.我正在尝试编写一些在 nostd 环境和 std 环境中工作的宏。 In order to do so I have this kind of code in proc macro crate:为了做到这一点,我在 proc macro crate 中有这样的代码:

#[cfg(not(feature = "alloc"))]
{
    quote!(err.message = Some(::std::borrow::Cow::from(#m));)
}
#[cfg(feature = "alloc")]
{
    quote!(err.message = Some(::alloc::borrow::Cow::from(#m));)
}

This correctly produces the code that uses alloc when alloc feature is enabled, but the compiler complains这会在启用 alloc 功能时正确生成使用 alloc 的代码,但编译器会报错

error[E0433]: failed to resolve: could not find `alloc` in the list of imported crates

Of course the reason is that the macro expansion is missing当然原因是缺少宏扩展

extern crate alloc;

But adding that is a problem.但是添加它是一个问题。 Since it's a procedural derive macro, the extern crate will be added on each derive call.因为它是一个过程派生宏,所以 extern crate 将被添加到每个派生调用中。 How can I refer to an extern crate in macro expansion?我如何在宏扩展中引用外部板条箱? Using $crate does not seem to work inside quote!quote!内使用$crate似乎不起作用! . .

You can wrap the expansion in a block, then you can define alloc multiple times.您可以将扩展包装在一个块中,然后您可以多次定义alloc

Another common practice for proc macros that need auxiliary types is to create a crate that provides them, and reexport the macro from it.需要辅助类型的 proc 宏的另一种常见做法是创建一个提供它们的板条箱,并从中重新导出宏。 Eg create mycrate and mycrate-macros .例如创建mycratemycrate-macros Then you can get rid of the whole alloc feature if you only need alloc -accessible types, like:然后,如果您只需要alloc可访问的类型,则可以摆脱整个alloc功能,例如:

#![no_std]

extern crate alloc;

#[doc(inline)]
pub use mycrate_macros::my_macro;

#[doc(hidden)]
pub use alloc:borrow::Cow;

Then in the macro refer to ::my_crate::Cow .然后在宏中引用::my_crate::Cow

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM