How to parse the value of a macro's helper attribute?

I'm working on implementation a proc macro that can be used like this:

[derive(Modbus)]
struct Registers {
    #[holding_register(4)]
    value: i32
}

Currently macro is already able to get all fields having the attribute holding_register. But I am unable to figure how I parse the 4 out of the attribute.

use quote::{quote, TokenStreamExt};
use proc_macro::TokenStream;

use syn;
use syn::{parse_macro_input, DeriveInput};

#[derive(Debug)]
struct RegisterMapping {
    ident: syn::Ident,
    address: u16,
    count: u16,
}

#[proc_macro_derive(Modbus, attributes(holding_register))]
pub fn my_macro(input: TokenStream) -> TokenStream {
    // Parse the input tokens into a syntax tree
    let ast = parse_macro_input!(input as DeriveInput);
    let name = &ast.ident;

    let struct_: syn::DataStruct = match ast.data {
        syn::Data::Struct(data) => data,
        _ => panic!("Usage of #[Modbus] on a non-struct type"),
    };

    let fields: Vec<RegisterMapping> = struct_
        .fields
        .iter()
        .filter_map(|field| {
            for attr in field.attrs.iter() {
                let x: TokenStream = attr.tokens.clone().into();
                dbg!(attr.clone());

                //let _input = parse_macro_input!(x);
                for segment in attr.path.segments.iter() {
                    if segment.ident.to_string() == String::from("holding_register") {
                        return Some(RegisterMapping {
                            ident: field.clone().ident.unwrap().clone(),
                            address: 32,
                            count: 16,
                        });
                    };
                }
            }

            return None;
        })
        .collect();
}

```

Anyone that could give a hint?
if attr.path.is_ident("holding_register") {
    let lit: syn::LitInt = attr.parse_args()?;
    let n: u16 = lit.base10_parse()?;
    ...
}

Thanks a lot. I was totally looking into the wrong direction.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.