Refactor export

This commit is contained in:
Jan-Niclas Loosen
2025-11-22 18:37:11 +01:00
parent ddb6eee609
commit ee0e5b0b4c
2 changed files with 17 additions and 14 deletions

Binary file not shown.

Before

Width:  |  Height:  |  Size: 35 KiB

After

Width:  |  Height:  |  Size: 224 KiB

View File

@@ -47,7 +47,14 @@ def pretty_print(node, indent=0):
else:
print(f"{prefix} {key}: {value}")
def prompt_choice(prompt: str, options: list) -> int:
def export_dot_file(dot_string: str, filename: str):
try:
Path(filename).write_text(dot_string, encoding="utf-8")
print(f"Saved DOT file as: {filename}")
except Exception as e:
print(f"Could not save DOT file: {e}")
def __prompt_choice(prompt: str, options: list) -> int:
print(prompt)
for i, opt in enumerate(options, 1):
print(f" {i}. {opt}")
@@ -62,13 +69,13 @@ def prompt_choice(prompt: str, options: list) -> int:
pass
print(f"Invalid. Enter a number between 1-{len(options)}.")
def prompt_yesno(question: str, default="y"):
def __prompt_yesno(question: str, default="y"):
s = input(f"{question} (y/n) [{default}]: ").strip().lower()
if not s:
s = default
return s.startswith("y")
def search_programs():
def __search_programs():
base = Path(__file__).parent / "triplaprograms"
if not base.exists():
return []
@@ -78,42 +85,38 @@ if __name__ == "__main__":
print("\nTRIPLA Parser Tool")
while True:
choice = prompt_choice("\nSelect action:", ["Parse .tripla", "Exit"])
choice = __prompt_choice("\nSelect action:", ["Parse .tripla", "Exit"])
if choice == 1:
print("\nBye Bye.")
break
programs = search_programs()
programs = __search_programs()
if not programs:
print("\nNo .tripla files found.")
continue
idx = prompt_choice("\nSelect program to parse:", [p.name for p in programs])
idx = __prompt_choice("\nSelect program to parse:", [p.name for p in programs])
path = programs[idx]
source = path.read_text()
ast = yacc.parser.parse(source)
# Pretty print
if prompt_yesno("\nPretty-print AST?"):
if __prompt_yesno("\nPretty-print AST?"):
print("")
pretty_print(ast)
# Export DOT
dot_str = ast.to_dot()
if prompt_yesno("Export AST as .dot file?"):
if __prompt_yesno("Export AST as .dot file?"):
default = f"{path.stem}.dot"
out = input(f"Filename [{default}]: ").strip()
if not out:
out = default
try:
Path(out).write_text(dot_str, encoding="utf-8")
print(f"Saved DOT file as: {out}")
except Exception as e:
print(f"Could not save DOT file: {e}")
export_dot_file(dot_str, out)
# Display AST diagram
if prompt_yesno("Display AST diagram?"):
if __prompt_yesno("Display AST diagram?"):
render_ast_from_string(dot_str)
print("Rendered AST diagram.")