Skip to content

Instantly share code, notes, and snippets.

@Yoxem
Created January 31, 2021 10:14
Show Gist options
  • Save Yoxem/7044521b0209da4d3775cd9c3e78f755 to your computer and use it in GitHub Desktop.
Save Yoxem/7044521b0209da4d3775cd9c3e78f755 to your computer and use it in GitHub Desktop.
A draft of a assembly language-like machine emulator written in Python
#!/usr/bin/env/python3
# Authur: Yoxem
# License: Public Domain
code = [["MOV", 12 ,"GEN1"], ["MOV", "GEN1", ["GEN2", 6]], ["ADD", "GEN1", 12], ["ADD", "GEN1", "GEN2"]]
memory = [0] * 20;
registers = {
'GEN1' : 0,
'GEN2' : 0,
'GEN3' : 0,
'GEN4' : 0,
'GEN5' : 0,
'GEN6' : 0,
'GEN7' : 0,
'GEN8' : 0,
'STB' : 10, # STACK BOTTOM
'STT' : 5, # STACK TOP
'FRM' : 0
}
def emulator(code, register, memory):
label = dict()
i = 0
while i < len(code):
this_line = code[i]
if this_line[0] == 'MOV':
if isinstance(this_line[1], list):
address = registers[this_line[1][0]] + this_line[1][1]
registers[this_line[2]] = memory[address]
elif isinstance(this_line[2], list):
address = registers[this_line[2][0]] + this_line[2][1]
memory[address] = registers[this_line[1]]
else:
if isinstance(this_line[1], int):
registers[this_line[2]] = this_line[1]
else:
registers[this_line[2]] = registers[this_line[1]]
elif this_line[0] == 'ADD':
if isinstance(this_line[2], int):
registers[this_line[1]] += this_line[2]
else:
registers[this_line[1]] += registers[this_line[2]]
elif this_line[0] == "LABL" : # label
label[this_line[1]] = i
elif this_line[0] == "JUMP":
i = label[this_line[1]]
elif this_line[0] == "PUSH":
memory[registers["STT"]] = registers[this_line[1]]
register["STT"] -= 1
elif this_line[0] == "POP":
registers[this_line[1]] = memory[registers["STT"]]
register["STT"] += 1
if this_line[0] != "JUMP":
i += 1
emulator(code, registers, memory)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment