Polishing. Uso di next()

This commit is contained in:
Giulio De Pasquale 2017-05-18 13:20:17 +02:00
parent 702bb1ad9b
commit 8eab267645

View File

@ -65,8 +65,8 @@ class VMAssembler:
def process_code_line(self, line): def process_code_line(self, line):
sys.stdout.write("CODE: ") sys.stdout.write("CODE: ")
components = [x for x in re.split('\W', line) if x] components = [x for x in re.split('\W', line) if x]
instruction = VMInstruction(components[0], components[1:]) instruction = VMInstruction(components[0], components[1:])
sys.stdout.write(str(instruction) + "\n")
self.parse(instruction) self.parse(instruction)
def imm2reg(self, instruction): def imm2reg(self, instruction):
@ -225,16 +225,14 @@ class VMInstruction:
""" """
def __init__(self, opcode, instr_list): def __init__(self, opcode, instr_list):
# TODO EXCEPTION SE REGISTRO / IMM / OPCODE NON VALIDO
immediate_regexp = re.compile("^(0x*|[0-9]*$)") immediate_regexp = re.compile("^(0x*|[0-9]*$)")
opc_name, opc_value = value_from_list(ops, opcode) self.opcode = next((x for x in ops if x.name == opcode), None)
self.opcode = VMComponent(opc_name, opc_value)
self.args = [] self.args = []
for el in instr_list: for el in instr_list:
if not immediate_regexp.match(el): if not immediate_regexp.match(el):
# create a VM component for a register # create a VM component for a register
reg_name, reg_value = value_from_list(regs, el) reg_comp = next((x for x in regs if x.name == el), None)
self.args.append(VMComponent(reg_name, reg_value)) self.args.append(reg_comp)
else: else:
# directly append the immediate # directly append the immediate
self.args.append(VMComponent(el, el)) self.args.append(VMComponent(el, el))
@ -250,7 +248,8 @@ op_names = ["MOVI",
"ADDR", "ADDR",
"SUBI", "SUBI",
"SUBR", "SUBR",
"XORI", "XORB",
"XORW",
"XORR", "XORR",
"NOTR", "NOTR",
"MULI", "MULI",
@ -276,29 +275,6 @@ ops = [VMComponent(s.casefold(), i) for i, s in enumerate(op_names)]
regs = [VMComponent(s.casefold(), i) for i, s in enumerate(reg_names)] regs = [VMComponent(s.casefold(), i) for i, s in enumerate(reg_names)]
def value_from_list(fromlist, name):
"""
returns a tuple (name, value) from a list of VMComponents
"""
for el in fromlist:
if el.name == name:
return (el.name, el.value)
if fromlist == ops:
raise InvalidOperation(name)
elif fromlist == regs:
raise InvalidRegister(name)
def name_from_list(fromlist, value):
"""
returns a tuple (name, value) from a list of VMComponents
"""
for el in fromlist:
if el.value == value:
return (el.name, el.value)
return None
def assemble_data(line): def assemble_data(line):
sys.stdout.write("DATA:\t") sys.stdout.write("DATA:\t")
sys.stdout.write(line.strip(",") + "\n") sys.stdout.write(line.strip(",") + "\n")