diff --git a/term.py b/term.py index d2798a1..4d88f7e 100644 --- a/term.py +++ b/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())