Question: A while language is a very simple imperative programming language with 5 statements Assign - consists of a variable and an expression While - consists

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

Compound - consists of a sequence of statements

Output - consists of a variable

You are required to code a class hierarchy in Java that defines the abstract syntax of "while" programs.

For example, you will have:

abstract class Statement {

... some methods ...

}

class Assign extends Statement {

constructor Assign(Variable x, Expression y) { ... }

... some methods ...

}

Of course, there must be a symbol table containing the binding of the variables.( you can use Hashmap)

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.

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!