Finish main task, start refactoring
This commit is contained in:
@@ -1,18 +1,52 @@
|
||||
# This is a sample Python script for testing your TRIPLA parser.
|
||||
|
||||
# In PyCharm press Umschalt+F10 to execute it.
|
||||
# (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 test_parser(name):
|
||||
source = "\n".join(open(name).readlines())
|
||||
ast = yacc.parser.parse(source) # ,debug=True)
|
||||
print("AST:")
|
||||
|
||||
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)
|
||||
|
||||
# Press the green button in the gutter to run the script.
|
||||
if __name__ == '__main__':
|
||||
test_parser('whileprograms/complex.while')
|
||||
# Export DOT file
|
||||
syntax.export_dot(ast, "ast.dot")
|
||||
|
||||
# See PyCharm help at https://www.jetbrains.com/help/pycharm/
|
||||
# Display AST diagram
|
||||
print("Rendering AST diagram with matplotlib...")
|
||||
display_ast_graph("ast.dot")
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
test_parser('triplaprograms/or.tripla')
|
||||
|
||||
Reference in New Issue
Block a user