From 160b7d58d50fd052be9917b013c9325c0a5bca58 Mon Sep 17 00:00:00 2001 From: Valentin Gehrke Date: Sun, 20 Nov 2016 11:04:20 +0100 Subject: [PATCH] Added proper AST display to term.py --- term.py | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) 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())