Attempting to print the expression tree. I think the printing code is fine but the Parser is bugged and not building the tree correctly.

This commit is contained in:
2022-03-02 21:43:22 +00:00
parent 221d575c16
commit 7bf7304bd4
2 changed files with 24 additions and 2 deletions
+22 -2
View File
@@ -1,4 +1,6 @@
#include "parser.h"
#include "expr.h"
#include <stdio.h>
Expr* Expression(void);
Expr* Equality(void);
@@ -135,9 +137,9 @@ Expr* Primary() {
if (Match(1, LParen)) {
free(expr);
expr = Expression();
if (!Check(RParen)) printf("Unbalcnace\n");
//Consume(RParen, "Expect ')' after expression.");
expr->type = GROUPING;
return expr;
}
return expr;
@@ -181,7 +183,25 @@ Token* AdvanceParser() {
}
void PrintExpressionTree(const Expr* tree) {
if (!tree) return;
if (tree->type == BINARY) {
printf("(");
PrintExpressionTree(tree->expression.Binary.left);
PrintExpressionTree(tree->expression.Binary.right);
printf("%s", tree->expression.Binary.op->lexeme);
printf(")\n");
}
else if (tree->type == UNARY) {
printf("(");
printf("%s", tree->expression.Unary.op->lexeme);
PrintExpressionTree(tree->expression.Unary.right);
printf(")\n");
}
else if (tree->type == GROUPING) {
PrintExpressionTree(tree->expression.Grouping.expression);
}
else if (tree->type == LITERAL) printf("%s", tree->expression.Literal.type->lexeme);
}
void FreeExpressionTree(Expr* tree) {