From c1a1bd2320b4c1508c4ab20d23b7c193a94d8026 Mon Sep 17 00:00:00 2001 From: Carlos Maniero Date: Tue, 25 Apr 2023 03:52:59 -0300 Subject: parser: Add support for variables and identifiers in function body This commit adds support for variables and identifiers in the function body of the parser, stored as a vector. However, at this point, identifier resolution is not fully implemented, and we currently accept identifiers without checking if they can be resolved. This is a known limitation that will be addressed in a future commit once hash-tables are added to the parser. Signed-off-by: Carlos Maniero Reviewed-by: Johnny Richard --- src/ast.c | 45 +++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 43 insertions(+), 2 deletions(-) (limited to 'src/ast.c') diff --git a/src/ast.c b/src/ast.c index b2efc42..645a2dd 100644 --- a/src/ast.c +++ b/src/ast.c @@ -67,20 +67,35 @@ ast_node_new() return node; } +static void +ast_node_destroy_vector(vector_t *vector) +{ + for (size_t i=0; i < vector->size; i++) { + ast_node_destroy(vector_at(vector, i)); + } + vector_destroy(vector); +} + void ast_node_destroy(ast_node_t *node) { switch (node->kind) { case AST_FUNCTION_DECLARATION: - ast_node_destroy(node->data.function.body); + ast_node_destroy_vector(node->data.function.body); break; case AST_BINARY_OPERATION: ast_node_destroy(node->data.binary_operation.left); ast_node_destroy(node->data.binary_operation.right); break; + case AST_VARIABLE_DECLARATION: + ast_node_destroy(node->data.variable.value); + break; case AST_LITERAL: break; case AST_RETURN_STMT: + ast_node_destroy(node->data.return_stmt.argument); + break; + case AST_IDENTIFIER: break; case AST_UNKOWN_NODE: break; @@ -103,7 +118,7 @@ ast_node_init_return_stmt(ast_node_t *node, ast_node_t *argument) } void -ast_node_init_function_declaration(ast_node_t *node, string_view_t name, type_t return_type, ast_node_t* body) +ast_node_init_function_declaration(ast_node_t *node, string_view_t name, type_t return_type, vector_t *body) { node->accept_visitor = &ast_node_function_accept_visitor, node->kind = AST_FUNCTION_DECLARATION; @@ -144,3 +159,29 @@ ast_node_init_binary_operation(ast_node_t *node, string_view_t op, ast_node_t *l } }; } + +void +ast_node_init_variable_declaration(ast_node_t *node, string_view_t variable_name, type_t type, ast_node_t *value) +{ + // FIXME: define the visitor strategy + node->kind = AST_VARIABLE_DECLARATION; + node->data = (ast_node_data_t) { + .variable = { + .name = variable_name, + .type = type, + .value = value + } + }; +} + +void +ast_node_init_identifier(ast_node_t *node, string_view_t name) +{ + // FIXME: define the visitor strategy + node->kind = AST_IDENTIFIER; + node->data = (ast_node_data_t) { + .variable = { + .name = name, + } + }; +} -- cgit v1.2.3