-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlexer.c
120 lines (115 loc) · 2.61 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
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include "AST.h"
#define INITIAL_STR_LEN (128)
int take() {
int c;
while (isspace(c = getc(stdin))) { }
return c;
}
int yylex() {
int c = take();
if (c == EOF) {
return 0;
}
switch (c) {
case '+':
case '-':
case '*':
case '/':
case '(':
case ')':
case '{':
case '}':
case '[':
case ']':
case ';':
case ',':
return c;
}
if (c == '=') {
int next = getc(stdin);
if (next == '=') {
return OP_EQ;
}
ungetc(next, stdin);
return c;
}
if (c == '<') {
int next = getc(stdin);
if (next == '=') {
return OP_LE;
}
ungetc(next, stdin);
return c;
}
if (c == '>') {
int next = getc(stdin);
if (next == '=') {
return OP_GE;
}
ungetc(next, stdin);
return c;
}
if (c == '!') {
int next = getc(stdin);
if (next == '=') {
return OP_NEQ;
}
ungetc(next, stdin);
return c;
}
if (c == '"') {
char *str = (char *)malloc(sizeof(char) * INITIAL_STR_LEN);
char *s = str;
c = getc(stdin); // skip current '"'
for (; c != '"'; c = getc(stdin), ++s) {
*s = c;
}
*s = '\0';
yylval.val = AST_makeString(strdup(str));
free(str);
return STRING;
}
if (isdigit(c)) {
int n;
for (n = 0; isdigit(c); c = getc(stdin)) {
n = n * 10 + (c - '0');
}
ungetc(c, stdin);
yylval.val = AST_makeValue(n);
return NUMBER;
}
if (isalpha(c)) {
char *str = (char *)malloc(sizeof(char) * MAX_SYMBOL_LEN);
char *s = str;
for (; isalpha(c); c = getc(stdin), ++s) {
*s = c;
}
*s = '\0';
ungetc(c, stdin);
int retval = 0;
if (strcmp(str, "println") == 0) {
retval = PRINTLN;
} else if (strcmp(str, "var") == 0) {
retval = VAR;
} else if (strcmp(str, "return") == 0) {
retval = RETURN;
} else if (strcmp(str, "for") == 0) {
retval = FOR;
} else {
yylval.val = AST_makeSymbol(strdup(str));
retval = SYMBOL;
}
free(str);
return retval;
}
fprintf(stderr, "unexpected token %c\n", c);
abort();
}
int yyerror(const char *s) {
fprintf(stderr, "%s\n", s);
return 0;
}
/* vim: set et ts=4 sts=4 sw=4: */