-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathlexer.c
150 lines (132 loc) · 2.3 KB
/
lexer.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
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
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
#include "rdp_calc.h"
int lexer_atoi(char **expr)
{
int res;
res = 0;
while (**expr >= '0' && **expr <= '9')
res = res * 10 + *(*expr)++ - '0';
return (res);
}
token_t getToken(char c)
{
switch (c)
{
case '(':
return opar;
case ')':
return cpar;
case '+':
return plus;
case '-':
return minus;
case '*':
return mult;
case '/':
return div_;
default:
return unknown;
}
}
lexer_t *lexer(char *expr)
{
lexer_t *tokens;
tokens = new_list();
while (*expr)
{
if (isspace(*expr)) {
expr++;
continue ;
}
else if (isdigit(*expr)) {
push_back(tokens, new_node(number, lexer_atoi(&expr)));
}
else {
token_t token = getToken(*expr);
if (token == unknown)
{
error("lexer: invalid token '%c'\n", *expr);
list_clear(tokens);
return NULL;
}
push_back(tokens, new_node(token, none));
expr++;
}
}
push_back(tokens, new_node(endofexpr, none));
return tokens;
}
/**
* @brief lexer utils bellow
* All I need to create/destroy a list of tokens
*/
lexer_t *new_list(void)
{
lexer_t *tokens;
tokens = (lexer_t *)malloc(sizeof(lexer_t));
tokens->len = 0;
tokens->top = NULL;
tokens->bottom = NULL;
return (tokens);
}
Node *new_node(token_t tok, int val)
{
Node *new;
new = (Node *)malloc(sizeof(Node));
new->tok = tok;
new->val = val;
new->next = NULL;
new->prev = NULL;
return (new);
}
Node *push_front(lexer_t *tokens, Node *new)
{
new->next = tokens->top;
if (tokens->top)
tokens->top->prev = new;
else
tokens->bottom = new;
tokens->top = new;
(tokens->len)++;
return (new);
}
Node *push_back(lexer_t *tokens, Node *new)
{
new->prev = tokens->bottom;
if (tokens->bottom)
tokens->bottom->next = new;
else
tokens->top = new;
tokens->bottom = new;
(tokens->len)++;
return (new);
}
Node *del_front(lexer_t *tokens)
{
Node *ret;
if (tokens->len == 0)
return (NULL);
ret = tokens->top;
tokens->top = tokens->top->next;
if (tokens->top)
tokens->top->prev = NULL;
(tokens->len)--;
return (free(ret), ret);
}
Node *del_back(lexer_t *list)
{
Node *ret;
if (list->len == 0)
return (NULL);
ret = list->bottom;
list->bottom = list->bottom->prev;
if (list->bottom)
list->bottom->next = NULL;
(list->len)--;
return (free(ret), ret);
}
void list_clear(lexer_t *list)
{
while (list->len)
del_front(list);
free(list);
}