/
parse.py
executable file
·268 lines (205 loc) · 5.26 KB
/
parse.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
#!/usr/bin/env python2
"""
parse.py
"""
from __future__ import print_function
import os
import sys
# PYTHONPATH=$REPO_ROOT/vendor
from typing import Tuple, Optional, cast
# PYTHONPATH=$REPO_ROOT/mycpp
from mycpp.mylib import log, tagswitch
from mycpp import mylib
from _devbuild.gen.expr_asdl import (
expr,
expr_e, # for translation only?
expr_t, expr__Var, expr__Const, expr__Binary, tok_e, tok_t
)
# PYTHONPATH=$REPO_ROOT
from asdl import format as fmt
class Lexer(object):
# "type declaration" of members
def __init__(self, s):
# type: (str) -> None
self.s = s
self.i = 0
self.n = len(s)
def Read(self):
# type: () -> Tuple[tok_t, str]
if self.i >= self.n:
return tok_e.Eof, '' # sentinel
tok = self.s[self.i]
self.i += 1
if tok.isdigit():
return tok_e.Const, tok
if tok.isalpha():
return tok_e.Var, tok
if tok in '+-':
return tok_e.Op1, tok # lower precedence
if tok in '*/':
return tok_e.Op2, tok # higher precedence
if tok in '()':
return tok_e.Paren, tok
return tok_e.Invalid, tok
def _MethodCallingOtherMethod(self):
# type: () -> None
# Make sure we don't get a member var called Read!
# This is easy because we're only checking assignment statements.
self.Read()
class ParseError(Exception):
def __init__(self, msg):
# type: (str) -> None
self.msg = msg
class Parser(object):
"""
Grammar from http://compilers.iecc.com/crenshaw/tutor6.txt, adapted to ANTLR
syntax.
Expr = Term ('+' Term)*
Term = Factor ('*' Factor)*
Factor = VAR
| CONST
| '(' Expr ')'
"""
def __init__(self, lexer):
# type: (Lexer) -> None
self.lexer = lexer
self.tok_type = tok_e.Eof # type: tok_t
self.tok_val = ''
def Next(self):
# type: () -> None
self.tok_type, self.tok_val = self.lexer.Read()
#log('-- %r %r', self.tok_type, self.tok_val)
def Eat(self, tok_val):
# type: (str) -> None
if self.tok_val != tok_val:
#raise ParseError('Expected %r, got %r' % (tok_val, self.tok_val))
raise ParseError('Expected ' + tok_val)
self.Next()
def ParseFactor(self):
# type: () -> expr_t
#log('ParseFactor')
if self.tok_type == tok_e.Var:
n1 = expr__Var(self.tok_val)
self.Next()
return n1
if self.tok_type == tok_e.Const:
n2 = expr__Const(int(self.tok_val))
self.Next()
return n2
if self.tok_type == tok_e.Paren:
self.Eat('(')
n3 = self.ParseExpr()
self.Eat(')')
return n3
#raise ParseError('Unexpected token %s %s' % (self.tok_type, self.tok_val))
raise ParseError('Unexpected token ' + self.tok_val)
def ParseTerm(self):
# type: () -> expr_t
#log('ParseTerm')
node = self.ParseFactor()
# TODO: Iterate and create nodes
while self.tok_type == tok_e.Op2:
op = self.tok_val
self.Next()
n2 = self.ParseFactor()
node = expr__Binary(op, node, n2)
return node
def ParseExpr(self):
# type: () -> expr_t
#log('ParseExpr')
node = self.ParseTerm()
while self.tok_type == tok_e.Op1:
op = self.tok_val
self.Next()
n2 = self.ParseTerm()
node = expr__Binary(op, node, n2)
return node
def Parse(self):
# type: () -> expr_t
self.Next()
return self.ParseExpr()
def TestParse():
# type: () -> None
lex = Lexer('abc')
while True:
tok_type, tok_val = lex.Read()
if tok_type == tok_e.Eof:
break
#print('%s %s' % (tok_type, tok_val))
log('tok_val %s', tok_val)
CASES = [
'1+2', '1+2*3', '1*2+3', '(1+2)*3', 'a+b+c+d', 'a*b*3*4',
'1', 'a',
# expect errors here:
'(',
')',
'(a+b',
' ',
' $$ ',
]
for expr in CASES:
lex = Lexer(expr)
p = Parser(lex)
log('')
log('--')
log('%s =>', expr)
node = None # type: Optional[expr_t]
try:
node = p.Parse()
except ParseError as e:
log('Parse error: %s', e.msg)
continue
#log('%s', tree)
htree = node.PrettyTree()
ast_f = fmt.AnsiOutput(mylib.Stdout())
fmt.PrintTree(htree, ast_f)
ast_f.write('\n')
UP_node = node
with tagswitch(UP_node) as case:
if case(expr_e.Const):
node = cast(expr__Const, UP_node)
log('Const %d', node.i)
elif case(expr_e.Var):
node = cast(expr__Var, UP_node)
log('Var %s', node.name)
else:
log('Other')
def TestCreate():
# type: () -> None
c = expr.Const.Create()
log('c.i %d', c.i)
v = expr.Var.Create()
log('v.name %r', v.name)
b = expr.Binary.Create()
log('b.op %r', b.op)
b.op = '+'
# Must assign these
b.left = c
b.right = v
htree = b.PrettyTree()
ast_f = fmt.AnsiOutput(mylib.Stdout())
fmt.PrintTree(htree, ast_f)
ast_f.write('\n')
def run_tests():
# type: () -> None
TestParse()
TestCreate()
def run_benchmarks():
# type: () -> None
n = 100000
result = 0
i = 0
while i < n:
lex = Lexer('a*b*3*4')
p = Parser(lex)
tree = p.Parse()
i += 1
mylib.MaybeCollect() # manual GC point
log('result = %d', result)
log('iterations = %d', n)
if __name__ == '__main__':
if os.getenv('BENCHMARK'):
log('Benchmarking...')
run_benchmarks()
else:
run_tests()