-
Notifications
You must be signed in to change notification settings - Fork 0
/
Example_ArithmeticExpressionParser.cc
187 lines (182 loc) · 3.99 KB
/
Example_ArithmeticExpressionParser.cc
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
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
#include "./LL1.hpp"
#include "./LR1.hpp"
#include <bits/stdc++.h>
using namespace std;
#define debug(x) std::cout << #x << " is " << (x) << '\n'
const char* nc;
char isConstNum(double* n)
{
double num = 0;
double f = 1.0 / 10;
int p = 0;
bool isnegi = false;
char state = -1;
bool flag = false;
while (1)
{
switch (state)
{
case -1:
if (isdigit(*nc))
{
state = 0;
}
else
flag = true;
break;
case 0:
if (isdigit(*nc))
{
while (isdigit(*nc))
{
num = num * 10 + *nc - '0';
++nc;
}
state = 0;
}
else if (*nc == '.')
{
state = 1;
++nc;
}
else if (*nc == 'e')
{
state = 3;
++nc;
}
else
flag = true;
break;
case 1:
if (isdigit(*nc))
state = 2;
else
flag = true;
break;
case 2:
if (isdigit(*nc))
{
while (isdigit(*nc))
{
num += (*nc - '0') * f;
f /= 10;
++nc;
}
}
else if (*nc == 'e')
{
state = 3;
++nc;
}
else
flag = true;
break;
case 3:
if (*nc == '+')
{
state = 4;
++nc;
}
else if (*nc == '-')
{
isnegi = true;
state = 4;
++nc;
}
else if (isdigit(*nc))
{
state = 6;
}
else
flag = true;
break;
case 4:
if (isdigit(*nc))
state = 5;
else
flag = true;
break;
case 5:
if (isdigit(*nc))
{
while (isdigit(*nc))
{
p = p * 10 + *nc - '0';
++nc;
}
}
else
flag = true;
break;
default:
flag = true;
break;
}
if (flag)
break;
}
p = (isnegi == true) ? -p : p;
num *= pow(10, p);
*n = num;
return state;
}
signed main(void)
{
Parser::LR1 p("grammar/2.txt");
Parser::LL1 p2("grammar/2.txt");
string str("xx+y10*(33*a+0.7)-b/523e-2");
// cin >> str;
nc = str.data();
string token;
double tmp;
while (*nc)
{
while (isspace(*nc))
nc++;
if (*nc == 0)
break;
switch (*nc)
{
case '+':
case '-':
case '*':
case '/':
case '(':
case ')':
token.push_back(*nc);
token.push_back(' ');
nc++;
break;
default:
if (isdigit(*nc))
{
switch (isConstNum(&tmp))
{
case 0:
case 2:
case 5:
token += "Num ";
break;
default:
cout << "输入数字有误!" << endl;
return 1;
break;
}
}
else if (*nc == '_' or isalpha(*nc))
{
while (*nc == '_' or isalnum(*nc))
{
nc++;
}
token += "Id ";
}
break;
}
}
// cout << token << endl;
assert(p.parse(token));
assert(p2.parse(token));
cout << "Success!" << endl;
return 0;
}