-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathInterpreter.py
More file actions
52 lines (44 loc) · 1.74 KB
/
Interpreter.py
File metadata and controls
52 lines (44 loc) · 1.74 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
from Token import *
class Interpreter(object):
def __init__(self, lexer):
# client string input, e.g. "3 + 5", "12 - 5 + 3", etc
self.lexer = lexer
self.current_token = self.lexer.get_next_token()
def error(self):
raise Exception('Invalid syntax')
def eat(self, token_type):
# compare the current token type with the passed token
# type and if they match then "eat" the current token
# and assign the next token to the self.current_token,
# otherwise raise an exception.
if self.current_token.type == token_type:
self.current_token = self.lexer.get_next_token()
else:
self.error()
def factor(self):
"""Return an INTEGER token value."""
token = self.current_token
self.eat(INTEGER)
return token.value
def expr(self):
"""Arithmetic expression parser / interpreter."""
# set current token to the first token taken from the input
#self.current_token = self.lexer.get_next_token()
result = self.factor()
while self.current_token.type in (PLUS, MINUS):
token = self.current_token
if token.type == PLUS:
self.eat(PLUS)
result = result + self.factor()
elif token.type == MINUS:
self.eat(MINUS)
result = result - self.factor()
while self.current_token.type in (DIVIDE, MULTIPLY):
token = self.current_token
if token.type == DIVIDE:
self.eat(DIVIDE)
result = result / self.factor()
elif token.type == MULTIPLY:
self.eat(MULTIPLY)
result = result * self.factor()
return result