From e1a45db57a60c1998f0990e392000bd26a8ebdde Mon Sep 17 00:00:00 2001 From: Lukas Jiriste Date: Fri, 21 Jun 2024 15:23:51 +0200 Subject: [PATCH] Refactor functions to comply with the Norm --- ft_parse/ft_parse.c | 65 +++++++++++++++++++++------------------------ 1 file changed, 31 insertions(+), 34 deletions(-) diff --git a/ft_parse/ft_parse.c b/ft_parse/ft_parse.c index ef59f8c..7a47bd6 100644 --- a/ft_parse/ft_parse.c +++ b/ft_parse/ft_parse.c @@ -6,7 +6,7 @@ /* By: ljiriste +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2024/05/20 20:51:36 by ljiriste #+# #+# */ -/* Updated: 2024/06/21 13:56:25 by ljiriste ### ########.fr */ +/* Updated: 2024/06/21 15:22:31 by ljiriste ### ########.fr */ /* */ /* ************************************************************************** */ @@ -73,6 +73,8 @@ ssize_t find_token_index(t_token token, const t_vec *tokens) { size_t i; + if (!token.type) + return (-1); i = 0; while (i < tokens->size) { @@ -167,55 +169,50 @@ const t_parser_action *get_action(t_stack *stack, t_token token, return (ft_vec_caccess(&state->lookahead, column)); } +t_token get_token(const t_vec *tokens, size_t index) +{ + static char end_token[] = "$"; + + if (index < tokens->size) + return (*(t_token *)ft_vec_caccess(tokens, index)); + else + return ((t_token){.type = end_token, .str = NULL}); +} + +t_parse_tree_node *handle_accept(t_stack *stack) +{ + t_parse_tree_node *root; + + root = ((t_parser_stack_element *)ft_stack_top(stack))->node; + ft_stack_free(stack, NULL); + return (root); +} + t_parse_tree_node *ft_parse(const t_vec *tokens, const t_parsing_table *table) { t_stack stack; size_t i; t_token token; const t_parser_action *action; - t_parse_tree_node *root; initialize_parser_stack(&stack); i = 0; while (1) { - if (i < tokens->size) - token = *(t_token *)ft_vec_caccess(tokens, i); - else if (i == tokens->size) - token = (t_token){.type = "$", .str = NULL}; - else - { - ft_stack_free(&stack, ft_stack_element_free); - return (NULL); - } + token = get_token(tokens, i); action = get_action(&stack, token, table); - if (!action || action->type == parser_refuse) + if (!action || action->type == parser_refuse + || (action->type == parser_reduce + && follow_rule(&stack, action->number, table)) + || (action->type == parser_shift + && push_state(&stack, action->number, token))) { ft_stack_free(&stack, ft_stack_element_free); return (NULL); } - else if (action->type == parser_reduce) - { - if (follow_rule(&stack, action->number, table)) - { - ft_stack_free(&stack, ft_stack_element_free); - return (NULL); - } - } - else if (action->type == parser_shift) - { - if (push_state(&stack, action->number, token)) - { - ft_stack_free(&stack, ft_stack_element_free); - return (NULL); - } - ++i; - } else if (action->type == parser_accept) - { - root = ((t_parser_stack_element *)ft_stack_top(&stack))->node; - ft_stack_free(&stack, NULL); - return (root); - } + return (handle_accept(&stack)); + if (action->type == parser_shift) + ++i; } } -- 2.30.2