COP 4020 Programming Assignment 7: Tail Recursion Optimization

Educational Objectives: After completing this assignment, the student should be able to do the following:

Operational Objectives: Eliminate tail recursion in the supplied program Calc.java

Deliverables: Two files AST7.java and Calc7.java

In this programming exercise we will improve the performance of the CalcAST application. The performance is improved by a tail-recursion optimization that you will have to implement by hand (that is, hand write the code, as opposed to generate it automatically from the grammar as a non-optimizing compiler would).

Tail recursion optimization changes a recursive call into a jump (goto) statement back to the beginning of the function. The arguments to the function are set accordingly to ensure that the jump passes the new argument values to the beginning of the function. This requires overwriting the argument values with updated values if necessary.

For example, when we have a Java method like

private int method(MyClass arg)
{
  if (...)
  {
    ...
    return method(someNewValue);
  }
  else
  {
    ...
    return method(someOtherNewValue);
  }
  return 0;
}

In order to implement tail-recursion optimization, we must transfer control from the return statements back to the beginning of the method. Something that is similar to:

private int method(MyClass arg)
{ 
/* start: */
  if (...)
  {
    ...
    arg = someNewValue;
    /* goto start  */
  }
  else
  {
    ...
    arg = someOtherNewValue;
    /* goto start  */
  }
  return 0;
}

In the interest of enforcing "non goto" programming, Java does not support goto statements, so you will have to figure out a way to implement the jump back to the start of the method to achieve a loop. In addition, methods may have more than one argument, so be careful to handle them all to obtain a correct optimization.

Begin again with the CalcAST.java and AST.java souce code that was the beginning for the previous assgnment. Copy (and download if needed) the CalcAST.java and AST.java source files from

~cop4020p/fall08/examples/

Recall that CalcAST constructs an abstract syntax tree (AST) representation of arithmetic expressions, after which a depth-first left-right traversal outputs a Lisp expression equivalent to the input. Modify the program CalcAST.java by elimination of tail-recursion for the following methods:

term_tail
factor_tail

You are not required to implement the simplification as in the previous assignment. Therefore, your program should just output the non-simplified Lisp representation. In other words, your program output should be exactly the same as the original program.

Turn in the files AST7.java and Calc7.java using the submit script pr7submit.sh.