read write register

This commit is contained in:
Sam Hadow 2024-03-24 22:21:49 +01:00
parent ae5b003eb3
commit e3a803469c
2 changed files with 50 additions and 0 deletions

1
src/main.py Normal file
View File

@ -0,0 +1 @@

49
src/ram.py Normal file
View File

@ -0,0 +1,49 @@
class Ram(object):
def __init__(self, instr, input_registers):
self.instr = instr # list of instructions
self.current = 0 # current instruction
self.input_registers = input_registers # I registers
self.output_registers = [] # O registers
self.work_registers = [] # R registers
def read_register(self, type, index, ref_origin=None, ref_target=None):
'''
Read from a register
'''
if type == "input":
return self.input_registers[index]
elif type == "work":
value = self.work_registers[index]
if value is None:
raise ValueError("register empty")
else:
return self.work_registers[index]
elif type == "output":
raise TypeError("output registers are write only")
elif type == "value":
return index
elif type == "reference":
target_index = self.read_register(ref_origin, index)
return self.read_register(ref_target, target_index)
def write_register(self, type, index, value, ref_origin=None, ref_target=None):
'''
Write to a register
'''
if type == "input":
raise TypeError("output registers are read only")
elif type == "work":
if len(self.work_registers) <= index:
self.work_registers.extend([None] * (index + 1 - len(self.work_registers))) # extend with uninitialized values
self.work_registers[index] = value
elif type == "output":
if len(self.output_registers) <= index:
self.output_registers.extend([None] * (index + 1 - len(self.output_registers))) # extend with uninitialized values
self.output_registers[index] = value
elif type == "reference":
target_index = self.read_register(ref_origin, index)
self.write_register(ref_target, target_index, value)
# def op(self, type_r1, index_r1, type_r2, index_r2, type_r3, index_r3)