这是我的指令集模拟器Python脚本:
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;
文件ass-2.asm
包含要运行的汇编语言指令:
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
我期望的输出是:
100
500
我收到的输出和错误是:
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'
问题似乎出现在runm
函数中。
我认为在调用函数之前应该将2个数字加载到寄存器中,并且应该在函数调用之后添加它们!打印的内存值应为500,但我不知道如何获得它。
答案 0 :(得分:4)
您的虚拟机错过了处理ret
命令的函数。这样的事情应该有效:
def ret(opr):
reg['pc'] = memory[reg['sp']]
reg['sp'] = reg['sp'] - 1