forked from YanShulinjj/Sample-Compiler
-
Notifications
You must be signed in to change notification settings - Fork 0
/
operator_first.py
378 lines (342 loc) · 14.6 KB
/
operator_first.py
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
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
# -*- coding:utf-8 -*-
# @Time : 2020-05-23 11:43
# @Author : Rage
# @File : operator_first.py
class Oper_First:
def __init__(self, input_str="", grammer=""):
self.scanf_process(input_str, grammer)
def scanf_process(self, input_str="", grammer=""):
# 测试样例文法
if grammer:
grammer = grammer.split('\n')
# print(grammer)
for index, g in enumerate(grammer):
grammer[index] = g.split("->")
if grammer[0][1][0] != '#':
t = ['S']
t.append('#'+str(grammer[0][0][0])+'#')
grammer.insert(0, t)
# print(grammer)
self.grammar = grammer
else:
self.grammar = [["A", "#E#"],
["E", "E+T"],
["E", "T"],
["T", "T*F"],
["T", "F"],
["F", "P|F"],
["F", "P"],
["P", "(E)"],
["P", "i"]]
if input_str:
self.input_str = input_str+"#"
else:
self.input_str = "i+i#"
#返回所有的左边的非终结符
def get_state(self):
result = []
for i in self.grammar:
if i[0] not in result:
result.append(i[0])
return result
def get_firstvt(self):
state = self.get_state()
# print(state)
# 初始化FIRST表
firstvt_table = {i:[] for i in state}
# print(firstvt_table)
for i in state:
result = self.get_first_recursion(i)
firstvt_table[i].extend(result)
# print(firstvt_table)
return firstvt_table
# First集合
# P->a...或者P->Qa...
def get_first_recursion(self, target):
result = []
for g in self.grammar:
# 当前要推导的符号和式子相同
if g[0] == target:
# 判断是否为终结符号
# P->a...
if g[1][0].islower() or not g[1][0].isalpha():
for i in g[1][0]:
if i not in result:
result.extend(i)
else:
# P->Qa...
# 若为非终结符号,进行递归查询
# 若非终结符号为自身,则不进行递归查询
if target != g[1][0]:
temp = self.get_first_recursion(g[1][0])
for i in temp:
if i not in result:
result.extend(i)
# 若后续有终结符号,则也加入
if len(g[1]) >= 2:
if g[1][1].islower() or g[1][1].isalpha() == False:
for i in g[1][1]:
if i not in result:
result.extend(i)
return result
def get_lastvt(self):
# 获取FIRST中的状态集合
state = self.get_state()
# 初始化FIRST表
lastvt_table = {i: [] for i in state}
# print(lastvt_table)
for i in state:
result = self.get_last_recursion(i)
lastvt_table[i].extend(result)
# print(lastvt_table)
return lastvt_table
# P->...a或者P->...aQ
def get_last_recursion(self, target):
result = []
for g in self.grammar:
# 当前要推导的符号和式子相同
if g[0] == target:
# 判断是否为终结符号
# P->...a
if g[1][-1].islower() or g[1][-1].isalpha() == False:
# print(g[1][-1])
for i in g[1][-1]:
if i not in result:
result.extend(i)
else:
# P->...aQ
# 若为非终结符号
# 若非终结符号为自身,则不进行递归查询
if target != g[1][-1]:
temp = self.get_last_recursion(g[1][-1])
for i in temp:
if i not in result:
result.extend(i)
# 若后续有终结符号,则也加入
if len(g[1]) >= 2:
# print(g[1][-2])
if g[1][-2].islower() or g[1][-2].isalpha() == False:
for i in g[1][-2]:
if i not in result:
result.extend(i)
return result
# 得到firstvt、lastvt所有的终极符
def get_priority_state(self, firstvt, lastvt):
state = []
for i in firstvt.values():
state += i
for i in lastvt.values():
state += i
state = list(set(state))
# print(state)
return state
# 确定符号的位置
def get_x_y(self, c_x, c_y, state):
# 得到行坐标
x, y = -1, -1
for i in range(len(state)):
if c_x == state[i]:
x = i
for i in range(len(state)):
if c_y == state[i]:
y = i
return x, y
# 得到优先关系表
def get_priority_table(self, firstvt, lastvt):
# 标记该文法是否符合算法优先文法任一终结符号之间至多只有一种关系
isflag = True
state = self.get_priority_state(firstvt, lastvt)
# 初始化预测分析表
table = [["0" for col in range(len(state))] for row in range(len(state))]
# 寻找=关系
# P->...ab...或者P->...aQb...
for g in self.grammar:
# 得到该文法语句长度
length = len(g[1])
for i in range(len(g[1])):
if i + 2 > length - 1:
break
if (g[1][i] == g[1][i + 2] and g[1][i] == "#") or (g[1][i] == "(" and g[1][i + 2] == ")"):
x, y = self.get_x_y(g[1][i], g[1][i + 2], state)
if table[x][y] != "0":
isflag = False
table[x][y] = "="
# 寻找<关系
# P->...aR...而R->b...或R->Qb...
for g in self.grammar:
# 得到该文法的长度
length = len(g[1])
for i in range(len(g[1])):
# 若出现数字越界,跳出
if i + 1 > length - 1:
break
# 如果该符号是终结符号且下一位是非终结符号(右左)
if g[1][i] in state and g[1][i + 1] not in state:
# 取出FIRSTVT的元素,对关系表进行修改
temp = firstvt[g[1][i + 1]]
for t in temp:
x, y = self.get_x_y(t, g[1][i], state)
if table[y][x] != "0":
isflag = False
table[y][x] = "<"
# 寻找>关系
# P->...Rb...而R->...a或R->...aQ
for g in self.grammar:
# 得到该文法的长度
length = len(g[1])
for i in range(len(g[1])):
# 若出现数字越界,跳出
if i + 1 > length - 1:
break
# 如果该符号是终结符号且下一位是非终结符号
if g[1][i] not in state and g[1][i + 1] in state:
# 取出LASTVT的元素,对关系表进行修改
temp = lastvt[g[1][i]]
for t in temp:
x, y = self.get_x_y(t, g[1][i + 1], state)
if table[x][y] != "0":
isflag = False
table[x][y] = ">"
return table, state, isflag
def statute(self, input, symbol):
# 用来记录标志位规约情况
for g in self.grammar:
#判断是否在文法中
if len(g[1]) == len(input) and symbol in g[1]:
# 用来进行符号规约
count = 0
for x in range(len(g[1])):
if g[1][x] == symbol:
count += 1
elif str(g[1][x]).isupper() and str(input[x]).isupper():
count += 1
# 查看是否能进行规约
if count == len(g[1]):
return True
elif symbol.isalpha():
return True
return False
# 使用算符优先表分析输入串
def analysis_operator(self, table, state):
steps = []
# 初始化分析栈
ana_stack = []
# 输入串栈
input_stack = []
# 对栈初始化,入栈
ana_stack.append("#")
input_stack.extend(list(reversed((self.input_str))))
# print(input_stack)
# 用来打印输出顺序
show_count = 1
steps.append(["步骤", "栈", "优先关系", "剩余输入串", "移进或规约"])
# print("%s %8s %8s %8s %8s" % ("步骤", "栈", "优先关系", "剩余输入串", "移进或规约"))
while True:
step = []
step.append(show_count)
# print(show_count, end="")
show_count += 1
step.append("".join(ana_stack))
# print("%12s" % ("".join(ana_stack)), end="")
# 充当指针,指向当前栈内参与比较的元素,默认是栈顶
indicator = len(ana_stack) - 1
# 如果为非终结符号,向栈底读取字符,至到读取到非终结字符
if ana_stack[indicator].isupper():
for i in reversed(range(len(ana_stack) - 1)):
if ana_stack[i].isupper() == False:
indicator = i
break
# print(ana_stack[indicator], input_stack[-1])
# 对栈顶符号进行比较,
if input_stack[-1].isalpha() and len(input_stack[-1]) == 1:
# print(input_stack[-1])
x, y = self.get_x_y(ana_stack[indicator], 'i', state)
else:
x, y = self.get_x_y(ana_stack[indicator], input_stack[-1], state)
relationship = table[x][y]
step.append(relationship)
# print("%8s" % (relationship), end="")
step.append("".join(list((reversed("".join(input_stack))))))
# print("%14s" % "".join(list((reversed("".join(input_stack))))), end="")
if (relationship == "<" or relationship == "=") and len(input_stack) != 1:
step.append("移进")
# print("%8s" % ("移进"))
elif relationship == ">":
step.append("归约")
# print("%8s" % ("归约"))
else:
step.append("接受")
# print("%8s" % ("接受"))
# break
steps.append(step)
# 如果运算栈内只剩下非终结符号一个,并且输入栈无符号,则规约成功
if len(ana_stack) == 2 and len(input_stack) == 1:
break
#
# 执行移入操作
if relationship == "<" or relationship == "=":
ana_stack.append(input_stack.pop())
# print(input_stack, ana_stack)
# break
# 执行规约操作
elif relationship == ">":
if indicator == len(ana_stack) - 1:
# 如果规约符号位于栈顶,则只将栈顶的非终结符号进行规约
if self.statute(ana_stack[indicator], ana_stack[indicator]):
ana_stack.pop()
ana_stack.append("N")
else:
# 如果不位于栈顶,则将运算符左右两边的符号一起进行规约
if self.statute(ana_stack[indicator - 1:indicator + 2], ana_stack[indicator]):
ana_stack.pop()
ana_stack.pop()
ana_stack.pop()
ana_stack.append("N")
return steps
def judge_grammar(self):
# 得到FIRSTVT集合
firstvt = self.get_firstvt()
# 得到LASTVT集合
lastvt = self.get_lastvt()
# 得到算符优先关系表
table, state, isflag = self.get_priority_table(firstvt, lastvt)
return isflag, firstvt, lastvt, table, state
def run(self):
print("进行构造的文法G[S]")
for i in self.grammar:
print("%s -> %s" % (i[0], i[1]))
print("===============================================", end="\n")
# 得到FIRSTVT集合
firstvt = self.get_firstvt()
print("该文法的FIRSTVT:")
for key, value in firstvt.items():
print("FIRSTVT(%s) = {%s}" % (key, str(value)[1:-1]))
print("===============================================", end="\n")
# 得到LASTVT集合
lastvt = self.get_lastvt()
print("该文法的LASTVT集合:")
for key, value in lastvt.items():
print("LASTVT(%s) = {%s}" % (key, str(value)[1:-1]))
print("===============================================", end="\n\n")
# 得到算符优先关系表
table, state, isflag = self.get_priority_table(firstvt, lastvt)
if not isflag:
print("该文法是否属于算符优先文法:%s" % (str(isFlag)), end="\n\n")
else:
print("%27s" % ("算符优先关系表"))
print("---------------------------------------------------------")
for i in state:
print("%8s" % i, end="")
print()
for i in range(len(table)):
print("%s" % state[i], end="")
print("%7s" % table[i][0], end="")
for x in table[i][1:]:
print("%8s" % x, end="")
print("")
# 对文法进行算符分析
print("接下来对输入串 %16s 进行规约" % (self.input_str))
print("---------------------------------------------------")
steps = self.analysis_operator(table, state)
# print(steps)
return steps