summaryrefslogtreecommitdiff
path: root/src/parser.c
diff options
context:
space:
mode:
authorCarlos Maniero <carlosmaniero@gmail.com>2023-04-20 13:42:10 -0300
committerJohnny Richard <johnny@johnnyrichard.com>2023-04-20 18:57:43 +0200
commit219dfdfdc98529ce173f894b79d88919a65c2808 (patch)
tree8792c686d05b107875d43f570ed6666f91dda19e /src/parser.c
parent58da5195ef7d517f851ebfabfe79cfa27c0b2dde (diff)
parser: Create the literal node type
Since we want to extend our code to support multiple kind of expression it does not make sense that the return statement always return a number. For now on, return statement has an ast_node_t as argument, meaning that it could be anything. The literal_node_t was also implemented in order to keep the application behavior. Following the C's calling convention the literal values are stored at %eax and the return takes this argument to do anything it is needed. Signed-off-by: Carlos Maniero <carlosmaniero@gmail.com> Reviewed-by: Johnny Richard <johnny@johnnyrichard.com>
Diffstat (limited to 'src/parser.c')
-rw-r--r--src/parser.c43
1 files changed, 36 insertions, 7 deletions
diff --git a/src/parser.c b/src/parser.c
index 4646de0..176a4a8 100644
--- a/src/parser.c
+++ b/src/parser.c
@@ -99,6 +99,39 @@ parser_parse_type(type_t *type, parser_t *parser)
}
bool
+parser_literal_integer_node(ast_node_t *node, token_t *token)
+{
+ char number_as_str[token->value.size];
+ string_view_to_str(&token->value, number_as_str);
+
+ ast_literal_integer_create(node, atoi(number_as_str));
+ return true;
+}
+
+bool
+parser_parse_next_expression(parser_t *parser, ast_node_t *node)
+{
+ token_t token;
+ lexer_next_token(parser->lexer, &token);
+
+ if (token.kind == TOKEN_NUMBER)
+ {
+ return parser_literal_integer_node(node, &token);
+ }
+
+ parser_error_t error;
+ error.token = token;
+ sprintf(
+ error.message,
+ "unexpected '%s ("SVFMT")' token",
+ token_kind_to_str(token.kind),
+ SVARG(&token.value)
+ );
+ parser->errors[parser->errors_len++] = error;
+ return false;
+}
+
+bool
parser_parse_return_stmt(parser_t *parser, ast_node_t *node)
{
token_t return_keyword_token;
@@ -121,17 +154,13 @@ parser_parse_return_stmt(parser_t *parser, ast_node_t *node)
return false;
}
- token_t number_token;
-
- if (!expected_token(&number_token, parser, TOKEN_NUMBER)) return false;
+ ast_node_t *argument_token = ast_node_new();
+ if (!parser_parse_next_expression(parser, argument_token)) return false;
if (!drop_expected_token(parser, TOKEN_SEMICOLON)) return false;
if (!drop_expected_token(parser, TOKEN_CCURLY)) return false;
- char number_as_str[number_token.value.size];
- string_view_to_str(&number_token.value, number_as_str);
-
- ast_node_init_return_stmt(node, atoi(number_as_str));
+ ast_node_init_return_stmt(node, argument_token);
return true;
}