-
Notifications
You must be signed in to change notification settings - Fork 0
/
interpreter.py
32 lines (24 loc) · 962 Bytes
/
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
from nodes import *
from values import Number
class Interpreter:
def visit(self, node):
method_name = f'visit_{type(node).__name__}'
method = getattr(self, method_name)
return method(node)
def visit_NumberNode(self, node):
return Number(node.value)
def visit_AddNode(self, node):
return Number(self.visit(node.node_a).value + self.visit(node.node_b).value)
def visit_SubtractNode(self, node):
return Number(self.visit(node.node_a).value - self.visit(node.node_b).value)
def visit_MultiplyNode(self, node):
return Number(self.visit(node.node_a).value * self.visit(node.node_b).value)
def visit_DivideNode(self, node):
try:
return Number(self.visit(node.node_a).value / self.visit(node.node_b).value)
except:
raise Exception("Runtime math error")
def visit_PlusNode(self, node):
return self.visit(node.node)
def visit_MinusNode(self, node):
return Number(-self.visit(node.node).value)