def cleanupTypes(a):
"""Remove any unneccessary type mappings"""
if not isinstance(a, ast.AST):
return a
# No need to cast something if it'll be changed anyway by a binary operation
if type(a) == ast.BinOp:
a.left = cleanupTypes(a.left)
a.right = cleanupTypes(a.right)
# Ints become floats naturally
if eventualType(a.left) == eventualType(a.right) == float:
if type(a.right) == ast.Call and type(a.right.func) == ast.Name and \
a.right.func.id == "float" and len(a.right.args) == 1 and len(a.right.keywords) == 0 and \
eventualType(a.right.args[0]) in [int, float]:
a.right = a.right.args[0]
elif type(a.left) == ast.Call and type(a.left.func) == ast.Name and \
a.left.func.id == "float" and len(a.left.args) == 1 and len(a.left.keywords) == 0 and \
eventualType(a.left.args[0]) in [int, float]:
a.left = a.left.args[0]
return a
elif type(a) == ast.Call and type(a.func) == ast.Name and len(a.args) == 1 and len(a.keywords) == 0:
a.func = cleanupTypes(a.func)
a.args = [cleanupTypes(a.args[0])]
# If the type already matches, no need to cast it
funName = a.func.id
argType = eventualType(a.args[0])
if type(a.func) == ast.Name:
if (funName == "float" and argType == float) or \
(funName == "int" and argType == int) or \
(funName == "bool" and argType == bool) or \
(funName == "str" and argType == str):
return a.args[0]
return applyToChildren(a, cleanupTypes)
评论列表
文章目录