def read_data(fname):
with open(fname) as f:
data = f.read().splitlines()
return data
def remove_comments(data):
result = []
for line in data:
if line.strip() != "":
if line[0] != "#":
result.append(line.upper())
return result
def create_registers(data):
registers = {}
for line in data:
xs = line.split()
if len(xs) > 1 and xs[1] == "=": # lazy evaluation b1 and b2
registers[xs[0]] = int(xs[2])
elif len(xs) == 2:
if xs[1][0] == "R":
if xs[1] not in registers:
registers[xs[1]] = 0
elif len(xs) == 3:
pass
elif len(xs) == 4:
pass
else:
pass
return registers
def create_labels(data):
labels = {}
ino = 0
for line in data:
xs = line.split()
if xs[0][-1] == ":":
labels[xs[0]] = ino
if len(xs) == 1 or (len(xs) > 1 and xs[1] != "="):
ino = ino + 1
return labels
def create_labels_from_code(code):
pass# simple for-loop accumulator code on code
def create_code(data):
code = []
for line in data:
xs = line.split()
....
if "INC" in xs:
if len(xs) == 1 or len(xs) > 3:
print("INVALID INSTRUCTION")
return []
elif len(xs) == 2:
code.append({'opcode':"INC","register1":xs[1]})
else:
code.append({'labeldef':xs[0][:-1].upper(),'opcode':"INC","register1":xs[2].upper()})
elif "DEC" in xs:
pass
elif "CLR" in xs:
pass
elif "MOV" in xs:
pass
elif "JMP" in xs:
pass
elif "CONTINUE" in xs:
pass
else:
pass
....
...
return code
def run_ram_program(registers,code,labels):
pc = 0
while True:
if opcode ==
elif
elif
...
else:
fname = "p2.ram"
data = read_data(fname)
data = remove_comments(data)
#print(data)
registers = create_registers(data)
code = create_code(data)
#labels = create_labels(data)
labels = create_labels_from_code(code)
print(registers)
print(labels)
#print(registers,code,labels)
if code == []:
print("I cannot run your program")
else:
...
print input
run_ram_program(registers,code,labels)
print output
{'R1': 200, 'R2': 50, 'R22': 0} {'N1:': 1, 'N2:': 3, 'N3:': 9, 'N4:': 11}
xs = ["MOV","R3","R2"]