This homework is based on notions of chapters 6 and previous chapters of the textbook.
A "while language" is a very simple imperative programming language with 5 statements
Assign | consists of a variable and an expression |
While | consists of an expression and a statement |
If | consists of an expression and two statements |
Compoud | consists of a sequence of statements |
Output | consists of a variable |
You are required to code a class hierarchy in some OO language of your choice that defines the abstract syntax of while programs.
For example, you will have:
abstract class Statement {
... some methods ...
}
class Assign is_subclass_of Statement {
constructor Assign(Variable x, Expression y) {
...
}
... some methods ...
}
Expressions are very similar to those of a previous homework, but may contain variables and relational operators, e.g., < or >. Of course, there must be a symbol table containing the binding of the variables.
You must code two methods in your classes: one for pretty printing the statements and one for executing (interpreting) the statements. The execution of the Output statement prints the name and the value of its argument variable.
Below is a plausible (no specific language) abstract syntax representation of a program that computes the factorial of 5.
factorial = Compound([
Assign(Var("n"),Val(5)),
Assign(Var("r"),Val(1)),
While(Bin('>',Var("n"),Val(0)),
Compound([
Assign(Var("r"),Bin('*',Var("r"),Var("n"))),
Assign(Var("n"),Bin('-',Var("n"),Val(1))),
])),
Output(Var("r"))
]);
Pretty printing the above program should produce something like the printout below. Beside the indentation, spaces and parentheses are flexible.
begin
n := 5
r := 1
while (n > 0) do
begin
r := (r * n)
n := (n - 1)
end
output r
end
Executing (interpreting) the above program should produce
r = 120
Finally, you are required to code a simple (comparable to factorial) program of your choice, and pretty print and execute it. Turn in your code and a trace of execution.
Hints: This is a relatively simple exercise. I recommend that you code expressions, statements and programs each one in its own file. The first two should be about one page long each. For your own benefit, you should code unit test before coding the program and test your code incrementally as you add classes and methods.