-
Notifications
You must be signed in to change notification settings - Fork 20
/
clex.c
96 lines (92 loc) · 1.43 KB
/
clex.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
char yytext[100];
/* for debug */
int getChar()
{
int c;
c = getc(stdin);
return c;
}
void ungetChar(int c)
{
ungetc(c,stdin);
}
int yylex()
{
int c,n;
char *p;
again:
c = getChar();
if (isspace(c)) {
goto again;
}
switch (c) {
case '+':
case '-':
case '*':
case '>':
case '<':
case '(':
case ')':
case '{':
case '}':
case ']':
case '[':
case ';':
case ',':
case '=':
case EOF:
return c;
case '"':
p = yytext;
while ((c = getChar()) != '"') {
*p++ = c;
}
*p = '\0';
yylval.val = makeStr(strdup(yytext));
return STRING;
}
if (isdigit(c)) {
n = 0;
do {
n = n*10 + c - '0';
c = getChar();
} while (isdigit(c));
ungetChar(c);
yylval.val = makeNum(n);
return NUMBER;
}
if (isalpha(c)) {
p = yytext;
do {
*p++ = c;
c = getChar();
} while (isalpha(c));
*p = '\0';
ungetChar(c);
if (strcmp(yytext,"var") == 0) {
return VAR;
} else if (strcmp(yytext,"if") == 0) {
return IF;
} else if (strcmp(yytext,"else") == 0) {
return ELSE;
} else if (strcmp(yytext,"return") == 0) {
return RETURN;
} else if (strcmp(yytext,"while") == 0) {
return WHILE;
} else if (strcmp(yytext,"for") == 0) {
return FOR;
} else if (strcmp(yytext,"println") == 0) {
return PRINTLN;
} else {
yylval.val = makeSymbol(yytext);
return SYMBOL;
}
}
fprintf(stderr,"bad char '%c'\n",c);
exit(1);
}
void yyerror()
{
printf("syntax error near '%s'\n", yytext);
exit(1);
}