Added proper AST display to term.py

This commit is contained in:
madmaurice 2016-11-20 11:04:20 +01:00
parent 5cfbbf8832
commit 160b7d58d5

15
term.py
View file

@ -63,6 +63,7 @@ def lex(text):
c = next(it,END) c = next(it,END)
class OperatorNode: class OperatorNode:
operator = "?"
def __init__(self, left, right): def __init__(self, left, right):
self.left = left self.left = left
self.right = right self.right = right
@ -73,19 +74,28 @@ class OperatorNode:
def __repr__(self): def __repr__(self):
return "%s < %s, %s >" % (self.__class__.__name__, repr(self.left), repr(self.right)) 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): class AdditionNode(OperatorNode):
operator = "+"
def calculate(self): def calculate(self):
return self.left.calculate() + self.right.calculate() return self.left.calculate() + self.right.calculate()
class SubtractionNode(OperatorNode): class SubtractionNode(OperatorNode):
operator = "-"
def calculate(self): def calculate(self):
return self.left.calculate() - self.right.calculate() return self.left.calculate() - self.right.calculate()
class MultiplicationNode(OperatorNode): class MultiplicationNode(OperatorNode):
operator = "*"
def calculate(self): def calculate(self):
return self.left.calculate() * self.right.calculate() return self.left.calculate() * self.right.calculate()
class DivisionNode(OperatorNode): class DivisionNode(OperatorNode):
operator = "/"
def calculate(self): def calculate(self):
right = self.right.calculate() right = self.right.calculate()
if right == 0: if right == 0:
@ -102,6 +112,9 @@ class NumNode:
def __repr__(self): def __repr__(self):
return "NumNode < %d >" % self.value return "NumNode < %d >" % self.value
def printAST(self,tab=0):
print("\t"*tab,self.value)
# 1. S -> E # 1. S -> E
# 2. E -> E+T # 2. E -> E+T
# 3. E -> E-T # 3. E -> E-T
@ -270,6 +283,6 @@ if __name__ == '__main__':
print('"%s"' % l) print('"%s"' % l)
print(list(lex(l))) print(list(lex(l)))
ast = parse(l) ast = parse(l)
print(repr(ast)) ast.printAST()
print(l," = ",ast.calculate()) print(l," = ",ast.calculate())