/* A unified-stack abstract machine for imperative programs sestoft@dina.kvl.dk * 2001-03-21, 2003-03-05 To execute a program file using this abstract machine, do: java Machine ... or java Machinetrace ... */ import java.io.*; import java.util.*; class Machine { public static void main(String[] args) throws FileNotFoundException, IOException { if (args.length == 0) System.out.println("Usage: java Machine ...\n"); else execute(args, false); } // These numeric instruction codes must agree with Machine.sml: final static int CST = 0, ADD = 1, SUB = 2, MUL = 3, DIV = 4, MOD = 5, EQ = 6, LT = 7, NOT = 8, DUP = 9, SWAP = 10, LDI = 11, STI = 12, GETBP = 13, GETSP = 14, INCSP = 15, GOTO = 16, IFZERO = 17, IFNZRO = 18, CALL = 19, TCALL = 20, RET = 21, PRINTI = 22, PRINTC = 23, LDARGS = 24, STOP = 25; // Read code from file and execute it final static int STACKSIZE = 1000; static void execute(String[] args, boolean trace) throws FileNotFoundException, IOException { int[] p = readfile(args[0]); // Read the program from file int[] s = new int[STACKSIZE]; // The evaluation stack int[] iargs = new int[args.length-1]; for (int i=1; i=0; i--) // Discard variables s[sp-i-pop] = s[sp-i]; sp = sp - pop; pc = p[pc]; } break; case RET: { int res = s[sp]; sp = sp-p[pc]; bp = s[--sp]; pc = s[--sp]; s[sp] = res; } break; case PRINTI: System.out.print(s[sp] + " "); break; case PRINTC: System.out.print((char)(s[sp])); break; case LDARGS: for (int i=0; i"; } } // Print current stack and current instruction static void printsppc(int[] s, int bp, int sp, int[] p, int pc) { System.out.print("[ "); for (int i=0; i<=sp; i++) System.out.print(s[i] + " "); System.out.print("]"); System.out.println("{" + pc + ": " + insname(p, pc) + "}"); } // Read instructions from a file public static int[] readfile(String filename) throws FileNotFoundException, IOException { ArrayList /* of String */ rawprogram = new ArrayList(); Reader inp = new FileReader(filename); StreamTokenizer tstream = new StreamTokenizer(inp); tstream.parseNumbers(); tstream.nextToken(); while (tstream.ttype == StreamTokenizer.TT_NUMBER) { rawprogram.add(new Integer((int)tstream.nval)); tstream.nextToken(); } inp.close(); final int programsize = rawprogram.size(); int[] program = new int[programsize]; for (int i=0; i ...\n"); else Machine.execute(args, true); } }