5.5. The LOOP Statement

We could stop right here, and have a language that works. It's been shown many times that a high-order language with only two constructs, the IF and the WHILE, is sufficient to write structured code. But we're on a roll now, so let's richen up the repertoire a bit.

This construct is even easier, since it has no condition test at all … it's an infinite loop. What's the point of such a loop? Not much, by itself, but later on we're going to add a BREAK command, that will give us a way out. This makes the language considerably richer than Pascal, which has no break, and also avoids the funny while(1) or WHILE TRUE of C and Pascal.

The syntax is simply

LOOP <block> ENDLOOP

and the syntax-directed translation is:

LOOP            { L = NewLabel;
                  PostLabel(L) }
<block>
ENDLOOP         { Emit(BRA L }

The corresponding code is shown below. Since I've already used l for the ELSE, I've used the last letter, p, as the “keyword” this time.

{ Parse and Translate a LOOP Statement }
procedure DoLoop;
var L: string;
begin
   Match('p');
   L := NewLabel;
   PostLabel(L);
   Block;
   Match('e');
   EmitLn('BRA ' + L);
end;

When you insert this routine, don't forget to add a line in Block to call it.