SimpleVM

SimpleVM emulates a computer with a 1K x 32 bit random access memory (RAM) and a small instruction set:

load i, v      // ram[i] = v

copy i, j      // ram[j] = ram[i]

add i, j, k    // ram[k] = ram[i] + ram[j]

print i        // displays ram[i]

{CMMD+}        // command block

loop CMMD i    // while (0 < ram[i]) {CMMD; ram[i] = ram[i] – 1}

ifElse i CMMD1 [CMMD2]? // if (ram[i] != 0) CMMD1 else CMMD2

For example, the following program computes 5 * 6:

TestVM.java

Here's the complete code:

VM.java

Command.java

Interfaces

All of the above commands are represented by objects that implement the Command interface:

public interface Command {
   void execute(int[] ram) throws Exception;
}

Generic Collections

A VM program is an instance of Java's ArrayList<Command>, which implement's Java's List<Command> interface.

private List<Command> program = new ArrayList<Command>();

Delegators

VM uses the delegators add and clear to allow users to add commands to the program and clear it. This is generally preferable to supplying getters and setters for a private collection.

Constructors

VM provides a principle constructor that allows users to set memory size and a default constructor that simply calls the principle constructor with a default memory size.

Catching Exceptions

The run method executes program commands inside a catch-throw block.

Polymorphism

Notice that the run method does not know what kind of commands it is executing:

for(ip = 0; ip < program.size(); ip++) {
   program.get(ip).execute(ram);
}

This ignorance means new types of commands can be added to the VM instruction set without the need to alter the VM.

Throwing Exceptions

Load, Copy, Add, and Print implement the Command interface. They are pretty simple. Notice that all throw exceptions if given an invalid address. Often the location where an error is detected  is different from where the error should be handled.

Enhancing the SimpleVM Lab

Turn in a single file called TestFact.java. This file should include all of the command class declarations you declared as well as the TestFact class containing a main method containing the implementation of the factorial function. Test your program and paste the interaction into the bottom of TestFact.java as a comment. It should not be necessary to modify any of the classes provided by me, and so you don't need to tur these in.

Implement Multiply and Subtract commands

mul i, j, k    // ram[k] = ram[i] * ram[j]

sub i, j, k    // ram[k] = ram[i] - ram[j]

Implement Block and IfElse commands

{CMMD0 CMMD1 CMMD2 etc}

ifElse i CMMD1 [CMMD2]? // if (ram[i] != 0) CMMD1 else CMMD2

 

Test your implementations by writing and running a program that computes N! (N factorial) for N = 5.