Exemplo n.º 1
0
    def test_generate_if_same_node(self):
        node = ast.Sub()
        mutations = [
            operators.Mutation(
                operator=operators.ArithmeticOperatorReplacement, node=node),
            operators.Mutation(
                operator=operators.ArithmeticOperatorReplacement, node=node),
        ]
        hom_strategy = controller.FirstToLastHOMStrategy(order=2)

        changes_to_apply = list(hom_strategy.generate(mutations))

        self.assertEqual(len(changes_to_apply), 2)
        self.assertEqual(len(changes_to_apply[0]), 1)
        self.assertEqual(changes_to_apply[0][0], mutations[0])
        self.assertEqual(len(changes_to_apply[1]), 1)
        self.assertEqual(changes_to_apply[1][0], mutations[1])
Exemplo n.º 2
0
    def test_generate_if_same_node(self):
        node = ast.Sub()
        mutations = [
            self.aor_mutation(node=node),
            self.aor_mutation(node=node),
        ]

        changes_to_apply = self.apply_strategy_to_mutations_with_order_2(
            controller.FirstToLastHOMStrategy, mutations)

        self.assert_num_changesets(changes_to_apply, 2)
        self.assert_num_changeset_entries(changes_to_apply, 0, 1)
        self.assert_mutation_in_changeset_at_position_equals(
            changes_to_apply, 0, 0, mutations[0])
        self.assert_num_changeset_entries(changes_to_apply, 1, 1)
        self.assert_mutation_in_changeset_at_position_equals(
            changes_to_apply, 1, 0, mutations[1])
Exemplo n.º 3
0
    def test_generate_if_two_operators(self):
        mutations = self.TWO_AOR_MUTATIONS_ON_SUBTRACTION + [
            self.asr_mutation(node=ast.Sub(children=[]))
        ]

        changes_to_apply = self.apply_strategy_to_mutations_with_order_2(
            BetweenOperatorsHOMStrategy, mutations)
        self.assert_num_changesets(changes_to_apply, 2)
        self.assert_num_changeset_entries(changes_to_apply, 0, 2)
        self.assert_mutation_in_changeset_at_position_equals(
            changes_to_apply, 0, 0, mutations[0])
        self.assert_mutation_in_changeset_at_position_equals(
            changes_to_apply, 0, 1, mutations[2])
        self.assert_num_changeset_entries(changes_to_apply, 1, 2)
        self.assert_mutation_in_changeset_at_position_equals(
            changes_to_apply, 1, 0, mutations[1])
        self.assert_mutation_in_changeset_at_position_equals(
            changes_to_apply, 1, 1, mutations[2])
Exemplo n.º 4
0
 def p_expr1(self, p):
     """
     expr1 : MINUS expr %prec UMINUS
           | PLUS expr %prec UMINUS
           | NEG expr
           | HANDLE ident
           | PLUSPLUS ident
           | MINUSMINUS ident
     """
     if p[1] == '@':
         p[0] = p[2]
     elif p[1] == '++':
         p[2].ctx = ast.Store()
         p[0] = self._new_node(p, ast.AugAssign, p[2], ast.Add(), self._new_node(p, ast.Num, 1))
     elif p[1] == '--':
         p[2].ctx = ast.Store()
         p[0] = self._new_node(p, ast.AugAssign, p[2], ast.Sub(), self._new_node(p, ast.Num, 1))
     else:
         p[0] = self._new_node(p, ast.UnaryOp, Parser.UNARY_OPS[p[1]](), p[2])
Exemplo n.º 5
0
 def swap_Op(self, node):
     if (isinstance(node.op, ast.Add)):  #BinOp
         node.op = ast.Sub()
     elif (isinstance(node.op, ast.Sub)):  #BinOp
         node.op = ast.Add()
     elif (isinstance(node.op, ast.Mult)):  #BinOp
         node.op = ast.Div()
     elif (isinstance(node.op, ast.Div)):  #BinOp
         node.op = ast.Mult()
     elif (isinstance(node.op, ast.FloorDiv)):  #BinOp
         node.op = ast.Div()
         # elif(isinstance(node.op, ast.And)): #BoolOp
         # 	node.op = ast.Or()
         # elif(isinstance(node.op, ast.Or)): #BoolOp
         # 	node.op = ast.And()
         # elif(isinstance(node.op, ast.UAdd)): #UnaryOp
         # 	node.op = ast.USub()
         # elif(isinstance(node.op, ast.USub)): #UnaryOp
         node.op = ast.UAdd()
Exemplo n.º 6
0
    def expr(self):
        """expr: term ((PLUS | MINUS) term)*"""
        print("BEGIN expr")
        node = self.term()

        while self.current_token.token_type in (TokenType.PLUS,
                                                TokenType.MINUS):
            token = self.current_token
            op = None
            if token.token_type == TokenType.PLUS:
                op = ast.Add()
                self.eat(TokenType.PLUS)
            elif token.token_type == TokenType.MINUS:
                op = ast.Sub()
                self.eat(TokenType.MINUS)

            node = ast.BinOp(node, op, self.term())
        print("END expr")
        return node
Exemplo n.º 7
0
    def test_nodeclasses(self):
        x = ast.BinOp(1, 2, 3, lineno=0)
        self.assertEquals(x.left, 1)
        self.assertEquals(x.op, 2)
        self.assertEquals(x.right, 3)
        self.assertEquals(x.lineno, 0)

        # node raises exception when not given enough arguments
        self.assertRaises(TypeError, ast.BinOp, 1, 2)

        # can set attributes through kwargs too
        x = ast.BinOp(left=1, op=2, right=3, lineno=0)
        self.assertEquals(x.left, 1)
        self.assertEquals(x.op, 2)
        self.assertEquals(x.right, 3)
        self.assertEquals(x.lineno, 0)

        # this used to fail because Sub._fields was None
        x = ast.Sub()
Exemplo n.º 8
0
def _build_node(node):
    """Convert an AST node to an expression node."""
    node_ref = {
        type(ast.Add()): '+',
        type(ast.Sub()): '-',
        type(ast.Mult()): '*',
        type(ast.Div()): '/'
    }
    if isinstance(node, ast.BinOp) and type(node.op) in node_ref:
        built_node = Node(type=Node.NODE_TYPE_OPERATOR,
                          ch=node_ref[type(node.op)],
                          left=_build_node(node.left),
                          right=_build_node(node.right))
    elif isinstance(node, ast.Num) and type(node.n) is int and node.n in list(
            range(0, 14)):
        built_node = Node(type=Node.NODE_TYPE_NUMBER, ch=node.n)
    else:
        raise SyntaxError('Unallowed operator or operands.')
    return built_node
Exemplo n.º 9
0
 def to_node(self):
     """
     Creates a node that represent arithmetic operations (+ and -).
     This node can be inserted into the AST being constructed.
     :return: The node to be inserted into the AST
     """
     node = self.left.to_node()
     if len(self.operator) == 0:
         return node
     else:
         # Because there can be chained operations, the trick is to
         # recursively build the node by creating it as follow:
         # node = ast.BinOp(node, ast.Op(), right) <-- note that node
         # inside ast.BinOp() is reused when creating the final node
         for i in range(len(self.right)):
             if self.operator[i] in ['+', 'plus']:
                 node = ast.BinOp(node, ast.Add(), self.right[i].to_node())
             elif self.operator[i] in ['-', 'minus']:
                 node = ast.BinOp(node, ast.Sub(), self.right[i].to_node())
         return node
Exemplo n.º 10
0
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)
Exemplo n.º 11
0
    def generate(self, element: Element, GC: GenerationContext):

        acode = element.code

        if len(acode) == 2:
            arg = acode[1]

            with GC.let(domain=ExDom):
                arg_code = GC.generate(arg)

            return expr_wrap(ast.UnaryOp(op=ast.USub(), operand=arg_code), GC)

        else:
            assert len(acode) == 3

            left_element, right_element = acode[1], acode[2]

            with GC.let(domain=ExDom):
                left_code = GC.generate(left_element)
                right_code = GC.generate(right_element)

            return expr_wrap(ast.BinOp(left_code, ast.Sub(), right_code), GC)
Exemplo n.º 12
0
def BinOp(draw, expression) -> ast.BinOp:
    op = draw(
        sampled_from([
            ast.Add(),
            ast.Sub(),
            ast.Mult(),
            ast.Div(),
            ast.FloorDiv(),
            ast.Mod(),
            ast.Pow(),
            ast.LShift(),
            ast.RShift(),
            ast.BitOr(),
            ast.BitXor(),
            ast.BitOr(),
            ast.BitAnd(),
            ast.MatMult()
        ]))

    le = draw(lists(expression, min_size=2, max_size=2))

    return ast.BinOp(le[0], op, le[1])
Exemplo n.º 13
0
 def setUp(self):
     # Translated from https://github.com/gvanrossum/pegen/blob/ec2b354f64f6dbfcb46133757fe4c0e07880f526/test/test_pegen.py#L232
     ident = Alpha + Alnum.repeat()
     atom = (ident.value(lambda v: ast.Name(id=v, ctx=ast.Load()))
             | Digit.repeat(1).value(
                 lambda v: ast.Constant(value=ast.literal_eval(v))))
     expr = Forward()
     factor = (Terminal('(').then(expr).skip(')') | atom)
     term = Forward()
     term.is_(
         term.skip('*').then(
             factor, lambda l, r: ast.BinOp(l, ast.Mult(), r)) ^ term.skip(
                 '/').then(factor, lambda l, r: ast.BinOp(l, ast.Div(), r))
         ^ factor)
     expr.is_(
         expr.skip('+').then(term, lambda l, r: ast.BinOp(l, ast.Add(), r))
         ^ expr.skip('-').then(
             term, lambda l, r: ast.BinOp(l, ast.Sub(), r)) ^ term)
     start = expr.skip(Terminal('\n').repeat(0, 1)).filter(
         lambda r: not r.remain).value(lambda v: ast.fix_missing_locations(
             ast.Expression(v, lineno=1, col_offset=0)))
     self.parser = start
Exemplo n.º 14
0
def AugAssign(draw):
    op = draw(
        sampled_from([
            ast.Add(),
            ast.Sub(),
            ast.Mult(),
            ast.Div(),
            ast.FloorDiv(),
            ast.Mod(),
            ast.Pow(),
            ast.LShift(),
            ast.RShift(),
            ast.BitOr(),
            ast.BitXor(),
            ast.BitOr(),
            ast.BitAnd(),
            ast.MatMult()
        ]))

    return ast.AugAssign(target=draw(Name(ast.Store)),
                         op=op,
                         value=draw(expression()))
Exemplo n.º 15
0
    def p_complex_number(self, p):
        """
        complex_number : number
                       | MINUS number
                       | number PLUS number
                       | number MINUS number
                       | MINUS number PLUS number
                       | MINUS number MINUS number
        """

        ops = {"+": ast.Add(), "-": ast.Sub()}
        build_complex = False
        loc = self.get_line_cols(p, 1)

        match list(p):
            case [_, x]:
                p[0] = x
            case [_, "-", x]:
                p[0] = ast.UnaryOp(op=ast.USub(), operand=x, **loc)
            case [_, left, ("+" | "-") as op_char, right]:
                build_complex = True
                negate_left_side = False
            case [_, "-", left, ("+" | "-") as op_char, right]:
                build_complex = True
                negate_left_side = True
            case _:
                raise AssertionError()

        if build_complex:
            # TODO raise syntax error instead (see reason in p_literal_expr_number_or_string_literal_list)
            assert isinstance(
                right.value, complex
            ), "right part of complex literal must be imaginary"

            if negate_left_side:
                left = ast.UnaryOp(op=ast.USub(), operand=left, **loc)

            p[0] = ast.BinOp(left=left, op=ops[op_char], right=right, **loc)
Exemplo n.º 16
0
    def test_nodeclasses(self):
        # IronPyhon performs argument typechecking
        l=ast.Str('A')
        o=ast.Mult()
        r=ast.Num('13')
        x=ast.BinOp(l,o,r,lineno=42)
        self.assertEqual(x.left, l)
        self.assertEqual(x.op, o)
        self.assertEqual(x.right, r)
        self.assertEqual(x.lineno, 42)

        # node raises exception when not given enough arguments
        self.assertRaises(TypeError, ast.BinOp, l, o)

        # can set attributes through kwargs too
        x = ast.BinOp(left=l, op=o, right=r, lineno=42)
        self.assertEqual(x.left, l)
        self.assertEqual(x.op, o)
        self.assertEqual(x.right, r)
        self.assertEqual(x.lineno, 42)

        # this used to fail because Sub._fields was None
        x = ast.Sub()
Exemplo n.º 17
0
def branch_dist(test):
    if isinstance(test.ops[0], ast.Eq):
        return 0, 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):
        return 1, 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):
        return 1, ast.BinOp(left=test.left,
                            op=ast.Sub(),
                            right=test.comparators[0])

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

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

    elif isinstance(test.ops[0], ast.GtE):
        return 0, ast.BinOp(left=test.comparators[0],
                            op=ast.Sub(),
                            right=test.left)
Exemplo n.º 18
0
 def visit_For(self, for_stmt):
     it = for_stmt.iter
     ty = "controls_forEach"
     if isinstance(it, ast.Call):
         if isinstance(it.func, ast.Name):
             if it.func.id == "range":
                 ty = "controls_for"
     else:
         root = self.add_block(for_stmt, ty)
         var = for_stmt.target
         if not isinstance(var, ast.Name):
             raise AssertionError
         self.visit(var)
         self.add_field(root, "VAR", var.id)
         if ty == "controls_for":
             args = it.args
             if len(args) == 1:
                 args.insert(0, ast.Num(n=0))
             else:
                 if len(args) == 2:
                     args.append(ast.Num(n=1))
                 self.add_value(root, "FROM", args[0])
                 if isinstance(args[1], ast.Num):
                     self.add_value(root, "TO", ast.Num(args[1].n - 1))
                 else:
                     self.add_value(
                         root,
                         "TO",
                         ast.BinOp(left=(args[1]),
                                   right=ast.Num(n=1),
                                   op=(ast.Sub())),
                     )
             self.add_value(root, "BY", args[2])
         else:
             self.add_value(root, "LIST", it)
     self.add_statement(root, "DO", for_stmt.body)
Exemplo n.º 19
0
 def visit_UnaryOp(self, node):
     assert isinstance(node.op, ast.USub), 'only unary minus is supported'
     self.visit(ast.Num(n=0))
     self.visit(node.operand)
     self.visit(ast.Sub())
Exemplo n.º 20
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=[])
Exemplo n.º 21
0
 def visit_BinOp(self, node):
     if isinstance(node.op, ast.Add):
         node.op = ast.Sub()
     return node
Exemplo n.º 22
0
    def visit_For(self, node):
        """
        function to be run while traversing ast node of `For` loops
        
            ast.For attributes: 'target', 'iter', 'body', 'orelse'
        """
        node = super().generic_visit(node)
        ## if iteration expression (iter) evaluates as a constant, using only (env) variables we determine it is unrollable
        try:
            iter_obj = eval(astor.to_source(node.iter), {}, self.env)
            is_constant = True
        except Exception as e:
            is_constant = False

        ## we only allow this transform on ranges, not on lists
        ## TODO: We could apply an additional type check and specialisation for lists below, better to do so outside of this tight for loop
        if is_constant and isinstance(iter_obj, range):

            if iter_obj.step not in [1, -1]:
                raise ValueError(
                    f'unrolling range({iter_obj.start}, {iter_obj.stop}, {iter_obj.step}) is not supported, '
                    f'only ranges with step=1, or step=-1 are supported, but {iter_obj.step} was provided'
                )

            iteration_range = abs(abs(iter_obj.start) - abs(iter_obj.stop))
            ## loop is NOP
            if iteration_range == 0:
                return None

            if self.factor > iteration_range:
                raise ValueError(
                    f'factor {self.factor} was larger than the iteration range of {iteration_range}'
                )

            if iteration_range % self.factor > 0:
                raise ValueError(
                    f'the iteration_range: {iteration_range} is not exactly divisible by factor: {self.factor}'
                )

            new_loop_body = []

            ## imcrementing range
            if iter_obj.stop > iter_obj.start:

                for unrol_iter in range(0, self.factor):
                    """
                    For each iteration to be unrolled, it appends the contents of the For loop body to the return list (after) 
                    replacing any instances of the loop variable with the current iteration's value. `ast.Num(i, kind=None)`
                    This is done using the symbol_table
                    """

                    replacement_ast_node = ast.BinOp(
                        left=ast.Name(id=node.target.id, ctx=ast.Load()),
                        op=ast.Add(),
                        right=ast.Num(n=unrol_iter, kind=None))

                    ## node.target.id is the iteration variable's name, eg `i` from the example `for i in range(4)` which is replaced by the iteration's value of i
                    symbol_table = {node.target.id: replacement_ast_node}

                    ## iterating through loop body
                    for body_object in node.body:
                        new_loop_body.append(
                            replace_symbols(tree=deepcopy(body_object),
                                            symbol_table=symbol_table))

                ## create new ast.For object with the newly unrolled loop body
                replacement_for_node = ast.For(
                    target=ast.Name(id='i', ctx=ast.Store()),
                    iter=ast.Call(func=ast.Name(id='range', ctx=ast.Load()),
                                  args=[
                                      ast.Num(n=iter_obj.start),
                                      ast.Num(n=iter_obj.stop),
                                      ast.Num(n=self.factor),
                                  ],
                                  keywords=[]),
                    body=new_loop_body,
                    orelse=[])

                return replacement_for_node

            ## decrementing range
            else:

                for unroll_iteration in range(0, self.factor):
                    """
                    For each iteration to be unrolled, it appends the contents of the For loop body to the return list (after) 
                    replacing any instances of the loop variable with the current iteration's value. `ast.Num(i, kind=None)`
                    This is done using the symbol_table
                    """

                    replacement_ast_node = ast.BinOp(
                        left=ast.Name(id=node.target.id, ctx=ast.Load()),
                        op=ast.Sub(),
                        right=ast.Num(n=unroll_iteration, kind=None))

                    ## node.target.id is the iteration variable's name, eg `i` from the example `for i in range(4)` which is replaced by the iteration's value of i
                    symbol_table = {node.target.id: replacement_ast_node}

                    ## iterating through loop body
                    for body_object in node.body:
                        new_loop_body.append(
                            replace_symbols(tree=deepcopy(body_object),
                                            symbol_table=symbol_table))

                ## create new ast.For object with the newly unrolled loop body
                replacement_for_node = ast.For(
                    target=ast.Name(id='i', ctx=ast.Store()),
                    iter=ast.Call(func=ast.Name(id='range', ctx=ast.Load()),
                                  args=[
                                      ast.Num(n=iter_obj.start),
                                      ast.Num(n=iter_obj.stop),
                                      ast.Num(n=self.factor * -1),
                                  ],
                                  keywords=[]),
                    body=new_loop_body,
                    orelse=iter_obj.orelse)

                return replacement_for_node

        ## if isinstance of a general iterator over say a list, could likely do the same trick as above over the list indicies
        elif is_constant and isinstance(iter_obj, unroll):
            raise NotImplementedError(
                'Only implemented for `for` loops which iterate over a range, eg `for i in range(22)`'
            )

        return node
Exemplo n.º 23
0
 def aor_mutation_on_subtraction():
     return operators.Mutation(
         operator=operators.ArithmeticOperatorReplacement,
         node=ast.Sub(children=[]))
Exemplo n.º 24
0
    def __repr__(self):
        return "comment"


COMMENT = Comment()


class Char(object):
    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(),
Exemplo n.º 25
0
 def test_str(self):
     for op, char in zip((ast.Add(), ast.Sub(), ast.Mult(), ast.Div()), "+-*/"):
         res = OpResult("X1", Mod(0, 5), op, Mod(2, 5), Mod(3, 5))
         self.assertEqual(str(res), "X1")
Exemplo n.º 26
0
 def test_no_fields(self):
     # this used to fail because Sub._fields was None
     x = ast.Sub()
     self.assertEqual(x._fields, ())
Exemplo n.º 27
0
 def test_SubAssign(self):
     py_ast = ast.AugAssign(ast.Name('i', ast.Load()), ast.Sub(),
                            ast.Num(3))
     c_ast = SubAssign(SymbolRef('i'), Constant(3))
     self._check(py_ast, c_ast)
Exemplo n.º 28
0
 def __sub__(self, other):
     return BinOp(self, ast.Sub(), other)
Exemplo n.º 29
0
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
Exemplo n.º 30
0
def branch_dist_not(test, args):
    return ast.BinOp(left=ast.Num(n=args.k),
                     op=ast.Sub(),
                     right=branch_dist(test.operand, args))