-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathgrammar_desugaring.py
215 lines (171 loc) · 6.23 KB
/
grammar_desugaring.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
from collections import namedtuple
import re
class DesugaringError(Exception):
pass
class Empty:
def to_productions(self, builder):
return ((),)
def as_dict(self):
return {
'type': 'empty',
}
class StringTerminal(namedtuple('StringTerminal', ('string',))):
def to_productions(self, builder):
if self.string == '':
return Empty().to_productions(builder)
else:
string = ('string', self.string)
return ((builder.store_terminal(string),),)
def as_dict(self):
return {
'type': 'string',
'string': self.string,
}
class RangeTerminal(namedtuple('StringTerminal', ('min', 'max'))):
def to_productions(self, builder):
regexp = ('regexp', '[{}-{}]'.format(
re.escape(chr(self.min)),
re.escape(chr(self.max)),
))
return ((builder.store_terminal(regexp),),)
def as_dict(self):
return {
'type': 'range_terminal',
'min': self.min,
'max': self.max,
}
class Name(namedtuple('Name', ('name',))):
def to_productions(self, builder):
return ((self.name,),)
def as_dict(self):
return {
'type': 'name',
'name': self.name,
}
class Optional(namedtuple('Optional', ('child',))):
def to_productions(self, builder):
return Alternative((self.child, Empty())).to_productions(builder)
def as_dict(self):
return {
'type': 'optional',
'child': self.child.as_dict(),
}
class ExactRepetition(namedtuple('ExactRepetition', ('count', 'child'))):
def to_productions(self, builder):
return Sequence((self.child,) * self.count).to_productions(builder)
def as_dict(self):
return {
'type': 'exact_repetition',
'count': self.count,
'child': self.child.as_dict(),
}
class RangeRepetition:
def __init__(self, child, min_count=None, max_count=None):
if min_count is None:
min_count = 0
assert (max_count is None) or (min_count <= max_count)
self.child = child
self.min = min_count
self.max = max_count
def to_productions(self, builder):
"""Convert to 'a a a [[[a] a] a]' or 'a a a a*'"""
if self.max is None:
looping_rule_name = builder.new_anonymous_name()
looping_rule = Name(looping_rule_name)
builder.store_productions(
Alternative((
Empty(),
Sequence((looping_rule, self.child)),
)).to_productions(builder),
looping_rule_name,
)
tail = looping_rule
elif self.max - self.min > 0:
tail = Optional(self.child)
for _ in range(self.max - self.min - 1):
tail = Optional(Sequence(
(tail, self.child),
))
return Sequence((self.child,) * self.min + (tail,)).to_productions(builder)
def as_dict(self):
return {
'type': 'range_repetition',
'min': self.min,
'max': self.max,
'child': self.child.as_dict(),
}
class Alternative(namedtuple('Alternative', ('children',))):
def to_productions(self, builder):
productions = []
for child in self.children:
productions.extend(child.to_productions(builder))
return tuple(productions)
def as_dict(self):
return {
'type': 'alternative',
'children': [c.as_dict() for c in self.children],
}
class Sequence(namedtuple('Sequence', ('children',))):
def to_productions(self, builder):
production = []
for child in self.children:
cp = child.to_productions(builder)
if len(cp) == 1:
production.extend(cp[0])
else:
name = builder.store_productions(cp)
production.append(name)
return (tuple(production),)
def as_dict(self):
return {
'type': 'sequence',
'children': [c.as_dict() for c in self.children],
}
class ProductionsBuilder:
def __init__(self):
self.productions_dict = {} # name -> productions
self.names = {} # productions -> name
self.anonymous_count = 0
self.terminals = {} # name -> terminal definition
self.terminal_names = {} # terminal definition -> name
def new_anonymous_name(self):
name = "__a{}".format(self.anonymous_count)
self.anonymous_count += 1
return name
def store_productions(self, productions, name=None):
if name is None:
if productions in self.names:
return self.names[productions]
else:
name = self.new_anonymous_name()
if name in self.productions_dict:
raise DesugaringError("production for symbol {} are already defined".format(name))
if productions in self.names and productions != ((),):
raise DesugaringError(
"productions {} are already stored under name {} (trying to store them as {})".format(
productions,
self.names[productions],
name,
),
)
self.productions_dict[name] = productions
self.names[productions] = name
return name
def store_terminal(self, definition):
if definition not in self.terminal_names:
name = "__t{}".format(len(self.terminals))
assert definition not in self.terminal_names
assert name not in self.terminals
self.terminal_names[definition] = name
self.terminals[name] = definition
return self.terminal_names[definition]
class Grammar:
def __init__(self, rules):
self.rules = rules
def to_productions_dict(self):
builder = ProductionsBuilder()
for name, definition in self.rules.items():
builder.store_productions(definition.to_productions(builder), name)
return builder.productions_dict, builder.terminals
def as_dict(self):
return {k: v.as_dict() for k, v in self.rules.items()}