我有一个宏可以将令牌处理成一些嵌套结构。
我使用这些结构体是一种“中间表示”,然后被宏转换为输出标记。
不过,我也想在运行时使用这些“中间表示”类型。
因此,如果我在宏中有一个 Rust 结构的实例,我该如何将其输出到最终程序中?
我可以在宏包和输出程序包之间共享类型,但是要获取实例数据,我必须执行诸如序列化为 JSON 字符串之类的操作,嵌入到最终程序中,然后在以下位置解析 JSON 字符串运行时?
谢谢。
宏的简单示例:
// This type will be used in both the macro and the program.
pub struct X {
a: String,
b: String
}
fn impl_x(ast: &syn::DeriveInput) -> TokenStream {
let x: X = ast.into();
let gen = quote! {
fn get_x() -> X {
// How to transfer instance `x` to the output TokenStream?
}
};
gen.into()
}
注意:我正在寻找一种适用于大型嵌套结构的通用方法。