Analisis-Lenguaje_Robot / codigo_intermedio
Ethgoin's picture
Create codigo_intermedio
5c54be1 verified
raw
history blame
2.33 kB
class GeneradorIntermedio:
def __init__(self):
self.codigo = []
self.temp_id = 1
def nuevo_temp(self):
temp = f"t{self.temp_id}"
self.temp_id += 1
return temp
def generar(self, ast):
for instruccion in ast:
self.generar_instruccion(instruccion)
return self.codigo
def generar_instruccion(self, nodo):
tipo = nodo["type"]
if tipo == "assign":
temp = self.generar_expresion(nodo["value"])
self.codigo.append(f"{nodo['var']} = {temp}")
elif tipo == "function":
arg = self.generar_expresion(nodo["arg"]) if nodo["arg"] else None
if arg:
self.codigo.append(f"PARAM {arg}")
self.codigo.append(f"CALL {nodo['name']}")
elif tipo == "if":
cond = self.generar_expresion(nodo["condition"])
etiqueta = self.nueva_etiqueta()
self.codigo.append(f"IF NOT {cond} GOTO {etiqueta}")
for instr in nodo["body"]:
self.generar_instruccion(instr)
self.codigo.append(f"{etiqueta}:")
elif tipo == "while":
inicio = self.nueva_etiqueta()
fin = self.nueva_etiqueta()
self.codigo.append(f"{inicio}:")
cond = self.generar_expresion(nodo["condition"])
self.codigo.append(f"IF NOT {cond} GOTO {fin}")
for instr in nodo["body"]:
self.generar_instruccion(instr)
self.codigo.append(f"GOTO {inicio}")
self.codigo.append(f"{fin}:")
def generar_expresion(self, expr):
tipo = expr["type"]
if tipo in ("num", "var", "bool", "string"):
return expr["value"]
elif tipo == "binop":
izq = self.generar_expresion(expr["left"])
der = self.generar_expresion(expr["right"])
temp = self.nuevo_temp()
self.codigo.append(f"{temp} = {izq} {expr['op']} {der}")
return temp
elif tipo == "call":
return self.generar_expresion(expr["arg"])
else:
temp = self.nuevo_temp()
self.codigo.append(f"{temp} = ???")
return temp
def nueva_etiqueta(self):
etiq = f"L{self.temp_id}"
self.temp_id += 1
return etiq