-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlexer.c
More file actions
79 lines (65 loc) · 1.39 KB
/
lexer.c
File metadata and controls
79 lines (65 loc) · 1.39 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
#include "ds.h"
static const t_rules g_precedence[UCHAR_MAX] = {
[TOK_DIV] = 3,
[TOK_MULT] = 3,
[TOK_PLUS] = 2,
[TOK_MINUS] = 2,
[TOK_LPAREN] = 1,
[TOK_RPAREN] = 1,
};
void lexer_init(const char *input, t_lexer *lex) {
lex->input = input;
lex->len = ft_strlen(input);
lexer_read(lex);
}
void lexer_read(t_lexer *lex) {
if (!(lex->cursor >= lex->len)) {
lex->ch = lex->input[lex->cursor++];
return;
}
lex->ch = TOK_NUL;
}
void lexer_skip(t_lexer *lex) {
while (lex->ch == TOK_SPACE || lex->ch == TOK_TAB)
lexer_read(lex);
}
void token_create(t_token *tok,t_tok_type type, long data) {
tok->type = type;
tok->data = data;
if (type == TOK_NUM){
tok->pre = -1;
return;
}
tok->pre = g_precedence[data];
}
long lexer_atoi(t_lexer *lex) {
long data;
data = 0;
while (ft_isdigit(lex->ch)) {
data = data * 10 + (lex->ch - ZERO);
lexer_read(lex);
}
return (data);
}
void lexer_next(t_lexer *lex, t_token *token) {
long data = 0;
unsigned char c = 0;
lexer_skip(lex);
if (lex->ch == TOK_NUL)
return token_create(token ,TOK_NUL, 0);
if (ft_isdigit(lex->ch)) {
data = lexer_atoi(lex);
return token_create(token, TOK_NUM, data);
}
if (tok_issign(lex->ch)) {
c = lex->ch;
lexer_read(lex);
return token_create(token, (t_tok_type)c, c);
}
if (tok_isparen(lex->ch)) {
c = lex->ch;
lexer_read(lex);
return token_create(token, (t_tok_type)c, c);
}
lexer_read(lex);
}