-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlexer.c
More file actions
76 lines (65 loc) · 1.43 KB
/
lexer.c
File metadata and controls
76 lines (65 loc) · 1.43 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
#include "shell.h"
void strapp(char **dstp, const char *src) {
assert(dstp != NULL);
if (*dstp == NULL) {
*dstp = strdup(src);
} else {
size_t s = strlen(*dstp) + strlen(src) + 1;
*dstp = realloc(*dstp, s);
strcat(*dstp, src);
}
}
token_t *tokenize(char *s, int *tokc_p) {
int capacity = 10;
int ntoks = 0;
token_t *tokvec = malloc(sizeof(token_t) * (capacity + 1));
while (*s != 0) {
/* Consume whitespace characters. */
if (isspace(*s)) {
*s++ = 0;
continue;
}
/* Make sure there's enough space to add new token. */
if (ntoks == capacity) {
capacity *= 2;
tokvec = realloc(tokvec, sizeof(token_t) * (capacity + 1));
}
size_t l = strcspn(s, " |&<>;!");
if (l > 0) {
tokvec[ntoks++] = s;
s += l;
continue;
}
token_t tok;
if (s[0] == '|') {
if (s[1] == '|') {
*s++ = 0;
tok = T_OR;
} else {
tok = T_PIPE;
}
} else if (s[0] == '&') {
if (s[1] == '&') {
*s++ = 0;
tok = T_AND;
} else {
tok = T_BGJOB;
}
} else if (s[0] == '<') {
tok = T_INPUT;
} else if (s[0] == '>') {
tok = T_OUTPUT;
} else if (s[0] == ';') {
tok = T_COLON;
} else if (s[0] == '!') {
tok = T_BANG;
} else {
continue;
}
*s++ = 0;
tokvec[ntoks++] = tok;
}
tokvec[ntoks] = NULL;
*tokc_p = ntoks;
return tokvec;
}