Esempio n. 1
0
    def setup_method(self, method):
        def c(x, y, *args):
            pass

        code = PyCode._from_code(self.space, c.func_code)

        class ConcreteFastscopeFrame(Frame):
            def __init__(self, space, code, numlocals):
                self.code = code
                Frame.__init__(self, space)
                self.numlocals = numlocals
                self._fastlocals_w = [None] * self.numlocals

            def getcode(self):
                return self.code

            def setfastscope(self, scope_w):
                self._fastlocals_w = scope_w

            def getfastscope(self):
                return self._fastlocals_w

            def getfastscopelength(self):
                return self.numlocals

        self.f = ConcreteFastscopeFrame(self.space, code, numlocals=5)
Esempio n. 2
0
    def test_flatcall(self):
        space = self.space

        def f(a):
            return a

        code = PyCode._from_code(self.space, f.func_code)
        fn = Function(self.space, code, self.space.newdict())

        assert fn.code.fast_natural_arity == 1 | PyCode.FLATPYCALL

        def bomb(*args):
            assert False, "shortcutting should have avoided this"

        code.funcrun = bomb
        code.funcrun_obj = bomb

        w_3 = space.newint(3)
        w_res = space.call_function(fn, w_3)

        assert w_res is w_3

        w_res = space.appexec([fn, w_3], """(f, x):
        return f(x)
        """)

        assert w_res is w_3
Esempio n. 3
0
    def setup_method(self, method):
        def c(x, y, *args):
            pass
        code = PyCode._from_code(self.space, c.func_code)

        class ConcreteFastscopeFrame(Frame):
            
            def __init__(self, space, code, numlocals):
                self.code = code
                Frame.__init__(self, space)
                self.numlocals = numlocals
                self.fastlocals_w = [None] * self.numlocals

            def getcode(self):
                return self.code

            def setfastscope(self, scope_w):
                self.fastlocals_w = scope_w

            def getfastscope(self):
                return self.fastlocals_w

            def getfastscopelength(self):
                return self.numlocals

        self.f = ConcreteFastscopeFrame(self.space, code, numlocals=5)
Esempio n. 4
0
    def test_flatcall_default_arg(self):
        space = self.space

        def f(a, b):
            return a+b
        code = PyCode._from_code(self.space, f.func_code)
        fn = Function(self.space, code, self.space.newdict(),
                      defs_w=[space.newint(1)])

        assert fn.code.fast_natural_arity == 2|eval.Code.FLATPYCALL

        def bomb(*args):
            assert False, "shortcutting should have avoided this"

        code.funcrun = bomb
        code.funcrun_obj = bomb

        w_3 = space.newint(3)
        w_4 = space.newint(4)
        # ignore this for now
        #w_res = space.call_function(fn, w_3)
        # assert space.eq_w(w_res, w_4)

        w_res = space.appexec([fn, w_3], """(f, x):
        return f(x)
        """)

        assert space.eq_w(w_res, w_4)
    def test_flatcall_method(self):
        space = self.space
        
        def f(self, a):
            return a
        code = PyCode._from_code(self.space, f.func_code)
        fn = Function(self.space, code, self.space.newdict())

        assert fn.code.fast_natural_arity == 2|PyCode.FLATPYCALL

        def bomb(*args):
            assert False, "shortcutting should have avoided this"

        code.funcrun = bomb
        code.funcrun_obj = bomb

        w_3 = space.newint(3)
        w_res = space.appexec([fn, w_3], """(f, x):
        class A(object):
           m = f
        y = A().m(x)
        b = A().m
        z = b(x)
        return y is x and z is x
        """)

        assert space.is_true(w_res)
Esempio n. 6
0
    def test_flatcall_default_arg_method(self):
        space = self.space

        def f(self, a, b):
            return a+b
        code = PyCode._from_code(self.space, f.func_code)
        fn = Function(self.space, code, self.space.newdict(),
                      defs_w=[space.newint(1)])

        assert fn.code.fast_natural_arity == 3|eval.Code.FLATPYCALL

        def bomb(*args):
            assert False, "shortcutting should have avoided this"

        code.funcrun = bomb
        code.funcrun_obj = bomb

        w_3 = space.newint(3)

        w_res = space.appexec([fn, w_3], """(f, x):
        class A(object):
           m = f
        y = A().m(x)
        b = A().m
        z = b(x)
        return y+10*z
        """)

        assert space.eq_w(w_res, space.wrap(44))
Esempio n. 7
0
    def test_flatcall_method(self):
        space = self.space

        def f(self, a):
            return a

        code = PyCode._from_code(self.space, f.func_code)
        fn = Function(self.space, code, self.space.newdict())

        assert fn.code.fast_natural_arity == 2 | PyCode.FLATPYCALL

        def bomb(*args):
            assert False, "shortcutting should have avoided this"

        code.funcrun = bomb
        code.funcrun_obj = bomb

        w_3 = space.newint(3)
        w_res = space.appexec([fn, w_3], """(f, x):
        class A(object):
           m = f
        y = A().m(x)
        b = A().m
        z = b(x)
        return y is x and z is x
        """)

        assert space.is_true(w_res)
Esempio n. 8
0
    def test_flatcall_default_arg(self):
        space = self.space

        def f(a, b):
            return a + b

        code = PyCode._from_code(self.space, f.__code__)
        fn = Function(self.space,
                      code,
                      self.space.newdict(),
                      defs_w=[space.newint(1)])

        assert fn.code.fast_natural_arity == 2 | eval.Code.FLATPYCALL

        def bomb(*args):
            assert False, "shortcutting should have avoided this"

        code.funcrun = bomb
        code.funcrun_obj = bomb

        w_3 = space.newint(3)
        w_4 = space.newint(4)
        # ignore this for now
        #w_res = space.call_function(fn, w_3)
        # assert space.eq_w(w_res, w_4)

        w_res = space.appexec([fn, w_3], """(f, x):
        return f(x)
        """)

        assert space.eq_w(w_res, w_4)
Esempio n. 9
0
    def test_flatcall_default_arg_method(self):
        space = self.space

        def f(self, a, b):
            return a + b

        code = PyCode._from_code(self.space, f.__code__)
        fn = Function(self.space,
                      code,
                      self.space.newdict(),
                      defs_w=[space.newint(1)])

        assert fn.code.fast_natural_arity == 3 | eval.Code.FLATPYCALL

        def bomb(*args):
            assert False, "shortcutting should have avoided this"

        code.funcrun = bomb
        code.funcrun_obj = bomb

        w_3 = space.newint(3)

        w_res = space.appexec([fn, w_3], """(f, x):
        class A(object):
           m = f
        y = A().m(x)
        b = A().m
        z = b(x)
        return y+10*z
        """)

        assert space.eq_w(w_res, space.wrap(44))
Esempio n. 10
0
    def test_call_function(self):
        space = self.space

        d = {}
        for i in range(10):
            args = "(" + ''.join(["a%d," % a for a in range(i)]) + ")"
            exec """
def f%s:
    return %s
""" % (args, args) in d
            f = d['f']
            res = f(*range(i))
            code = PyCode._from_code(self.space, f.__code__)
            fn = Function(self.space, code, self.space.newdict())

            assert fn.code.fast_natural_arity == i | PyCode.FLATPYCALL
            if i < 5:

                def bomb(*args):
                    assert False, "shortcutting should have avoided this"

                code.funcrun = bomb
                code.funcrun_obj = bomb

            args_w = map(space.wrap, range(i))
            w_res = space.call_function(fn, *args_w)
            check = space.is_true(space.eq(w_res, space.wrap(res)))
            assert check
Esempio n. 11
0
    def test_method_get(self):
        space = self.space

        # Create some function for this test only
        def m(self):
            return self

        func = Function(space, PyCode._from_code(self.space, m.__code__),
                        space.newdict())
        # Some shorthands
        obj1 = space.wrap(23)
        obj2 = space.wrap(42)
        args = Arguments(space, [])
        # Check method returned from func.__get__()
        w_meth1 = descr_function_get(space, func, obj1, space.type(obj1))
        meth1 = space.unwrap(w_meth1)
        assert isinstance(meth1, Method)
        assert meth1.call_args(args) == obj1
        # Check method returned from method.__get__()
        # --- meth1 is already bound so meth1.__get__(*) is meth1.
        w_meth2 = meth1.descr_method_get(obj2, space.type(obj2))
        meth2 = space.unwrap(w_meth2)
        assert isinstance(meth2, Method)
        assert meth2.call_args(args) == obj1
        # Check method returned from unbound_method.__get__()
        w_meth3 = descr_function_get(space, func, space.w_None,
                                     space.type(obj2))
        meth3 = space.unwrap(w_meth3)
        assert meth3 is func
Esempio n. 12
0
    def test_flatcall(self):
        space = self.space
        
        def f(a):
            return a
        code = PyCode._from_code(self.space, f.func_code)
        fn = Function(self.space, code, self.space.newdict())

        assert fn.code.fast_natural_arity == 1|PyCode.FLATPYCALL

        def bomb(*args):
            assert False, "shortcutting should have avoided this"

        code.funcrun = bomb
        code.funcrun_obj = bomb

        w_3 = space.newint(3)
        w_res = space.call_function(fn, w_3)

        assert w_res is w_3

        w_res = space.appexec([fn, w_3], """(f, x):
        return f(x)
        """)

        assert w_res is w_3
Esempio n. 13
0
    def test_call_function(self):
        space = self.space
        
        d = {}
        for i in range(10):
            args = "(" + ''.join(["a%d," % a for a in range(i)]) + ")"
            exec """
def f%s:
    return %s
""" % (args, args) in d
            f = d['f']
            res = f(*range(i))
            code = PyCode._from_code(self.space, f.func_code)
            fn = Function(self.space, code, self.space.newdict())

            assert fn.code.fast_natural_arity == i|PyCode.FLATPYCALL
            if i < 5:

                 def bomb(*args):
                     assert False, "shortcutting should have avoided this"

                 code.funcrun = bomb
                 code.funcrun_obj = bomb

            args_w = map(space.wrap, range(i))            
            w_res = space.call_function(fn, *args_w)
            check = space.is_true(space.eq(w_res, space.wrap(res)))
            assert check
Esempio n. 14
0
 def test_method_get(self):
     space = self.space
     # Create some function for this test only
     def m(self): return self
     func = Function(space, PyCode._from_code(self.space, m.func_code),
                     space.newdict())
     # Some shorthands
     obj1 = space.wrap(23)
     obj2 = space.wrap(42)
     args = Arguments(space, [])
     # Check method returned from func.__get__()
     w_meth1 = descr_function_get(space, func, obj1, space.type(obj1))
     meth1 = space.unwrap(w_meth1)
     assert isinstance(meth1, Method)
     assert meth1.call_args(args) == obj1
     # Check method returned from method.__get__()
     # --- meth1 is already bound so meth1.__get__(*) is meth1.
     w_meth2 = meth1.descr_method_get(obj2, space.type(obj2))
     meth2 = space.unwrap(w_meth2)
     assert isinstance(meth2, Method)
     assert meth2.call_args(args) == obj1
     # Check method returned from unbound_method.__get__()
     w_meth3 = descr_function_get(space, func, None, space.type(obj2))
     meth3 = space.unwrap(w_meth3)
     w_meth4 = meth3.descr_method_get(obj2, space.w_None)
     meth4 = space.unwrap(w_meth4)
     assert isinstance(meth4, Method)
     assert meth4.call_args(args) == obj2
     # Check method returned from unbound_method.__get__()
     # --- with an incompatible class
     w_meth5 = meth3.descr_method_get(space.wrap('hello'), space.w_str)
     assert space.is_w(w_meth5, w_meth3)
Esempio n. 15
0
def test_AppFrame(space):
    import sys
    co = PyCode._from_code(space, somefunc.func_code)
    pyframe = space.FrameClass(space, co, space.newdict(), None)
    runner = AppFrame(space, pyframe)
    interpret("f = lambda x: x+1", runner, should_fail=False)
    msg = interpret("assert isinstance(f(2), float)", runner)
    assert msg.startswith("assert isinstance(3, float)\n" " +  where 3 = ")
Esempio n. 16
0
def test_AppFrame(space):
    import sys
    co = PyCode._from_code(space, somefunc.func_code)
    pyframe = PyFrame(space, co, space.newdict(), None)
    runner = AppFrame(space, pyframe)
    exprinfo.run("f = lambda x: x+1", runner)
    msg = exprinfo.interpret("assert isinstance(f(2), float)", runner)
    assert msg.startswith("assert isinstance(3, float)\n" " +  where 3 = ")
Esempio n. 17
0
def test_AppFrame(space):
    import sys
    co = PyCode._from_code(space, somefunc.func_code)
    pyframe = space.FrameClass(space, co, space.newdict(), None)
    runner = AppFrame(space, pyframe)
    interpret("f = lambda x: x+1", runner, should_fail=False)
    msg = interpret("assert isinstance(f(2), float)", runner)
    assert msg.startswith("assert isinstance(3, float)\n"
                          " +  where 3 = ")
Esempio n. 18
0
 def check(self, w_dict, evalexpr, expected):
     # for now, we compile evalexpr with CPython's compiler but run
     # it with our own interpreter to extract the data from w_dict
     co_expr = compile(evalexpr, "<evalexpr>", "eval")
     space = self.space
     pyco_expr = PyCode._from_code(space, co_expr)
     w_res = pyco_expr.exec_code(space, w_dict, w_dict)
     res = space.str_w(space.repr(w_res))
     assert res == repr(expected)
Esempio n. 19
0
 def check(self, w_dict, evalexpr, expected):
     # for now, we compile evalexpr with CPython's compiler but run
     # it with our own interpreter to extract the data from w_dict
     co_expr = compile(evalexpr, '<evalexpr>', 'eval')
     space = self.space
     pyco_expr = PyCode._from_code(space, co_expr)
     w_res = pyco_expr.exec_code(space, w_dict, w_dict)
     res = space.str_w(space.repr(w_res))
     assert res == repr(expected)
Esempio n. 20
0
def test_AppFrame(space):
    import sys
    co = PyCode._from_code(space, somefunc.func_code)
    pyframe = PyFrame(space, co, space.newdict(), None)
    runner = AppFrame(space, pyframe)
    exprinfo.run("f = lambda x: x+1", runner)
    msg = exprinfo.interpret("assert isinstance(f(2), float)", runner)
    assert msg.startswith("assert isinstance(3, float)\n"
                          " +  where 3 = ")
Esempio n. 21
0
 def eval(self, expression, w_globals, w_locals):
     "NOT_RPYTHON: For internal debugging."
     import types
     from pypy.interpreter.pycode import PyCode
     if isinstance(expression, str):
         expression = compile(expression, '?', 'eval')
     if isinstance(expression, types.CodeType):
         expression = PyCode._from_code(self, expression)
     if not isinstance(expression, PyCode):
         raise TypeError, 'space.eval(): expected a string, code or PyCode object'
     return expression.exec_code(self, w_globals, w_locals)
Esempio n. 22
0
 def eval(self, expression, w_globals, w_locals):
     "NOT_RPYTHON: For internal debugging."
     import types
     from pypy.interpreter.pycode import PyCode
     if isinstance(expression, str):
         expression = compile(expression, '?', 'eval')
     if isinstance(expression, types.CodeType):
         expression = PyCode._from_code(self, expression)
     if not isinstance(expression, PyCode):
         raise TypeError, 'space.eval(): expected a string, code or PyCode object'
     return expression.exec_code(self, w_globals, w_locals)
Esempio n. 23
0
def _testfile(space, magic, mtime, co=None):
    cpathname = str(udir.join('test.pyc'))
    f = file(cpathname, "wb")
    f.write(_getlong(magic))
    f.write(_getlong(mtime))
    if co:
        # marshal the code object with the PyPy marshal impl
        pyco = PyCode._from_code(space, co)
        w_marshal = space.getbuiltinmodule('marshal')
        w_marshaled_code = space.call_method(w_marshal, 'dumps', pyco)
        marshaled_code = space.bytes_w(w_marshaled_code)
        f.write(marshaled_code)
    f.close()
    return cpathname
Esempio n. 24
0
 def check(self, w_dict, evalexpr, expected):
     # for now, we compile evalexpr with CPython's compiler but run
     # it with our own interpreter to extract the data from w_dict
     co_expr = compile(evalexpr, '<evalexpr>', 'eval')
     space = self.space
     pyco_expr = PyCode._from_code(space, co_expr)
     w_res = pyco_expr.exec_host_bytecode(w_dict, w_dict)
     res = space.str_w(space.repr(w_res))
     if not isinstance(expected, float):
         assert res == repr(expected)
     else:
         # Float representation can vary a bit between interpreter
         # versions, compare the numbers instead.
         assert eval(res) == expected
Esempio n. 25
0
 def check(self, w_dict, evalexpr, expected):
     # for now, we compile evalexpr with CPython's compiler but run
     # it with our own interpreter to extract the data from w_dict
     co_expr = compile(evalexpr, '<evalexpr>', 'eval')
     space = self.space
     pyco_expr = PyCode._from_code(space, co_expr)
     w_res = pyco_expr.exec_host_bytecode(w_dict, w_dict)
     res = space.str_w(space.repr(w_res))
     if not isinstance(expected, float):
         assert res == repr(expected)
     else:
         # Float representation can vary a bit between interpreter
         # versions, compare the numbers instead.
         assert eval(res) == expected
Esempio n. 26
0
 def exec_(self, statement, w_globals, w_locals, hidden_applevel=False):
     "NOT_RPYTHON: For internal debugging."
     import types
     from pypy.interpreter.pycode import PyCode
     if isinstance(statement, str):
         statement = compile(statement, '?', 'exec')
     if isinstance(statement, types.CodeType):
         statement = PyCode._from_code(self, statement,
                                       hidden_applevel=hidden_applevel)
     if not isinstance(statement, PyCode):
         raise TypeError, 'space.exec_(): expected a string, code or PyCode object'
     w_key = self.wrap('__builtins__')
     if not self.is_true(self.contains(w_globals, w_key)):
         self.setitem(w_globals, w_key, self.wrap(self.builtin))
     return statement.exec_code(self, w_globals, w_locals)
Esempio n. 27
0
 def exec_(self, statement, w_globals, w_locals, hidden_applevel=False):
     "NOT_RPYTHON: For internal debugging."
     import types
     from pypy.interpreter.pycode import PyCode
     if isinstance(statement, str):
         statement = compile(statement, '?', 'exec')
     if isinstance(statement, types.CodeType):
         statement = PyCode._from_code(self,
                                       statement,
                                       hidden_applevel=hidden_applevel)
     if not isinstance(statement, PyCode):
         raise TypeError, 'space.exec_(): expected a string, code or PyCode object'
     w_key = self.wrap('__builtins__')
     if not self.is_true(self.contains(w_globals, w_key)):
         self.setitem(w_globals, w_key, self.wrap(self.builtin))
     return statement.exec_code(self, w_globals, w_locals)
Esempio n. 28
0
    def test_method_get(self):
        space = self.space

        # Create some function for this test only
        def m(self):
            return self

        func = Function(space, PyCode._from_code(self.space, m.func_code),
                        space.newdict())
        # Some shorthands
        obj1 = space.wrap(23)
        obj2 = space.wrap(42)
        args = Arguments(space, [])
        # Check method returned from func.__get__()
        w_meth1 = descr_function_get(space, func, obj1, space.type(obj1))
        meth1 = space.unwrap(w_meth1)
        assert isinstance(meth1, Method)
        assert meth1.call_args(args) == obj1
        # Check method returned from method.__get__()
        # --- meth1 is already bound so meth1.__get__(*) is meth1.
        w_meth2 = meth1.descr_method_get(obj2, space.type(obj2))
        meth2 = space.unwrap(w_meth2)
        assert isinstance(meth2, Method)
        assert meth2.call_args(args) == obj1
        # Check method returned from unbound_method.__get__()
        w_meth3 = descr_function_get(space, func, space.w_None,
                                     space.type(obj2))
        meth3 = space.unwrap(w_meth3)
        w_meth4 = meth3.descr_method_get(obj2, space.w_None)
        meth4 = space.unwrap(w_meth4)
        assert isinstance(meth4, Method)
        assert meth4.call_args(args) == obj2
        # Check method returned from unbound_method.__get__()
        # --- with an incompatible class
        w_meth5 = meth3.descr_method_get(space.wrap('hello'), space.w_text)
        assert space.is_w(w_meth5, w_meth3)
        # Same thing, with an old-style class
        w_oldclass = space.call_function(space.builtin.get('__metaclass__'),
                                         space.wrap('OldClass'),
                                         space.newtuple([]), space.newdict())
        w_meth6 = meth3.descr_method_get(space.wrap('hello'), w_oldclass)
        assert space.is_w(w_meth6, w_meth3)
        # Reverse order of old/new styles
        w_meth7 = descr_function_get(space, func, space.w_None, w_oldclass)
        meth7 = space.unwrap(w_meth7)
        w_meth8 = meth7.descr_method_get(space.wrap('hello'), space.w_text)
        assert space.is_w(w_meth8, w_meth7)
Esempio n. 29
0
    def getframe(self, func):
        space = self.space
        try:
            func = func.im_func
        except AttributeError:
            pass
        code = func.func_code
        code = PyCode._from_code(self.space, code)
        w_globals = Constant({})  # space.newdict()
        frame = self.space.createframe(code, w_globals)

        formalargcount = code.getformalargcount()
        dummy = Constant(None)
        # dummy.dummy = True
        arg_list = [Variable() for i in range(formalargcount)] + [dummy] * (frame.nlocals - formalargcount)
        frame.setfastscope(arg_list)
        return frame
Esempio n. 30
0
    def build_flow(self, func, constargs={}):
        """
        """
        if func.func_doc and func.func_doc.lstrip().startswith('NOT_RPYTHON'):
            raise Exception, "%r is tagged as NOT_RPYTHON" % (func, )
        code = func.func_code
        if code.co_flags & 32:
            # generator
            raise TypeError("%r is a generator" % (func, ))
        code = PyCode._from_code(self, code)
        if func.func_closure is None:
            closure = None
        else:
            closure = [
                extract_cell_content(c, name, func) for c, name in zip(
                    func.func_closure, func.func_code.co_freevars)
            ]
        # CallableFactory.pycall may add class_ to functions that are methods
        name = func.func_name
        class_ = getattr(func, 'class_', None)
        if class_ is not None:
            name = '%s.%s' % (class_.__name__, name)
        for c in "<>&!":
            name = name.replace(c, '_')
        ec = flowcontext.FlowExecutionContext(self, code, func.func_globals,
                                              constargs, closure, name)
        graph = ec.graph
        graph.func = func
        # attach a signature and defaults to the graph
        # so that it becomes even more interchangeable with the function
        # itself
        graph.signature = cpython_code_signature(code)
        graph.defaults = func.func_defaults or ()
        self.setup_executioncontext(ec)

        from pypy.tool.error import FlowingError, format_global_error

        try:
            ec.build_flow()
        except FlowingError, a:
            # attach additional source info to AnnotatorError
            _, _, tb = sys.exc_info()
            e = FlowingError(
                format_global_error(ec.graph, ec.crnt_offset, str(a)))
            raise FlowingError, e, tb
Esempio n. 31
0
 def check(self, w_dict, evalexpr, expected):
     # for now, we compile evalexpr with CPython's compiler but run
     # it with our own interpreter to extract the data from w_dict
     co_expr = compile(evalexpr, '<evalexpr>', 'eval')
     space = self.space
     pyco_expr = PyCode._from_code(space, co_expr)
     w_res = pyco_expr.exec_host_bytecode(w_dict, w_dict)
     res = space.str_w(space.repr(w_res))
     expected_repr = self.get_py3_repr(expected)
     if isinstance(expected, float):
         # Float representation can vary a bit between interpreter
         # versions, compare the numbers instead.
         assert eval(res) == expected
     elif isinstance(expected, long):
         assert expected_repr.endswith('L')
         assert res == expected_repr[:-1] # in py3 we don't have the L suffix
     else:
         assert res == expected_repr
Esempio n. 32
0
    def getframe(self, func):
        space = self.space
        try:
            func = func.im_func
        except AttributeError:
            pass
        code = func.func_code
        code = PyCode._from_code(self.space, code)
        w_globals = Constant({})  # space.newdict()
        frame = self.space.createframe(code, w_globals)

        formalargcount = code.getformalargcount()
        dummy = Constant(None)
        #dummy.dummy = True
        arg_list = ([Variable() for i in range(formalargcount)] + [dummy] *
                    (len(frame.fastlocals_w) - formalargcount))
        frame.setfastscope(arg_list)
        return frame
Esempio n. 33
0
    def build_flow(self, func, constargs={}, tweak_for_generator=True):
        """
        """
        if func.func_doc and func.func_doc.lstrip().startswith('NOT_RPYTHON'):
            raise Exception, "%r is tagged as NOT_RPYTHON" % (func, )
        code = func.func_code
        is_generator = bool(code.co_flags & CO_GENERATOR)
        code = PyCode._from_code(self, code)
        if func.func_closure is None:
            cl = None
        else:
            cl = [extract_cell_content(c) for c in func.func_closure]
        # CallableFactory.pycall may add class_ to functions that are methods
        name = func.func_name
        class_ = getattr(func, 'class_', None)
        if class_ is not None:
            name = '%s.%s' % (class_.__name__, name)
        for c in "<>&!":
            name = name.replace(c, '_')

        class outerfunc:  # hack
            closure = cl

        ec = flowcontext.FlowExecutionContext(self, code, func.func_globals,
                                              constargs, outerfunc, name,
                                              is_generator)
        graph = ec.graph
        graph.func = func
        # attach a signature and defaults to the graph
        # so that it becomes even more interchangeable with the function
        # itself
        graph.signature = cpython_code_signature(code)
        graph.defaults = func.func_defaults or ()
        self.setup_executioncontext(ec)

        try:
            ec.build_flow()
        except error.FlowingError, a:
            # attach additional source info to AnnotatorError
            _, _, tb = sys.exc_info()
            formated = error.format_global_error(ec.graph, ec.crnt_offset,
                                                 str(a))
            e = error.FlowingError(formated)
            raise error.FlowingError, e, tb
Esempio n. 34
0
 def check(self, w_dict, evalexpr, expected):
     # for now, we compile evalexpr with CPython's compiler but run
     # it with our own interpreter to extract the data from w_dict
     co_expr = compile(evalexpr, '<evalexpr>', 'eval')
     space = self.space
     pyco_expr = PyCode._from_code(space, co_expr)
     w_res = pyco_expr.exec_host_bytecode(w_dict, w_dict)
     res = space.str_w(space.repr(w_res))
     expected_repr = self.get_py3_repr(expected)
     if isinstance(expected, float):
         # Float representation can vary a bit between interpreter
         # versions, compare the numbers instead.
         assert eval(res) == expected
     elif isinstance(expected, long):
         assert expected_repr.endswith('L')
         assert res == expected_repr[:
                                     -1]  # in py3 we don't have the L suffix
     else:
         assert res == expected_repr
Esempio n. 35
0
 def test_method_get(self):
     space = self.space
     # Create some function for this test only
     def m(self): return self
     func = Function(space, PyCode._from_code(self.space, m.func_code),
                     space.newdict())
     # Some shorthands
     obj1 = space.wrap(23)
     obj2 = space.wrap(42)
     args = Arguments(space, [])
     # Check method returned from func.__get__()
     w_meth1 = descr_function_get(space, func, obj1, space.type(obj1))
     meth1 = space.unwrap(w_meth1)
     assert isinstance(meth1, Method)
     assert meth1.call_args(args) == obj1
     # Check method returned from method.__get__()
     # --- meth1 is already bound so meth1.__get__(*) is meth1.
     w_meth2 = meth1.descr_method_get(obj2, space.type(obj2))
     meth2 = space.unwrap(w_meth2)
     assert isinstance(meth2, Method)
     assert meth2.call_args(args) == obj1
     # Check method returned from unbound_method.__get__()
     w_meth3 = descr_function_get(space, func, space.w_None, space.type(obj2))
     meth3 = space.unwrap(w_meth3)
     w_meth4 = meth3.descr_method_get(obj2, space.w_None)
     meth4 = space.unwrap(w_meth4)
     assert isinstance(meth4, Method)
     assert meth4.call_args(args) == obj2
     # Check method returned from unbound_method.__get__()
     # --- with an incompatible class
     w_meth5 = meth3.descr_method_get(space.wrap('hello'), space.w_str)
     assert space.is_w(w_meth5, w_meth3)
     # Same thing, with an old-style class
     w_oldclass = space.call_function(
         space.builtin.get('__metaclass__'),
         space.wrap('OldClass'), space.newtuple([]), space.newdict())
     w_meth6 = meth3.descr_method_get(space.wrap('hello'), w_oldclass)
     assert space.is_w(w_meth6, w_meth3)
     # Reverse order of old/new styles
     w_meth7 = descr_function_get(space, func, space.w_None, w_oldclass)
     meth7 = space.unwrap(w_meth7)
     w_meth8 = meth7.descr_method_get(space.wrap('hello'), space.w_str)
     assert space.is_w(w_meth8, w_meth7)
Esempio n. 36
0
    def build_flow(self, func, constargs={}):
        """
        """
        if func.func_doc and func.func_doc.lstrip().startswith('NOT_RPYTHON'):
            raise Exception, "%r is tagged as NOT_RPYTHON" % (func,)
        code = func.func_code
        if code.co_flags & 32:
            # generator
            raise TypeError("%r is a generator" % (func,))
        code = PyCode._from_code(self, code)
        if func.func_closure is None:
            closure = None
        else:
            closure = [extract_cell_content(c, name, func)
                       for c, name in zip(func.func_closure,
                                          func.func_code.co_freevars)]
        # CallableFactory.pycall may add class_ to functions that are methods
        name = func.func_name
        class_ = getattr(func, 'class_', None)
        if class_ is not None:
            name = '%s.%s' % (class_.__name__, name)
        for c in "<>&!":
            name = name.replace(c, '_')
        ec = flowcontext.FlowExecutionContext(self, code, func.func_globals,
                                              constargs, closure, name)
        graph = ec.graph
        graph.func = func
        # attach a signature and defaults to the graph
        # so that it becomes even more interchangeable with the function
        # itself
        graph.signature = cpython_code_signature(code)
        graph.defaults = func.func_defaults or ()
        self.setup_executioncontext(ec)

        from pypy.tool.error import FlowingError, format_global_error

        try:
            ec.build_flow()
        except FlowingError, a:
            # attach additional source info to AnnotatorError
            _, _, tb = sys.exc_info()
            e = FlowingError(format_global_error(ec.graph, ec.crnt_offset, str(a)))
            raise FlowingError, e, tb
Esempio n. 37
0
    def build_flow(self, func, constargs={}, tweak_for_generator=True):
        """
        """
        if func.func_doc and func.func_doc.lstrip().startswith('NOT_RPYTHON'):
            raise Exception, "%r is tagged as NOT_RPYTHON" % (func,)
        code = func.func_code
        is_generator = bool(code.co_flags & CO_GENERATOR)
        code = PyCode._from_code(self, code)
        if func.func_closure is None:
            cl = None
        else:
            cl = [extract_cell_content(c) for c in func.func_closure]
        # CallableFactory.pycall may add class_ to functions that are methods
        name = func.func_name
        class_ = getattr(func, 'class_', None)
        if class_ is not None:
            name = '%s.%s' % (class_.__name__, name)
        for c in "<>&!":
            name = name.replace(c, '_')
        class outerfunc: # hack
            closure = cl
        ec = flowcontext.FlowExecutionContext(self, code, func.func_globals,
                                              constargs, outerfunc, name,
                                              is_generator)
        graph = ec.graph
        graph.func = func
        # attach a signature and defaults to the graph
        # so that it becomes even more interchangeable with the function
        # itself
        graph.signature = cpython_code_signature(code)
        graph.defaults = func.func_defaults or ()
        self.setup_executioncontext(ec)

        try:
            ec.build_flow()
        except error.FlowingError, a:
            # attach additional source info to AnnotatorError
            _, _, tb = sys.exc_info()
            formated = error.format_global_error(ec.graph, ec.crnt_offset,
                                                 str(a))
            e = error.FlowingError(formated)
            raise error.FlowingError, e, tb
Esempio n. 38
0
            # TODO use a custom UnicodeError
            raise OperationError(
                space.w_UnicodeDecodeError,
                space.newtuple([
                    space.wrap(e.encoding),
                    space.wrap(e.object),
                    space.wrap(e.start),
                    space.wrap(e.end),
                    space.wrap(e.reason)
                ]))
        except ValueError, e:
            raise OperationError(space.w_ValueError, space.wrap(str(e)))
        except TypeError, e:
            raise OperationError(space.w_TypeError, space.wrap(str(e)))
        from pypy.interpreter.pycode import PyCode
        return PyCode._from_code(space, c)

    compile._annspecialcase_ = "override:cpy_compile"

    def _warn_explicit(self,
                       message,
                       category,
                       filename,
                       lineno,
                       module=None,
                       registry=None):
        if hasattr(category, '__bases__') and \
           issubclass(category, SyntaxWarning):
            assert isinstance(message, str)
            space = self.space
            w_mod = space.sys.getmodule('warnings')
Esempio n. 39
0
    def setup_method(self, method):
        def c(self, bar):
            return bar

        code = PyCode._from_code(self.space, c.func_code)
        self.fn = Function(self.space, code, self.space.newdict())
Esempio n. 40
0
                                                       space.wrap(e.lineno),
                                                       space.wrap(e.offset),
                                                       space.wrap(e.text)])])
            raise OperationError(space.w_SyntaxError, w_synerr)
        except UnicodeDecodeError, e:
            # TODO use a custom UnicodeError
            raise OperationError(space.w_UnicodeDecodeError, space.newtuple([
                                 space.wrap(e.encoding), space.wrap(e.object),
                                 space.wrap(e.start),
                                 space.wrap(e.end), space.wrap(e.reason)]))
        except ValueError, e:
            raise OperationError(space.w_ValueError, space.wrap(str(e)))
        except TypeError, e:
            raise OperationError(space.w_TypeError, space.wrap(str(e)))
        from pypy.interpreter.pycode import PyCode
        return PyCode._from_code(space, c)
    compile._annspecialcase_ = "override:cpy_compile"

    def _warn_explicit(self, message, category, filename, lineno,
                       module=None, registry=None):
        if hasattr(category, '__bases__') and \
           issubclass(category, SyntaxWarning):
            assert isinstance(message, str)
            space = self.space
            w_mod = space.sys.getmodule('warnings')
            if w_mod is not None:
                w_dict = w_mod.getdict()
                w_reg = space.call_method(w_dict, 'setdefault',
                                          space.wrap("__warningregistry__"),
                                          space.newdict())
                try:
Esempio n. 41
0
 def setup_method(self, method):
     def c(self, bar):
         return bar
     code = PyCode._from_code(self.space, c.func_code)
     self.fn = Function(self.space, code, self.space.newdict())