-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patheval_pascal.py
More file actions
492 lines (347 loc) · 12.1 KB
/
eval_pascal.py
File metadata and controls
492 lines (347 loc) · 12.1 KB
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
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
'''
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
'''
import sys
# Token Types
INTEGER = 'INTEGER'
PLUS = 'PLUS'
MINUS = 'MINUS'
MULTIPLY = 'MULTIPLY'
DIVIDE = 'DIVIDE'
LPAREN = 'LPAREN'
RPAREN = 'RPAREN'
EOF = 'EOF'
# Pascal token types
BEGIN = 'BEGIN'
END = 'END'
ASSIGN = 'ASSIGN'
ID = 'ID'
DOT = 'DOT'
SEMI = 'SEMI'
# global symbol table
GLOBAL_SCOPE = {}
# 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))
class CompoundNode(object):
def __init__(self):
self.children = []
class Assign(object):
def __init__(self, left, op, right):
self.left = left
self.op = op
self.right = right
class Var(object):
def __init__(self, token):
self.token = token
self.value = token.value
class NoOp(object):
pass
# 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
# good ol' fashioned evaluation of arithmetic expressions
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
elif isinstance(ast, CompoundNode):
for child in ast.children:
eval_AST(child)
elif isinstance(ast, NoOp):
pass
elif isinstance(ast, Assign):
var_name = ast.left.value
GLOBAL_SCOPE[var_name.lower()] = eval_AST(ast.right)
elif isinstance(ast, Var):
value = GLOBAL_SCOPE.get(ast.value.lower(), None)
if value is None:
raise NameError(str(ast.value))
else:
return 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 ###
# look ahead at next char of input expression
def peek(self):
next_pos = self.pos + 1
if next_pos > len(self.text):
return None
else:
return self.text[next_pos]
# create token for variables and reserved keywords
def _id(self):
RESERVED_KEYWORDS = {'BEGIN':Token('BEGIN', 'BEGIN'),
'END':Token('END', 'END')}
result = ''
while self.curr_char != None and self.curr_char.isalnum() or self.curr_char == '_':
result += self.curr_char
self.advance()
return RESERVED_KEYWORDS.get(result.upper(), Token(ID, result.lower()))
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 == ':' and self.peek() == '=':
self.advance()
self.advance()
return Token(ASSIGN, ':=')
elif self.curr_char == '.':
self.advance()
return Token(DOT, '.')
elif self.curr_char == ';':
self.advance()
return Token(SEMI, ';')
elif 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.text[self.pos:self.pos+3] == 'div':
self.advance()
self.advance()
self.advance()
return Token(DIVIDE, '/')
elif self.curr_char == '(':
self.advance()
return Token(LPAREN, '(')
elif self.curr_char == ')':
self.advance()
return Token(RPAREN, ')')
elif self.curr_char.isalpha() or self.curr_char == '_':
return self._id()
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())
elif self.curr_token.type == ID:
return self.variable()
else:
#self.consume(INTEGER)
node = IntNode(self.curr_token)
self.consume(INTEGER)
return node
def program(self):
'''program : compound_statement DOT'''
node = self.compound_statement()
self.consume(DOT)
return node
def compound_statement(self):
'''compound_statement : BEGIN statement_list END'''
#print self.curr_token
self.consume(BEGIN)
node = self.statement_list()
self.consume(END)
return node
def statement_list(self):
'''statement_list : statement | statement SEMI statement_list'''
s = self.statement()
children = [s]
while self.curr_token.type == SEMI:
self.consume(SEMI)
children.append(self.statement())
node = CompoundNode()
node.children = children
return node
def statement(self):
'''statement : compound_statement | assignment_statement | empty'''
node = None
if self.curr_token.type == BEGIN:
node = self.compound_statement()
elif self.curr_token.type == ID:
node = self.assignment_statement()
else:
node = NoOp()
return node
def assignment_statement(self):
'''assignment_statement : variable ASSIGN expr'''
left = self.variable()
#print 'left:', left.value
token = self.curr_token
#print 'token:', self.curr_token
self.consume(ASSIGN)
right = self.expr()
return Assign(left, token, right)
def variable(self):
'''variable : ID'''
node = Var(self.curr_token)
self.consume(ID)
return node
def empty(self):
return NoOp()
# INTERPRETER CODE #
def eval(self):
ast = self.program()
eval_AST(ast)
def file_to_input(filename):
fp = open(filename, 'r')
out_text = ''
for line in fp:
out_text += line.strip() + ' '
return out_text
def main():
'''
Main logic for presenting CLI to user of interpreter
'''
GLOBAL_SCOPE.clear()
input_expr = file_to_input(sys.argv[1])
#input_expr = 'BEGIN x := 2; y := (x + 2) * 3 END.'
interpreter = Interpreter(input_expr)
interpreter.eval()
print GLOBAL_SCOPE
if __name__ == '__main__':
main()