-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcalc6.py
379 lines (269 loc) · 9.36 KB
/
calc6.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
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
'''
An interpreter for a subset of the
Pascal programming language, written in
Python
(with support for unary +/- operators)
Inspired by tutorial from Ruslan Spivak
Author: GotoCode
'''
# Token Types
INTEGER = 'INTEGER'
PLUS = 'PLUS'
MINUS = 'MINUS'
MULTIPLY = 'MULTIPLY'
DIVIDE = 'DIVIDE'
LPAREN = 'LPAREN'
RPAREN = 'RPAREN'
EOF = 'EOF'
# A Token is a pair - (type, value)
class Token(object):
def __init__(self, type, value):
self.type = type
self.value = value
def __str__(self):
return 'Token({type}, {value})'.format(type=self.type, value=self.value)
def __repr__(self):
return self.__str__()
# Abstract Syntax Tree #
class BinOp(object):
def __init__(self, left, op, right):
self.left = left
self.op = op
self.right = right
def __str__(self):
return 'BinOp({left}, {op}, {right})'.format(left=str(self.left),
op=self.op.type,
right=str(self.right))
class IntNode(object):
def __init__(self, token):
self.token = token
self.value = token.value
def __str__(self):
return 'IntNode(%d)' % self.value
class UnaryOp(object):
def __init__(self, op, expr):
self.op = op
self.expr = expr
def __str__(self):
return 'UnaryOp({op}, {expr})'.format(op=self.op.type, expr=str(self.expr))
# AST traversal functions (i.e. evaluation) #
# post-order traversal
def handle_binop(binop_node):
left_val = eval_AST(binop_node.left)
right_val = eval_AST(binop_node.right)
op_type = binop_node.op.type
#print binop_node.op
if op_type == PLUS:
return left_val + right_val
elif op_type == MINUS:
return left_val - right_val
elif op_type == MULTIPLY:
return left_val * right_val
elif op_type == DIVIDE:
return left_val / right_val
else:
raise Exception("Unknown operator found")
def handle_unaryop(unaryop_node):
result = eval_AST(unaryop_node.expr)
op_type = unaryop_node.op.type
if op_type == PLUS:
return +result
else:
return -result
def handle_binop_rpn(binop_node):
left_val = get_rpn(binop_node.left)
right_val = get_rpn(binop_node.right)
op_type = binop_node.op.type
#print binop_node.op
if op_type == PLUS:
return left_val + ' ' + right_val + ' + '
elif op_type == MINUS:
return left_val + ' ' + right_val + ' - '
elif op_type == MULTIPLY:
return left_val + ' ' + right_val + ' * '
elif op_type == DIVIDE:
return left_val + ' ' + right_val + ' / '
else:
raise Exception("Unknown operator found")
def handle_binop_lisp(binop_node):
left_val = get_rpn(binop_node.left)
right_val = get_rpn(binop_node.right)
op_type = binop_node.op.type
#print binop_node.op
if op_type == PLUS:
return '(' + '+ ' + left_val + ' ' + right_val + ')'
elif op_type == MINUS:
return '(' + '- ' + left_val + ' ' + right_val + ')'
elif op_type == MULTIPLY:
return '(' + '* ' + left_val + ' ' + right_val + ')'
elif op_type == DIVIDE:
return '(' + '/ ' + left_val + ' ' + right_val + ')'
else:
raise Exception("Unknown operator found")
# good ol' fashioned evaluation of arithmetic expression
def eval_AST(ast):
if ast is None:
raise Exception("Invalid AST for input expression")
else:
if isinstance(ast, BinOp):
return handle_binop(ast)
elif isinstance(ast, UnaryOp):
return handle_unaryop(ast)
elif isinstance(ast, IntNode):
return ast.value
def get_rpn(ast):
if ast is None:
raise Exception("Invalid AST for input expression")
else:
if isinstance(ast, BinOp):
return handle_binop_lisp(ast)
elif isinstance(ast, IntNode):
return str(ast.value)
# An Interpreter which converts a single-line
# expression into a stream of tokens
class Interpreter(object):
def __init__(self, text):
# input expression
self.text = text
# pointer to current symbol
self.pos = 0
# character being pointed at by 'pos' index
self.curr_char = self.text[self.pos]
# most recent token available for processing
self.curr_token = self.get_next_token()
def error(self):
raise Exception('Error parsing input...')
def advance(self):
'''
Advance the pos pointer forward by one,
updating both pos and curr_char
'''
self.pos += 1
if self.pos >= len(self.text):
self.curr_char = None
else:
self.curr_char = self.text[self.pos]
def skip_whitespace(self):
'''
Skip over chars until first non-whitespace char is found
'''
while self.curr_char is not None and self.curr_char.isspace():
self.advance()
def integer(self):
'''
Return an integer value based on multi-digit number
'''
result = ''
while self.curr_char is not None and self.curr_char.isdigit():
result += self.curr_char
self.advance()
return int(result)
### LEXER CODE ###
def get_next_token(self):
'''
Lexical analyzer which returns a stream of
tokens corresponding to input expression
RETURN: Token object
'''
while self.curr_char is not None:
if self.curr_char.isspace():
self.skip_whitespace()
continue
elif self.curr_char.isdigit():
return Token(INTEGER, self.integer())
elif self.curr_char == '+':
self.advance()
return Token(PLUS, '+')
elif self.curr_char == '-':
self.advance()
return Token(MINUS, '-')
elif self.curr_char == '*':
self.advance()
return Token(MULTIPLY, '*')
elif self.curr_char == '/':
self.advance()
return Token(DIVIDE, '/')
elif self.curr_char == '(':
self.advance()
return Token(LPAREN, '(')
elif self.curr_char == ')':
self.advance()
return Token(RPAREN, ')')
else:
self.error()
return Token(EOF, None)
def consume(self, type):
'''
If the given type matches that of the
current token, then consume it, else
raise an error
'''
if type == self.curr_token.type:
self.curr_token = self.get_next_token()
else:
self.error()
### PARSER CODE ###
def expr(self):
node = self.term()
#print 'Hello!'
#print self.curr_token
while self.curr_token.type in (PLUS, MINUS):
op = self.curr_token
if self.curr_token.type == PLUS:
self.consume(PLUS)
elif self.curr_token.type == MINUS:
self.consume(MINUS)
node = BinOp(node, op, self.term())
return node
def term(self):
node = self.factor()
while self.curr_token.type in (MULTIPLY, DIVIDE):
op = self.curr_token
if self.curr_token.type == MULTIPLY:
self.consume(MULTIPLY)
elif self.curr_token.type == DIVIDE:
self.consume(DIVIDE)
node = BinOp(node, op, self.factor())
return node
def factor(self):
node = None
#print self.curr_token
if self.curr_token.type == LPAREN:
self.consume(LPAREN)
node = self.expr()
self.consume(RPAREN)
elif self.curr_token.type == PLUS:
self.consume(PLUS)
node = UnaryOp(Token(PLUS, 'PLUS'), self.factor())
elif self.curr_token.type == MINUS:
self.consume(MINUS)
node = UnaryOp(Token(MINUS, 'MINUS'), self.factor())
else:
#self.consume(INTEGER)
node = IntNode(self.curr_token)
self.consume(INTEGER)
return node
# INTERPRETER CODE #
def eval(self):
ast = self.expr()
#print ast
return eval_AST(ast)
#return get_rpn(ast)
def main():
'''
Main logic for presenting CLI to user of interpreter
'''
while True:
try:
input_expr = raw_input('calc> ')
except EOFError:
print
break
# ignore any empty lines of input
if not input_expr:
continue
interpreter = Interpreter(input_expr)
result = interpreter.eval()
print result
if __name__ == '__main__':
main()