CPU/program.py
2024-04-29 22:03:14 +08:00

75 lines
1.7 KiB
Python

from error import *
class Program:
def __init__(self, code: str):
self.codelist = code.split("\n")
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:
if i[0] == "r":
self.List.append(RegisterArg(int(i[1:]), cpu))
elif i[0:2] == "0x":
index = int(i, 16)
self.List.append(MemoryArg(index, cpu))
elif i.isdigit():
self.List.append(ImmediateArg(int(i)))
def __getitem__(self, key: int):
return self.List[key]