Computer Science 301 - 2003

Tutorial for week 26 - Code generation

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? You might like to look at Exercise 13.20 on page 230 which will give you some further ideas.

-------------------------------------------------------------------------------------------

In response to various requests I have made the source code for the Parva compiler described in chapter 14 available for people to study and to play with. There is no compulsion to do so, but if you would like to study the code in detail, go right ahead. You will not be expected to answer practical questions on this code in the examination. If we had had another week it might have been a different story!

There are several files zipped up in the file PRAC26.ZIP. You can copy this in the usual way from the course web pages or the I: directory, for example

         l:
         md  prac26
         cd  prac26
         copy  i:\csc301\trans\prac26.zip
         unzip  prac26.zip

Make the compiler:

CMAKE Parva

Try it out, for example:

PARVA queens.pav

Look at the code in QUEENS.COD in the usual way.

The interpreter in this kit can handle several extended opcodes like LDC_1 or LDGA_1, but the code generator and parser are not set up to do those optimizations (which would, of course take the same sort of form as you are supposed to be developing in Practical 25).

Have fun. Ask me if there is anything you do not understand or would like explained further.


Home  © P.D. Terry