aboutsummaryrefslogtreecommitdiff
path: root/src/repl.c
blob: 3988a4268b8c241d9f58782940b2b1e24ccc7ca4 (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
/* ************************************************************************** */
/*                                                                            */
/*                                                        :::      ::::::::   */
/*   repl.c                                             :+:      :+:    :+:   */
/*                                                    +:+ +:+         +:+     */
/*   By: chuhlig <chuhlig@student.42.fr>            +#+  +:+       +#+        */
/*                                                +#+#+#+#+#+   +#+           */
/*   Created: 2024/06/24 16:07:04 by dkaiser           #+#    #+#             */
/*   Updated: 2025/01/23 17:42:33 by chuhlig          ###   ########.fr       */
/*                                                                            */
/* ************************************************************************** */

#include "../include/minishell.h"
#include "token.h"

t_token *shallow_copy_token(t_token *token)
{
	if (token == NULL)
		return (NULL);

	if (token->type == STRING_TOKEN)
		return (new_str_token(token->content.string, NULL, NULL));
	else if (token->type == REDIR_TOKEN)
		return (new_redir_token(token->content.redir_type, NULL, NULL));
	else
		return (new_redir_token(token->type, NULL, NULL));
}

t_token *shallow_copy_tokens(t_token *tokens)
{
	t_token *result;
	t_token *cur;

	result = shallow_copy_token(tokens);
	if (!result)
		return (NULL);
	cur = result;
	while (tokens->next != NULL)
	{
		tokens = tokens->next;
		cur->next = shallow_copy_tokens(tokens);
		cur = cur->next;
	}
	return (result);
}

void	free_repl(char *input, t_node *ast)
{
	free(input);
	if(ast)
		free_node(ast);
}

void	repl(const char *prompt, t_env **env, int *promptflag)
{
	char	*input;
	t_token	*token_list;
	t_node	*ast;
	t_token *tokens_copy;

	(*promptflag)++;
	while (1)
	{
		input = readline(prompt);
		if (input == NULL)
		{
			if (*promptflag > 1)
				(*promptflag)--;
			printf("exit\n");
			break ;
		}
		if (input[0] == '\0')
			continue ;
		add_history(input);
		token_list = NULL;
		tokenizer(input, &token_list, '\0');
		tokens_copy = shallow_copy_tokens(token_list);
		free_tokens(tokens_copy);
		// print_token_list(token_list);
		ast = parse(token_list, env);
		if (ast)
			set_return_code(eval(ast, env), env);
		free_repl(input, ast);
		print_token_list(tokens_copy);
	}
}