1001-asm-imitator.py
# -*- coding: utf-8 -*- import re def remove_all(val, lst): # dirty, simple and stupid for x in lst: if x == val: lst.remove(x) return lst instructions = remove_all('', re.split('[\r|\n]', ''' store a 1 store b 2 add a 1 add b -1 jlz 2 jmp -3 jmp 0 '''.lower())) reg_file = {} # register file: 装register的柜子。register: 登记簿 pc = 0 # pc: program counter msb = 0 # most significat bit, 符号位 while True: i = instructions[pc] # fetch instruction 取指 print('"' + i + '"', end='\t') pieces = remove_all('', i.split()) # 译码 op_code = pieces[0] # op: operation if op_code == 'store': (reg_name, immd) = pieces[1:] reg_file[reg_name] = int(immd) pc += 1 elif op_code == 'add': (reg_name, immd) = pieces[1:] reg_file[reg_name] += int(immd) if reg_file[reg_name] < 0: msb = 1 pc += 1 elif op_code == 'jlz': # jump if less than 0 immd = int(pieces[1]) if msb: pc += immd else: pc += 1 elif op_code == 'jmp': immd = int(pieces[1]) if immd == 0: break pc += immd print('\t', reg_file, ' pc=', pc, ' msb=', msb, sep='') input('Press the Enter key')
store b, 2也行——寄存器的名字叫B-逗号。注意b和b,是两个不同的寄存器。b和,之间不能有空格。
硬件实现呗: