Added rudimentary type analysis.

This commit is contained in:
madmaurice 2016-11-20 11:43:49 +01:00
parent 160b7d58d5
commit e1897e2a8c

25
term.py
View file

@ -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())