GATE / CS ARCHIVE

GATE CSE 2001 / QUESTION 17

Translate repeat-until statements

Compiler Design · Semantic Analysis & Type Checking · Full GATE CSE 2001 paper

GATE 2001, Q17 Descriptive
Report issue

Semantic Analysis & Type Checking

Question 17, GATE 2001: S→repeat S1 until E. S1.code is body code; E.code computes a Boolean into E.varName (1=true,0=false). newlabel() returns a fresh label; gen(s) emits a code line.
Question 17, GATE 2001: S→repeat S1 until E. S1.code is body code; E.code computes a Boolean into E.varName (1=true,0=false). newlabel() returns a fresh label; gen(s) emits a code line.
Tap to enlarge
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.

Original paper, page 9