MiniDevil As beautiful as a shell
ast_utils.c
Go to the documentation of this file.
1 /* ************************************************************************** */
2 /* */
3 /* ::: :::::::: */
4 /* ast_utils.c :+: :+: :+: */
5 /* +:+ +:+ +:+ */
6 /* By: baelgadi <baelgadi@student.42.fr> +#+ +:+ +#+ */
7 /* +#+#+#+#+#+ +#+ */
8 /* Created: 2025/12/07 21:02:54 by zotaj-di #+# #+# */
9 /* Updated: 2026/03/04 04:46:13 by baelgadi ### ########.fr */
10 /* */
11 /* ************************************************************************** */
12 
13 #include "ast.h"
14 #include "libft.h"
15 
21 static void free_args(char **args)
22 {
23  int i;
24 
25  if (!args)
26  return ;
27  i = 0;
28  while (args[i])
29  {
30  free(args[i]);
31  i++;
32  }
33  free(args);
34 }
35 
46 void free_ast(t_ast *node)
47 {
48  if (!node)
49  return ;
50  if (node->type == NODE_COMMAND)
51  free_args(node->data.cmd.args);
52  else if (node->type == NODE_PIPE)
53  {
54  free_ast(node->data.binary.left);
55  free_ast(node->data.binary.right);
56  }
57  else if (node->type >= NODE_REDIR_IN && node->type <= NODE_REDIR_HEREDOC)
58  {
59  if (node->data.redir.heredoc_fd >= 0)
60  close(node->data.redir.heredoc_fd);
61  free(node->data.redir.file);
62  free_ast(node->data.redir.cmd);
63  }
64  free(node);
65 }
AST node creation and destruction prototypes.
void free_ast(t_ast *node)
Recursively free an entire AST tree.
Definition: ast_utils.c:46
static void free_args(char **args)
Free a string array and its entries.
Definition: ast_utils.c:21
@ NODE_REDIR_HEREDOC
Definition: structs.h:57
@ NODE_COMMAND
Definition: structs.h:52
@ NODE_PIPE
Definition: structs.h:53
@ NODE_REDIR_IN
Definition: structs.h:54
AST node (union based ↑)
Definition: structs.h:151
t_ast_data data
cmd, redir or binary data
Definition: structs.h:153
t_node_type type
To determine which union member to pick.
Definition: structs.h:152
struct s_ast * left
left child (before pipe)
Definition: structs.h:124
struct s_ast * right
right child (after pipe)
Definition: structs.h:125
char ** args
NULL terminated args array.
Definition: structs.h:103
int heredoc_fd
Heredoc pipe fd (-1 if not used)
Definition: structs.h:116
char * file
Target filename or delimiter.
Definition: structs.h:112
struct s_ast * cmd
Command subtree.
Definition: structs.h:113
t_binary_node binary
Definition: structs.h:143
t_cmd_node cmd
Definition: structs.h:141
t_redir_node redir
Definition: structs.h:142