CPU/program.py

80 lines
1.8 KiB
Python
Raw Permalink Normal View History

2024-04-29 16:00:03 +08:00
from error import *
class Program:
def __init__(self, code: str):
self.codelist = code.split("\n")
2024-05-02 08:54:42 +08:00
self.res = []
def parser(self):
for i in self.codelist:
print(i)
2024-04-29 16:00:03 +08:00
class BaseArg:
def __init__(self, tp, val):
self.type = tp
self._val = val
def isRegister(self):
return self.type == "reg"
def isMemory(self):
return self.type == "mem"
def isImmediate(self):
return self.type == "int"
class RegisterArg(BaseArg):
def __init__(self, n, cpu):
super().__init__("reg", n)
if n > len(cpu.registers):
raise AddressError("寄存器不存在:" + str(n))
self.cpu = cpu
def set(self, val: int):
self.cpu.registers.write(self._val, val)
def get(self):
return self.cpu.registers[self._val]
class MemoryArg(BaseArg):
def __init__(self, n, cpu):
super().__init__("mem", n)
if n > len(cpu.dtMemory):
raise AddressError("内存地址不存在:" + str(n))
self.cpu = cpu
def set(self, val: int):
self.cpu.dtMemory.write(self._val, val)
def get(self):
return self.cpu.dtMemory[self._val]
class ImmediateArg(BaseArg):
def __init__(self, val):
super().__init__("int", val)
def get(self):
return self._val
class Operand:
def __init__(self, operList, cpu):
self.List = []
for i in operList:
2024-05-02 08:54:42 +08:00
2024-04-29 16:00:03 +08:00
if i[0] == "r":
self.List.append(RegisterArg(int(i[1:]), cpu))
2024-04-29 22:03:14 +08:00
elif i[0:2] == "0x":
2024-04-29 16:00:03 +08:00
index = int(i, 16)
self.List.append(MemoryArg(index, cpu))
elif i.isdigit():
self.List.append(ImmediateArg(int(i)))
2024-05-02 08:54:42 +08:00
2024-04-29 16:00:03 +08:00
def __getitem__(self, key: int):
return self.List[key]