From 7781e41927247bff9e567a47f9fa1862ed5596e6 Mon Sep 17 00:00:00 2001 From: Johnny Richard Date: Sat, 6 May 2023 00:01:25 +0200 Subject: cli: Add AST pretty-printing option (--ast-dump) Parsing can be a complex process, and it's not always easy to get a clear picture of what's happening with the AST. This commit adds a new feature to the CLI that allows us to pretty-print the AST (outputs to stdout), making it easier to visualize the tree structure and understand how the parser is working. The new --ast-dump option generates a human-readable representation of the AST, including node types, values, and child relationships. This information can be invaluable for debugging and understanding the parser's behavior. Signed-off-by: Johnny Richard Reviewed-by: Carlos Maniero --- src/main.c | 30 ++++++++++++++++++++++++++++-- 1 file changed, 28 insertions(+), 2 deletions(-) (limited to 'src/main.c') diff --git a/src/main.c b/src/main.c index e3caec1..4f68256 100644 --- a/src/main.c +++ b/src/main.c @@ -19,6 +19,7 @@ #include #include "ast.h" +#include "ast_pretty_printer.h" #include "gas_assembly_generator.h" #include "lexer.h" #include "parser.h" @@ -33,6 +34,14 @@ generate_gas_x86_64_linux(ast_node_t *func) gas_assembly_generator_compile(&gen, func); } +static void +pretty_print_ast(ast_node_t *ast) +{ + ast_pretty_printer_t printer; + ast_pretty_printer_init(&printer, stdout); + ast_pretty_printer_print_ast(&printer, ast); +} + static void print_usage(void) { @@ -58,7 +67,20 @@ main(int argc, char **argv) return EXIT_FAILURE; } - char *filepath = argv[1]; + char *filepath; + bool should_dump_ast = false; + + // TODO: Handle command line arguments properly + if (argc < 3) { + filepath = argv[1]; + } else { + if (strcmp(argv[1], "--ast-dump") != 0) { + print_usage(); + return EXIT_FAILURE; + } + should_dump_ast = true; + filepath = argv[2]; + } lexer_t lexer; lexer_init(&lexer, filepath); @@ -74,7 +96,11 @@ main(int argc, char **argv) return EXIT_FAILURE; } - generate_gas_x86_64_linux(func); + if (should_dump_ast) { + pretty_print_ast(func); + } else { + generate_gas_x86_64_linux(func); + } scope_destroy(scope); ast_node_destroy(func); -- cgit v1.2.3