-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtokenise.c
More file actions
129 lines (109 loc) · 2.36 KB
/
tokenise.c
File metadata and controls
129 lines (109 loc) · 2.36 KB
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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
#include "simple_shell.h"
#include <assert.h>
/**
* get_double_quoted_str - return a double quoted ("") string.
* @str: pointer to the start of the quoted string.
*
* Return: `view_string` type with the quoted string,
* NULL `view_string` on error.
*/
static view_string get_double_quoted_str(view_string *str)
{
view_string quote = {0};
unsigned char is_escaped = 0;
char c = 0;
assert(str);
assert(str->s && str->i > -1 && str->size > 0);
quote.s = &str->s[str->i];
c = string_readc(str);
assert(c == '"');
c = string_readc(str);
for (quote.size = 1; c > -1; ++quote.size, c = string_readc(str))
{
if (is_escaped == 1)
{
is_escaped = 0;
continue;
}
if (c == '\\')
is_escaped = 1;
if (c == '"')
break;
}
if (c != '"')
{
quote.size = 0;
quote.s = NULL;
return (quote);
}
++quote.size;
return (quote);
}
/**
* get_single_quoted_str - return a single quoted (') string.
* @str: pointer to the start of the quoted string.
*
* Return: `view_string` type with the quoted string,
* NULL `view_string` on error.
*/
static view_string get_single_quoted_str(view_string *str)
{
view_string quote = {0};
char c = 0;
assert(str);
assert(str->s && str->i > -1 && str->size > 0);
quote.s = &str->s[str->i];
c = string_readc(str);
assert(c == '\'');
c = string_readc(str);
for (quote.size = 0; c > -1 && c != '\'';
++quote.size, c = string_readc(str))
;
if (c != '\'')
{
quote.size = 0;
quote.s = NULL;
return (quote);
}
++quote.size;
return (quote);
}
/**
* tokenise - parse a string into shell tokens.
* @command_str: the string to parse.
* @size: size of the string in bytes.
*
* Return: a queue of the parsed tokens.
*/
queue *tokenise(const char *const command_str, intmax_t size)
{
view_string str = {0}, tok = {0};
queue *tokens = NULL;
if (!command_str || size < 1)
return (NULL);
tokens = queue_new();
if (!tokens)
return (NULL);
str.s = command_str;
str.size = size;
tok = _strtok(&str, " \t");
while (tok.s)
{
if (*tok.s == '"')
{
str.i -= tok.size;
tok = get_double_quoted_str(&str);
}
if (*tok.s == '\'')
{
str.i -= tok.size;
tok = get_single_quoted_str(&str);
}
if (!tok.s)
return (queue_delete(tokens, string_delete));
if (!enqueue(tokens, &tok, string_dup))
return (queue_delete(tokens, string_delete));
tok = _strtok(&str, NULL);
}
return (tokens);
}