Kasun Sampath Kasun Sampath - 2 months ago 21
Python Question

Instruction set simulator written in Python fails

This is my instruction set simulator Python script:

MEM_SIZE=100;

reg={'a':0, 'b':0, 'c':0, 'd':0, 'e':0,'f':0,'sp':0,'acc':0, 'pc':0, 'ivec':0, 'int':0, 'timer':0, 'halt':False};

memory=[0]*MEM_SIZE;

def mov(opr):
reg[opr[0]]=reg[opr[1]];
reg['pc']=reg['pc']+1;

def movv(opr):
reg[opr[0]]=int(opr[1]);
reg['pc']=reg['pc']+1;

def load(opr):
reg[opr[0]]=memory[int(opr[1])];
reg['pc']=reg['pc']+1;

def loadr(opr):
reg[opr[0]]=memory[reg[opr[1]]];
reg['pc']=reg['pc']+1;


def add(opr):
reg['acc']=reg[opr[0]]+reg[opr[1]];
reg['pc']=reg['pc']+1;

def sub(opr):
reg['acc']=reg[opr[0]]-reg[opr[1]];
reg['pc']=reg['pc']+1;


def call(opr):
reg['sp']=reg['sp']+1;
memory[reg['sp']]=reg['pc']+1;
reg['pc']=int(opr[0]);


def out(opr):
print reg[opr[0]];
reg['pc']=reg['pc']+1;

def push(opr):
reg['sp']=reg['sp']+1;
memory[reg['sp']]=reg[opr[0]];
reg['pc']=reg['pc']+1;

def pop(opr):
reg[opr[0]]=memory[reg['sp']];
reg['sp']=reg['sp']-1;
reg['pc']=reg['pc']+1;


def halt(opr):
reg['halt']=True;
reg['pc']=reg['pc']+1;


f=open('ass-2.asm','r');

def runm():
while reg['halt']==False:
i=reg['pc'];
op=globals()[memory[i][0]];
#print i,memory[i][0:] ;
op(memory[i][1:]);
pass;

reg['timer']=reg['timer']-1;
if reg['int']==1 and reg['timer']==0:
reg['sp']=reg['sp']+1;
memory[reg['sp']]=reg['pc'];
reg['pc']=reg['ivec'];
reg['int']=0;



for l in f:
if l.startswith("#"):
continue;

comm= l.split();
if comm:
memory[int(comm[0])] = comm[1:];

runm();

print reg;
print memory;


The file
ass-2.asm
contains the assembly language instructions to run:

0 movv sp 80
1 movv a 100
2 movv b 400
3 call 20
4 add a b
5 out acc
6 halt

20 push a
21 push b
22 push acc
23 movv a 20
24 movv b 80
25 add a b
26 out acc
27 pop acc
28 pop b
29 pop a
30 ret


The output and error I receive is:

100
Traceback (most recent call last):
File "sim.py", line 86, in <module>
runm();
File "sim.py", line 64, in runm
op=globals()[memory[i][0]];
KeyError: 'ret'


The problem appears to be in the
runm
function.

I think 2 numbers should be loaded to a register before the function is called and they should be added after the function call! The value of the memory printed should be 500 but I don't know how to get it.

Answer

Your virtual machine misses a function that handles the ret command. Something like this should work:

def ret(opr):
    reg['pc'] = memory[reg['sp']]
    reg['sp'] = reg['sp'] - 1
Comments