Ethgoin commited on
Commit
5c54be1
·
verified ·
1 Parent(s): ace0b6b

Create codigo_intermedio

Browse files
Files changed (1) hide show
  1. codigo_intermedio +64 -0
codigo_intermedio ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ class GeneradorIntermedio:
2
+ def __init__(self):
3
+ self.codigo = []
4
+ self.temp_id = 1
5
+
6
+ def nuevo_temp(self):
7
+ temp = f"t{self.temp_id}"
8
+ self.temp_id += 1
9
+ return temp
10
+
11
+ def generar(self, ast):
12
+ for instruccion in ast:
13
+ self.generar_instruccion(instruccion)
14
+ return self.codigo
15
+
16
+ def generar_instruccion(self, nodo):
17
+ tipo = nodo["type"]
18
+ if tipo == "assign":
19
+ temp = self.generar_expresion(nodo["value"])
20
+ self.codigo.append(f"{nodo['var']} = {temp}")
21
+ elif tipo == "function":
22
+ arg = self.generar_expresion(nodo["arg"]) if nodo["arg"] else None
23
+ if arg:
24
+ self.codigo.append(f"PARAM {arg}")
25
+ self.codigo.append(f"CALL {nodo['name']}")
26
+ elif tipo == "if":
27
+ cond = self.generar_expresion(nodo["condition"])
28
+ etiqueta = self.nueva_etiqueta()
29
+ self.codigo.append(f"IF NOT {cond} GOTO {etiqueta}")
30
+ for instr in nodo["body"]:
31
+ self.generar_instruccion(instr)
32
+ self.codigo.append(f"{etiqueta}:")
33
+ elif tipo == "while":
34
+ inicio = self.nueva_etiqueta()
35
+ fin = self.nueva_etiqueta()
36
+ self.codigo.append(f"{inicio}:")
37
+ cond = self.generar_expresion(nodo["condition"])
38
+ self.codigo.append(f"IF NOT {cond} GOTO {fin}")
39
+ for instr in nodo["body"]:
40
+ self.generar_instruccion(instr)
41
+ self.codigo.append(f"GOTO {inicio}")
42
+ self.codigo.append(f"{fin}:")
43
+
44
+ def generar_expresion(self, expr):
45
+ tipo = expr["type"]
46
+ if tipo in ("num", "var", "bool", "string"):
47
+ return expr["value"]
48
+ elif tipo == "binop":
49
+ izq = self.generar_expresion(expr["left"])
50
+ der = self.generar_expresion(expr["right"])
51
+ temp = self.nuevo_temp()
52
+ self.codigo.append(f"{temp} = {izq} {expr['op']} {der}")
53
+ return temp
54
+ elif tipo == "call":
55
+ return self.generar_expresion(expr["arg"])
56
+ else:
57
+ temp = self.nuevo_temp()
58
+ self.codigo.append(f"{temp} = ???")
59
+ return temp
60
+
61
+ def nueva_etiqueta(self):
62
+ etiq = f"L{self.temp_id}"
63
+ self.temp_id += 1
64
+ return etiq