开源 企业版 高校版 私有云 模力方舟 AI 队友
代码拉取完成,页面将自动刷新
捐赠
捐赠前请先登录
扫描微信二维码支付
取消
支付完成
支付提示
将跳转至支付宝完成支付
确定
取消
2 Star 0 Fork 1

mgang/python-study

加入 Gitee
与超过 1400万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
已有帐号? 立即登录
文件
master
分支 (1)
master
master
分支 (1)
master
克隆/下载
克隆/下载
提示
下载代码请复制以下命令到终端执行
为确保你提交的代码身份被 Gitee 正确识别,请执行以下命令完成配置
初次使用 SSH 协议进行代码克隆、推送等操作时,需按下述提示完成 SSH 配置
1 生成 RSA 密钥
2 获取 RSA 公钥内容,并配置到 SSH公钥
在 Gitee 上使用 SVN,请访问 使用指南
使用 HTTPS 协议时,命令行会出现如下账号密码验证步骤。基于安全考虑,Gitee 建议 配置并使用私人令牌 替代登录密码进行克隆、推送等操作
Username for 'https://gitee.com': userName
Password for 'https://userName@gitee.com': # 私人令牌
master
分支 (1)
master
python-study
/
cpu
/
compiler.py
python-study
/
cpu
/
compiler.py
compiler.py 6.85 KB
一键复制 编辑 原始数据 按行查看 历史
mgang 提交于 2022年10月23日 16:12 +08:00 . cpu 完成内中断指令
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256
# 汇编程序编译器 将汇编指令编译为我的CPU里指令
# 指令存储格式 8位指令 后跟操作数
import os
import re
from cpu import asm as ASM
from cpu import pin
# 指定当前目录,并设置程序编译为program.bin
my_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 = 1
TYPE_LABEL = 2
def __init__(self, number, source):
self.number = number
self.source = source.upper()
self.op = None
self.dst = None
self.src = None
self.type = self.TYPE_CODE # 默认是代码
self.name = None
self.index = 0
# 代码预处理
self.prepare_source()
def prepare_source(self):
# 以冒号结尾,为标记
if self.source.endswith(':'):
self.type = self.TYPE_LABEL
self.name = self.source.strip(':')
return
arr = 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 marks
if addr in marks:
return pin.AM_INS, marks[addr].index * 3
if 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],A
match = 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 0
ams = ams or 0
dst = dst or 0
src = src or 0
# 组装ir
# ir=2地址指令时 4位指令 | 2位目标数 | 2位源操作数
# ir=1地址指令时 6位指令 | 2位目标数
# ir=0地址指令时 8位指令
if op in OP2SET:
ir = op | amd << 2 | ams
if op in OP1SET:
ir = op | amd
if 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 = code
def compile_program():
global codes
global 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 = None
for var in range(len(codes) - 1, -1, -1):
code = codes[var]
# 倒叙处理标记,如果是标记则加入到marks字典,是代码则加入代码集合
if code.type == Code.TYPE_CODE:
current = code
result.insert(0, code)
continue
if code.type == Code.TYPE_LABEL:
marks[code.name] = current
continue
raise 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)
pass
def main():
compile_program()
# try:
# compile_program()
# except CodeSyntaxError as e:
# print(e)
# except Exception as e:
# print(e)
print("程序编译成功")
pass
if __name__ == '__main__':
main()
Loading...
举报
举报成功
我们将于2个工作日内通过站内信反馈结果给你!
请认真填写举报原因,尽可能描述详细。
请选择举报类型
取消
发送
误判申诉

此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。

如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。

取消
提交

简介

和妙一起学python
暂无标签
Apache-2.0
使用 Apache-2.0 开源许可协议
取消

发行版

暂无发行版

贡献者

全部

近期动态

不能加载更多了
编辑仓库简介
简介内容
主页
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Python
1
https://gitee.com/mgang/python-study.git
git@gitee.com:mgang/python-study.git
mgang
python-study
python-study
master
点此查找更多帮助

搜索帮助

评论
仓库举报
回到顶部
登录提示
该操作需登录 Gitee 帐号,请先登录后再操作。
立即登录
没有帐号,去注册

AltStyle によって変換されたページ (->オリジナル) /