aboutsummaryrefslogtreecommitdiff
path: root/tabla.py
blob: c8ca4240dbcf2c750907dd5b36efd8a20b7c33f0 (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
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 __str__(self):
        output = ""
        for t in self.tabla:
            output += str(t) + "\n"
        return output