transformations.py 文件源码

python
阅读 24 收藏 0 点赞 0 评论 0

项目:ITAP-django 作者: krivers 项目源码 文件源码
def cleanupBoolOps(a):
    """When possible, combine adjacent boolean expressions"""
    """Note- we are assuming that all ops are the first op (as is done in the simplify function)"""
    if not isinstance(a, ast.AST):
        return a
    if type(a) == ast.BoolOp:
        allTypesWork = True
        for i in range(len(a.values)):
            a.values[i] = cleanupBoolOps(a.values[i])
            if eventualType(a.values[i]) != bool or hasattr(a.values[i], "multiComp"):
                allTypesWork = False

        # We can't reduce if the types aren't all booleans
        if not allTypesWork:
            return a

        i = 0
        while i < len(a.values) - 1:
            current = a.values[i]
            next = a.values[i+1]
            # (a and b and c and d) or (a and e and d) == a and ((b and c) or e) and d
            if type(current) == type(next) == ast.BoolOp:
                if type(current.op) == type(next.op):
                    minlength = min(len(current.values), len(next.values)) # shortest length

                    # First, check for all identical values from the front
                    j = 0
                    while j < minlength:
                        if compareASTs(current.values[j], next.values[j], checkEquality=True) != 0:
                            break
                        j += 1

                    # Same values in both, so get rid of the latter line
                    if j == len(current.values) == len(next.values):
                        a.values.pop(i+1)
                        continue
            i += 1
        ### If reduced to one item, just return that item
        return a.values[0] if (len(a.values) == 1) else a
    return applyToChildren(a, cleanupBoolOps)
评论列表
文章目录


问题


面经


文章

微信
公众号

扫码关注公众号