Files
Construction-of-Compilers/Project-02/main.py
2025-11-20 15:10:38 +01:00

53 lines
1.2 KiB
Python

# (c) Stephan Diehl / Updated for AST display by ChatGPT
import triplayacc as yacc
import triplalex as lex
import syntax
from graphviz import Source
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
def display_ast_graph(dotfile="ast.dot"):
"""Render DOT → PNG and display via matplotlib (always)."""
# Read DOT
with open(dotfile) as f:
dot_data = f.read()
# Render using Graphviz
src = Source(dot_data)
src.render("ast", format="png", cleanup=True)
# Load rendered PNG
img = mpimg.imread("ast.png")
# Show in matplotlib window
plt.imshow(img)
plt.axis('off')
plt.show()
def test_parser(filepath):
# Load program
with open(filepath) as f:
source = f.read()
# Parse input
ast = yacc.parser.parse(source)
# Print plain-text version of the AST (optional)
print("AST object:")
print(ast)
# Export DOT file
syntax.export_dot(ast, "ast.dot")
# Display AST diagram
print("Rendering AST diagram with matplotlib...")
display_ast_graph("ast.dot")
if __name__ == '__main__':
test_parser('triplaprograms/or.tripla')