這是我的指令集仿真器的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,但我不知道如何得到它。
你在哪裏處理'ret'? –