Computer Science 301 - Translators


Tutorial 11 - Code generation for a "for" loop

Many languages provide for a ForStatement in one or other form. Although most people are familiar with these, their semantics and implementation can actually be quite tricky.

Suppose we were to add a simple Pascal-style for loop to Parva, to allow statements with concrete syntax defined by

       ForStatement = "for" Designator "=" Expression ("to" | "downto") Expression "do" Statement .

for example

       for i = 1 to 10 do write(i);          // forwards  1 2 3 4 5 6 7 8 9 10
       for i = 10 downto 1 do write(i);      // backwards 10 9 8 7 6 5 4 3 2 1
       for i = 10 to 5 do write(i);          // no effect
       for b = false to true do write(b);    // writes "false true"
       for i = i - 1 to i + 6 do write(i);   // what does this do?
       for i = 1 to 5 do read(i);            // should we allow this?
       for i = 1 to 5 do i = i + 1;          // should we allow this?

What would you suggest in the way of constraints, how would you enforce the constraints, and how would you generate code for these sorts of statements?


Home  © P.D. Terry