LARA

Exercise: Loop with Exit

Recall the rule for compiling while statement:

[[ while(c) s ]] =
nStart: [[c]]
        if_eq nAfter
        [[s]]
        goto nStart
nAfter: 

Programming language Oberon-2, has a statement of the form

LOOP
  code1
  EXIT IF cond
  code2
END

which executes a loop and exits when the condition is met. Observe how this construct generalizes 'while' and 'do … while' looping constructs in other languages.

Task 1

Give a translation scheme for the LOOP construct.

Task 2

Apply the translation to

j = i
LOOP
  j = j + 1
  EXIT IF j > 10
  s = s + j
END
z = s + j - i

Task 3

A more common way to exit from a loop is to use a 'break' statement, as in

while (true) {
  code1
  if (cond) break
  cond2
}

Consider a language that has expressions, assignments, the {…} blocks, 'if' statements, while, and a 'break' statement. The 'break' exits the innermost loop and can appear inside arbitrarily complex blocks and if conditions. How would translation schemes or a code generator for such construct look like?

Answer: break jumps to the label. Need to pass in labels. This will be great, also for generating nicer code in the EXIT IF example.