Using `for` to loop over repetative elements in a macro

#1

Hello, I want to loop over the repetative idents in a macro and generate code. The code is here. In short I want to do some thing like

macro_rules! force_eq_macro {
    ($dest:ident, $source:ident, $foo:expr) => {
        force_equation(
            &$dest.x, &$dest.y, &$dest.u, &$dest.v, &src.x, &src.y, &src.u, &src.v, $foo
        );
    };
}

// This doesn't work
macro_rules! force_eq_macro_many_sources {
    ($dest:ident, ($($sources:ident),*), $foo:expr) => {
        // how to loop over the sources
        for src in $sources {
            force_equation(
                &$dest.x, &$dest.y, &$dest.u, &$dest.v, &src.x, &src.y, &src.u, &src.v, $foo
            );
        }
    };
}

This will reduce the number of equations by x/3.
Is this possible?

0 Likes

#2

Shouldn’t this be “simple” as this?

$(force_equation(&$dest.x, &$dest.y, &$dest.u, &$dest.v, &$sources.x, &$sources.y, &$sources.u, &$sources.v, $foo);)*
1 Like

#3

I tried it. The play link. It says,

 Compiling playground v0.0.1 (/playground)
error: no rules expected the token `d1`
  --> src/main.rs:68:38
   |
38 | macro_rules! force_eq_macro_many_sources {
   | ---------------------------------------- when calling this macro
...
68 |     force_eq_macro_many_sources!(d1, d1, d2, d3, bar);
   |                                      ^^ no rules expected this token in macro call

error: aborting due to previous error
0 Likes

#4

You need to put the last token before sources or use a different delimiter after sources, as a quick guess at least…

0 Likes

#5

Nope, not this… But in your macro definition you wrapped the repeating tokens in a pair of parens, so you need to do as well in the invocvation:

playground

    force_eq_macro_many_sources!(d1, (d1, d2, d3), bar);
1 Like

#6

Thanks.

0 Likes