circle icon indicating copy to clipboard operation
circle copied to clipboard

question: generating nested loops with @meta expression

Open samuelpmish opened this issue 2 years ago • 0 comments

Is there a way to use @meta to generate nested for loops?

I've got a tensor class where, depending on the ranks of the tensors, the calculations require a different number of for loops to iterate over the relevant indices. This is something that is hard to do in C++, and I often end up writing a lot of different overloads for some calculations, depending on the tensor ranks (but for functions with multiple tensor arguments, each of arbitrary rank, this strategy is not feasible).

For example, the regular C++ code (intentionally unindented to emphasize how it might be generated):

int n0 = 2, n1 = 2, n2 = 2, n3 = 2;
for (int i0 = 0; i0 < n0; i0++) {
for (int i1 = 0; i1 < n1; i1++) {
for (int i2 = 0; i2 < n2; i2++) {
for (int i3 = 0; i3 < n3; i3++) {
    printf("%d, %d, %d, %d\n", i0, i1, i2, i3);
}
}
}
}

has an obvious structure: a bunch of for loops with unterminated curly braces, then the body of the nested loops, and then the closing curly braces. I tried to do this with @meta: but wasn't able to get it working.

int n0 = 2, n1 = 2, n2 = 2, n3 = 2;

// trying to use @meta to generate the nested for loops
// for (int i0 = 0; i0 < n0; i0++) {
// for (int i1 = 0; i1 < n1; i1++) {
// for (int i2 = 0; i2 < n2; i2++) {
// for (int i3 = 0; i3 < n3; i3++) {
@meta for (int d = 0; d < 4; d++) {
    for (int @("i", @string(d)) = 0; @("i", @string(d)) < @("n", @string(d)); @("i", @string(d))++) {
}

// nested for-loop body
//printf("%d, %d, %d, %d\n", i0, i1, i2, i3);

// trying to use @meta to generate the closing braces for nested for loops
// }
// }
// }
// }
@meta for (int d = 0; d < 4; d++) {
    }
}

https://godbolt.org/z/xToedcf3b

The tuple/pack features in circle (indexing, slicing, filtering) have simplified the rest of the tensor class implementation considerably, so if there is a mechanism to generate these nested loops, 95% of the implementation would disappear!

samuelpmish avatar Oct 08 '22 18:10 samuelpmish