From: Lukas Jiriste Date: Fri, 21 Jun 2024 07:43:38 +0000 (+0200) Subject: Fix the code to actually produce a tree X-Git-Url: https://git.ljiriste.work/?a=commitdiff_plain;h=faa06ffa7159c575c44abbf5caeddae16e3bc9a0;p=Libft.git Fix the code to actually produce a tree As the previous commit was only checked to compile there were some minor defects. Notably the parser stack was not initialized properly. It has to return state_num 0 when empty, which was solved by inserting a dummy state 0 wih no node attached. --- diff --git a/ft_parse/ft_parse.c b/ft_parse/ft_parse.c index bef5a61..e101c5c 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/20 17:45:45 by ljiriste ### ########.fr */ +/* Updated: 2024/06/21 09:39:33 by ljiriste ### ########.fr */ /* */ /* ************************************************************************** */ @@ -20,6 +20,8 @@ void ft_parse_tree_free(void *v_node) t_parse_tree_node *node; node = v_node; + if (!node) + return ; ft_vec_free(&node->children, ft_parse_tree_free); free_token(&node->token); return ; @@ -30,6 +32,8 @@ void ft_stack_element_free(void *v_el) t_parser_stack_element *el; el = v_el; + if (!el) + return ; ft_parse_tree_free(el->node); return ; } @@ -114,7 +118,18 @@ int follow_rule(t_stack *stack, size_t rule_num, t_parsing_table *table) return (ft_stack_push(stack, &element) != success || element.state_num < 0); } -t_parse_tree_node *ft_parse(__attribute__((unused)) t_vec *tokens, __attribute__((unused)) t_parsing_table *table) +void initialize_parser_stack(t_stack *stack) +{ + t_parser_stack_element zero; + + zero.state_num = 0; + zero.node = NULL; + ft_stack_init(stack, sizeof(t_parser_stack_element)); + ft_stack_push(stack, &zero); + return ; +} + +t_parse_tree_node *ft_parse(t_vec *tokens, t_parsing_table *table) { t_stack stack; size_t i; @@ -124,13 +139,13 @@ t_parse_tree_node *ft_parse(__attribute__((unused)) t_vec *tokens, __attribute__ ssize_t column; t_parse_tree_node *root; - ft_stack_init(&stack, sizeof(t_parser_stack_element)); + initialize_parser_stack(&stack); i = 0; while (1) { if (i < tokens->size) token = *(t_token *)ft_vec_access(tokens, i); - if (i == tokens->size) + else if (i == tokens->size) token = (t_token){.type = "$", .str = NULL}; else { @@ -140,7 +155,7 @@ t_parse_tree_node *ft_parse(__attribute__((unused)) t_vec *tokens, __attribute__ state = ft_vec_access(&table->states, ((t_parser_stack_element *)ft_stack_top(&stack))->state_num); column = find_token_index(token, &table->tokens); - if (column < 0 || (size_t)column + 1 > table->terminal_tokens_num) + if (column < 0 || (size_t)column > table->terminal_tokens_num) { ft_stack_free(&stack, ft_stack_element_free); return (NULL);