# 汇编程序编译器 将汇编指令编译为我的CPU里指令# 指令存储格式 8位指令 后跟操作数import osimport refrom cpu import asm as ASMfrom cpu import pin# 指定当前目录,并设置程序编译为program.binmy_dir = os.path.dirname(__file__)dst_name = os.path.join(my_dir, 'program.bin')src_name = os.path.join(my_dir, 'program.asm')# 汇编代码的正则表达式annotation = re.compile(r"(.*?);.*")# 代码集合codes = []# 标记字典marks = {}# 支持的指令OP2 = {'MOV': ASM.MOV,'ADD': ASM.ADD,'SUB': ASM.SUB,'CMP': ASM.CMP,'AND': ASM.AND,'OR': ASM.OR,'XOR': ASM.XOR}OP1 = {'INC': ASM.INC,'DEC': ASM.DEC,'NOT': ASM.NOT,'JMP': ASM.JMP,'JO': ASM.JO,'JNO': ASM.JNO,'JZ': ASM.JZ,'JNZ': ASM.JNZ,'JP': ASM.JP,'JNP': ASM.JNP,'PUSH': ASM.PUSH,'POP': ASM.POP,'CALL': ASM.CALL,'INT': ASM.INT,}OP0 = {'NOP': ASM.NOP,'RET': ASM.RET,'IRET': ASM.IRET,'STI': ASM.STI,'CLI': ASM.CLI,'HLT': ASM.HLT,}OP2SET = set(OP2.values())OP1SET = set(OP1.values())OP0SET = set(OP0.values())# 可使用的寄存器字典REGISTERS = {"A": pin.A,"B": pin.B,"C": pin.C,"D": pin.D,"SS": pin.SS,"SP": pin.SP,}# 代码类class Code:# 代码类型TYPE_CODE = 1TYPE_LABEL = 2def __init__(self, number, source):self.number = numberself.source = source.upper()self.op = Noneself.dst = Noneself.src = Noneself.type = self.TYPE_CODE # 默认是代码self.name = Noneself.index = 0# 代码预处理self.prepare_source()def prepare_source(self):# 以冒号结尾,为标记if self.source.endswith(':'):self.type = self.TYPE_LABELself.name = self.source.strip(':')returnarr = self.source.split(',')if len(arr) > 2:raise SyntaxError(self)if len(arr) == 2:# 取到源操作数self.src = arr[1].strip()arr = re.split(r" +", arr[0])if len(arr) > 2:raise SyntaxError(self)if len(arr) == 2:# 取到目的操作数self.dst = arr[1].strip()# 取到指令助记符self.op = arr[0].strip()pass# 通过MOV字符指令转换为二进制数据def get_op(self):if self.op in OP2:return OP2[self.op]if self.op in OP1:return OP1[self.op]if self.op in OP0:return OP0[self.op]print(f"不支持的OP {self.op} ")raise CodeSyntaxError(self)# 通过地址获取def get_am(self, addr):global marksif addr in marks:return pin.AM_INS, marks[addr].index * 3if not addr:return None, None# MOV A, B 寄存器寻址if addr in REGISTERS:return pin.AM_REG, REGISTERS[addr]# MOV A, 5 立即寻址if re.match(r'^[0-9]+$', addr):return pin.AM_INS, int(addr)# MOV A, 0X5f 立即寻址,16进制if re.match(r'^0X[0-9A-F]+$', addr):return pin.AM_INS, int(addr, 16)# MOV A, [5]match = re.match(r'^\[([0-9]+)\]$', addr)if match:return pin.AM_DIR, int(match.group(1))# MOV A,[0x13]match = re.match(r'^\[(0X[0-9A-F]+)\]$', addr)if match:return pin.AM_DIR, int(match.group(1), 16)# MOV [0x5],Amatch = re.match(r'^\[(.+)\]$', addr)if match and match.group(1) in REGISTERS:return pin.AM_RAM, REGISTERS[match.group(1)]print(f"不支持的指令 {self.source}")raise CodeSyntaxError(self)def __repr__(self):return f'[{self.number}] - {self.source}'def compile_code(self):op = self.get_op()amd, dst = self.get_am(self.dst)ams, src = self.get_am(self.src)# print(f'src={src} and dst={dst}')if src is not None and dst is not None and (amd, ams) not in ASM.INS_SUPPORT_LIST[2][op]:raise CodeSyntaxError(self)if src is None and dst is not None and amd not in ASM.INS_SUPPORT_LIST[1][op]:raise CodeSyntaxError(self)if src is None and dst is None and op not in ASM.INS_SUPPORT_LIST[0]:raise CodeSyntaxError(self)amd = amd or 0ams = ams or 0dst = dst or 0src = src or 0# 组装ir# ir=2地址指令时 4位指令 | 2位目标数 | 2位源操作数# ir=1地址指令时 6位指令 | 2位目标数# ir=0地址指令时 8位指令if op in OP2SET:ir = op | amd << 2 | amsif op in OP1SET:ir = op | amdif op in OP0SET:ir = op# 返回指令, 目标操作数, 源操作数return [ir, dst, src]# 语法错误class CodeSyntaxError(Exception):def __init__(self, code: Code, *args, **kwargs):super().__init__(*args, **kwargs)self.code = codedef compile_program():global codesglobal marks# 读取源代码with open(src_name, encoding="utf-8") as file:lines = file.readlines()# 逐行处理for number,line in enumerate(lines):# 去掉空格source = line.strip()# 处理注释if ";" in source:match = annotation.match(source)source = match.group(1)if not source:continue# 加入代码集合codes.append(Code(number+1, source))# 最后加入一行停止程序的指令codes.append(Code(number+2,"HLT"))# 倒叙处理标记result = []current = Nonefor var in range(len(codes) - 1, -1, -1):code = codes[var]# 倒叙处理标记,如果是标记则加入到marks字典,是代码则加入代码集合if code.type == Code.TYPE_CODE:current = coderesult.insert(0, code)continueif code.type == Code.TYPE_LABEL:marks[code.name] = currentcontinueraise SyntaxError(code)# 设置代码当前指令行序号for index, var in enumerate(result):var.index = index# 将代码编译后生成program.bin二进制代码with open(dst_name, 'wb') as file:for code in result:values = code.compile_code()print(f'{code} , {values}')for value in values:result = value.to_bytes(1, byteorder='little')file.write(result)passdef main():compile_program()# try:# compile_program()# except CodeSyntaxError as e:# print(e)# except Exception as e:# print(e)print("程序编译成功")passif __name__ == '__main__':main()
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。