Computer Science 3 - 2003

Programming Language Translation


Practical for Weeks 25 - 26, beginning 13 October 2003

This extended prac is designed to take you the best part of two weeks. Hand in your solutions before lunch time on Monday 27 October, correctly packaged in a transparent folder with your cover sheets. Since the practical will have been done on a group basis, please hand in one copy of the cover sheet for each member of the group. Your solutions will be returned to you as soon as possible after that.

The reason for requiring all submissions by 27th October is to free you up during swot week to prepare for the final examinations.


Objectives:

In this practical you are to

You will need this prac sheet and your text book. As usual, copies of the prac sheet are also available at http://www.cs.ru.ac.za/CSc301/Translators/trans.htm.


Outcomes:

When you have completed this practical you should understand

Hopefully after doing these exercises (and studying the attributed grammar and the various other support modules carefully) you will find you have learned a lot more about compilers and programming languages than you ever did before (and, I suspect, a lot more than undergraduates at any other university in this country). I also hope that you will have begun to appreciate how useful it is to be able to base a really large and successful project on a clear formalism - namely the use of attributed context-free grammars - and will have learned to appreciate the use of sophisticated tools like Coco/R.


To hand in:

By the hand-in date you are required to hand in, besides the cover sheets (one per group member):

I do NOT require listings of any Java code produced by Coco/R.

Keep the prac sheet and your solutions until the end of the semester. Check carefully that your mark has been entered into the Departmental Records.

You are referred to the rules for practical submission which are clearly stated on page 13 of our Departmental Handbook. However, for this course pracs must be posted in the "hand-in" box outside the laboratory and not given to demonstrators.

A rule not stated there, but which should be obvious, is that you are not allowed to hand in another student's work as your own. Attempts to do this will result in (at best) a mark of zero and (at worst) severe disciplinary action and the loss of your DP. You are allowed - even encouraged - to work and study with other students, but if you do this you are asked to acknowledge that you have done so. You are expected to be familiar with the University Policy on Plagiarism, which you can consult at:

        http://www.scifac.ru.ac.za/plag.htm 


Before you begin

The tasks are presented below in an order which, if followed, should make the practical an enjoyable and enriching experience. Please do not try to leave everything to the last few hours, or you will come horribly short. You must work consistently, and with a view to getting an overview of the entire project, as the various components and tasks all interact in ways that will probably not at first be apparent. Please take the opportunity of coming to consult with me at any stage if you are in doubt as how best to continue. By all means experiment in other ways and with other extensions if you feel so inclined.

This version of Parva has been restricted so as not to include functions. This means that there will be no practical work set on chapter 14 of the text. Because of the timing of our courses this is unavoidable, if highly regrettable. You should be warned that some of the material of that chapter may be "examinable".

You are also advised that it is in your best interests to take this opportunity of really studying the code in the Parva grammar and its support files. The exercises have been designed to try to force you to do that, but it is always tempting just to guess and to hack. With a program of this size that often leads to wasting more time than it saves. Finally, remember the advice given in an earlier lecture:

Keep it as simple as you can, but no simpler.


A note on test programs

Throughout this project you will need to ensure that the features you explore are correctly implemented. This means that you will have to get a feel for understanding code sequences produced by the compiler. The best way to do this is usually to write some very minimal programs, that do not necessarily do anything useful, but simply have one, or maybe two or three statements, the object code for which is easily predicted and understood.

When the Parva compiler has finished compiling a program, say SILLY.PAV, you will find that it creates a file SILLY.COD in which the stack machine assembler code appears. Studying this is often very enlightening.

Useful test programs are small ones like the following. There are some specimen test programs in the kit, but these are deliberately incomplete, wrong in places, too large in some cases and so on. Get a feel for developing some of your own.

    $D+ // Turn on debugging mode
    void main (void) {
      int i;
      int[] List = new int[10];
      while (true) { // infinite loop, can generate an index error
        read(i);
        List[i] = 100;
      }
    }

The debugging pragma

It is useful when writing a compiler to be able to produce debugging output -but sometimes this just clutters up a production quality compiler. The PARVA.ATG grammar makes use of the PRAGMAS option of Coco/R (see text, page 159) to allow pragmas like those shown to have the desired effect.

$D+ /* Turn debugging mode on */
$D- /* Turn debugging mode off */


Task 1 - Create a working directory and unpack the prac kit

There are several files that you need, zipped up this week in the file PRAC25.ZIP.


Task 2 - Better use of the debugging pragma

We have already commented on the $D+ pragma. At present it is only used to request the printout of a symbol table. How would you change the system so that one would have to use a similar pragma or command line option if one wanted to obtain the assembler code file - so that the ".COD" file of assembler code is only produced when it is really needed?

$C+ /* Request that the .COD file be produced */
$C- /* Request that the .COD file not be produced */

Another useful (run-time) debugging aid is the undocumented stackdump statement. Compilation of this is also controlled by the $D pragma (in other words, the stack dumping code is only generated in debug mode).

(Most of the time you are testing your compiler you will probably be working in "debugging" mode, I expect).

Hint: This addition is almost trivially easy.


Task 3 - How long is a piece of string?

Why do you suppose languages generally impose a restriction that a literal string must be contained on a single line of code?

In C++, two or more literal strings that appear in source with nothing but white space between them are automatically concatenated into a single string. This provides a mechanism for breaking up strings that are too long to fit on one line of source code. How might this feature be added to the Parva compiler? This feature is not needed in languages like C# and Java that have proper strings, as the concatenation can be done with a + operator. Allow this concatenation operator as an option.


Task 4 - Things are not always what they seem

Although not strictly illegal, the appearance of a semicolon in a program immediately following the condition in an IfStatement or WhileStatement or immediately preceding a closing brace may be symptomatic of omitted code. The use of a so-called "empty statement" means that the example below almost certainly will not behave as its author intended:

         read(i);
         while (i > 10);
         { write(i); i = i - 1; }

Is it possible to warn the user when this sort of code is parsed, and if so, how? Here is another example that might warrant a warning (there are no statements inside the Block).

         read(i);
         while (i > 10) {
           /* write(i); i = i - 1; */
         }

Warnings are all very well, but they can become irritating. Use a $W- pragma or a -d command line option to allow advanced users to suppress warning messages.


Task 5 - Detecting other meaningless forms of code

Consider the following code, which has some further bits of nonsense:

         while (i > 10) int k;
         if (i > 10) { int k; }
         if (true) { ;;;; }
         if (true) { const max = 10; ; }

Find a way to warn a user silly enough to want to compile this sort of code.


Task 6 - Suppressing some error messages

Identifiers that are undeclared by virtue of mistyped declarations tend to be annoying, for they result in many subsequent errors being reported. Implement a strategy where each undeclared identifier is flagged as undeclared at the point of first reference, and then quietly entered as a variable of the noType pseudo-type in the symbol table. Can you extend the idea to recognize an undeclared array reference variable and thereby reduce the plethora of "unexpected subscript" messages that this non-declaration might otherwise generate?


Task 7 - Some simple statement extensions

The remaining tasks all involve coming to terms with the code generation process. The first extensions are very easy.

Extend the WriteStatement to have a variation introduced by a new key word writeLine that automatically appends a line feed to the output after the last WriteElement has been processed.

Extend the HaltStatement to have an optional string parameter that will be output just before execution ceases (a useful way of indicating how a program has ended prematurely).


Task 8 - Let's operate like C

The operator precedences in Parva as supplied resemble those in Pascal and Modula, where only three basic levels are supported. Modify Parva so that it uses a precedence structure based on that in C++ or Java (the basic grammar modifications were discussed in earlier practicals). Take special care to deal with "short circuit" semantics correctly (see page 226) and with type compatibility issues (see section 12.6.8)


Task 9 - You had better do this one or else....

Add an else option to the IfStatement. Oh, yes, it is trivial to add it to the grammar. But be careful. Some IfStatements will have else parts, others may not, and the code generator has to be able to produce the correct code for whatever form is actually to be compiled. The following silly examples are all valid.

         if (a == 1) { c = d; }
         if (a == 1) {}
         if (a == 1) {} else {}
         if (a == 1) {} else { b = 1; }


Task 10 - Something to do - while you wait for a tutor

Add the DoWhile loop to Parva, as exemplified by

         do { a = b; c = c + 10; } while (c < 100);


Task 11 - This has gone on long enough - time for a break

The BreakStatement is syntactically simple, but takes a bit of thought. Give it some! The catch, of course, is that breaks can only come inside loops, there might be several break statements inside a single loop, and loops can be nested inside one another.


Task 12 - Break over, let's continue

The ContinueStatement is also syntactically simple. Once you have puzzled out the BreakStatement the ContinueStatement should be simple, surely?


Task 13 - Make the change; enjoy life; upgrade now to Parva++ (Ta-ra!)

At last! Let's really make Parva useful and turn it into Parva++ by adding the increment and decrement statement forms exemplified by

         int parva;
         int [] list = new int[10];
         ...
         parva++;
         list[10]--;

Suggestions for doing this - specifically by introducing new operations into the PVM - are made in section 13.5.1 of the text. Remember that only integer variables can be handled in this way.


Task 14 - Other cute assignment operators

Parva is looking closer to C/C++/Java with each successive long hour spent in the Hamilton Labs. Seems a pity to stop now, so go right on and extend the system to allow statements like

         int parva;
         int [] list = new int[10];
         ...
         parva *= 2;
         list[10] += parva;

Once again, section 13.5.1 should give you some ideas of how to proceed. And, once again, remember that only integer variables can be handled in this way.


Task 15 - Generating slightly better code

Way back in Practical 20 we added some specialized opcodes like LDC_1, LDA_2 and so on to the PVM. They are still there in the version supplied with the kit. Seems a shame not to use them, so modify the code generator to achieve this for you.

Making use of LDL and STL and variations on them is rather more difficult and is not required, but feel free to experiment if you wish.


Home  © P.D. Terry