From 9d888723b763ae9a28f887dbe3f53c7b948eea04 Mon Sep 17 00:00:00 2001 From: Giulio De Pasquale Date: Tue, 16 May 2017 17:39:49 +0200 Subject: [PATCH] Assembler OO --- python/assembler.py | 354 ++++++++++++++++++++++---------------------- 1 file changed, 175 insertions(+), 179 deletions(-) diff --git a/python/assembler.py b/python/assembler.py index f09ff47..659a0bc 100644 --- a/python/assembler.py +++ b/python/assembler.py @@ -1,6 +1,160 @@ import sys import re import struct +import IPython + + +class VMAssembler: + assembled_code = bytearray() + + def parse(self, instruction): + action = getattr(self, "{}".format(instruction.opcode.name)) + action(instruction) + + def process_code_line(self, line): + sys.stdout.write("CODE: ") + components = [x for x in re.split('\W', line) if x] + + instruction = VMInstruction(components[0], components[1:]) + self.parse(instruction) + + def imm2reg(self, instruction): + """ + Intel syntax -> REG, IMM + """ + opcode = instruction.opcode + reg = instruction.args[0] + imm = instruction.args[1] + print(instruction) + if reg.name != "ip": + if opcode.uint8() and reg.uint8() and imm.uint16(): + self.assembled_code += opcode.uint8() + reg.uint8() + imm.uint16() + else: + sys.stderr.write( + "ERROR WHILE ASSEMBLING UNKNOWN VALUES\n") + return False + else: + sys.stderr.write("CAN'T MOVI TO IP!\n") + return False + return True + + def reg2reg(self, instruction): + return + + def reg2imm(self, instruction): + """ + Intel syntax -> IMM, REG + """ + opcode = instruction.opcode + imm = instruction.args[0] + reg = instruction.args[1] + print(instruction) + if reg.name != "ip": + if opcode.uint8() and reg.uint8() and imm.uint16(): + self.assembled_code += opcode.uint8() + imm.uint16() + reg.uint8() + else: + sys.stderr.write( + "ERROR WHILE ASSEMBLING UNKNOWN VALUES\n") + return False + else: + sys.stderr.write("CAN'T MOVI TO IP!\n") + return False + return True + + def imm(self, instruction): + return + + def movi(self, instruction): + if not self.imm2reg(instruction): + print("WAT") + return False + return True + + def movr(self, instruction): + if not self.reg2reg(instruction): + print("WAT") + return False + return True + + def getm(self, instruction): + if not self.imm2reg(instruction): + print("WAT") + return False + return True + + def putm(self, instruction): + if not self.reg2imm(instruction): + print("WAT") + return False + return True + + def addi(self, instruction): + if not self.imm2reg(instruction): + print("WAT") + return False + return True + + +class VMComponent: + """ + Represents a register or a operation the VM recognizes + """ + name = "" + value = "" + + def __init__(self, name, value): + self.name = name + self.value = value + + def __repr__(self): + return "{}".format(self.name) + + def uint8(self): + numre = re.compile("^[0-9]+$") + if isinstance(self.value, int): + return struct.pack("