宏中的元组索引

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

我试图在宏中索引数据元组,为特征实现生成签名,但有一些错误。我可以索引元组还是需要其他解决方案?用tuple_index破解我在google中发现但它不适用于我。

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);

编译错误:

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
rust rust-macros rust-decl-macros
1个回答
1
投票

我可以索引元组还是需要其他解决方案?

否。表达式$idx + 1将生成不同的标记,例如0+1,并且无法在声明性宏中对单个文字标记进行评估。

© www.soinside.com 2019 - 2024. All rights reserved.