Rust宏会计数并生成重复的结构字段

问题描述 投票:1回答:1

我想编写一个从整数参数生成不同结构的宏。例如,make_struct!(3)可能会生成如下内容:

pub struct MyStruct3 {
    field_0: u32,
    field_1: u32,
    field_2: u32
}

将“ 3”文字转换为可用于生成代码的数字的最佳方法是什么?我应该使用macro_rules!还是proc-macro

rust macros
1个回答
0
投票

您需要一个过程属性宏和大量的管道工作。 Github上有一个示例实现;请记住,它的边缘很粗糙,但是从一开始就很好用。

目标是拥有以下内容:

#[derivefields(u32, "field", 3)]
struct MyStruct {
     foo: u32
}

转换为:

struct MyStruct {
   pub field_0: u32,
   pub field_1: u32,
   pub field_2: u32,
   foo: u32
}

为此,我们首先要确定两件事。我们将需要struct来轻松存储和检索参数:

struct MacroInput {
    pub field_type: syn::Type,
    pub field_name: String,
    pub field_count: u64
}

其余是管道:

impl Parse for MacroInput {
    fn parse(input: ParseStream) -> syn::Result<Self> {
        let field_type = input.parse::<syn::Type>()?;
        let _comma = input.parse::<syn::token::Comma>()?;
        let field_name = input.parse::<syn::LitStr>()?;
        let _comma = input.parse::<syn::token::Comma>()?;
        let count = input.parse::<syn::LitInt>()?;
        Ok(MacroInput {
            field_type: field_type,
            field_name: field_name.value(),
            field_count: count.base10_parse().unwrap()
        })
    }
}

这在syn::Parse上定义了struct,并允许我们使用syn::parse_macro_input!()轻松解析我们的参数。

#[proc_macro_attribute]
pub fn derivefields(attr: TokenStream, item: TokenStream) -> TokenStream {
    let input = syn::parse_macro_input!(attr as MacroInput);
    let mut found_struct = false; // We actually need a struct
    item.into_iter().map(|r| {
        match &r {
            &proc_macro::TokenTree::Ident(ref ident) if ident.to_string() == "struct" => { // react on keyword "struct" so we don't randomly modify non-structs
                found_struct = true;
                r
            },
            &proc_macro::TokenTree::Group(ref group) if group.delimiter() == proc_macro::Delimiter::Brace && found_struct == true => { // Opening brackets for the struct
                let mut stream = proc_macro::TokenStream::new();
                stream.extend((0..input.field_count).fold(vec![], |mut state:Vec<proc_macro::TokenStream>, i| {
                    let field_name_str = format!("{}_{}", input.field_name, i);
                    let field_name = Ident::new(&field_name_str, Span::call_site());
                    let field_type = input.field_type.clone();
                    state.push(quote!(pub #field_name: #field_type,
                    ).into());
                    state
                }).into_iter());
                stream.extend(group.stream());
                proc_macro::TokenTree::Group(
                    proc_macro::Group::new(
                        proc_macro::Delimiter::Brace,
                        stream
                    )
                )
            }
            _ => r
        }
    }).collect()
}

修饰符的行为创建一个新的TokenStream并添加我们的字段first。这是极其重要;假定提供的结构为struct Foo { bar: u8 };附加last会由于缺少,而导致解析错误。前置允许我们不必关心这一点,因为结构中的尾部逗号不是解析错误。

[一旦有了这个TokenStream,我们就用从extend()生成的令牌连续quote::quote!();这使我们不必自己构建令牌片段。一个陷阱是,字段名称需要转换为Ident(否则将其加引号,这不是我们想要的)。

然后我们将此修改后的TokenStream返回为TokenTree::Group,以表示这确实是一个由方括号分隔的块。

这样做,我们还解决了一些问题:

  • 由于没有命名成员的结构(例如,pub struct Foo(u32)从未真正有一个开括号,因此此宏对此不起作用)>
  • 它将不操作不是结构的任何项目
  • 没有成员也将没有操作结构
© www.soinside.com 2019 - 2024. All rights reserved.