This commit is contained in:
Sam Hadow 2024-04-05 09:37:11 +02:00
parent 5f5ce35a08
commit 9260d34ae4

View File

@ -9,7 +9,7 @@ class Ram(object):
def read_register(self, type_register, index, ref_origin=None, ref_target=None):
'''
Read from a register
Read from a register, return the value
'''
if type_register == "i": # input
return self.input_registers[index]
@ -48,6 +48,10 @@ class Ram(object):
self.write_register(value, ref_target, target_index)
def op(self, type_op, r1, r2, r3):
'''
Arithmetic operation (addition, subtraction, division, multiplication)
r3 = r1 op r2
'''
self.current += 1
if type_op == 'ADD':
value_1 = self.read_register(*r1)
@ -71,6 +75,9 @@ class Ram(object):
self.write_register(value_3, *r3)
def op_ctrl(self, type_op, z, r1=None, r2=None):
'''
Control operation (Jump, Jump if equal, Jump if less)
'''
if type_op == 'JUMP':
if isinstance(z, int):
self.current += z
@ -92,12 +99,19 @@ class Ram(object):
self.current += 1
def execute(self):
'''
Run machine to completion
'''
while self.current < len(self.instr):
print(self.current)
print(*self.instr[self.current]['args'])
self.instr[self.current]['op'](self, *self.instr[self.current]['args'])
def generate_graph(self):
'''
Return precedance graph edges between instructions
(instr1, instr2) exists if instr2 is reachable from instr1 in 1 step
'''
graph_edges = []
n_instr = len(self.instr)
for (n,instr) in enumerate(self.instr):
@ -114,6 +128,9 @@ class Ram(object):
return graph_edges
def accessible_instr(self):
'''
Return a list of accessible instructions in a machine
'''
graph_edges = self.generate_graph()
accessible_from_instr = dict()
for edge in graph_edges:
@ -133,32 +150,12 @@ class Ram(object):
return sorted(accessible)
def remove_unreachable_instr(self):
'''
Remove dead code in a machine (unreachable instructions)
Print all the instructions still in the machine after
'''
accessible = self.accessible_instr()
new_instr = [instr for (i,instr) in enumerate(self.instr) if i in accessible]
for instr in new_instr:
print(instr)
self.instr = new_instr
### example
# input_registers = [10, 5, 1]
#
# instructions = [
# {'op': Ram.op, 'args': ('ADD', ('i', 0), ('value', 1), ('o', 2))},
# {'op': Ram.op, 'args': ('ADD', ('value', 0), ('@', 2, 'i', 'i'), ('o', 1))},
# ]
# input_registers = [10, 5, 1, 2, 4]
# instructions = [ {"op": Ram.op, "args": ('ADD', ('i', 0), ('value', 1), ('r', 0))},
# {"op": Ram.op, "args": ('SUB', ('i', 1), ('value', 3), ('r', 1))},
# {"op": Ram.op, "args": ('MULT', ('r', 1), ('r', 0), ('o', 1))},
# ]
# ram = Ram(instructions, input_registers)
# ram.execute()
# print("Result:", ram.output_registers)