Added proper AST display to term.py
This commit is contained in:
parent
5cfbbf8832
commit
160b7d58d5
1 changed files with 14 additions and 1 deletions
15
term.py
15
term.py
|
@ -63,6 +63,7 @@ def lex(text):
|
|||
c = next(it,END)
|
||||
|
||||
class OperatorNode:
|
||||
operator = "?"
|
||||
def __init__(self, left, right):
|
||||
self.left = left
|
||||
self.right = right
|
||||
|
@ -73,19 +74,28 @@ class OperatorNode:
|
|||
def __repr__(self):
|
||||
return "%s < %s, %s >" % (self.__class__.__name__, repr(self.left), repr(self.right))
|
||||
|
||||
def printAST(self,tab=0):
|
||||
self.left.printAST(tab+1)
|
||||
print("\t"*tab,self.operator)
|
||||
self.right.printAST(tab+1)
|
||||
|
||||
class AdditionNode(OperatorNode):
|
||||
operator = "+"
|
||||
def calculate(self):
|
||||
return self.left.calculate() + self.right.calculate()
|
||||
|
||||
class SubtractionNode(OperatorNode):
|
||||
operator = "-"
|
||||
def calculate(self):
|
||||
return self.left.calculate() - self.right.calculate()
|
||||
|
||||
class MultiplicationNode(OperatorNode):
|
||||
operator = "*"
|
||||
def calculate(self):
|
||||
return self.left.calculate() * self.right.calculate()
|
||||
|
||||
class DivisionNode(OperatorNode):
|
||||
operator = "/"
|
||||
def calculate(self):
|
||||
right = self.right.calculate()
|
||||
if right == 0:
|
||||
|
@ -102,6 +112,9 @@ class NumNode:
|
|||
def __repr__(self):
|
||||
return "NumNode < %d >" % self.value
|
||||
|
||||
def printAST(self,tab=0):
|
||||
print("\t"*tab,self.value)
|
||||
|
||||
# 1. S -> E
|
||||
# 2. E -> E+T
|
||||
# 3. E -> E-T
|
||||
|
@ -270,6 +283,6 @@ if __name__ == '__main__':
|
|||
print('"%s"' % l)
|
||||
print(list(lex(l)))
|
||||
ast = parse(l)
|
||||
print(repr(ast))
|
||||
ast.printAST()
|
||||
print(l," = ",ast.calculate())
|
||||
|
||||
|
|
Loading…
Reference in a new issue