0
votes

I'm trying to index data tuple in macro that generate signature for trait implementation, but have some errors. Can I index tuple or need another solution? Hack with tuple_index I found in google but it not works for me.

https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=7d4bc0f56c643cf4693279a9bd9db973

macro_rules! expr { ($x:expr) => ($x) } // HACK
macro_rules! tuple_index {
    ($tuple:expr, $idx:tt) => { expr!($tuple.$idx) }
}
macro_rules! gen_packer {
    (@step $data: expr, $_idx:expr,) => {};

    (@step $data: expr, $idx:expr, $T:ident, $($tail:ident,)*) => {
        // out.append(&mut $T::pack(tuple_index!(data,$idx)));
        tuple_index!($data, $idx);

        gen_packer!(@step $data, $idx + 1, $($tail,)*);
    };

    ($($T:ident),*) => {
        impl<$($T,)+> Packer<($($T,)+)> for Iproto
        where $($T: Pack<$T>,)+
        {
            fn pack(self, data: ($($T,)+)) -> Vec<u8> {
                let mut out = vec![];
                gen_packer!(@step data, 0, $($T,)*);
                return out
            }
        }
    }
}

gen_packer!(A);

Errors on compilation:

error: unexpected token: `0`
--> src/lib/iproto.rs:70:29
   |
70 |         tuple_index!($data, $idx);
   |                             ^^^^
...
99 | gen_packer!(A);
   | --------------- in this macro invocation

error: unexpected token: `,`
  --> src/lib/iproto.rs:63:46
   |
63 |     ($tuple:expr, $idx:tt) => { expr!($tuple.$idx) }
   |                                              ^
...
99 | gen_packer!(A);
   | --------------- in this macro invocation

error: no rules expected the token `0`
  --> src/lib/iproto.rs:70:29
   |
61 | macro_rules! expr { ($x:expr) => ($x) } // HACK
   | ----------------- when calling this macro
...
70 |         tuple_index!($data, $idx);
   |                             ^^^^ no rules expected this token in macro call
...
99 | gen_packer!(A);
   | --------------- in this macro invocation

error: aborting due to 3 previous errors
1
Your code gives me no error. You may want to use that macro in a function. Please provide an example where we can reproduce that error you got in your code, e.g. on the playground - hellow
Btw: your code works... play.rust-lang.org/… You may want to be more specific about what works and what doesn't. That's why it is important to provide an example that fully works/doesn't work. Only in that case we can help you - hellow
@hellow need to call gen_packer, not tuple_index. I'm update code - Alexander Kudzin
@AlexanderKudzin what is A? - hellow
@hellow letter for generic (not variable) - Alexander Kudzin

1 Answers

1
votes

Can I index tuple or need another solution?

No. The expression $idx + 1 will produce distinct tokens, for example 0, +, 1, and there is no way to evaluate that to a single literal token within a declarative macro.