-
Notifications
You must be signed in to change notification settings - Fork 0
/
grammar_stuff.py
224 lines (180 loc) · 5.38 KB
/
grammar_stuff.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
##################################################################
'''
support functions for grammars. grammars are lists of tuples.
for example, the grammar,
exp : + exp exp
| - exp exp
| x
| y
| z
is represented as,
[('exp',['+','exp','exp']),
('exp',['-','exp','exp']),
('exp',['x']),
('exp',['y']),
('exp',['z'])]
and with lookahead sets it becomes,
[('exp', {'+'}, ['+', 'exp', 'exp']),
('exp', {'-'}, ['-', 'exp', 'exp']),
('exp', {'x'}, ['x']),
('exp', {'y'}, ['y']),
('exp', {'z'}, ['z'])]
'''
##################################################################
def start_symbol(G):
first_rule = G[0]
if len(first_rule) == 2:
(A,B) = first_rule
return A
elif len(first_rule) == 3:
(A,L,B) = first_rule
return A
##################################################################
def first_symbol(rule_body):
return rule_body[0]
##################################################################
def non_terminal_set(G):
nt = set()
for r in G:
if len(r) == 2:
(A, B) = r
else:
(A, L, B) = r
nt.add(A)
return nt
##################################################################
def terminal_set(G):
nt = non_terminal_set(G)
symbols = []
for r in G:
if len(r) == 2:
(A, B) = r
else:
(A, L, B) = r
symbols.extend(B)
t = set(symbols) - nt
return t
##################################################################
def find_matching_rule(GL, N, P):
for r in GL:
(A, L, B) = r
if A == N and P in L:
return r
elif A == N and len(L) == 1 and list(L)[0] == "":
return r
return None
##################################################################
def right_side_match(G, S):
for r in G:
if len(r) == 2:
(A, B) = r
else:
(A, L, B) = r
if S.match(B):
return r
return None
##################################################################
class Stack:
def __init__(self):
self.items = []
def push(self, item):
self.items.append(item)
def match(self, input_list):
if len(self.items) < len(input_list):
return False
l1 = len(input_list)
l2 = len(self.items)
ix = l2 - l1
tos_list = self.items[ix:]
return tos_list == input_list
def push_reverse(self, input_list):
symbol_list = input_list.copy()
while symbol_list:
self.push(symbol_list.pop())
def pop(self):
return self.items.pop()
def popn(self, n):
for i in range(n):
self.pop()
def peek(self):
return self.items[-1]
def empty(self):
return len(self.items) == 0
##################################################################
class InputStream:
def __init__(self, stream):
self.stream = stream # stream has to be a list of characters
self.stream.append('eof')
self.stream_ix = 0
def pointer(self):
if self.end_of_file():
return ""
else:
return self.stream[self.stream_ix]
def next(self):
self.stream_ix += 1
if self.end_of_file():
return ""
else:
return self.pointer()
def match(self, sym):
if sym == self.stream[self.stream_ix]:
self.next()
else:
raise SyntaxError('unexpected symbol {} while parsing, expected {}'
.format(self.stream[self.stream_ix], sym))
return self.pointer()
def end_of_file(self):
if self.stream[self.stream_ix] == 'eof':
return True
else:
return False
##################################################################
class TokenStream:
def __init__(self, lexer, stream):
self.lexer = lexer
self.lexer.input(stream) # stream is a string
self.lookahead = self.lexer.token()
def pointer(self):
return self.lookahead
def next(self):
self.lookahead = self.lexer.token()
return self.lookahead
def end_of_file(self):
# lexer.token() returns None when at EOF
if not self.lookahead:
return True
else:
return False
##################################################################
# this function will print any AST that follows the
#
# (TYPE [, child1, child2,...])
#
# tuple format for tree nodes.
def dump_AST(node):
_dump_AST(node)
print('')
def _dump_AST(node, level=0):
if isinstance(node, tuple):
indent(level)
nchildren = len(node) - 1
print("(%s" % node[0], end='')
if nchildren > 0:
print(" ", end='')
for c in range(nchildren):
_dump_AST(node[c+1], level+1)
if c != nchildren-1:
print(' ', end='')
print(")", end='')
else:
print("%s" % str(node), end='')
def indent(level):
print('')
for i in range(level):
print(' |',end='')
##################################################################
def assert_match(input, expected):
if input != expected:
raise ValueError("Pattern match failed: expected {} but got {}".format(expected, input))
##################################################################