diff --git a/include/lexer.h b/include/lexer.h index d695d16..1fa8dfb 100644 --- a/include/lexer.h +++ b/include/lexer.h @@ -74,5 +74,6 @@ LexerErr tokenize_number(const char* input, size_t *offset, ASTNode *out); LexerErr string_to_integer(const char buf[], int64_t *number); bool isoperator(int c); Operator char_to_operator(int c); +char operator_to_char(Operator op); #endif // !LEXER_H diff --git a/include/parser.h b/include/parser.h index 5a6ca6b..e0d0866 100644 --- a/include/parser.h +++ b/include/parser.h @@ -19,5 +19,9 @@ ASTNode *led(ASTNodeSlice *slice, size_t right_precedence); uint8_t node_lbp(ASTNode node); uint8_t node_rbp(ASTNode node); + AST parse(ASTNodeArray *arr); ASTNode *parse_expr(ASTNodeSlice *slice, uint8_t min_bp); + +void print_AST(AST tree); +void print_node(ASTNode *node, int depth); diff --git a/src/lexer.c b/src/lexer.c index 6a1e901..4847e20 100644 --- a/src/lexer.c +++ b/src/lexer.c @@ -248,3 +248,16 @@ Operator char_to_operator(int c) { return -1; } } + +char operator_to_char(Operator op) { + switch (op) { + case OP_ADD: + return '+'; + case OP_SUB: + return '-'; + case OP_MUL: + return '*'; + case OP_DIV: + return '/'; + } +} diff --git a/src/parser.c b/src/parser.c index b1f5287..041d81a 100644 --- a/src/parser.c +++ b/src/parser.c @@ -3,6 +3,7 @@ #include #include #include +#include uint8_t node_lbp(ASTNode node) { if (node.type == NODE_INTEGER) { @@ -100,3 +101,34 @@ ASTNode *parse_expr(ASTNodeSlice *slice, uint8_t min_bp) { return left_side; } + +void print_AST(AST tree) { + print_node(tree.head, 0); +} + +void print_node(ASTNode *node, int depth) { + if (!node) return; + + if (node->type == NODE_BINARY_OP) { + print_node(node->data.binary.right, depth + 1); + } + + for (int i = 0; i < depth; i++) { + printf(" "); + } + + switch (node->type) { + case NODE_INTEGER: + printf("%ld\n", node->data.integer); + break; + + case NODE_BINARY_OP: + printf("%c\n", operator_to_char(node->data.binary.op)); + break; + } + + if (node->type == NODE_BINARY_OP) { + print_node(node->data.binary.left, depth + 1); + } +} +