aboutsummaryrefslogtreecommitdiff
path: root/src/parser.c
blob: 13ab10d3cc84654d72f850cf2989dfe4ae43341d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
/* ************************************************************************** */
/*                                                                            */
/*                                                        :::      ::::::::   */
/*   parser.c                                           :+:      :+:    :+:   */
/*                                                    +:+ +:+         +:+     */
/*   By: chuhlig <chuhlig@student.42.fr>            +#+  +:+       +#+        */
/*                                                +#+#+#+#+#+   +#+           */
/*   Created: 2024/06/29 15:53:29 by dkaiser           #+#    #+#             */
/*   Updated: 2025/01/20 19:13:31 by chuhlig          ###   ########.fr       */
/*                                                                            */
/* ************************************************************************** */

#include "libft.h"
#include "minishell.h"
#include "token.h"
#include "env.h"

static t_token	*find_token_by_type(t_token *tokens, int type);
t_token			*split_at_first(t_token **tokens, int type);
static t_node	*parse_statement(t_token *tokens, t_env **env);

t_list	*parse(t_token *tokens, t_env **env)
{
	t_node	*result;

	if ((*tokens).type == PIPE_TOKEN)
		result = NULL;
	else
		result = parse_statement(tokens, env);
	if (result == NULL)
		printf("Parsing error.\n");
	return (ft_lstnew(result));
}

static t_node	*parse_statement(t_token *tokens, t_env **env)
{
	t_token	*left_side_tokens;

	left_side_tokens = split_at_first(&tokens, PIPE_TOKEN);
	if (left_side_tokens == NULL)
	{
		free_tokens(tokens);
		tokens = NULL;
		return (NULL);
	}
	else if (tokens != NULL)
	{
		return (new_pipe_node(parse_cmd(left_side_tokens, env),
				parse_statement(tokens, env)));
	}
	else
	{
		return (parse_cmd(left_side_tokens, env));
	}
}

t_token	*split_at_first(t_token **tokens, int type)
{
	t_token	*split;
	t_token	*result;

	split = find_token_by_type(*tokens, type);
	if (split == NULL)
	{
		result = *tokens;
		*tokens = NULL;
		return (result);
	}
	result = *tokens;
	*tokens = split->next;
	if (result == split)
		result = NULL;
	free_token(split);
	split = NULL;
	return (result);
}

static t_token	*find_token_by_type(t_token *tokens, int type)
{
	while (tokens != NULL)
	{
		if (tokens->type == type)
			return (tokens);
		tokens = tokens->next;
	}
	return (NULL);
}