package duckMachine.architecture; import java.io.*; /** * A simple hardware machine with a memory, a processor, and an IO unit. * The machine can perform two operations: run a program, and step * through a program. * @author Amr Sabry * @version jdk-1.1 */ public class Machine implements MachineI { private MemoryI mem; private ProcessorI proc; private ioUnitI io; public Machine () { this(Memory.DEFAULT_SIZE, ioUnit.DEFAULT_ISTREAM, ioUnit.DEFAULT_OSTREAM); } public Machine (int memorySize) { this(memorySize, ioUnit.DEFAULT_ISTREAM, ioUnit.DEFAULT_OSTREAM); } public Machine (InputStream istream, OutputStream ostream) { this(Memory.DEFAULT_SIZE, istream, ostream); } public Machine (int memorySize, InputStream istream, OutputStream ostream) { mem = new Memory (memorySize); proc = new Processor (); io = new ioUnit (istream, ostream); Load(); } public MemoryI getMem () { return mem; } public ProcessorI getProc () { return proc; } public ioUnitI getIO () { return io; } /** * @exception MemoryE If the word fetched from memory is not an instruction * or the PC contains an out-of-range address. */ private void fetchInstruction () throws MemoryE { Word currentPC = proc.fetchPC(); Word nextPC = proc.getALU().inc(currentPC); proc.storePC(nextPC); Word currentWord = mem.fetch(currentPC); if (currentWord instanceof Instruction) { Instruction currentIns = (Instruction)currentWord; proc.storeIR(currentIns); } else throw new MemoryE ("Can only fetch instructions into the IR"); } /** * step fetches the next instruction and executes it * @exception MachineE If an error occurs during the execution of * the instruction. */ public void step () throws MachineE { fetchInstruction(); proc.fetchIR().execute(mem,proc,io); } /** * run executes all instructions from the current one * until it encounters a HALT instruction. * @exception MachineE If an error occurs during the execution of * one of the instructions. */ public void run () throws MachineE { try { while (true) step(); } catch (HaltE e) { return; } } }