summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorJohnny Richard <johnny@johnnyrichard.com>2023-05-01 01:57:21 +0200
committerCarlos Maniero <carlos@maniero.me>2023-05-01 18:14:39 -0300
commit8c56ddf0b640b8880eb5b97e5ca1b787585c29c0 (patch)
treed56ef0f1360019d1c375de708c531d0946e452b4
parent1d9981e5879260d9f158f5b3d9e13b12df43c68e (diff)
parser: Use peek and drop token when parsing expressions
-rw-r--r--src/lexer.c7
-rw-r--r--src/lexer.h2
-rw-r--r--src/parser.c16
3 files changed, 12 insertions, 13 deletions
diff --git a/src/lexer.c b/src/lexer.c
index f937170..b60fbb5 100644
--- a/src/lexer.c
+++ b/src/lexer.c
@@ -232,11 +232,10 @@ lexer_peek_next_token(lexer_t *lexer, token_t *token)
}
void
-lexer_step_back_to(lexer_t *lexer, token_t *token)
+lexer_drop_next_token(lexer_t *lexer)
{
- lexer->cur = token->bol + token->col;
- lexer->row = token->row;
- lexer->bol = token->bol;
+ token_t token;
+ lexer_next_token(lexer, &token);
}
void
diff --git a/src/lexer.h b/src/lexer.h
index 0b9f2ad..abee53a 100644
--- a/src/lexer.h
+++ b/src/lexer.h
@@ -83,7 +83,7 @@ void
lexer_drop_char(lexer_t *lexer);
void
-lexer_step_back_to(lexer_t *lexer, token_t *token);
+lexer_drop_next_token(lexer_t *lexer);
void
lexer_peek_next_token(lexer_t *lexer, token_t *token);
diff --git a/src/parser.c b/src/parser.c
index 662449b..af372fb 100644
--- a/src/parser.c
+++ b/src/parser.c
@@ -167,9 +167,11 @@ parser_parse_term(parser_t *parser, ast_node_t *node)
return false;
token_t token;
- lexer_next_token(parser->lexer, &token);
+ lexer_peek_next_token(parser->lexer, &token);
while (token.kind == TOKEN_STAR || token.kind == TOKEN_SLASH) {
+ lexer_drop_next_token(parser->lexer);
+
ast_node_t *left = ast_node_new();
*left = *node;
@@ -179,11 +181,9 @@ parser_parse_term(parser_t *parser, ast_node_t *node)
ast_node_init_binary_operation(node, token_to_binary_operation_kind(&token), left, right);
- lexer_next_token(parser->lexer, &token);
+ lexer_peek_next_token(parser->lexer, &token);
}
- lexer_step_back_to(parser->lexer, &token);
-
return true;
}
@@ -201,9 +201,11 @@ parser_parse_expression(parser_t *parser, ast_node_t *node)
return false;
token_t token;
- lexer_next_token(parser->lexer, &token);
+ lexer_peek_next_token(parser->lexer, &token);
while (token.kind == TOKEN_PLUS || token.kind == TOKEN_MINUS) {
+ lexer_drop_next_token(parser->lexer);
+
ast_node_t *left = ast_node_new();
*left = *node;
@@ -213,11 +215,9 @@ parser_parse_expression(parser_t *parser, ast_node_t *node)
ast_node_init_binary_operation(node, token_to_binary_operation_kind(&token), left, right);
- lexer_next_token(parser->lexer, &token);
+ lexer_peek_next_token(parser->lexer, &token);
}
- lexer_step_back_to(parser->lexer, &token);
-
return true;
}