-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmeaning_analysis.py
More file actions
258 lines (223 loc) · 10.6 KB
/
meaning_analysis.py
File metadata and controls
258 lines (223 loc) · 10.6 KB
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
# @Author : Edlison
# @Date : 11/30/20 23:43
import os
from typing import List
from compiler_exception import GrammarAnalyseException, MeaningAnalyseException
class Node:
def __init__(self, place):
self.place = place
class Grammar:
def __init__(self, id: int, left: str, right: str):
"""
As same sa Grammar in grammar_analysis.
Args:
Returns:
@Author : Edlison
@Date : 12/1/20 02:48
"""
self.id = id # 文法序号
self.left = left # 文法左半部分
self.right = right # 文法右半部分
self.terminal = []
self.non_terminal = []
for each in right.split(' '):
if each.isupper():
self.non_terminal.append(each)
else:
self.terminal.append(each)
def __str__(self):
return 'ID: {} \t Left: {} \t Right: {} \n end: {} \n not_end: {} \n'.format(
self.id, self.left, self.right, self.terminal, self.non_terminal)
class PriorityTable:
def __init__(self):
"""
As same as PriorityTable in grammar_analysis.
Args:
Returns:
@Author : Edlison
@Date : 12/1/20 02:48
"""
self.terminal = [] # 所有的非终结符
self.firstvt: (str, set) = {}
self.lastvt: (str, set) = {}
self.relation = {0: 'ni', 1: '=', 2: '<', 3: '>'}
def is_in_terminal(self, s):
for each in self.terminal:
if s == each:
return True
return False
class MeaningAnalyzer:
def __init__(self, grammar_table_path):
self.text = ''
self.grammar_table: List[Grammar] = []
self.priority_table: PriorityTable = PriorityTable()
self._load_grammar_table(grammar_table_path)
self._gen_firstvt_lastvt()
self._gen_priority_table()
def _load_grammar_table(self, path):
if not os.path.exists(path):
raise GrammarAnalyseException('文法表不存在')
with open(path) as f:
grammar_list = f.read()
grammar_list = eval(grammar_list)
for each in grammar_list:
self.grammar_table.append(Grammar(each[0], each[1], each[2]))
def _gen_firstvt_lastvt(self):
# 生成priority_table独立的firstvt lastvt
for each_grammar in self.grammar_table:
if not self.priority_table.firstvt.get(each_grammar.left) and not self.priority_table.lastvt.get(
(each_grammar.left)):
self.priority_table.firstvt[each_grammar.left] = set()
self.priority_table.lastvt[each_grammar.left] = set()
# 考虑只是终结符的情况
for each_grammar in self.grammar_table:
right = each_grammar.right.split(' ')
# firstvt
if not right[0].isupper() and right[0] is not '?':
self.priority_table.firstvt[each_grammar.left].add(right[0])
else:
if len(right) > 1:
if not right[1].isupper():
self.priority_table.firstvt[each_grammar.left].add(right[1])
# lastvt
last = len(right) - 1
if not right[last].isupper() and right[last] is not '?':
self.priority_table.lastvt[each_grammar.left].add((right[last]))
else:
if len(right) > 1:
if not right[last - 1].isupper():
self.priority_table.lastvt[each_grammar.left].add(right[last - 1])
# 考虑非终结符开头结尾的情况
for each_grammar in reversed(self.grammar_table):
if each_grammar.right[0].isupper():
self.priority_table.firstvt[each_grammar.left].update(
self.priority_table.firstvt[each_grammar.right[0]])
if each_grammar.right[-1].isupper():
self.priority_table.lastvt[each_grammar.left].update(self.priority_table.lastvt[each_grammar.right[-1]])
def _gen_priority_table(self):
# Table拿到所有终结符
for each_grammar in self.grammar_table:
terminal = each_grammar.terminal
for each_terminal in terminal:
if not self.priority_table.is_in_terminal(each_terminal) and each_terminal is not '?':
self.priority_table.terminal.append(each_terminal)
row_col = len(self.priority_table.terminal)
table = [[self.priority_table.relation[0] for _ in range(row_col)] for _ in range(row_col)]
for each_grammar in self.grammar_table:
right = each_grammar.right.split(' ')
for i, _ in enumerate(right[:-1]):
if not right[i].isupper() and not right[i + 1].isupper():
row = self.priority_table.terminal.index(right[i])
col = self.priority_table.terminal.index(right[i + 1])
table[row][col] = self.priority_table.relation[1] # 1: '='
if i < len(right) - 2 and not right[i].isupper() and not right[i + 2].isupper():
row = self.priority_table.terminal.index(right[i])
col = self.priority_table.terminal.index(right[i + 2])
table[row][col] = self.priority_table.relation[1] # 1: '='
if not right[i].isupper() and right[i + 1].isupper():
row = self.priority_table.terminal.index(right[i])
for each_firstvt in self.priority_table.firstvt[right[i + 1]]:
col = self.priority_table.terminal.index(each_firstvt)
table[row][col] = self.priority_table.relation[2] # 2: '<'
if right[i].isupper() and not right[i + 1].isupper():
col = self.priority_table.terminal.index(right[i + 1])
for each_lastvt in self.priority_table.lastvt[right[i]]:
row = self.priority_table.terminal.index(each_lastvt)
table[row][col] = self.priority_table.relation[3] # 3: '>'
# raise GrammarAnalyseException('优先表无此关系')
self.table = table
def analyse(self, word_token: List):
analyse_stack = ['#']
buffer_input = word_token
buffer_input.append('#')
relation_stack = []
nextquad = 100
newtemp = 0
newid = 0
tree_stack = []
while analyse_stack != ['#', 'P', '#']:
if analyse_stack[-1] in self.priority_table.terminal:
last_non_terminal = analyse_stack[-1]
else:
last_non_terminal = analyse_stack[-2]
next_ch = buffer_input[0]
priority = self.table[self.priority_table.terminal.index(last_non_terminal)][
self.priority_table.terminal.index(next_ch)]
if priority is '<' or priority is '=': # 如果是<或=直接接上
analyse_stack.append(next_ch)
buffer_input.pop(0)
relation_stack.append(priority)
else: # 进行规约
relation_begin = self._find_last_less(relation_stack)
analyse_begin = self._find_analyse_begin(analyse_stack, relation_begin)
N = analyse_stack[analyse_begin:] # 拿到需要规约的部分
flag = 0
while flag == 0: # 对语句进行持续规约 到最顶层语句
flag = 1
for each_grammar in self.grammar_table:
right = each_grammar.right.split(' ')
if N == right:
N = [each_grammar.left]
# 判断表达式翻译
if each_grammar.id == 1:
print(nextquad, end='')
nextquad += 1
self._emit('=', tree_stack.pop(), Node(''), Node('id.name'))
elif each_grammar.id == 2:
node = Node('T' + str(newtemp))
newtemp += 1
print(nextquad, end='')
nextquad += 1
self._emit('+', tree_stack.pop(), tree_stack.pop(), node)
tree_stack.append(node)
elif each_grammar.id == 3:
node = Node('T' + str(newtemp))
newtemp += 1
print(nextquad, end='')
nextquad += 1
self._emit('*', tree_stack.pop(), tree_stack.pop(), node)
tree_stack.append(node)
elif each_grammar.id == 4:
...
elif each_grammar.id == 5:
tree_stack.append(Node('id' + str(newid)))
newid += 1
else: # 待加入其他语法翻译
raise MeaningAnalyseException('未找到相关语义')
flag = 0
break
if len(N) != 1:
raise MeaningAnalyseException('未找到规约语法')
analyse_stack = analyse_stack[:analyse_begin] # 删掉需要规约的最左素短语
relation_stack = relation_stack[:relation_begin] # 删掉规约用过的符号
analyse_stack.append(N[0]) # 加上规约后的
def _emit(self, op: str, node1: Node, node2: Node, node_current: Node):
print('(' + op + ', ' + node1.place + ', ' + node2.place + ', ' + node_current.place + ')')
def _find_last_less(self, relation_stack):
res = -1
for index, value in enumerate(relation_stack):
if value == '<':
res = index
if res == -1:
raise GrammarAnalyseException('规约出错,没有<')
else:
return res
def _find_analyse_begin(self, analyse_stack, relation_begin):
res = relation_begin + 1
index = 0
for each in analyse_stack:
if res == 0:
break
if not each.isupper():
res -= 1
index += 1
return index
def show_table(self):
for i in self.priority_table.terminal:
print('\t' + i, end='')
print()
for i, each in enumerate(self.table):
print(self.priority_table.terminal[i] + '\t', end='')
for j in each:
print(j + '\t', end='')
print()