我正在尝试在Rust中编写自己的派生模式宏,并且在其中的documentation在示例中有些缺乏。
我有一个像这样的结构:
#[derive(MyMacroHere)]
struct Example {
id: i64,
value: Option<String>,
}
我希望我的宏生成一个方法àla
fn set_fields(&mut self, id: i64, value: Option<String>) {
// ...
}
使用TokenStream
特性实现类似的基本步骤是什么?
cargo new my_derive --lib
[lib]
proc-macro = true
extern crate proc_macro;
use proc_macro::TokenStream;
#[proc_macro_derive(MyMacroHere)]
pub fn my_macro_here_derive(input: TokenStream) -> TokenStream {
// ...
}
extern crate my_derive;
use my_derive::MyMacroHere;
#[derive(MyMacroHere)]
struct Example {
id: i64,
value: Option<String>,
}
困难的部分在于宏的实现。大多数人使用syn和quote包来解析传入的Rust代码,然后生成新代码。
例如,syn的文档以an example of a custom derive开头。您将解析结构(或枚举或联合),然后处理定义结构(单元,元组,命名字段)的各种方法。您将收集所需的信息(类型,可能是名称),然后您将生成相应的代码。
也可以看看: