summaryrefslogtreecommitdiff
path: root/src/parser.c
diff options
context:
space:
mode:
authorCarlos Maniero <carlos@maniero.me>2023-05-08 23:53:44 -0300
committerJohnny Richard <johnny@johnnyrichard.com>2023-05-09 22:48:17 +0200
commit8c8fc8cc30b38ef00d606a4991b655df97a52fb6 (patch)
treee5ceb46de265fea9dae3e66c7e4b3a9bdaac80a8 /src/parser.c
parent50ce0fb2a436eb5e765b2764c9468f648f18a4f8 (diff)
parser: create a block node type
Since the next step to pipa programming language is about having control flow statements we could benefit ourselves by having a block node to control scope. Now, functions has a block node, instead of an vector as body. As you can see through the ast-dump: FunctionDecl name='main' └─ body: └─ Block └─ ReturnStmt └─ Literal type=i32 value='69' This same node kind can be used for parsing if, for and while blocks. I could use ast_block_t as body for functions but instead, I opted to use an ast_node_t. This brings the flexibility to, in the future, having another function body kinds, such as arrow functions if we want to: fn add(a: i32, b: i32): i32 => a + b; Signed-off-by: Carlos Maniero <carlos@maniero.me>
Diffstat (limited to 'src/parser.c')
-rw-r--r--src/parser.c15
1 files changed, 8 insertions, 7 deletions
diff --git a/src/parser.c b/src/parser.c
index 2817fa0..848bb4a 100644
--- a/src/parser.c
+++ b/src/parser.c
@@ -516,9 +516,11 @@ parser_error_report_unexpected_token(parser_t *parser)
}
static bool
-parser_ensure_function_return_statement(parser_t *parser, vector_t *body, token_t *function_token)
+parser_ensure_function_return_statement(parser_t *parser, ast_node_t *block, token_t *function_token)
{
- ast_node_t *latest_node = vector_at(body, body->size - 1);
+ assert(block->kind == AST_BLOCK);
+
+ ast_node_t *latest_node = vector_at(block->data.block.body, block->data.block.body->size - 1);
if (latest_node->kind != AST_RETURN_STMT) {
parser_error_t error;
@@ -527,14 +529,13 @@ parser_ensure_function_return_statement(parser_t *parser, vector_t *body, token_
sprintf(error.message, "expected 'return' keyword.");
parser->errors[parser->errors_len++] = error;
- vector_destroy(body);
return false;
}
return true;
}
-static vector_t *
+static ast_node_t *
parser_parse_block_declarations(parser_t *parser, type_t result_type)
{
if (!drop_expected_token(parser, TOKEN_OCURLY)) {
@@ -602,7 +603,7 @@ parser_parse_block_declarations(parser_t *parser, type_t result_type)
return NULL;
}
- return body;
+ return ast_node_new_block(body);
}
static bool
@@ -638,14 +639,14 @@ parser_parse_function_declaration(parser_t *parser)
return NULL;
}
- vector_t *body = parser_parse_block_declarations(parser, return_type);
+ ast_node_t *body = parser_parse_block_declarations(parser, return_type);
if (body == NULL) {
return NULL;
}
if (!parser_ensure_function_return_statement(parser, body, &func_name_token)) {
- vector_destroy(body);
+ ast_node_destroy(body);
return NULL;
}