예제 #1
0
    def visit_Compare(self, node):
        # cmpop = Eq | NotEq | Lt | LtE | Gt | GtE | Is | IsNot | In | NotIn
        print("  in MyTransformer.visit_Compare()")
        print("   node     =", node)
        print("   op       =", node.ops[0])

        curr_op = node.ops[0]
        comp_negate = curr_op

        rand_num = random.randint(1, 10)
        if rand_num >= 7:
            print("   negating...")
            if isinstance(curr_op, ast.Eq): comp_negate = ast.NotEq()
            elif isinstance(curr_op, ast.NotEq): comp_negate = ast.Eq()

            elif isinstance(curr_op, ast.Lt): comp_negate = ast.GtE()
            elif isinstance(curr_op, ast.LtE): comp_negate = ast.Gt()

            elif isinstance(curr_op, ast.Gt): comp_negate = ast.LtE()
            elif isinstance(curr_op, ast.GtE): comp_negate = ast.Lt()

            elif isinstance(curr_op, ast.Is): comp_negate = ast.IsNot()
            elif isinstance(curr_op, ast.IsNot): comp_negate = ast.Is()

            elif isinstance(curr_op, ast.In): comp_negate = ast.NotIn()
            elif isinstance(curr_op, ast.NotIn): comp_negate = ast.In()
            else: comp_negate = ast.Eq()
        else:
            print("   mixing up...")
            if isinstance(curr_op, ast.Lt): comp_negate = ast.LtE()
            elif isinstance(curr_op, ast.LtE): comp_negate = ast.And()

            elif isinstance(curr_op, ast.Gt): comp_negate = ast.Or()
            elif isinstance(curr_op, ast.GtE): comp_negate = ast.Gt()

            elif isinstance(curr_op, ast.Is): comp_negate = ast.Gt()
            elif isinstance(curr_op, ast.IsNot): comp_negate = ast.Lt()

            elif isinstance(curr_op, ast.In):
                comp_negate = ast.In(
                )  #leave the same for for loops (for x in this)
            elif isinstance(curr_op, ast.NotIn):
                comp_negate = ast.Lt()
            else:
                comp_negate = ast.Eq()

        print("   new comparator =", comp_negate)

        # create negated node | Compare(expr left, cmpop* ops, expr* comparators)
        new_node = node
        new_node.ops = [comp_negate]
        ast.copy_location(new_node, node)
        ast.fix_missing_locations(new_node)
        return new_node
예제 #2
0
    def visit_Compare(self, node):
        self.generic_visit(node)
        self.binop_count += 1

        if (self.binop_count == self.count_of_node_to_mutate):
            new_node = copy.deepcopy(node)
            print('IN COMPARE')
            print('THIS IS THE PREVIOUS OP', node.ops)
            for (i, op) in enumerate(node.ops):
                if (isinstance(op, ast.Gt)):
                    num = random.randint(0, 2)
                    if num == 0:
                        new_node.ops[i] = ast.GtE()
                    if num == 1:
                        new_node.ops[i] = ast.LtE()
                    if num == 2:
                        new_node.ops[i] = ast.Lt()
                if (isinstance(op, ast.GtE)):
                    num = random.randint(0, 2)
                    if num == 0:
                        new_node.ops[i] = ast.Gt()
                    if num == 1:
                        new_node.ops[i] = ast.Lt()
                    if num == 2:
                        new_node.ops[i] = ast.LtE()
                if (isinstance(op, ast.Lt)):
                    num = random.randint(0, 2)
                    if num == 0:
                        new_node.ops[i] = ast.LtE()
                    if num == 1:
                        new_node.ops[i] = ast.GtE()
                    if num == 2:
                        new_node.ops[i] = ast.Gt()
                if (isinstance(op, ast.LtE)):
                    num = random.randint(0, 2)
                    if num == 0:
                        new_node.ops[i] = ast.Lt()
                    if num == 1:
                        new_node.ops[i] = ast.GtE()
                    if num == 2:
                        new_node.ops[i] = ast.Gt()
                if (isinstance(op, ast.Eq)):
                    new_node.ops[i] = ast.NotEq()
                if (isinstance(op, ast.NotEq)):
                    new_node.ops[i] = ast.Eq()
                if (isinstance(op, ast.Is)):
                    new_node.ops[i] = ast.IsNot()
                if (isinstance(op, ast.IsNot)):
                    new_node.ops[i] = ast.Is()
                print('THIS IS THE NEW OP', new_node.ops)
                print('I AM CREATING A NEW NODE HERE', self.binop_count)
                return new_node
        return node
예제 #3
0
 def __le__(self, other):
     if isinstance(other, Expr):
         comp = ast.Compare(left=self._expr,
                            ops=[ast.LtE()],
                            comparators=[other._expr])
         return Expr(comp)
     elif other is not None:
         comp = ast.Compare(
             left=self._expr,
             ops=[ast.LtE()],
             comparators=[ast.Constant(value=other)],
         )
         return Expr(comp)
     else:
         return False
예제 #4
0
    def visit_Compare(self, node):

        global visit_count, visit_target
        visit_count += 1
        if (visit_count == visit_target):
            ##print("Rewrite compare Line: ", node.lineno)
            if (isinstance(node.ops[0], ast.GtE)):
                new_node = ast.Compare(left=node.left,
                                       ops=[ast.Lt()],
                                       comparators=node.comparators)
                return new_node
            elif (isinstance(node.ops[0], ast.LtE)):
                new_node = ast.Compare(left=node.left,
                                       ops=[ast.Gt()],
                                       comparators=node.comparators)
                return new_node
            elif (isinstance(node.ops[0], ast.Gt)):
                new_node = ast.Compare(left=node.left,
                                       ops=[ast.LtE()],
                                       comparators=node.comparators)
                return new_node
            elif (isinstance(node.ops[0], ast.Lt)):
                new_node = ast.Compare(left=node.left,
                                       ops=[ast.GtE()],
                                       comparators=node.comparators)
                return new_node

        return node
예제 #5
0
    def visit_Compare(self, node):
        global number_of_comparisons

        if (isinstance(node.ops[0], ast.GtE)):
            new_node = ast.Compare(left=node.left,
                                   ops=[ast.Lt()],
                                   comparators=node.comparators)
            number_of_comparisons += 1
        elif (isinstance(node.ops[0], ast.LtE)):
            new_node = ast.Compare(left=node.left,
                                   ops=[ast.Gt()],
                                   comparators=node.comparators)
            number_of_comparisons += 1
        elif (isinstance(node.ops[0], ast.Gt)):
            new_node = ast.Compare(left=node.left,
                                   ops=[ast.LtE()],
                                   comparators=node.comparators)
            number_of_comparisons += 1
        elif (isinstance(node.ops[0], ast.Lt)):
            new_node = ast.Compare(left=node.left,
                                   ops=[ast.GtE()],
                                   comparators=node.comparators)
            number_of_comparisons += 1

        return node
예제 #6
0
 def __compare(self, compare):
     return ast.Compare(left=ast.Attribute(value=ast.Name(id=self.id,
                                                          ctx=ast.Load()),
                                           attr='level',
                                           ctx=ast.Load()),
                        ops=[ast.LtE()],
                        comparators=[compare])
예제 #7
0
    def __init__(self, base_node):
        BaseMutator.__init__(self, base_node)
        self.original_ops = base_node.ops

        index_count = 0
        for op in base_node.ops:

            if type(op) in [ast.Gt, ast.GtE, ast.Lt, ast.LtE]:
                if type(op) is ast.Gt:
                    ops_mutant_Gt = copy.deepcopy(base_node.ops)
                    ops_mutant_Gt[index_count] = ast.GtE()
                    self.mutations.append({"ops": ops_mutant_Gt})

                if type(op) is ast.GtE:
                    ops_mutant_GtE = copy.deepcopy(base_node.ops)
                    ops_mutant_GtE[index_count] = ast.Gt()
                    self.mutations.append({"ops": ops_mutant_GtE})

                if type(op) is ast.Lt:
                    ops_mutant_Lt = copy.deepcopy(base_node.ops)
                    ops_mutant_Lt[index_count] = ast.LtE()
                    self.mutations.append({"ops": ops_mutant_Lt})

                if type(op) is ast.LtE:
                    ops_mutant_LtE = copy.deepcopy(base_node.ops)
                    ops_mutant_LtE[index_count] = ast.Lt()
                    self.mutations.append({"ops": ops_mutant_LtE})

            index_count += 1
예제 #8
0
 def to_node(self):
     if len(self.operator) == 0:
         return self.left.to_node()
     else:
         right_nodes = []
         comp_operator = []
         for i in range(len(self.right)):
             right_nodes.append(self.right[i].to_node())
             if self.operator[i] in ['<', 'is lower than']:
                 comp_operator.append(ast.Lt())
             elif self.operator[i] in ['<=', 'is lower or equal to']:
                 comp_operator.append(ast.LtE())
             elif self.operator[i] in ['>', 'is greater than']:
                 comp_operator.append(ast.Gt())
             elif self.operator[i] in ['>=', 'is greater or equal to']:
                 comp_operator.append(ast.GtE())
             elif self.operator[i] in ['==', 'is equal to']:
                 comp_operator.append(ast.Eq())
             elif self.operator[i] in ['!=', 'is different from',
                                       'is not equal to']:
                 comp_operator.append(ast.NotEq())
             elif self.operator[i] == 'in':
                 comp_operator.append(ast.In())
             elif self.operator[i] == 'not in':
                 comp_operator.append(ast.NotIn())
             elif self.operator[i] == 'is':
                 comp_operator.append(ast.Is())
             elif self.operator[i] == 'is not':
                 comp_operator.append(ast.IsNot())
             else:
                 raise Exception("Unrecognized argument in Comparison")
         return ast.Compare(left=self.left.to_node(), ops=comp_operator,
                            comparators=right_nodes)
예제 #9
0
    def visit_Compare(self, node):
        """
        For ==, !=, >, >=, <, <= : put the arguments in alphabetical order.
        Replace >= and <= by > and > is the other value is a number
        """
        self.generic_visit(node)
        if len(node.ops) != 1:
            return node
        if isinstance(node.ops[0],
                      (ast.NotEq, ast.Eq, ast.Gt, ast.GtE, ast.Lt, ast.LtE)):
            left = ast.dump(node.left, annotate_fields=False)
            right = ast.dump(node.comparators[0], annotate_fields=False)
            if left > right:
                node.left, node.comparators[0] = node.comparators[0], node.left
                if isinstance(node.ops[0], ast.Gt):
                    node.ops[0] = ast.Lt()
                elif isinstance(node.ops[0], ast.GtE):
                    node.ops[0] = ast.LtE()
                elif isinstance(node.ops[0], ast.Lt):
                    node.ops[0] = ast.Gt()
                elif isinstance(node.ops[0], ast.LtE):
                    node.ops[0] = ast.GtE()
        if (len(node.comparators) == 1
                and isinstance(node.comparators[0], ast.Num)):
            if isinstance(node.ops[0], ast.LtE):
                # <= 6   ===>   < 7
                node.ops[0] = ast.Lt()
                node.comparators[0].n += 1
            elif isinstance(node.ops[0], ast.GtE):
                # >= 6   ===>   > 5
                node.ops[0] = ast.Gt()
                node.comparators[0].n -= 1

        return node
예제 #10
0
    def test_visit_Compare(self, get_logger_mock):
        node = MagicMock()
        node.left = "left"
        node.comparators = ["middle", "right"]
        node.ops = [ast.LtE(), ast.IsNot()]
        analyzer = ExpressionAnalyzer()
        self.assertIsNone(analyzer.visit_Compare(node))
        self.assertEqual(
            analyzer.parts,
            ["left", " ", "<=", " ", "middle", " ", "is not", " ", "right"],
        )

        node.ops = [ast.LtE(), ast.Import]
        analyzer = ExpressionAnalyzer()
        self.assertIsNone(analyzer.visit_Compare(node))
        self.assertEqual(
            analyzer.parts,
            ["left", " ", "<=", " ", "middle", " ", "...", " ", "right"])
        get_logger_mock().warning.assert_called_once_with(ANY)
예제 #11
0
def with_guard(node, lowest, highest):
    if lowest is None:
        # sys.version_info <= highest
        assert highest is not None
        condition = ast.Compare(_SYS_VERSION, [ast.LtE()],
                                [ast.Constant(highest)])
    elif highest is None:
        # sys.version_info >= highest
        assert lowest is not None
        condition = ast.Compare(_SYS_VERSION, [ast.GtE()],
                                [ast.Constant(lowest)])
    else:
        # lowest <= sys.version_info <= highest
        condition = ast.Compare(
            ast.Constant(lowest),
            [ast.LtE()] * 2,
            [_SYS_VERSION, ast.Constant(highest)],
        )

    return ast.If(condition, body=[node], orelse=[])
예제 #12
0
 def 比较(片段):
     对照表 = {
         '>': ast.Gt(),
         '>=': ast.GtE(),
         '<': ast.Lt(),
         '<=': ast.LtE(),
         '==': ast.Eq(),
         '!=': ast.NotEq(),
         '===': ast.Is(),
         '!==': ast.IsNot()
     }
     return 语法树.比较(前项=片段[0], 操作符=对照表[片段[1].getstr()], 后项=片段[2], 片段=片段)
예제 #13
0
 def Random_Compare(self):
     random_int = random.randint(0, 5)
     if random_int == 0:
         return ast.Eq()
     elif random_int == 1:
         return ast.NotEq()
     elif random_int == 2:
         return ast.Gt()
     elif random_int == 3:
         return ast.Lt()
     elif random_int == 4:
         return ast.GtE()
     else:
         return ast.LtE()
예제 #14
0
def undoReverse(a):
	tmp = None
	if type(a) == ast.Lt:
		tmp = ast.Gt()
	elif type(a) == ast.LtE:
		tmp = ast.GtE()
	elif type(a) == ast.Gt:
		tmp = ast.Lt()
	elif type(a) == ast.GtE:
		tmp = ast.LtE()
	else:
		return a
	transferMetaData(a, tmp)
	return tmp
예제 #15
0
class BinaryInfixOperand(object):
    n_terms = 2
    assoc = 'LEFT'

    keyword_aliases = _kw(
        (['and', '&&'], ast.And()),
        (['or', '||'], ast.Or()),
        (['<', 'lt'], ast.Lt()),
        (['==', 'eq'], ast.Eq()),
        (['<=', 'le'], ast.LtE()),
        (['!=', 'ne'], ast.NotEq()),
        (['>=', 'ge'], ast.GtE()),
        (['>', 'gt'], ast.Gt()),
    )

    def __init__(self, tokens):
        tokens = tokens[0]
        if len(tokens) % 2 == 1:
            self.op_token = tokens[1]
            self.comparators = tokens[::2]
        else:
            err = "Invalid number of infix expressions: {}"
            err = err.format(len(tokens))
            raise ParseException(err)
        assert self.op_token in self.keyword_aliases

        # Check for too many literals and not enough keywords
        op = self.keyword_aliases[self.op_token]
        if isinstance(op, ast.boolop):
            if any(isinstance(c, Literal) for c in self.comparators):
                raise ValueError("Cannot use literals as truth")
        else:
            if all(isinstance(c, Literal) for c in self.comparators):
                raise ValueError("Cannot compare literals.")

    def ast(self):
        op = self.keyword_aliases[self.op_token]

        if isinstance(op, ast.boolop):
            # and and or use one type of AST node
            value = ast.BoolOp(op=op,
                               values=[e.ast() for e in self.comparators])
        else:
            # remaining operators use another
            value = ast.Compare(
                left=self.comparators[0].ast(),
                ops=[op],
                comparators=[e.ast() for e in self.comparators[1:]])
        return value
예제 #16
0
파일: ddl.py 프로젝트: zzl200012/railgun
def p_comp_op(p):
    '''comp_op : ">"
			| "<"
			| OP_EQ
			| OP_GE
			| OP_LE
			| OP_NE
			| OP_NNE
			| TAG_IN
			| TAG_NOT TAG_IN
			| TAG_IS
			| TAG_IS TAG_NOT'''

    if len(p) == 2:
        if p.get_item(1).type == 'OP_EQ':
            p[0] = ast.Eq()

        elif p.get_item(1).type == '>':
            p[0] = ast.Gt()

        elif p.get_item(1).type == '<':
            p[0] = ast.Lt()

        elif p.get_item(1).type == 'OP_GE':
            p[0] = ast.GtE()

        elif p.get_item(1).type == 'OP_LE':
            p[0] = ast.LtE()

        elif p.get_item(1).type == 'OP_NE':
            p[0] = ast.NotEq()

        elif p.get_item(1).type == 'OP_NNE':
            p[0] = ast.NotEq()

        elif p[1] == 'is':
            p[0] = ast.Is()

        elif p[1] == 'in':
            p[0] = ast.In()

    elif len(p) == 3:
        if p[1] == 'is':
            p[0] = ast.IsNot()

        elif p[1] == 'not':
            p[0] = ast.NotIn()

    return
예제 #17
0
    def mutate(cls, node):
        if node not in config.visited_nodes:
            if node.__class__ in [
                    ast.Eq, ast.NotEq, ast.Lt, ast.Gt, ast.LtE, ast.GtE
            ]:
                if node.__class__ in config.comparison_operators:
                    config.comparison_operators.remove(node.__class__)

                while len(config.comparison_operators) > 0:

                    original_node = deepcopy(node)
                    parent = config.parent_dict[node]
                    del config.parent_dict[node]

                    node_type = config.comparison_operators.pop()
                    if node_type is ast.Eq:
                        node = ast.Eq()
                    elif node_type is ast.NotEq:
                        node = ast.NotEq()
                    elif node_type is ast.Lt:
                        node = ast.Lt()
                    elif node_type is ast.Gt:
                        node = ast.Gt()
                    elif node_type is ast.LtE:
                        node = ast.LtE()
                    elif node_type is ast.GtE:
                        node = ast.GtE()
                    else:
                        print "TypeError in AOR"

                    config.parent_dict[node] = parent
                    config.node_pairs[node] = original_node
                    config.current_mutated_node = node
                    config.mutated = True
                    return node

                if len(config.arithmetic_operators) == 0:
                    config.arithmetic_operators = [
                        ast.Eq, ast.NotEq, ast.Lt, ast.Gt, ast.LtE, ast.GtE
                    ]
                    config.visited_nodes.add(node)

        return node
예제 #18
0
        def _revert_compare(node):
            """
            Helper function to revert a compare node to its negation.
            """
            rev_node = copy.deepcopy(node)
            op = rev_node.ops[0]

            if isinstance(op, ast.Is):
                rev_node.ops = [ast.IsNot()]
            elif isinstance(op, ast.Gt):
                rev_node.ops = [ast.LtE()]
            elif isinstance(op, ast.Lt):
                rev_node.ops = [ast.GtE()]
            elif isinstance(op, ast.Eq):
                rev_node.ops = [ast.NotEq()]
            elif isinstance(op, ast.In):
                rev_node.ops = [ast.NotIn()]
            else:
                raise ConstraintError('Unknown operator: %s' % op)
            return rev_node
예제 #19
0
def branch_dist_boolop(op, values, args):
    if len(values) == 1:
        return branch_dist(values[0], args)

    else:
        return ast.Call(func=ast.Lambda(
            args=ast.arguments(
                args=[ast.arg(arg=args.lambda_arg, annotation=None)],
                vararg=None,
                kwonlyargs=[],
                kw_defaults=[],
                kwarg=None,
                defaults=[]),
            body=ast.IfExp(test=ast.Compare(
                left=ast.Name(id=args.lambda_arg),
                ops=[ast.Gt() if isinstance(op, ast.And) else ast.LtE()],
                comparators=[ast.Num(n=0)]),
                           body=ast.Name(id=args.lambda_arg),
                           orelse=branch_dist_boolop(op, values[1:], args))),
                        args=[branch_dist(values[0], args)],
                        keywords=[])
예제 #20
0
파일: interp.py 프로젝트: caioariede/be
def resolve_value(value, scope):
    if isinstance(value, EId):
        node = ast.Name(id=value.v, ctx=ast.Load())
    elif isinstance(value, EInt):
        node = ast.Num(n=value.v)
    elif isinstance(value, EList):
        lst = [resolve_value(a, scope) for a in value.v]
        node = ast.List(elts=lst, ctx=ast.Load())
    elif isinstance(value, EOp):
        lft, rgt = value.v
        lft = resolve_value(lft, scope)
        rgt = resolve_value(rgt, scope)

        operators = {
            '+': ast.Add(),
            '-': ast.Sub(),
            '*': ast.Mult(),
            '/': ast.Div(),
            '%': ast.Mod(),
        }

        node = ast.BinOp(left=lft, right=rgt, op=operators[value.t])
    elif isinstance(value, ECompare):
        lft, rgt = value.v
        lft = resolve_value(lft, scope)
        rgt = resolve_value(rgt, scope)

        operators = {
            '<': ast.Lt(),
            '>': ast.Gt(),
            '<=': ast.LtE(),
            '>=': ast.GtE(),
            '==': ast.Eq(),
        }

        node = ast.Compare(left=lft,
                           ops=[operators[value.t]],
                           comparators=[rgt])

    return ast.fix_missing_locations(node)
예제 #21
0
    def p_expr_compare(self, p):
        '''expr : expr EQUALITY expr
                | expr INEQUALITY expr
                | expr LESSTHAN expr
                | expr GREATERTHAN expr
                | expr LESSTHANOREQUAL expr
                | expr GREATERTHANOREQUAL expr
        '''
        op = None
        if p[2] == '==':
            op = ast.Eq()
        elif p[2] == '!=':
            op = ast.NotEq()
        elif p[2] == '<':
            op = ast.Lt()
        elif p[2] == '>':
            op = ast.Gt()
        elif p[2] == '<=':
            op = ast.LtE()
        elif p[2] == '>=':
            op = ast.GtE()

        p[0] = ast.Compare(left=p[1], ops=[op], comparators=[p[3]])
예제 #22
0
def neg(pred):
    ops = pred.ops[0]
    if type(ops) == ast.Eq:
        pred.ops[0] = ast.NotEq()
        return pred
    elif type(ops) == ast.NotEq:
        pred.ops[0] = ast.Eq()
        return pred
    elif type(ops) == ast.Lt:
        pred.ops[0] = ast.GtE()
        return pred
    elif type(ops) == ast.Gt:
        pred.ops[0] = ast.LtE()
        return pred
    elif type(ops) == ast.LtE:
        pred.ops[0] = ast.Gt()
        return pred
    elif type(ops) == ast.GtE:
        pred.ops[0] = ast.Lt()
        return pred
    else:
        print('%s Not Supported' % type(ops).__name__)
        exit(1)
예제 #23
0
    def create_boolean_entity_node(self, boolean_entity):
        left_node = self.to_node(boolean_entity.left)
        if boolean_entity.operator is None:
            return left_node
        elif boolean_entity.operator in ['==', 'is equal to']:
            python_cmp_op = ast.Eq()
        elif boolean_entity.operator in [
                '!=', 'is not equal to', 'is different from'
        ]:
            python_cmp_op = ast.NotEq()
        elif boolean_entity.operator in ['>', 'is greater than']:
            python_cmp_op = ast.Gt()
        elif boolean_entity.operator in ['>=', 'is greater or equal to']:
            python_cmp_op = ast.GtE()
        elif boolean_entity.operator in ['<', 'is lower than']:
            python_cmp_op = ast.Lt()
        elif boolean_entity.operator in ['<=', 'is lower or equal to']:
            python_cmp_op = ast.LtE()
        else:
            raise

        right_node = self.to_node(boolean_entity.right)
        return ast.Compare(left_node, (python_cmp_op, ), (right_node, ))
예제 #24
0
def parse_lookup(ast_state, l):
    assert isinstance(l, dict)
    assert set(l.keys()) >= set(('key', 'op', 'table'))

    key = ast_value(ast_state, l['key'])

    # only support >=, <= for now
    assert l['op'] in ['>=', '<=']
    op = ast.GtE() if l['op'] == '>=' else ast.LtE()

    default = ast_value(ast_state, l.get('default'))

    table = l['table']
    assert isinstance(table, list)

    expr = default
    for entry in reversed(table):
        assert isinstance(entry, list)
        assert len(entry) == 2
        output, cond = entry
        test = ast.Compare(key, [op], [ast_value(ast_state, cond)])
        expr = ast.IfExp(test, ast_value(ast_state, output), expr)

    return expr
예제 #25
0
def compare_action(s, loc, tokens):
    node = tokens[0]
    ops = []
    comparators = []
    for op_char, right in tokens[1:]:
        if op_char == '==':
            ops.append(ast.Eq())
        elif op_char == '<':
            ops.append(ast.Lt())
        elif op_char == '<=':
            ops.append(ast.LtE())
        elif op_char == '>':
            ops.append(ast.Gt())
        elif op_char == '>=':
            ops.append(ast.GtE())
        else:  # !=
            ops.append(ast.NotEq)

        comparators.append(right)

    if len(ops) > 0:
        node = ast.Compare(left=node, ops=ops, comparators=comparators)

    return node
예제 #26
0
def branch_dist_comp(test, args):
    if isinstance(test.ops[0], ast.Eq):
        op_type = 0
        br_dist = ast.Call(func=ast.Name(id='abs'),
                           args=[
                               ast.BinOp(left=test.left,
                                         op=ast.Sub(),
                                         right=test.comparators[0])
                           ],
                           keywords=[],
                           starags=None,
                           kwargs=None)

    elif isinstance(test.ops[0], ast.NotEq):
        op_type = 1
        br_dist = ast.UnaryOp(op=ast.USub(),
                              operand=ast.Call(
                                  func=ast.Name(id='abs'),
                                  args=[
                                      ast.BinOp(left=test.left,
                                                op=ast.Sub(),
                                                right=test.comparators[0])
                                  ],
                                  keywords=[],
                                  starags=None,
                                  kwargs=None))

    elif isinstance(test.ops[0], ast.Lt):
        op_type = 1
        br_dist = ast.BinOp(left=test.left,
                            op=ast.Sub(),
                            right=test.comparators[0])

    elif isinstance(test.ops[0], ast.LtE):
        op_type = 0
        br_dist = ast.BinOp(left=test.left,
                            op=ast.Sub(),
                            right=test.comparators[0])

    elif isinstance(test.ops[0], ast.Gt):
        op_type = 1
        br_dist = ast.BinOp(left=test.comparators[0],
                            op=ast.Sub(),
                            right=test.left)

    elif isinstance(test.ops[0], ast.GtE):
        op_type = 0
        br_dist = ast.BinOp(left=test.comparators[0],
                            op=ast.Sub(),
                            right=test.left)

    return ast.Call(func=ast.Lambda(
        args=ast.arguments(
            args=[ast.arg(arg=args.lambda_arg, annotation=None)],
            vararg=None,
            kwonlyargs=[],
            kw_defaults=[],
            kwarg=None,
            defaults=[]),
        body=ast.IfExp(test=ast.Compare(
            left=ast.Name(id=args.lambda_arg),
            ops=[ast.LtE() if op_type == 0 else ast.Lt()],
            comparators=[ast.Num(n=0)]),
                       body=ast.Name(id=args.lambda_arg),
                       orelse=ast.BinOp(left=ast.Name(id=args.lambda_arg),
                                        op=ast.Add(),
                                        right=ast.Num(args.k)))),
                    args=[br_dist],
                    keywords=[])
예제 #27
0
def find_if(body, parent, args, reach):
    try:
        for field in body._fields:
            find_if(getattr(body, field), parent, args, reach)

    except AttributeError:
        if isinstance(body, list):
            ind = 0

            while ind in range(len(body)):
                line = body[ind]

                if isinstance(line, ast.Return):
                    reach = False

                elif isinstance(line, ast.If) or isinstance(line, ast.While):
                    node = branch_dist(line.test, args)
                    new_branch = branch(parent, line.lineno, reach)

                    # Assign branch distance to temporary variable
                    body.insert(
                        ind,
                        ast.Assign(targets=[ast.Name(id=args.temp_name)],
                                   value=node))

                    # Print branch_id, op_type, branch distance in order
                    body.insert(
                        ind + 1,
                        ast.Expr(value=ast.Call(
                            func=ast.Attribute(value=ast.Name(
                                id=args.file_name),
                                               attr='write'),
                            args=[
                                ast.Call(func=ast.Attribute(
                                    value=ast.Str(s='{} {}\n'), attr='format'),
                                         args=[
                                             ast.Num(n=new_branch.ind),
                                             ast.Name(id=args.temp_name)
                                         ],
                                         keywords=[],
                                         starargs=None,
                                         kwargs=None)
                            ],
                            keywords=[],
                            starargs=None,
                            kwargs=None)))

                    line.test = ast.Compare(left=ast.Name(id=args.temp_name),
                                            ops=[ast.LtE()],
                                            comparators=[ast.Num(n=0)])

                    if isinstance(line, ast.While):
                        line.body.append(body[ind])
                        line.body.append(body[ind + 1])

                    find_if(line.body, new_branch.ind, args, reach)
                    find_if(line.orelse, -new_branch.ind, args, reach)

                    ind += 2

                else:
                    find_if(line, parent, args, reach)

                ind += 1
예제 #28
0
 def ast(self):
     return ast.Compare(left=self._center.ast(), ops=[ast.LtE(), ast.LtE()],
                        comparators=[self._from.ast(), self._to.ast()])
예제 #29
0
파일: unparse.py 프로젝트: sherfert/GTR
def as_ast(dct):
    """See https://docs.python.org/2/library/ast.html"""
    if dct['ast_type'] == "Module":
        return ast.Module(dct["body"])
    elif dct['ast_type'] == "Interactive":
        return ast.Interactive(dct["body"])
    elif dct['ast_type'] == "Expression":
        return ast.Expression(dct["body"])
    elif dct['ast_type'] == "Suite":
        return ast.Suite(dct["body"])
    elif dct['ast_type'] == "FunctionDef":
        return ast.FunctionDef(dct["name"], dct["args"], dct["body"],
                               dct["decorator_list"])
    elif dct['ast_type'] == "ClassDef":
        return ast.ClassDef(dct["name"], dct["bases"], dct["body"],
                            dct["decorator_list"])
    elif dct['ast_type'] == "Return":
        return ast.Return(dct["value"])
    elif dct['ast_type'] == "Delete":
        return ast.Delete(dct["targets"])
    elif dct['ast_type'] == "Assign":
        return ast.Assign(dct["targets"], dct["value"])
    elif dct['ast_type'] == "AugAssign":
        return ast.AugAssign(dct["target"], dct["op"], dct["value"])
    elif dct['ast_type'] == "Print":
        return ast.Print(dct["dest"], dct["values"], dct["nl"])
    elif dct['ast_type'] == "For":
        return ast.For(dct["target"], dct["iter"], dct["body"], dct["orelse"])
    elif dct['ast_type'] == "While":
        return ast.While(dct["test"], dct["body"], dct["orelse"])
    elif dct['ast_type'] == "If":
        return ast.If(dct["test"], dct["body"], dct["orelse"])
    elif dct['ast_type'] == "With":
        return ast.With(dct["context_expr"], dct["optional_vars"], dct["body"])
    elif dct['ast_type'] == "Raise":
        return ast.Raise(dct["type"], dct["inst"], dct["tback"])
    elif dct['ast_type'] == "TryExcept":
        return ast.TryExcept(dct["body"], dct["handlers"], dct["orelse"])
    elif dct['ast_type'] == "TryFinally":
        return ast.TryFinally(dct["body"], dct["finalbody"])
    elif dct['ast_type'] == "Assert":
        return ast.Assert(dct["test"], dct["msg"])
    elif dct['ast_type'] == "Import":
        return ast.Import(dct["names"])
    elif dct['ast_type'] == "ImportFrom":
        return ast.ImportFrom(dct["module"], dct["names"], dct["level"])
    elif dct['ast_type'] == "Exec":
        return ast.Exec(dct["body"], dct["globals"], dct["locals"])
    elif dct['ast_type'] == "Global":
        return ast.Global(dct["names"])
    elif dct['ast_type'] == "Expr":
        return ast.Expr(dct["value"])
    elif dct['ast_type'] == "Pass":
        return ast.Pass()
    elif dct['ast_type'] == "Break":
        return ast.Break()
    elif dct['ast_type'] == "Continue":
        return ast.Continue()
    elif dct['ast_type'] == "BoolOp":
        return ast.BoolOp(dct["op"], dct["values"])
    elif dct['ast_type'] == "BinOp":
        return ast.BinOp(dct["left"], dct["op"], dct["right"])
    elif dct['ast_type'] == "UnaryOp":
        return ast.UnaryOp(dct["op"], dct["operand"])
    elif dct['ast_type'] == "Lambda":
        return ast.Lambda(dct["args"], dct["body"])
    elif dct['ast_type'] == "IfExp":
        return ast.IfExp(dct["test"], dct["body"], dct["orelse"])
    elif dct['ast_type'] == "Dict":
        return ast.Dict(dct["keys"], dct["values"])
    elif dct['ast_type'] == "Set":
        return ast.Set(dct["elts"])
    elif dct['ast_type'] == "ListComp":
        return ast.ListComp(dct["elt"], dct["generators"])
    elif dct['ast_type'] == "SetComp":
        return ast.SetComp(dct["elt"], dct["generators"])
    elif dct['ast_type'] == "DictComp":
        return ast.DictComp(dct["key"], dct["value"], dct["generators"])
    elif dct['ast_type'] == "GeneratorExp":
        return ast.GeneratorExp(dct["elt"], dct["generators"])
    elif dct['ast_type'] == "Yield":
        return ast.Yield(dct["value"])
    elif dct['ast_type'] == "Compare":
        return ast.Compare(dct["left"], dct["ops"], dct["comparators"])
    elif dct['ast_type'] == "Call":
        return ast.Call(dct["func"], dct["args"], dct["keywords"],
                        dct["starargs"], dct["kwargs"])
    elif dct['ast_type'] == "Repr":
        return ast.Repr(dct["value"])
    elif dct['ast_type'] == "Num":
        return ast.Num(dct["n"])
    elif dct['ast_type'] == "Str":
        # Converting to ASCII
        return ast.Str(dct["s"].encode('ascii', 'ignore'))
    elif dct['ast_type'] == "Attribute":
        return ast.Attribute(dct["value"], dct["attr"], dct["ctx"])
    elif dct['ast_type'] == "Subscript":
        return ast.Subscript(dct["value"], dct["slice"], dct["ctx"])
    elif dct['ast_type'] == "Name":
        return ast.Name(dct["id"], dct["ctx"])
    elif dct['ast_type'] == "List":
        return ast.List(dct["elts"], dct["ctx"])
    elif dct['ast_type'] == "Tuple":
        return ast.Tuple(dct["elts"], dct["ctx"])
    elif dct['ast_type'] == "Load":
        return ast.Load()
    elif dct['ast_type'] == "Store":
        return ast.Store()
    elif dct['ast_type'] == "Del":
        return ast.Del()
    elif dct['ast_type'] == "AugLoad":
        return ast.AugLoad()
    elif dct['ast_type'] == "AugStore":
        return ast.AugStore()
    elif dct['ast_type'] == "Param":
        return ast.Param()
    elif dct['ast_type'] == "Ellipsis":
        return ast.Ellipsis()
    elif dct['ast_type'] == "Slice":
        return ast.Slice(dct["lower"], dct["upper"], dct["step"])
    elif dct['ast_type'] == "ExtSlice":
        return ast.ExtSlice(dct["dims"])
    elif dct['ast_type'] == "Index":
        return ast.Index(dct["value"])
    elif dct['ast_type'] == "And":
        return ast.And()
    elif dct['ast_type'] == "Or":
        return ast.Or()
    elif dct['ast_type'] == "Add":
        return ast.Add()
    elif dct['ast_type'] == "Sub":
        return ast.Sub()
    elif dct['ast_type'] == "Mult":
        return ast.Mult()
    elif dct['ast_type'] == "Div":
        return ast.Div()
    elif dct['ast_type'] == "Mod":
        return ast.Mod()
    elif dct['ast_type'] == "Pow":
        return ast.Pow()
    elif dct['ast_type'] == "LShift":
        return ast.LShift()
    elif dct['ast_type'] == "RShift":
        return ast.RShift()
    elif dct['ast_type'] == "BitOr":
        return ast.BitOr()
    elif dct['ast_type'] == "BitXor":
        return ast.BitXor()
    elif dct['ast_type'] == "BitAnd":
        return ast.BitAnd()
    elif dct['ast_type'] == "FloorDiv":
        return ast.FloorDiv()
    elif dct['ast_type'] == "Invert":
        return ast.Invert()
    elif dct['ast_type'] == "Not":
        return ast.Not()
    elif dct['ast_type'] == "UAdd":
        return ast.UAdd()
    elif dct['ast_type'] == "USub":
        return ast.USub()
    elif dct['ast_type'] == "Eq":
        return ast.Eq()
    elif dct['ast_type'] == "NotEq":
        return ast.NotEq()
    elif dct['ast_type'] == "Lt":
        return ast.Lt()
    elif dct['ast_type'] == "LtE":
        return ast.LtE()
    elif dct['ast_type'] == "Gt":
        return ast.Gt()
    elif dct['ast_type'] == "GtE":
        return ast.GtE()
    elif dct['ast_type'] == "Is":
        return ast.Is()
    elif dct['ast_type'] == "IsNot":
        return ast.IsNot()
    elif dct['ast_type'] == "In":
        return ast.In()
    elif dct['ast_type'] == "NotIn":
        return ast.NotIn()
    elif dct['ast_type'] == "comprehension":
        return ast.comprehension(dct["target"], dct["iter"], dct["ifs"])
    elif dct['ast_type'] == "ExceptHandler":
        return ast.ExceptHandler(dct["type"], dct["name"], dct["body"])
    elif dct['ast_type'] == "arguments":
        return ast.arguments(dct["args"], dct["vararg"], dct["kwarg"],
                             dct["defaults"])
    elif dct['ast_type'] == "keyword":
        return ast.keyword(dct["arg"], dct["value"])
    elif dct['ast_type'] == "alias":
        return ast.alias(dct["name"], dct["asname"])
    else:
        return dct
예제 #30
0
    def __init__(self, str, lineno=0):
        self.value = str
        self.lineno = lineno


op_ast_map = {
    '+': ast.Add(),
    '-': ast.Sub(),
    '*': ast.Mult(),
    '/': ast.Div(),
    '%': ast.Mod(),
    '**': ast.Pow(),
    '<<': ast.LShift(),
    '>>': ast.RShift(),
    '|': ast.BitOr(),
    '^^': ast.BitXor(),
    '&&': ast.BitAnd(),
    '//': ast.FloorDiv(),
    '==': ast.Eq(),
    '!=': ast.NotEq(),
    '<': ast.Lt(),
    '<=': ast.LtE(),
    '>': ast.Gt(),
    '>=': ast.GtE(),
    'is': ast.Is(),
    'is_not': ast.IsNot(),
    'in': ast.In(),
    'not_in': ast.NotIn(),
    'and': ast.And(),
    'or': ast.Or()
}