aboutsummaryrefslogtreecommitdiff
path: root/compilador/tabla.py
blob: 637b9a62ee67944f506007945baaa8a773299b85 (plain)
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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
import json, os
from enum import Enum
from dataclasses import dataclass
from typing import Any

reservadas = [
    'BOOLEAN',
    'BREAK',
    'CHAR',
    'DOUBLE',
    'ELSE',
    'FOR'
    'IDENT',
    'IF',
    'INT',
    'PRINT',
    'READ',
    'RETURN',
    'STRING',
    'VOID',
    'WHILE'
]

literales = [
    'BOOLEAN_LIT',
    'CHAR_LIT',
    'DOUBLE_LIT',
    'INT_LIT',
    'STRING_LIT'
]

tokens = reservadas + literales + [
    '{', '}', '(', ')', ',', '\'',
    '"', ';', '=', '*', '/', '+',
    '-', '>', '<', '>=', '<=', '&&',
    '||', '==', '!=', '++', '--', '//'
]

@dataclass
class LexToken:
    tipo: str
    nombre: str
    valor: Any
    numlinea: int

    def __str__(self):
        return "LexToken(%s,%s,%s,%i)" % (
            self.tipo, self.nombre, self.valor, self.numlinea
        )

class TablaLex:
    def __init__(self):
        self.tabla = []

    def insertar(self, tok: LexToken):
        self.tabla.append(tok)

    def buscar(self, nombre: str):
        return [t for t in self.tabla if t.nombre == nombre][0]

    def actualizar(self, nombre: str, tok: LexToken):
        for i, t in enumerate(self.tabla):
            if t.nombre == nombre:
                self.tabla[i] = tok
                return

    def exportar(self, output_file):
        data = []
        for t in self.tabla:
            data.append({
                'tipo': t.tipo,
                'nombre': t.nombre,
                'valor': str(t.valor),
                'numlinea': t.numlinea
            })
        output = json.dumps(data)
        if os.path.exists(output_file):
            os.remove(output_file)
        with open(output_file, 'w+') as f:
            f.truncate(0)
            f.write(output)

    def __str__(self):
        output = ""
        for t in self.tabla:
            output += str(t) + "\n"
        return output