Semantic Analysis & Type Checking


Answer & solution
Answer: S.code = gen(L+":") || S1.code || E.code || gen("if "+E.varName+" == 0 goto "+L), where L=newlabel(). (no official key was published)
Associate the production with this semantic rule:
L = newlabel();
S.code = gen(L + ":")
|| S1.code
|| E.code
|| gen("if " + E.varName + " == 0 goto " + L);Here || denotes concatenation of generated code strings, not Boolean OR. The resulting three-address layout is:
L:
[body code]
[compute E into t]
if t == 0 goto L
[next statement]The body is before the condition so it runs at least once. A false result repeats; a true result falls through. E.code must be inside the loop because the condition is recomputed after every iteration. A fresh label for each production application avoids collisions when repeats are nested. No explicit exit label is necessary because the successful path falls through.