Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /****************************************************
- VIRTUAL MACHINE
- VERSION 1.0
- Kevin Taylor
- *****************************************************/
- public class VirtualMachine{
- private int pc = 0;
- private int[] memory = {8,5,
- 8,2,
- 11,
- 10, 16,
- 9, 16,
- 21,
- 0,
- 0,0,0,0,0,0,0,0,0,0,0,0};
- private IntStack stack = new IntStack(20);
- private int d, x, y, ir;
- public VirtualMachine(int pc, int[] memory, IntStack stack){
- this.pc = pc;
- this.memory = memory;
- this.stack = stack;
- this.x = x;
- this.y = y;
- this.ir = ir;
- this.d = d;
- //Switch Statement for handling op code instructions in the VM
- do{
- ir = memory[pc];
- pc++;
- switch(ir){
- case 8: // Load Constant
- stack.push( memory[pc] );
- pc++;
- break;
- case 9: //Load Variable from addess
- d = memory[pc];
- stack.push(d);
- pc++;
- break;
- case 10: //store variable in address
- d = stack.pop();
- memory[memory[pc]] = d;
- pc++;
- break;
- case 11: // add two operands and push the result
- y = stack.pop();
- x = stack.pop();
- d = x + y;
- stack.push(d);
- pc++;
- break;
- case 12: //subtract top two operands and push the result
- y = stack.pop();
- x = stack.pop();
- d = x - y;
- stack.push(d);
- pc++;
- break;
- case 13: //multiply top two operands and push the result
- y = stack.pop();
- x = stack.pop();
- d = x * y;
- stack.push(d);
- pc++;
- break;
- case 14: //Divide top two operands and push the result
- y = stack.pop();
- x = stack.pop();
- d = x / y;
- stack.push(d);
- pc++;
- break;
- case 15: // Check if equal
- y = stack.pop();
- x = stack.pop();
- if( x==y)
- stack.push(1);
- else
- stack.push(0);
- break;
- case 16: //Check if less
- y = stack.pop();
- x = stack.pop();
- if(x<y)
- stack.push(1);
- else
- stack.push(0);
- break;
- case 17: //Check if greater
- y = stack.pop();
- x = stack.pop();
- if(x>y)
- stack.push(1);
- else
- stack.push(0);
- break;
- case 18: //jump to address pc
- pc = memory[pc];
- break;
- case 19: //jump if false
- if(stack.pop() == 0)
- pc = memory[pc];
- break;
- case 20: //read an int
- d = memory[pc];
- stack.push(d);
- pc++;
- break;
- case 21: //write an int
- System.out.println(stack.pop());
- pc++;
- break;
- case 22: //call subprogram
- stack.push(pc + 1);
- pc = memory[pc];
- break;
- case 23: //return from subprogram
- pc = stack.pop();
- break;
- case 0: //halt program
- System.exit(0);
- break;
- } //end do
- }//end Switch
- while(true);
- }// end vm constructer
- public static void main(String[] args){
- int pc = 0;
- IntStack stack = new IntStack(20);
- int[] memory = {8,5,
- 8,2,
- 11,
- 10, 16,
- 9, 16,
- 21,
- 0,
- 0,0,0,0,0,0,0,0,0,0,0,0};
- VirtualMachine vm = new VirtualMachine(pc, memory, stack );
- }// end main
- }//end Class
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement