-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlr1.py
174 lines (130 loc) · 5.49 KB
/
lr1.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
#! /usr/bin/env python3
from copy import deepcopy
from typing import *
from grammar import *
from production import *
class State:
__slots__ = ['productions', 'str']
def __init__(self, production: Optional[Production] = None):
self.productions: List[ProductionWithPosAndTail] = list()
if production:
self.productions.append(ProductionWithPosAndTail(production.target, production.rule, 0).add_tail(['#']))
self.str: str = ''
def add_production(self, production: Production):
if isinstance(production, ProductionWithPosAndTail):
to_add = production
else:
to_add = ProductionWithPosAndTail(production.target,
production.rule,
0).add_tail(['#'])
try:
ind = self.productions.index(to_add)
self.productions[ind].merge(to_add)
except ValueError:
self.productions.append(to_add)
def closure(self, grammar: Grammar):
updated = True
while updated:
updated = False
for production in self.productions:
if production.is_shift():
next_t = production.rule[production.pos]
if not grammar.is_terminal(next_t):
tails: Set[str] = set()
for t in production.rule[production.pos + 1:]:
tails = tails.union(grammar.first[t])
if '' not in grammar.first[t]:
break
else:
tails = tails.union(production.tail)
tails: List[str] = list(tails)
for p in grammar.production[next_t]:
p_pos = ProductionWithPosAndTail(p.target, p.rule, 0)
p_pos.add_tail(tails)
try:
ind = self.productions.index(p_pos)
l1 = len(self.productions[ind].tail)
self.productions[ind].add_tail(tails)
if l1 != len(self.productions[ind].tail):
updated = True
except ValueError:
self.productions.append(p_pos)
updated = True
self.productions.sort(key=lambda x: str(x))
self.update_str()
def next(self, grammar: Grammar):
results: Dict[str, State] = {}
for production in self.productions:
if production.is_shift():
next_t = production.rule[production.pos]
if next_t not in results:
results[next_t] = State()
results[next_t].add_production(
ProductionWithPosAndTail(production.target,
production.rule,
production.pos + 1).add_tail(production.tail))
for _, state in results.items():
state.closure(grammar)
return results
def update_str(self):
self.str = '[' + '; '.join(map(str, self.productions)) + ']'
def __eq__(self, other):
return self.str == other.str
def __str__(self):
return self.str
def __repr__(self):
return str(self)
def __hash__(self):
return hash(tuple(self.productions))
class LR1Machine:
__slots__ = ['grammar', 'table', 'states']
def __init__(self, target: str):
self.grammar: Grammar = Grammar(target)
self.states: List[State] = []
self.table: Dict[int, Dict[str, int]] = {}
def add_production(self, *args, **kwargs):
self.grammar.add_production(*args, **kwargs)
return self
def get_state(self, s: State):
try:
return self.states.index(s)
except ValueError:
self.states.append(s)
return len(self.states) - 1
def calc(self):
self.grammar.calc_first()
self.grammar.calc_follow()
begin_state: State = State()
for production in self.grammar.production[self.grammar.target]:
begin_state.add_production(production)
begin_state.closure(self.grammar)
self.states.append(begin_state)
for ind, state in enumerate(self.states):
nexts = state.next(self.grammar)
self.table[ind] = {}
for term, next_state in nexts.items():
ind1 = self.get_state(next_state)
self.table[ind][term] = ind1
def to_string(self):
ret = []
for ind, state in enumerate(self.states):
ret.append(str(ind))
ret.append(' ')
ret.append(str(state))
ret.append('\n')
for begin, turns in self.table.items():
ret.append(str(begin))
ret.append(' ')
for term, end in turns.items():
ret.append(term + '->' + str(end) + ' ')
ret.append('\n')
return ''.join(ret)
if __name__ == '__main__':
grammar = LR1Machine('S\'') \
.add_production(Production('S\'', ['S'])) \
.add_production(Production('S', ['S', 'S', '+'])) \
.add_production(Production('S', ['S', 'S', '*'])) \
.add_production(Production('S', ['(', 'S', ')'])) \
.add_production(Production('S', ['a']))
grammar.calc()
print(grammar.to_string())