File size: 2,329 Bytes
5c54be1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
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