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:
@@ -39,7 +39,9 @@ void RunFile(const char* path) {
|
||||
TokenList* tokens = ScanTokens(contents);
|
||||
free(contents);
|
||||
Print(tokens);
|
||||
printf("TREE:\n");
|
||||
Expr* tree = GenerateExpressionTree(tokens);
|
||||
PrintExpressionTree(tree);
|
||||
FreeExpressionTree(tree);
|
||||
DestroyTokenList(tokens);
|
||||
}
|
||||
|
||||
@@ -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) {
|
||||
|
||||
Reference in New Issue
Block a user