-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathast_visualizer.py
More file actions
53 lines (43 loc) · 1.59 KB
/
ast_visualizer.py
File metadata and controls
53 lines (43 loc) · 1.59 KB
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
import pydot
from antlr4 import FileStream, CommonTokenStream
#from gen.CalculadoraLexer import CalculadoraLexer
#from gen.CalculadoraParser import CalculadoraParser
from gen.ExamenLexer import ExamenLexer
from gen.ExamenParser import ExamenParser
def gen_ast(tree, parser, graph):
if tree.getChildCount() == 0: # Es un nodo hoja
node = pydot.Node(str(id(tree)), label=tree.getText())
else: # Es un nodo interno
node = pydot.Node(str(id(tree)), label=parser.ruleNames[tree.getRuleIndex()])
graph.add_node(node)
for i in range(tree.getChildCount()):
child = tree.getChild(i)
gen_ast(child, parser, graph)
edge = pydot.Edge(str(id(tree)), str(id(child)))
graph.add_edge(edge)
# Entrada del usuario
user_input = FileStream("archivo.txt")
# Crear el lexer
lexer = ExamenLexer(user_input)
# Obtener los tokens
tokens = CommonTokenStream(lexer)
tokens.fill()
# Imprimir los tokens
print("\nTOKENS:\n")
for token in tokens.tokens:
if token.type != -1:
token_type = lexer.symbolicNames[token.type]
print(f"token: {token.text}, tipo: {token_type}")
# Generar el AST
parser = ExamenParser(tokens)
tree = parser.source()
# Imprimir el árbol AST en formato texto
print("\nAST (texto):\n")
print(tree.toStringTree(recog=parser))
# Crear el gráfico de pydot
graph = pydot.Dot(graph_type="digraph", rankdir="TB")
# Llamar a la función para generar el AST como gráfico
gen_ast(tree, parser, graph)
# Guardar la imagen del AST en formato PNG
graph.write_png("images/ast_output.png")
print("\nEl árbol AST ha sido guardado como 'ast_output.png'.")