views:

69

answers:

1

Hallo,

I need help in Lex/Yacc Programming. I wrote a compiler for a syntactical analysis for inputs of many statements. Now i have a special problem.

In case of an Input the compiler gives the right output, which statement is uses, constant operator or a jmp instructor to which label, now i have to write so, if now a if statement comes, first the first command (before the else) must be give out when the assignment of the if is yes then it must jump to the end because the command after the else isnt needed, so after this jmp then the second command must be give out. I show it in an example maybe you understand what i mean.

Input adr. Output

if(x==0)        10   if(x==0)
Wait 5          20   WAIT 5
else            30   JMP 50
Wait 1          40   WAIT 1
end             50   END

like so. I have an idea, maybe i can do it whith a special if statement like

IF exp jmp_stmt_end stmt_seq END

when the if statement is given in the input the compiler has to recognize the end ofthe statement and like my jmp_stmt in my compiler ( you have to download the files from http://bitbucket.org/matrix/changed-tiny) only to jump to the end. I hope you understand my problem.thanks.

+2  A: 

I would do this by a two-stage output: the first pass wold generate a list with each output statement, where the jump targets are encoded by labels, and a second pass, where this list is used to generate the real output. Something like this:

pass one:

Number Label Satatement
10           if(x==0)
20           WAIT 5
30           JMP (A)
40           WAIT 1
50       A   END
Rudi
+1. This process is called "backpatching" and, while it **can** be done in a single pass, the two-pass approach offered here is much, much easier to implement and works just as well.
Chris