Added rudimentary type analysis.
This commit is contained in:
parent
160b7d58d5
commit
e1897e2a8c
1 changed files with 23 additions and 2 deletions
25
term.py
25
term.py
|
@ -39,10 +39,13 @@ def lex(text):
|
||||||
break
|
break
|
||||||
elif c in "0123456789":
|
elif c in "0123456789":
|
||||||
s = ""
|
s = ""
|
||||||
while c != END and c in "0123456789":
|
vtype = int
|
||||||
|
while c != END and c in "0123456789.":
|
||||||
s+=c
|
s+=c
|
||||||
|
if(c == "."):
|
||||||
|
vtype = float
|
||||||
c = next(it,END)
|
c = next(it,END)
|
||||||
yield NumToken(int(s))
|
yield NumToken(vtype(s))
|
||||||
continue
|
continue
|
||||||
elif c == "+":
|
elif c == "+":
|
||||||
yield AddOpToken()
|
yield AddOpToken()
|
||||||
|
@ -67,6 +70,7 @@ class OperatorNode:
|
||||||
def __init__(self, left, right):
|
def __init__(self, left, right):
|
||||||
self.left = left
|
self.left = left
|
||||||
self.right = right
|
self.right = right
|
||||||
|
self.vtype = None
|
||||||
|
|
||||||
def calculate(self):
|
def calculate(self):
|
||||||
raise Exception("Not implemented")
|
raise Exception("Not implemented")
|
||||||
|
@ -79,6 +83,16 @@ class OperatorNode:
|
||||||
print("\t"*tab,self.operator)
|
print("\t"*tab,self.operator)
|
||||||
self.right.printAST(tab+1)
|
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):
|
class AdditionNode(OperatorNode):
|
||||||
operator = "+"
|
operator = "+"
|
||||||
def calculate(self):
|
def calculate(self):
|
||||||
|
@ -115,6 +129,12 @@ class NumNode:
|
||||||
def printAST(self,tab=0):
|
def printAST(self,tab=0):
|
||||||
print("\t"*tab,self.value)
|
print("\t"*tab,self.value)
|
||||||
|
|
||||||
|
def getType(self):
|
||||||
|
if(type(self.value) == int):
|
||||||
|
return int
|
||||||
|
else:
|
||||||
|
return float
|
||||||
|
|
||||||
# 1. S -> E
|
# 1. S -> E
|
||||||
# 2. E -> E+T
|
# 2. E -> E+T
|
||||||
# 3. E -> E-T
|
# 3. E -> E-T
|
||||||
|
@ -284,5 +304,6 @@ if __name__ == '__main__':
|
||||||
print(list(lex(l)))
|
print(list(lex(l)))
|
||||||
ast = parse(l)
|
ast = parse(l)
|
||||||
ast.printAST()
|
ast.printAST()
|
||||||
|
print("Result is of type: %s" % (repr(ast.getType())))
|
||||||
print(l," = ",ast.calculate())
|
print(l," = ",ast.calculate())
|
||||||
|
|
||||||
|
|
Loading…
Reference in a new issue