-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathlexer_2.c
102 lines (97 loc) · 2.92 KB
/
lexer_2.c
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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* lexer_2.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: phelebra <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2023/06/21 12:36:59 by fvonsovs #+# #+# */
/* Updated: 2023/08/01 17:33:27 by phelebra ### ########.fr */
/* */
/* ************************************************************************** */
#include "minishell.h"
/*
following functions called in lexer()
they tokenize <|> which is later joined with the rest of the args
*/
char **tokenize_opts(char *src, char *delims)
{
t_lexer lex;
char **ret;
int n;
lex.char_i = 0;
lex.word_n = 0;
lex.token_n = 0;
lex.quotes = 0;
lex.quote_c = 0;
if (!src)
return (NULL);
n = count_words_opts(src, delims, &lex);
if (n == -1)
return (NULL);
ret = malloc(sizeof(char *) * (n + 1));
if (ret == NULL)
return (NULL);
fill_array_opts(ret, src, delims, &lex);
ret[n] = NULL;
return (ret);
}
/*
modified count_words, increases the word count (word_n)
at the start of each loop, regardless of whether the
character at the current position (char_i) is a delimiter
*/
int count_words_opts(char *s, char *delims, t_lexer *lex)
{
lex->quotes = 0;
lex->quote_c = 0;
while (s[lex->char_i] != '\0')
{
lex->word_n++;
if (!ft_strchr(delims, s[lex->char_i]))
{
while ((!ft_strchr(delims, s[lex->char_i]) || lex->quotes
|| lex->quote_c) && s[lex->char_i] != '\0')
{
lex->quotes = (lex->quotes + (!lex->quote_c
&& s[lex->char_i] == '\'')) % 2;
lex->quote_c = (lex->quote_c + (!lex->quotes
&& s[lex->char_i] == '\"')) % 2;
lex->char_i++;
}
if (lex->quotes || lex->quote_c)
return (-1);
}
else
lex->char_i++;
}
return (lex->word_n);
}
// modified fill_array, doesnt check for delimiter
char **fill_array_opts(char **ret, char *s, char *delims, t_lexer *lex)
{
lex->quotes = 0;
lex->quote_c = 0;
lex->char_i = 0;
while (s[lex->char_i] != '\0')
{
lex->word_n = lex->char_i;
if (!ft_strchr(delims, s[lex->char_i]))
{
while ((!ft_strchr(delims, s[lex->char_i])
|| lex->quotes || lex->quote_c) && s[lex->char_i])
{
lex->quotes = (lex->quotes + (!lex->quote_c
&& s[lex->char_i] == '\'')) % 2;
lex->quote_c = (lex->quote_c + (!lex->quotes
&& s[lex->char_i] == '\"')) % 2;
lex->char_i++;
}
}
else
lex->char_i++;
ret[lex->token_n++] = ft_substr(s, lex->word_n,
lex->char_i - lex->word_n);
}
return (ret);
}