一种可能的解决方法:不是FooTrait
直接定义,而是将您需要的有关它的信息编码到某种结构中,将其存储在 a 中const
,并从派生宏和另一个生成FooTrait
.
编辑:如果你想要“的”令牌流FooTrait
,你不需要const
(这只是一个骨架,未经测试):
宏箱:
#[proc_macro]
pub fn foo_trait_definition(_input: TokenStream) -> TokenStream {
TokenStream::from(quote!(
trait FooTrait {
... // actual definition goes here
}
))
}
#[proc_macro_derive(FooTrait)]
pub fn foo_trait_derivation(input: TokenStream) -> TokenStream {
let foo_trait_tokens: TokenStream = foo_trait_definition(TokenStream::from(quote!()));
// you can parse foo_trait_tokens and use them just like input
TokenStream::from(quote!(
impl foo_mod::FooTrait for #name {
...
}
))
}
特质箱:
mod foo_mod {
foo_trait_definition!();
}
和
#[derive(FooTrait)]
struct Foo {
i: i32,
}
但我希望在大多数情况下,宏箱可以看起来像这样,而不是解析foo_trait_tokens
:
// lists method names here, if they are all (&self)
// but probably you want something more complex
const foo_trait_data = ["foo"];
#[proc_macro]
pub fn foo_trait_definition(_input: TokenStream) -> TokenStream {
// use foo_trait_data here
TokenStream::from(quote!(
trait FooTrait {
... // actual definition goes here
}
))
}
#[proc_macro_derive(FooTrait)]
pub fn foo_trait_derivation(input: TokenStream) -> TokenStream {
// use foo_trait_data here too
TokenStream::from(quote!(
impl foo_mod::FooTrait for #name {
...
}
))
}