Generating loops
Gary <[email protected]>
| Newsgroups | gmane.comp.gnu.m4.general |
|---|---|
| Message-ID | <[email protected]> |
This looked so easy when I started out on it... Assuming one is writing code in a language which doesn't have any loop constructs like for..next, while/do..while, only "goto" and labels, how could one generate the necessary code using m4? I thought I could figure it out, but a for loop looking a bit like (assuming some kind of automatic incrementing of 'count'): ,---- | for count = 0 to 2 | // some code | next `---- which might look something like: ,---- | count = 0 | loop_start: | | if count > 2 | goto loop_end | endif | | // some code | | count = count + 1 | goto loop_start | | loop_end: | // end of loop `---- seems to present a couple of problems I don't understand how (if) they can be achieved. Let's say my (probably rather naive) implementation of the "for" part is ,----[ m4 macro ] | define(`for', `$1' = `$3' | start_`$0'_`$1'_`$3'_`$4'_`$5': | if $1 > $5 | goto end_$0_$1_$3_$4_$5 | endif | ) `---- and I write and interpret some code via my macro: ,----[ incorrect generation ] | ,----[ code ] | | y = 0 | | | | for(i = 1 to 12) | | y = y + 1 | | next | `---- | = | ,----[ result ] | | y = 0 | | | | i = 1 to 12 = | | start_for_i = 1 to 12___: | | if i = 1 to 12 > | | goto end_for_i = 1 to 12___ | | endif | | | | y = y + 1 | | next | `---- `---- I get the "wrong" result (i.e. wrong in the sense that the macro doesn't get hold of the macro arguments correctly) although I know I can get the output I want by adding commas between the macro arguments in the call: ,----[ correct generation ] | ,----[ code ] | | for(i, =, 1, to, 12) | | y = y + 1 | | next | `---- | = | ,----[ result ] | | i = 1 | | start_for_i_1_to_12: | | if i > 12 | | goto end_for_i_1_to_12 | | endif | | | | y = y + 1 | | next | `---- `---- So, is there any way to make the original code look more like, well, code, by avoiding the commas? The other problem I see is that somehow I need my "next" macro (for the end of the loop) to know about the origin of the loop (i.e. the start label). Is there any way to do this, or should I somehow combine them into one macro?