Macro rules to dispatch multiple values

Hello,
I am fighting with a macro:

pub(crate) enum Args<A, B, C, D, E> {
    Args0(A),
    Args1(B),
    Args2(C),
    Args3(D),
    Args4(E),
}

macro_rules! test {
    ($t:ty,$($value:expr),*) => {
        #[test]
        fn test() {
            test_func(InputArgs {
                args: {
                    let mut v: Vec<$t> = Vec::new();
                     $(
                    if v.len()==0 {
                       v.push(Args::Args0($value));
                    } else if v.len()==1 {
                        v.push( Args::Args1($value));
                     }else if v.len()==2 {
                        v.push( Args::Args2($value));
                     }else if v.len()==3 {
                        v.push( Args::Args3($value));
                     }else if v.len()==4 {
                        v.push( Args::Args4($value));
                     }
                    )*
                    v
                },
            });
            run($($value,)*);
        }
    };
}

This pseudo code shows my goal:I am trying to populate a vector with enums of different types.
The main problem is that I don't know the index of the loop, so dispatch the proper value to the corresponding Args index.
Is it possible to do with macro rules ?

Thank you in advance for your help.

Here’s what I could come up with:

macro_rules! test {
    ($t:ty,$($value:expr),*) => {
        #[test]
        fn test() {
            test_func(InputArgs {
                args: {
                    let v: Vec<$t> = test_inner!([Args0 Args1 Args2 Args3 Args4][$($value),*][]);
                    v
                },
            });
            run($($value,)*);
        }
    };
}
macro_rules! test_inner {
    ([$ArgsN:ident $($Args:ident)*][$value:expr $(, $values:expr)*][$($applied:expr),*]) => {
        test_inner!(
            [$($Args)*][$($values),*][$($applied,)* Args::$ArgsN($value)]  
        )
    };
    ($unused_Args:tt[] $applied:tt) => {
        vec!$applied
    };
}

test! { Args<bool, i32, (), (), ()>, false, 42, () }

Rust Playground

In the future (or for follow-up questions, in case this doesn’t match your expectations), please consider including some test usage example with a macro request.

I agree with you: most of the time I like to add a rust playground when the question is about debugging.
But in that case, it was more to show my goal.
Thank you for this perfect answer.
I really need to find a better documentation about macro rules because some parts of your code are a mystery: need to investigate ...

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.