From e1897e2a8ce99065cdec763715988ad795040822 Mon Sep 17 00:00:00 2001 From: Valentin Gehrke Date: Sun, 20 Nov 2016 11:43:49 +0100 Subject: [PATCH] Added rudimentary type analysis. --- term.py | 25 +++++++++++++++++++++++-- 1 file changed, 23 insertions(+), 2 deletions(-) diff --git a/term.py b/term.py index 4d88f7e..b5a7947 100644 --- a/term.py +++ b/term.py @@ -39,10 +39,13 @@ def lex(text): break elif c in "0123456789": s = "" - while c != END and c in "0123456789": + vtype = int + while c != END and c in "0123456789.": s+=c + if(c == "."): + vtype = float c = next(it,END) - yield NumToken(int(s)) + yield NumToken(vtype(s)) continue elif c == "+": yield AddOpToken() @@ -67,6 +70,7 @@ class OperatorNode: def __init__(self, left, right): self.left = left self.right = right + self.vtype = None def calculate(self): raise Exception("Not implemented") @@ -79,6 +83,16 @@ class OperatorNode: print("\t"*tab,self.operator) self.right.printAST(tab+1) + def getType(self): + if self.vtype is None: + vlefttype = self.left.getType() + vrighttype = self.left.getType() + if vrighttype == float or vlefttype == float: + self.vtype = float + else: + self.vtype = int + return self.vtype + class AdditionNode(OperatorNode): operator = "+" def calculate(self): @@ -115,6 +129,12 @@ class NumNode: def printAST(self,tab=0): print("\t"*tab,self.value) + def getType(self): + if(type(self.value) == int): + return int + else: + return float + # 1. S -> E # 2. E -> E+T # 3. E -> E-T @@ -284,5 +304,6 @@ if __name__ == '__main__': print(list(lex(l))) ast = parse(l) ast.printAST() + print("Result is of type: %s" % (repr(ast.getType()))) print(l," = ",ast.calculate())