-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsyntax_tree.py
122 lines (89 loc) · 3.02 KB
/
syntax_tree.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
__author__ = 'rezenter'
import tree
class ASTNode(tree.Node):
def execute(self):
raise Exception("nope")
class IntLiteralNode(ASTNode):
def execute(self):
return self.getValue()
class UnaryOpNode(ASTNode):
def getArg(self):
return self.getLeft().getValue()
def getMnemonic(self):
return self.getValue()
class UnMinusNode(UnaryOpNode):
def __init__(self, node):
UnaryOpNode.__init__(self, '-', node)
def execute(self):
return -1*self.getLeft().execute()
class PrintNode(UnaryOpNode):
def __init__(self, node):
UnaryOpNode.__init__(self, 'print', node)
def execute(self):
x = self.getLeft().execute()
print(x)
return x
class BinaryOpNode(ASTNode):
def getMnemonic(self):
return self.getValue()
def getArgL(self):
return self.getLeft().getValue()
def getArgR(self):
return self.getRight().getValue()
class BinPlusNode(BinaryOpNode):
def __init__(self, l, r):
BinaryOpNode.__init__(self, '+', l, r)
def execute(self):
return self.getLeft().execute() + self.getRight().execute()
class BinMinusNode(BinaryOpNode):
def __init__(self, l, r):
BinaryOpNode.__init__(self, '-', l, r)
def execute(self):
return self.getLeft().execute() - self.getRight().execute()
class BinMulNode(BinaryOpNode):
def __init__(self, l, r):
BinaryOpNode.__init__(self, '*', l, r)
def execute(self):
return self.getLeft().execute() * self.getRight().execute()
class BinDivNode(BinaryOpNode):
def __init__(self, l, r):
BinaryOpNode.__init__(self, '//', l, r)
def execute(self):
return self.getLeft().execute() // self.getRight().execute()
class AST(tree.Tree):
def execute(self):
return self.getRoot().execute()
def parseExpr(expr):
expr = expr.split()
buffer = []
flag = True
e = 0
for i in expr:
try:
i = int(i)
buffer.append(IntLiteralNode(i))
except ValueError:
try:
if i == "print":
buffer.append(PrintNode(buffer.pop()))
elif i == "!":
buffer.append(UnMinusNode(buffer.pop()))
elif i == "+":
buffer.append(BinPlusNode(buffer.pop(), buffer.pop()))
elif i == '-':
r = buffer.pop()
buffer.append(BinMinusNode(buffer.pop(), r))
elif i == "*":
buffer.append(BinMulNode(buffer.pop(), buffer.pop()))
elif i == "/" or i == '//':
r = buffer.pop()
buffer.append(BinDivNode(buffer.pop(), r))
except IndexError:
e = i
flag = False
break
if flag and len(buffer) == 1:
return AST(PrintNode(buffer[0]))
elif not flag:
return AST(IntLiteralNode("Not enough args for " + str(e)))
return AST(IntLiteralNode("Too many args in expr"))