예제 #1
0
파일: test_ast.py 프로젝트: Qointum/pypy
    def test_classattrs(self):
        import ast
        x = ast.Num()
        assert x._fields == ('n', )
        exc = raises(AttributeError, getattr, x, 'n')
        assert str(exc.value) == "'Num' object has no attribute 'n'"

        x = ast.Num(42)
        assert x.n == 42
        exc = raises(AttributeError, getattr, x, 'lineno')
        assert str(exc.value) == "'Num' object has no attribute 'lineno'"

        y = ast.Num()
        x.lineno = y
        assert x.lineno == y

        exc = raises(AttributeError, getattr, x, 'foobar')
        assert str(exc.value) == "'Num' object has no attribute 'foobar'"

        x = ast.Num(lineno=2)
        assert x.lineno == 2

        x = ast.Num(42, lineno=0)
        assert x.lineno == 0
        assert x._fields == ('n', )
        assert x.n == 42

        raises(TypeError, ast.Num, 1, 2)
        raises(TypeError, ast.Num, 1, 2, lineno=0)
예제 #2
0
파일: test_ast.py 프로젝트: Qointum/pypy
 def test_node_identity(self):
     import _ast as ast
     n1 = ast.Num(1)
     n3 = ast.Num(3)
     addop = ast.Add()
     x = ast.BinOp(n1, addop, n3)
     assert x.left == n1
     assert x.op == addop
     assert x.right == n3
예제 #3
0
  def visit_For( self, node ):
    self.generic_visit( node )

    if not ( isinstance( node.iter,      _ast.Call ) and
             isinstance( node.iter.func, _ast.Name ) and
             node.iter.func.id in ['range', 'xrange'] ):
      raise VerilogTranslationError(
        'For loops are only translatable when using range or xrange!\n'
        'Please use "for i in range(...)/xrange(...)".',
        node.lineno
      )

    call = node.iter

    if   len( call.args ) == 1:
      start = _ast.Num( n=0 )
      stop  = call.args[0]
      step  = _ast.Num( n=1 )
    elif len( call.args ) == 2:
      start = call.args[0]
      stop  = call.args[1]
      step  = _ast.Num( n=1 ) # TODO: should be an expression
    elif len( call.args ) == 3:
      start = call.args[0]
      stop  = call.args[1]
      step  = call.args[2]
    else:
      raise VerilogTranslationError(
        'An invalid number of arguments provided to (x)range function!\n',
        node.lineno
      )

    # Must know if the step is negative or positive in order to set the
    # correct bound check. This is because of Python's range behavior.
    try:
      if   hasattr( step, '_object' ): step_val = step._object
      elif hasattr( step, 'n'       ): step_val = step.n
      assert step_val != 0
    except (UnboundLocalError,AssertionError):
      raise VerilogTranslationError(
        'An error occurred when translating a "for loop"!\n'
        'The "step" parameter to range must be a constant integer value != 0!',
        node.lineno
      )

    node.iter       = _ast.Slice( lower=start, upper=stop, step=step )
    node.iter.lt_gt = '<' if step_val > 0 else '>'

    return node
예제 #4
0
    def visit_Expr(self, expression_node):
        value = expression_node.value
        if not isinstance(value, _ast.BinOp) or not isinstance(
                value.op, _ast.Mult) or not isinstance(value.right, _ast.Call):
            return expression_node

        number_of_invocations = value.left
        if MockAssertionTransformer._value_is_a_wildcard(
                number_of_invocations):
            number_of_invocations = _ast.Num(n=-1)
        target_mock = value.right.func.value
        target_method = _ast.Str(s=value.right.func.attr)

        list_of_arguments = [
            MockAssertionTransformer._transform_arg_if_wildcard(x)
            for x in value.right.args
        ]
        spread_list_of_arguments = _ast.Starred(value=_ast.List(
            elts=list_of_arguments, ctx=_ast.Load()),
                                                ctx=_ast.Load())
        expression_node.value = _ast.Call(
            func=_ast.Attribute(value=_ast.Name(id='self', ctx=_ast.Load()),
                                attr='_assert_mock',
                                ctx=_ast.Load()),
            args=[
                number_of_invocations, target_mock, target_method,
                spread_list_of_arguments
            ],
            keywords=[])
        return expression_node
예제 #5
0
 def separate_assing_nodes(self, node: _ast.Assign, variables_names,
                           variables):
     if isinstance(node.targets[0], _ast.Tuple):
         tuple_key = meta.values_for_ast_type[type(node.targets[0])]
         for num, target_node in enumerate(
                 getattr(node.targets[0], tuple_key)):
             if isinstance(node.value, _ast.Tuple):
                 inner_value = getattr(node.value, tuple_key)[num]
             else:
                 node_value = self.get_value(node.value, variables_names,
                                             variables)
                 if isinstance(node_value, dict):
                     inner_value = _ast.Subscript(
                         value=node.value,
                         slice=_ast.Index(value=_ast.Num(n=num)))
                 else:
                     inner_value = node_value
             var = _ast.Assign(targets=[target_node], value=inner_value)
             yield var
     elif isinstance(node.value, _ast.List):
         for target in node.targets:
             for elem in node.value.elts:
                 # for items
                 var = _ast.Assign(targets=[target], value=elem)
                 yield var
     elif isinstance(node.value, _ast.Call):
         value = self.get_value(node.value, variables_names, variables)
         for target in node.targets:
             # for items in call result
             var = _ast.Assign(targets=[target], value=value)
             yield var
예제 #6
0
파일: test_ast.py 프로젝트: Qointum/pypy
 def test_issue1673_Num_notfullinit(self):
     import ast
     import copy
     num_node = ast.Num(n=2, lineno=2)
     assert num_node.n == 2
     assert num_node.lineno == 2
     num_node2 = copy.deepcopy(num_node)
예제 #7
0
파일: pyc_emitter.py 프로젝트: smac89/angle
 def visit_str(self, x):
     if x == '0': return _ast.Num(0)
     if x == 'False': return kast.false
     if isinstance(self.current, (ast.Str, ast.Name, ast.FunctionDef,
                                  ast.Attribute, ast.alias, ast.keyword)):
         return x  # todo: whitelist!!
     return ast.Str(x)
예제 #8
0
    def while_loop(self, instr, loop_block):

        kw = dict(lineno=instr.lineno, col_offset=0)

        loop_block_map = {instr.i: instr.op for instr in loop_block}

        first_i = loop_block[0].i

        func = lambda instr: instr.opname == 'JUMP_ABSOLUTE' and instr.oparg == first_i
        body_index = rfind_index(loop_block[:-1], func)

        if body_index is None:
            const_while = True
            body_index = len(loop_block) - 1
        else:
            if body_index + 1 < len(loop_block):
                pop_block = loop_block[body_index + 1]
                const_while = pop_block.opname != 'POP_BLOCK'
                const_else = True
            else:
                const_while = True
                const_else = False

        if const_while:
            test = _ast.Num(1, **kw)
            body_ = self.decompile_block(loop_block[:body_index]).stmnt()

            else_block = loop_block[body_index + 1:]
            if else_block:
                else_ = self.decompile_block(else_block).stmnt()
            else:
                else_ = []
        else:
            pop_block = loop_block[body_index + 1]

            func = lambda instr: instr.opname in [
                'POP_JUMP_IF_FALSE', 'POP_JUMP_IF_TRUE'
            ] and instr.oparg == pop_block.i
            idx = rfind_index(loop_block[:body_index], func)
            cond_block = loop_block[:idx]

            iter_stmnt = self.decompile_block(cond_block).stmnt()
            assert len(iter_stmnt) == 1
            test = iter_stmnt[0]

            body_ = self.decompile_block(loop_block[idx +
                                                    1:body_index]).stmnt()

            else_block = loop_block[body_index + 2:]
            if else_block:
                else_ = self.decompile_block(else_block[:]).stmnt()
            else:
                else_ = []

        while_ = _ast.While(test=test, body=body_, orelse=else_, **kw)

        self.ast_stack.append(while_)
예제 #9
0
파일: test_ast.py 프로젝트: Qointum/pypy
 def test_issue1673_Num_fullinit(self):
     import ast
     import copy
     num_node = ast.Num(n=2, lineno=2, col_offset=3)
     num_node2 = copy.deepcopy(num_node)
     assert num_node.n == num_node2.n
     assert num_node.lineno == num_node2.lineno
     assert num_node.col_offset == num_node2.col_offset
     dict_res = num_node2.__dict__
     assert dict_res == {'n': 2, 'lineno': 2, 'col_offset': 3}
예제 #10
0
 def test_compare(self):
     import ast
     
     def _mod(mod, msg=None, mode="exec", exc=ValueError):
         mod.lineno = mod.col_offset = 0
         ast.fix_missing_locations(mod)
         exc = raises(exc, compile, mod, "<test>", mode)
         if msg is not None:
             assert msg in str(exc.value)
     def _expr(node, msg=None, exc=ValueError):
         mod = ast.Module([ast.Expr(node)])
         _mod(mod, msg, exc=exc)
     left = ast.Name("x", ast.Load())
     comp = ast.Compare(left, [ast.In()], [])
     _expr(comp, "no comparators")
     comp = ast.Compare(left, [ast.In()], [ast.Num(4), ast.Num(5)])
     _expr(comp, "different number of comparators and operands")
     comp = ast.Compare(ast.Num("blah"), [ast.In()], [left])
     _expr(comp, "non-numeric", exc=TypeError)
     comp = ast.Compare(left, [ast.In()], [ast.Num("blah")])
     _expr(comp, "non-numeric", exc=TypeError)
예제 #11
0
  def visit_For(self, node):

    #try:
      if node.iter.func.id != 'range':
        raise AttributeError()

      args    = node.iter.args
      lower   = args[0] if len( args ) > 1 else _ast.Num(0)
      upper   = args[1] if len( args ) > 1 else args[0]
      step    = args[2] if len( args ) > 2 else _ast.Num(1)
      i       = node.target.id

      print  >> self.o, (self.ident+2)*" " + "for (int {}=".format(i),
      self.visit( lower )
      print  >> self.o, "; {}<".format(i),
      self.visit( upper )
      print  >> self.o, "; {0}={0}+".format(i),
      self.visit( step )
      print  >> self.o, ") { "
      for x in node.body:
        self.visit(x)
      print  >> self.o, (self.ident+2)*" " + "}"
예제 #12
0
 def make_const(i, bytecode):
   arg = bytecode[i][3]
   if isinstance(arg, basestring):
     return i, _ast.Str(arg)
   elif isinstance(arg, int) or isinstance(arg, float) or isinstance(arg, long):
     return i, _ast.Num(arg)
   elif isinstance(arg, dict):
     return i, _ast.Dict(arg.keys(), arg.values())
   elif isinstance(arg, set):
     return i, _ast.Dict(arg)
   elif isinstance(arg, tuple):
     return i, _ast.Tuple(arg, _ast.Load())
   elif isinstance(arg, list):
     return i, _ast.List(arg, _ast.Load())
   elif isinstance(arg, bytes):
     return i, _ast.Bytes(arg)
   return i, None
def make_const(arg, lineno=0, col_offset=0):
    kw = {'lineno': lineno, 'col_offset': col_offset}

    if isinstance(arg, str):
        const = _ast.Str(s=arg, **kw)
    elif isinstance(arg, (int, float, complex)):
        const = _ast.Num(n=arg, **kw)
    elif arg is None:
        const = _ast.Name(id='None', ctx=_ast.Load(), **kw)
    elif isinstance(arg, tuple):
        elts = []
        for item in arg:
            elts.append(make_const(item, **kw))
        const = _ast.Tuple(elts=elts, ctx=_ast.Load(), **kw)
    else:
        const = arg

    return const
예제 #14
0
파일: test_ast.py 프로젝트: purepython/pypy
 def test_list_syncing(self):
     ast = self.ast
     mod = ast.Module([ast.Lt()])
     raises(TypeError, compile, mod, "<string>", "exec")
     mod = self.get_ast("x = y = 3")
     assign = mod.body[0]
     assert len(assign.targets) == 2
     assign.targets[1] = ast.Name("lemon", ast.Store(),
                                  lineno=0, col_offset=0)
     name = ast.Name("apple", ast.Store(),
                     lineno=0, col_offset=0)
     mod.body.append(ast.Assign([name], ast.Num(4, lineno=0, col_offset=0),
                                lineno=0, col_offset=0))
     co = compile(mod, "<test>", "exec")
     ns = {}
     exec co in ns
     assert "y" not in ns
     assert ns["x"] == ns["lemon"] == 3
     assert ns["apple"] == 4
예제 #15
0
파일: test_ast.py 프로젝트: Qointum/pypy
 def test_bug_null_in_objspace_type(self):
     import ast
     code = ast.Expression(
         lineno=1,
         col_offset=1,
         body=ast.ListComp(
             lineno=1,
             col_offset=1,
             elt=ast.Call(lineno=1,
                          col_offset=1,
                          func=ast.Name(lineno=1,
                                        col_offset=1,
                                        id='str',
                                        ctx=ast.Load(lineno=1,
                                                     col_offset=1)),
                          args=[
                              ast.Name(lineno=1,
                                       col_offset=1,
                                       id='x',
                                       ctx=ast.Load(lineno=1, col_offset=1))
                          ],
                          keywords=[]),
             generators=[
                 ast.comprehension(
                     lineno=1,
                     col_offset=1,
                     target=ast.Name(lineno=1,
                                     col_offset=1,
                                     id='x',
                                     ctx=ast.Store(lineno=1, col_offset=1)),
                     iter=ast.List(
                         lineno=1,
                         col_offset=1,
                         elts=[ast.Num(lineno=1, col_offset=1, n=23)],
                         ctx=ast.Load(
                             lineno=1,
                             col_offset=1,
                         )),
                     ifs=[])
             ]))
     compile(code, '<template>', 'eval')
예제 #16
0
def parseString(a, v,tag=None):
    if not v: return None
    # if(a=='name'):return v
    # if(isinstance(v,Na)
    v=v.strip()
    if(v.isdigit()):v= _ast.Num(int(v)) #todo: float!
    elif(v.startswith("[") and tag!="Call" and tag!="Assign"): # too much suggar??
        args=v[1:-1].replace(","," ").split(" ")
        v=[]
        for arg in args:
            if(arg.isdigit()):v.append(Num(int(arg)))
            else:v.append(name(id=arg,ctx=Load()))
    elif(v.startswith("'")):
        v=Str(v[1:-1])
    elif(a!='id'):
        ctx=Load()
        if a=='func' or a=='value' or a=='values':
            ctx=Load()
        if a=='target':
            ctx=Store()
        v=name(id=v,ctx=ctx,tag=tag)
    return v
예제 #17
0
def _cfa(body, state, on_gen):
    assert isinstance(on_gen, list)
    for c in on_gen:
        assert callable(c)

    cfg = state.cfg

    def make_connect(cur_bid):
        assert isinstance(cur_bid, int)

        def inner(new_bid):
            assert isinstance(new_bid, int)
            state.connect([cur_bid], [new_bid])

        return inner

    def push_block(block):
        block_id = len(cfg.blocks)
        assert block_id not in cfg.blocks
        cfg.blocks[block_id] = block
        for c in on_gen:
            c(block_id)
        return block_id

    cur_block = []

    for b in body:
        if REDUCE_FORS_TO_WHILES and isinstance(b, _ast.For):
            if isinstance(b.iter, _ast.Call) and isinstance(
                    b.iter.func,
                    _ast.Name) and b.iter.func.id in ("range", "xrange"):
                if not b.iter.keywords and not b.iter.starargs and not b.iter.kwargs:
                    end_var = "__wfend_%d_%d_" % (b.lineno, b.col_offset)
                    iter_var = "__wfiter_%d_%d_" % (b.lineno, b.col_offset)
                    if len(b.iter.args) in (1, 2):
                        if len(b.iter.args) == 1:
                            start = _ast.Num(0)
                            end = b.iter.args[0]
                        elif len(b.iter.args) == 2:
                            start = b.iter.args[0]
                            end = b.iter.args[1]
                        else:
                            start = b.iter.args[0]
                            end = b.iter.args[1]
                        cur_block.append(
                            _ast.Assign([
                                _ast.Name(
                                    iter_var, _ast.Store(), not_real=True)
                            ],
                                        start,
                                        lineno=b.lineno,
                                        col_offset=b.col_offset,
                                        not_real=True))
                        cur_block.append(
                            _ast.Assign([
                                _ast.Name(end_var, _ast.Store(), not_real=True)
                            ],
                                        end,
                                        lineno=b.lineno,
                                        col_offset=b.col_offset,
                                        not_real=True))

                        body = [
                            _ast.Assign([b.target],
                                        _ast.Name(iter_var,
                                                  _ast.Load(),
                                                  not_real=True),
                                        lineno=b.lineno,
                                        col_offset=b.col_offset,
                                        not_real=True),
                            _ast.Assign([
                                _ast.Name(
                                    iter_var, _ast.Store(), not_real=True)
                            ],
                                        _ast.BinOp(
                                            _ast.Name(iter_var,
                                                      _ast.Load(),
                                                      not_real=True),
                                            _ast.Add(), _ast.Num(1)),
                                        lineno=b.lineno,
                                        col_offset=b.col_offset,
                                        not_real=True)
                        ] + b.body
                        b = _ast.While(_ast.Compare(
                            _ast.Name(iter_var, _ast.Load(),
                                      not_real=True), [_ast.Lt()],
                            [_ast.Name(end_var, _ast.Load(), not_real=True)],
                            lineno=b.lineno,
                            col_offset=b.col_offset,
                            not_real=True),
                                       body,
                                       b.orelse,
                                       not_real=True)

        if isinstance(b, (
                _ast.Assign,
                _ast.AugAssign,
                _ast.ClassDef,
                _ast.Delete,
                _ast.Exec,
                _ast.Expr,
                _ast.FunctionDef,
                _ast.Global,
                _ast.Import,
                _ast.ImportFrom,
                _ast.Print,
                _ast.Pass,
        )):
            cur_block.append(b)
        elif isinstance(b, _ast.Assert):
            cur_block.append(b)
            if isinstance(b.test, _ast.Call) and isinstance(
                    b.test.func, _ast.Name
            ) and b.test.func.id == "isinstance" and isinstance(
                    b.test.args[0], _ast.Name) and isinstance(
                        b.test.args[1], _ast.Name):
                varname = b.test.args[0].id
                cast = _ast.Call(_ast.Name(
                    "__cast__", _ast.Load(), not_real=True, **pos(b)), [
                        _ast.Name(
                            varname, _ast.Store(), not_real=True, **pos(b)),
                        b.test.args[1]
                    ], [],
                                 None,
                                 None,
                                 not_real=True,
                                 **pos(b))
                assign = _ast.Assign([
                    _ast.Name(varname, _ast.Store(), not_real=True, **pos(b))
                ],
                                     cast,
                                     not_real=True,
                                     lineno=b.lineno,
                                     col_offset=b.col_offset)
                cur_block.append(assign)
        elif isinstance(b, (_ast.Break, _ast.Continue)):
            f = state.add_break if isinstance(
                b, _ast.Break) else state.add_continue
            if cur_block:
                j = Jump()
                cur_block.append(j)
                block_id = push_block(cur_block)
                f(j.set_dest)
                f(make_connect(block_id))
            else:
                for c in on_gen:
                    f(c)
            return []
        elif isinstance(b, _ast.If):
            br = Branch(b.test, lineno=b.lineno)
            cur_block.append(br)
            next_block = push_block(cur_block)
            on_gen = None  # make sure this doesn't get used
            cur_block = []

            gen_true = [br.set_true, make_connect(next_block)]
            gen_false = [br.set_false, make_connect(next_block)]
            if ENFORCE_NO_MULTIMULTI:
                on_gen = gen_true
                j1 = Jump()
                gen_true = [make_connect(push_block([j1])), j1.set_dest]

                on_gen = gen_false
                j2 = Jump()
                gen_false = [make_connect(push_block([j2])), j2.set_dest]

                on_gen = None

            assert b.body
            body = b.body
            if isinstance(b.test, _ast.Call) and isinstance(
                    b.test.func, _ast.Name
            ) and b.test.func.id == "isinstance" and isinstance(
                    b.test.args[0], _ast.Name) and isinstance(
                        b.test.args[1], _ast.Name):
                varname = b.test.args[0].id
                cast = _ast.Call(_ast.Name(
                    "__cast__", _ast.Load(), not_real=True, **pos(b)), [
                        _ast.Name(
                            varname, _ast.Store(), not_real=True, **pos(b)),
                        b.test.args[1]
                    ], [],
                                 None,
                                 None,
                                 not_real=True,
                                 **pos(b))
                assign = _ast.Assign([
                    _ast.Name(varname, _ast.Store(), not_real=True, **pos(b))
                ],
                                     cast,
                                     not_real=True,
                                     lineno=b.lineno,
                                     col_offset=b.col_offset)
                body = [assign] + body
            if ADD_IF_ASSERTS:
                body = [_ast.Assert(b.test, None, not_real=True, **pos(b))
                        ] + body
            ending_gen = _cfa(body, state, gen_true)
            if b.orelse:
                ending_gen += _cfa(b.orelse, state, gen_false)
            else:
                ending_gen += gen_false
            on_gen = ending_gen

            if not on_gen and PRUNE_UNREACHABLE_BLOCKS:
                return []
        elif isinstance(b, _ast.TryExcept):
            j = Jump()
            cur_block.append(j)
            next_block = push_block(cur_block)
            on_gen = [j.set_dest, make_connect(next_block)]
            cur_block = []

            on_gen = _cfa(b.body, state, on_gen)

            # Set this to evaluate a string to try to defeat simple flow analysis
            br = Branch(_ast.Str("nonzero"))
            next_block = push_block([br])

            on_except = [br.set_false, make_connect(next_block)]
            on_fine = [br.set_true, make_connect(next_block)]

            assert len(b.handlers) >= 1
            # for handler in b.handlers:
            # on_except = _cfa(b.handlers[0].body, state, on_except)

            if b.orelse:
                on_fine = _cfa(b.orelse, state, on_fine)

            if ENFORCE_NO_MULTIMULTI:
                j = Jump()
                on_gen = on_fine
                next_block = push_block([j])
                on_fine = [j.set_dest, make_connect(next_block)]

                j = Jump()
                on_gen = on_except
                next_block = push_block([j])
                on_except = [j.set_dest, make_connect(next_block)]

            on_gen = on_fine + on_except
            cur_block = []
        elif isinstance(b, _ast.TryFinally):
            j = Jump()
            cur_block.append(j)
            next_block = push_block(cur_block)
            on_gen = [j.set_dest, make_connect(next_block)]
            cur_block = []

            on_gen = _cfa(b.body, state, on_gen)
            on_gen = _cfa(b.finalbody, state, on_gen)
        elif isinstance(b, _ast.While):
            # This could also be architected as having no extra block and having two jump statements, but I don't like that
            if cur_block:
                j = Jump()
                cur_block.append(j)
                on_gen = [make_connect(push_block(cur_block)), j.set_dest]
                cur_block = []

            always_true = False
            always_false = False
            if isinstance(b.test, _ast.Name):
                if b.test.id == "True":
                    always_true = True
                elif b.test.id == "False":
                    always_false = True
            elif isinstance(b.test, _ast.Num):
                if b.test.n:
                    always_true = True
                else:
                    always_false = True

            if always_true:
                br = Jump()
                on_true = br.set_dest
            elif always_false:
                br = Jump()
                on_false = br.set_dest
            else:
                br = Branch(b.test)
                on_true = br.set_true
                on_false = br.set_false
            init_id = push_block([br])
            on_gen = None
            assert cur_block == []  # just checking

            if not always_false:
                gen_true = [on_true, make_connect(init_id)]
            if not always_true:
                gen_false = [on_false, make_connect(init_id)]
            if ENFORCE_NO_MULTIMULTI:
                if not always_false:
                    on_gen = gen_true
                    j1 = Jump()
                    gen_true = [make_connect(push_block([j1])), j1.set_dest]

                if not always_true:
                    on_gen = gen_false
                    j2 = Jump()
                    gen_false = [make_connect(push_block([j2])), j2.set_dest]

                on_gen = None

            ending_gen = []
            if not always_false:
                state.push_loop()
                assert b.body
                loop_ending_gen = _cfa(b.body, state, gen_true)
                loop_ending_gen += state.get_continues()
                for c in loop_ending_gen:
                    c(init_id)
                ending_gen = state.get_breaks()
                state.pop_loop()

            if not always_true:
                if b.orelse:
                    ending_gen += _cfa(b.orelse, state, gen_false)
                else:
                    ending_gen += gen_false

            on_gen = ending_gen
            if not on_gen and PRUNE_UNREACHABLE_BLOCKS:
                return []
        elif isinstance(b, _ast.For):
            iter_func = _ast.Attribute(b.iter,
                                       "__iter__",
                                       _ast.Load(),
                                       not_real=True,
                                       lineno=b.lineno,
                                       col_offset=b.col_offset)
            iter_call = _ast.Call(iter_func, [], [],
                                  None,
                                  None,
                                  not_real=True,
                                  lineno=b.lineno,
                                  col_offset=b.col_offset)
            # iter_var = _make_temp_name()
            iter_var = "__foriter_%d_%d_" % (b.lineno, b.col_offset)
            iter_assign = _ast.Assign(
                [_ast.Name(iter_var, _ast.Store(), not_real=True, **pos(b))],
                iter_call,
                not_real=True,
                lineno=b.lineno,
                col_offset=b.col_offset)
            cur_block.append(iter_assign)

            j = Jump()
            cur_block.append(j)
            on_gen = [make_connect(push_block(cur_block)), j.set_dest]
            cur_block = []

            br = Branch(
                HasNext(
                    _ast.Name(iter_var, _ast.Load(), not_real=True, **pos(b)),
                    **pos(b)), **pos(b))
            init_id = push_block([br])
            on_gen = None
            assert cur_block == []  # just checking

            gen_true = [br.set_true, make_connect(init_id)]
            gen_false = [br.set_false, make_connect(init_id)]
            if ENFORCE_NO_MULTIMULTI:
                on_gen = gen_true
                j1 = Jump()
                gen_true = [make_connect(push_block([j1])), j1.set_dest]

                on_gen = gen_false
                j2 = Jump()
                gen_false = [make_connect(push_block([j2])), j2.set_dest]

                on_gen = None

            ending_gen = []

            state.push_loop()

            next_func = _ast.Attribute(_ast.Name(iter_var,
                                                 _ast.Load(),
                                                 not_real=True,
                                                 **pos(b)),
                                       "next",
                                       _ast.Load(),
                                       not_real=True,
                                       lineno=b.lineno,
                                       col_offset=b.col_offset)
            next = _ast.Call(next_func, [], [],
                             None,
                             None,
                             not_real=True,
                             lineno=b.lineno,
                             col_offset=b.col_offset)
            next_assign = _ast.Assign([b.target],
                                      next,
                                      not_real=True,
                                      lineno=b.lineno,
                                      col_offset=b.col_offset)
            next_iter_gen = _cfa([next_assign] + b.body, state, gen_true)
            next_iter_gen += state.get_continues()
            for c in next_iter_gen:
                c(init_id)

            loop_done_gen = list(state.get_breaks())

            state.pop_loop()

            if b.orelse:
                # if b.orelse and loop_ending_blocks:
                loop_done_gen += _cfa(b.orelse, state, gen_false)
            else:
                loop_done_gen += gen_false

            on_gen = loop_done_gen
            if not on_gen and PRUNE_UNREACHABLE_BLOCKS:
                return []
        elif isinstance(b, (_ast.Return, _ast.Raise)):
            cur_block.append(b)
            block_id = push_block(cur_block)
            state.returns.append(make_connect(block_id))
            return []
        elif isinstance(b, _ast.With):
            # XXX totally ignores the functionality of with statements

            # Have to save the context manager because the expression might not be valid later
            mgr_name = "__mgr_%s_%s_" % (b.lineno, b.col_offset)
            save_mgr = _ast.Assign([
                _ast.Name(mgr_name,
                          _ast.Store(),
                          lineno=b.lineno,
                          col_offset=b.col_offset,
                          not_real=True)
            ],
                                   b.context_expr,
                                   lineno=b.lineno,
                                   col_offset=b.col_offset,
                                   not_real=True)

            enter_func = _ast.Attribute(_ast.Name(mgr_name,
                                                  _ast.Load(),
                                                  lineno=b.lineno,
                                                  col_offset=b.col_offset,
                                                  not_real=True),
                                        "__enter__",
                                        _ast.Load(),
                                        lineno=b.lineno,
                                        col_offset=b.col_offset,
                                        not_real=True)
            bind = _ast.Call(enter_func, [], [],
                             None,
                             None,
                             lineno=b.lineno,
                             col_offset="__enter__()",
                             not_real=True)

            if b.optional_vars:
                assert isinstance(b.optional_vars, _ast.AST)
                init = _ast.Assign([b.optional_vars],
                                   bind,
                                   lineno=b.lineno,
                                   col_offset=b.col_offset,
                                   not_real=True)
            else:
                init = _ast.Expr(bind,
                                 lineno=b.lineno,
                                 col_offset=b.col_offset,
                                 not_real=True)

            exit_func = _ast.Attribute(_ast.Name(mgr_name,
                                                 _ast.Load(),
                                                 lineno=b.lineno,
                                                 col_offset=b.col_offset,
                                                 not_real=True),
                                       "__exit__",
                                       _ast.Load(),
                                       lineno=b.lineno,
                                       col_offset=b.col_offset,
                                       not_real=True)
            if SIMPLE_WITH_EXIT:
                exit_call = _ast.Call(exit_func, [], [],
                                      None,
                                      None,
                                      lineno=b.lineno,
                                      col_offset=b.col_offset,
                                      not_real=True)
            else:
                none_ = _ast.Name("None",
                                  _ast.Load(),
                                  lineno=b.lineno,
                                  col_offset=b.col_offset,
                                  not_real=True)
                exit_call = _ast.Call(exit_func, [none_, none_, none_], [],
                                      None,
                                      None,
                                      lineno=b.lineno,
                                      col_offset=b.col_offset,
                                      not_real=True)
            exit = _ast.Expr(exit_call,
                             lineno=b.lineno,
                             col_offset="__exit__()",
                             not_real=True)

            cur_block.extend([save_mgr, init])
            j = Jump()
            cur_block.append(j)
            next_block = push_block(cur_block)
            on_gen = [j.set_dest, make_connect(next_block)]
            cur_block = []

            body = b.body + [exit]
            next_gen = _cfa(body, state, on_gen)
            on_gen = next_gen
        else:
            raise Exception(b)

    if cur_block:
        j = Jump()
        cur_block.append(j)
        next = push_block(cur_block)
        return [j.set_dest, make_connect(next)]
    return on_gen

    return on_gen
예제 #18
0
 def visit_Name( self, node ):
   if node.id in self.captured_vars:
     return _ast.Num( n=self.captured_vars[ node.id ] )
   else:
     return node
예제 #19
0
def Num(number):
    """Creates an _ast.Num node."""
    return _ast.Num(number)
예제 #20
0
파일: test_ast.py 프로젝트: Qointum/pypy
 def test_dict_astNode(self):
     import ast
     num_node = ast.Num(n=2, lineno=2, col_offset=3)
     dict_res = num_node.__dict__
     assert dict_res == {'n': 2, 'lineno': 2, 'col_offset': 3}
예제 #21
0
 def visit_Num(self, node):
     if self.randomize():
         number = random.random() * node.n
         return ast.copy_location(_ast.Num(n=number), node)
     else:
         return node
예제 #22
0
파일: test_ast.py 프로젝트: Qointum/pypy
 def test_field_attr_writable(self):
     import _ast as ast
     x = ast.Num()
     # We can assign to _fields
     x._fields = 666
     assert x._fields == 666
예제 #23
0
 def num(n=None):
     return _ast.Num(n=n)
예제 #24
0
def test_return_value_is_int_zero():
    # when method return 0
    assert ReturnedExpression(_ast.Return(value=_ast.Num(n=0),
                                          lineno=1)).value_not_none() is True
예제 #25
0
def test_return_value_is_float_limit_to_zero():
    # when method return 0.0000000000000000000000001
    assert ReturnedExpression(
        _ast.Return(value=_ast.Num(n=0.0000000000000000000000001),
                    lineno=1), ).value_not_none() is True