minor changes for

This commit is contained in:
2025-11-20 13:15:24 +09:00
parent 3682559a56
commit 227c94c2ea
4 changed files with 144 additions and 2 deletions

96
src/ast_util.c Normal file
View File

@@ -0,0 +1,96 @@
#include "ast_util.h"
#include <stdlib.h>
ASTNode *ast_node_new(NodeKind kind, Token token) {
ASTNode *node = malloc(sizeof(ASTNode));
if (node == NULL) {
return NULL;
}
node->kind = kind;
node->token = token;
node->children = NULL;
node->capacity = 0;
node->child_count = 0;
return node;
}
ASTNode *ast_node_new_with_child(NodeKind kind, Token token, int child_count) {
ASTNode *node = ast_node_new(kind, token);
if (node == NULL) {
return NULL;
}
node->child_count = child_count;
node->capacity = child_count;
node->children = calloc(child_count, sizeof(ASTNode *));
if (node->children == NULL) {
free(node);
return NULL;
}
return node;
}
void ast_node_add_child(ASTNode *parent, ASTNode *child) {
if (parent->child_count >= parent->capacity) {
size_t new_capacity = parent->capacity == 0 ? 2 : parent->capacity * 2;
ASTNode **new_children = realloc(parent->children, new_capacity * sizeof(ASTNode *));
if (new_children == NULL) {
return;
}
parent->children = new_children;
parent->capacity = new_capacity;
}
parent->children[parent->child_count++] = child;
}
void ast_node_free(ASTNode *node) {
if (node == NULL) {
return;
}
for (size_t i = 0; i < node->child_count; i++) {
ast_node_free(node->children[i]);
}
free(node->children);
free(node);
}
ASTNode *ast_node_new_program() {
ASTNode *node = ast_node_new(NODE_PROGRAM, (Token) {PROGRAM, 0, {0, NULL}});
return node;
}
ASTNode *ast_node_new_defn(Token token, ASTNode *type_node, ASTNode *expr_node /* nullable */) {
ASTNode *node;
if (expr_node == NULL) {
node = ast_node_new_with_child(NODE_DEFN, token, 1);
} else {
node = ast_node_new_with_child(NODE_DEFN, token, 2);
}
if (node == NULL) {
return NULL;
}
node->children[0] = type_node;
if (expr_node != NULL) {
node->children[1] = expr_node;
}
return node;
}
ASTNode *ast_node_new_type_simple(Token token) {
ASTNode *node = ast_node_new(NODE_TYPE, token);
}
ASTNode *ast_node_new_type_functional(Token token, ASTNode *type_node_from, ASTNode *type_node_to) {
ASTNode *node = ast_node_new_with_child(
NODE_TYPE, token, 2);
}

View File

@@ -29,10 +29,30 @@ static void parser_expect(Parser *parser, TokenType type) {
if (parser->current.type == type) {
parser_next(parser);
} else {
parser->flag_error = 1;
parser->flag_error = 1; // TODO: 실패했을 떄, 예외전파
}
}
/*
IMPL. PARSER PARSE FUNCTIONS
*/
*/
ASTNode *parser_parse_defn(Parser *parser) {
parser_expect(parser, ID);
Token id_token = parser->current;
ASTNode *type_node = parser_parse_type(parser);
Token id = parser->current;
parser_expect(parser, ID);
ASTNode *expr = NULL;
if (parser->current.type != SEMI) {
expr = parser_parse_expr(parser);
}
parser_expect(parser, SEMI);
return NULL;
}