-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathinterpreter.py
56 lines (51 loc) · 2.02 KB
/
interpreter.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
from nodes import *
from values import Number
import tokens
class Interpreter:
def __init__(self):
pass
def visit(self, node) -> Number:
if isinstance(node, BinaryNode):
return self.visit_binary_node(node)
elif isinstance(node, UnaryNode):
return self.visit_unary_node(node)
elif isinstance(node, NumberNode):
return Number(node.value)
else:
raise RuntimeError("Unknown node")
def visit_binary_node(self, node: BinaryNode) -> Number:
if node.type == tokens.TT_PLUS:
return Number(
self.visit(node.left_node).value + self.visit(node.right_node).value
)
elif node.type == tokens.TT_MINUS:
return Number(
self.visit(node.left_node).value - self.visit(node.right_node).value
)
elif node.type == tokens.TT_MULTIPLY:
return Number(
self.visit(node.left_node).value * self.visit(node.right_node).value
)
elif node.type == tokens.TT_DIVIDE:
try:
return Number(
self.visit(node.left_node).value / self.visit(node.right_node).value
)
except ZeroDivisionError:
raise RuntimeError("Dividing by zero")
elif node.type == tokens.TT_MODULO:
try:
return Number(
self.visit(node.left_node).value % self.visit(node.right_node).value
)
except ZeroDivisionError:
raise RuntimeError("Modulo operation dividing by zero")
else:
raise RuntimeError("Unknown token type for BinaryNode")
def visit_unary_node(self, node: UnaryNode) -> Number:
if node.type == tokens.TT_PLUS:
return Number(+self.visit(node.node).value)
elif node.type == tokens.TT_MINUS:
return Number(-self.visit(node.node).value)
else:
raise RuntimeError("Unknown token type for UnaryNode")