Compilers and Interpreters: Assignment C5

April 6, 2004

In this assignment you will extend the mini-triangle compiler to handle a new construction, assertnonzero.

assertnonzero is equivalent to a procedure of one argument that returns the argument if it is not equal to zero, otherwise prints out a helpful error message and causes the program to exit. Ideally the error message should include the expression which caused the assertion to fail. The syntax has a keyword assertnonzero which precedes the expression, and a keyword enda which follows it.

Hand in:

  1. A brief description of your changes to
  2. your test cases and the output for each test case, showing that the compiler produces correct object code for programs involving these operators.
  3. print-outs of the lines of code you changed, with your changes circled or highlighted.

Here is some test code that may be useful. You are welcome to use your own test code if you prefer.


! test 1, for assertnonzero
let
   var i: Integer
in
  begin
    getint(i);
    i = assertnonzero i enda
  end


! test 2, for assertnonzero
let
   const onehundred ~ 100;
   var i: Integer;
   var j: Integer
in
  begin
    getint(i);  getint(j);
    putint(onehundred / assertnonzero i-j enda)
  end

When doing these problems, it may be helpful to examine the output of the compiler. The following code may be useful. To use it, add the line echo(op, n, r, d); in your version of emit in Encoder.java

private void echo (int op, int n, int r, int d) {
    String mnemonics [] = {
            "LOAD", "LOADA", "LOADI", "LOADL",
            "STORE", "STOREI", "CALL", "CALLI", 
	    "RETURN", "-", "PUSH", "POP",
            "JUMP", "JUMPI", "JUMPIF", "HALT"};
    String registers [] = {
        "CB", "CT", "PB", "PT", "SB", "ST", "HB", "HT",
        "LB", "L1", "L2", "L3", "L4", "L5", "L6", "CP"};
    System.out.print("Emitting: " + mnemonics[op] + " ");
    if (op == 0 || op == 2 || op == 4 || op == 5 || op == 6 ||
        op == 8 || op == 11 ||op == 14) {
			    System.out.print("(" + n + ") "); }
    if (op == 0 || op == 1 || op == 3 || op == 4 || op == 6 ||
        op == 8 || op == 10 ||op == 11 ||op == 12 || op == 14) {
			    System.out.print( d ); }
    if (op == 0 || op == 1 || op == 4 || op == 6 || op == 12 ||
        op == 14) {
			    System.out.print("[" + registers[r] + "]"); }
    System.out.println();
}

This function is also at http://www.cs.utep.edu/nigel/compilers/asst-c8.html


due April 20