Computer Science 301 - Translators


Tutorial 12 - A Python-like "for" loop for extended Parva

A Python-like version of the ForStatement has syntax that can be described by

         ForStatement = "for" Ident "in" "(" Expression { "," Expression } ")" Statement .

For example

    int i;  // small primes
    for i in (2, 3, 5, 7, 11)
      write(i, " is a small prime");

    bool a, b;  // truth tables
    for a in (false, true))
      for b in (false, true)
        writeLine(a, b, a || b, a && b);

As usual, the context-free grammar must be supplemented by semantic constraints and we need to be able to generate code for the PVM as well.

How would the productions be attributed to allow the constraint checking to proceed, how would the code generator routines be developed, and how would the PVM handle any new opcodes you might care to introduce?

Hint: It might be useful to consider one possible implementation strategy.

At run time, just before the Statement is executed, the top elements on the stack could be set up in a manner that is exemplified by the statement

              for i in (35, 64, -1, 235) write(i);   // loop to be executed 4 times

              ──────┬───────┬───────┬───────┬───────┬───────┬────────┬─────────
               ...  │   4   │  235  │  -1   │  64   │  35   │ adr i  │  ....
              ──────┴───────┴───────┴───────┴───────┴───────┴────────┴─────────

In this example the 4 on the top of the stack can then be used as a counter and decremented on each pass of the loop. The values below that can be assigned, one by one on each pass, to the designator whose address is lurking at the bottom of this segment.


Home  © P.D. Terry