/
lexer.cpp
144 lines (125 loc) · 2.27 KB
/
lexer.cpp
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
// Egrammar Lexer
#include "EGrammar.h"
char yytext[YYTEXT_MAX]; // Global token text buffer
static int yytextpos = 0;
ifstream fin; // lex input file stream
bool yylexopen(const char filename[])
{
fin.open(filename, ios_base::in);
return fin.is_open();
}
void yytextclear()
{
yytextpos = 0;
yytext[yytextpos] = 0;
}
void yytextappend(int c)
{
if (yytextpos >= YYTEXT_MAX - 1)
return; // ignore char
yytext[yytextpos++] = (char)c;
yytext[yytextpos] = 0; // null sentinel at end
}
int yylex()
{
int c;
while (1)
{
yytextclear();
int c;
while ((c = fin.get()) == ' ' || c == '\t' || c == '\n')
continue;
if (c == '/')
{
if (fin.peek() == '*')
{
fin.get();
while (c = fin.get())
{
if ((c == '*' && fin.peek() == '/') || c == '\n')
break;
}
fin.get();
continue;
}
else
yytext[0]='/';
yytext[1]=0;
return DIVOP; //MULOP be * | /
}
if (c == EOF){
return EOFSY;
}
if (c == ':' && fin.peek() == '=')
{
yytext[0]=c;
yytext[1]=fin.get();
yytext[2]=0;
return ASSIGNOPP;
}
if (c == '('){
yytext[0] = '(';
yytext[1]=0;
return LPAREN;
}
if (c == ')'){
yytext[0] = ')';
yytext[1]=0;
return RPAREN;
}
if (c == '+'){
yytext[0] = '+';
yytext[1]=0;
return ADDOP; //ADDOP can be + | -
}
if (c == '-'){
yytext[0] = '-';
yytext[1]=0;
return SUBOP; //ADDOP can be + | -
}
if (c == '*'){
yytext[0] = '*';
yytext[1]=0;
return MULOP; //MULOP can be * | /
}
if (c >= '0' && c <= '9')
{
int dec = 0;
yytext[0] = c;
int i = 1;
while (((c = fin.get()) >= '0' && c <= '9') || (c == '.'))
{
if (c == '.')
dec++;
if (dec == 2)
throw exception();
yytext[i] = c;
i++;
}
yytext[i]=0;
fin.unget();
return NUMCONST;
}
else
{
yytext[0] = toupper(c);
int i = 1;
while ((c = fin.get()) != ' ' && c != '\t' && c != '\n' && c != EOF && c != ':' && c != '(' && c != ')' && c != '+' && c != '-' && c != '*' && c != '/')
{
yytext[i] = toupper(c);
i++;
}
yytext[i] = 0;
fin.unget();
if (_stricmp(yytext, "read") == 0)
{
return READSY;
}
if (_stricmp(yytext, "write") == 0)
{
return WRITESY;
}
return ID;
}
}
}