Commits

Alex Gaynor  committed d1e2112

First stab, objspace tests pass, next step interpreter, then module!

  • Participants
  • Parent commits 38f19c2
  • Branches kill-faking

Comments (0)

Files changed (14)

File pypy/config/pypyoption.py

                    default=False),
         ]),
 
-    BoolOption("nofaking", "disallow faking in the object space",
-               default=False,
-               requires=[
-                   ("objspace.usemodules.posix", True),
-                   ("objspace.usemodules.time", True),
-                   ("objspace.usemodules.errno", True)],
-               cmdline='--nofaking'),
-
     OptionDescription("usemodules", "Which Modules should be used", [
         BoolOption(modname, "use module %s" % (modname, ),
                    default=modname in default_modules,

File pypy/interpreter/baseobjspace.py

-from pypy.interpreter.executioncontext import ExecutionContext, ActionFlag
-from pypy.interpreter.executioncontext import UserDelAction, FrameTraceAction
-from pypy.interpreter.error import OperationError, operationerrfmt
-from pypy.interpreter.error import new_exception_class, typed_unwrap_error_msg
+import sys
+
+from pypy.interpreter.executioncontext import (ExecutionContext, ActionFlag,
+    UserDelAction, FrameTraceAction)
+from pypy.interpreter.error import (OperationError, operationerrfmt,
+    new_exception_class, typed_unwrap_error_msg)
 from pypy.interpreter.argument import Arguments
 from pypy.interpreter.miscutils import ThreadLocals
 from pypy.tool.cache import Cache
 from pypy.tool.uid import HUGEVAL_BYTES
+from pypy.rlib import jit
+from pypy.rlib.debug import make_sure_not_resized
 from pypy.rlib.objectmodel import we_are_translated, newlist_hint,\
      compute_unique_id
-from pypy.rlib.debug import make_sure_not_resized
 from pypy.rlib.rarithmetic import r_uint
-from pypy.rlib import jit
-import os, sys
+
 
 __all__ = ['ObjSpace', 'OperationError', 'Wrappable', 'W_Root']
 
         if 'rctime' in modules and 'time' in modules:
             modules.remove('time')
 
-        if not self.config.objspace.nofaking:
-            for modname in self.ALL_BUILTIN_MODULES:
-                if not LIB_PYPY.join(modname+'.py').check(file=True):
-                    modules.append('faked+'+modname)
-
         self._builtinmodule_list = modules
         return self._builtinmodule_list
 

File pypy/jit/tl/pypyjit.py

 config = get_pypy_config(translating=True)
 config.translation.backendopt.inline_threshold = 0.1
 config.translation.gc = 'boehm'
-config.objspace.nofaking = True
 config.translating = True
 set_opt_level(config, level='jit')
 config.objspace.allworkingmodules = False

File pypy/module/array/test/test_array.py

         cls.tempfile = str(py.test.ensuretemp('array').join('tmpfile'))
         cls.maxint = sys.maxint
 
+
 class AppTestArray(BaseArrayTests):
-    spaceconfig = dict(usemodules=('array', 'struct', '_rawffi'))
+    spaceconfig = {'usemodules': ['array', 'struct', '_rawffi', 'binascii']}
 
     def setup_class(cls):
         cls.w_array = cls.space.appexec([], """():
         cls.w_tempfile = cls.space.wrap(
             str(py.test.ensuretemp('array').join('tmpfile')))
         cls.w_maxint = cls.space.wrap(sys.maxint)
-    
+
     def test_buffer_info(self):
         a = self.array('c', 'Hi!')
         bi = a.buffer_info()

File pypy/module/array/test/test_array_old.py

 
 
 class AppTestArray(BaseArrayTests):
-    spaceconfig = dict(usemodules=['struct', 'array'])
+    spaceconfig = {'usemodules': ['struct', 'array', 'binascii']}
 
     def setup_class(cls):
         """Import the array module and make it available as self.array."""

File pypy/objspace/std/fake.py

-import types
-
-from pypy.interpreter.error import OperationError, debug_print
-from pypy.interpreter import baseobjspace
-from pypy.interpreter import eval
-from pypy.interpreter.function import Function, BuiltinFunction
-from pypy.objspace.std.stdtypedef import StdTypeDef
-from pypy.objspace.std.model import W_Object, UnwrapError
-from pypy.interpreter.baseobjspace import Wrappable
-from pypy.interpreter.typedef import TypeDef
-from pypy.interpreter import gateway, argument
-
-# this file automatically generates non-reimplementations of CPython
-# types that we do not yet implement in the standard object space
-
-
-def fake_object(space, x):
-    if isinstance(x, file):
-        debug_print("fake-wrapping interp file %s" % x)
-    if isinstance(x, type):
-        ft = fake_type(x)
-        return space.gettypeobject(ft.typedef)
-    #debug_print("faking obj %s" % x)
-    ft = fake_type(type(x))
-    return ft(space, x)
-
-import sys
-
-_fake_type_cache = {}
-
-# real-to-wrapped exceptions
-def wrap_exception(space):
-    """NOT_RPYTHON"""
-    exc, value, tb = sys.exc_info()
-    if exc is OperationError:
-        raise exc, value, tb   # just re-raise it
-    name = exc.__name__
-    if hasattr(space, 'w_' + name):
-        w_exc = getattr(space, 'w_' + name)
-        w_value = space.call_function(w_exc,
-            *[space.wrap(a) for a in value.args])
-        for key, value in value.__dict__.items():
-            if not key.startswith('_'):
-                space.setattr(w_value, space.wrap(key), space.wrap(value))
-    else:
-        debug_print('likely crashes because of faked exception %s: %s' % (
-            exc.__name__, value))
-        w_exc = space.wrap(exc)
-        w_value = space.wrap(value)
-    raise OperationError, OperationError(w_exc, w_value), tb
-
-def fake_type(cpy_type):
-    assert isinstance(type(cpy_type), type)
-    try:
-        return _fake_type_cache[cpy_type]
-    except KeyError:
-        faked_type = really_build_fake_type(cpy_type)
-        _fake_type_cache[cpy_type] = faked_type
-        return faked_type
-
-def really_build_fake_type(cpy_type):
-    "NOT_RPYTHON (not remotely so!)."
-    debug_print('faking %r'%(cpy_type,))
-    kw = {}
-
-    if cpy_type.__name__ == 'SRE_Pattern':
-        import re
-        import __builtin__
-        p = re.compile("foo")
-        for meth_name in p.__methods__:
-            kw[meth_name] = EvenMoreObscureWrapping(__builtin__.eval("lambda p,*args,**kwds: p.%s(*args,**kwds)" % meth_name))
-    elif cpy_type.__name__ == 'SRE_Match':
-        import re
-        import __builtin__
-        m = re.compile("foo").match('foo')
-        for meth_name in m.__methods__:
-            kw[meth_name] = EvenMoreObscureWrapping(__builtin__.eval("lambda m,*args,**kwds: m.%s(*args,**kwds)" % meth_name))
-    else:
-        for s, v in cpy_type.__dict__.items():
-            if not (cpy_type is unicode and s in ['__add__', '__contains__']):
-                if s != '__getattribute__' or cpy_type is type(sys) or cpy_type is type(Exception):
-                    kw[s] = v
-
-    kw['__module__'] = cpy_type.__module__
-
-    def fake__new__(space, w_type, __args__):
-        args_w, kwds_w = __args__.unpack()
-        args = [space.unwrap(w_arg) for w_arg in args_w]
-        kwds = {}
-        for (key, w_value) in kwds_w.items():
-            kwds[key] = space.unwrap(w_value)
-        try:
-            r = cpy_type.__new__(*[cpy_type]+args, **kwds)
-        except:
-            wrap_exception(space)
-            raise
-        w_obj = space.allocate_instance(W_Fake, w_type)
-        W_Fake.__init__(w_obj, space, r)
-        return w_obj
-    fake__new__.func_name = "fake__new__" + cpy_type.__name__
-
-    kw['__new__'] = gateway.interp2app(fake__new__)
-    if cpy_type.__base__ is object or issubclass(cpy_type, Exception):
-        base = None
-    elif cpy_type.__base__ is basestring:
-        from pypy.objspace.std.basestringtype import basestring_typedef
-        base = basestring_typedef
-    elif cpy_type.__base__ is tuple:
-        from pypy.objspace.std.tupletype import tuple_typedef
-        base = tuple_typedef
-    elif cpy_type.__base__ is type:
-        from pypy.objspace.std.typetype import type_typedef
-        base = type_typedef
-    else:
-        raise NotImplementedError(cpy_type, cpy_type.__base__)
-    class W_Fake(W_Object):
-        typedef = StdTypeDef(
-            cpy_type.__name__, base, **kw)
-        def __init__(w_self, space, val):
-            w_self.val = val
-            w_self.space = space
-        def getdict(w_self, space):
-            try:
-                d = w_self.val.__dict__
-            except AttributeError:
-                return W_Object.getdict(w_self, space)
-            return space.wrap(d)
-        def unwrap(w_self, space):
-            return w_self.val
-        if cpy_type is types.FunctionType:
-            def __get__(self, obj, owner):
-                return fake_object(self.space, self.val.__get__(obj, owner))
-    W_Fake.__name__ = 'W_Fake%s'%(cpy_type.__name__.capitalize())
-    W_Fake.typedef.fakedcpytype = cpy_type
-    return W_Fake
-
-# ____________________________________________________________
-#
-# Special case for built-in functions, methods, and slot wrappers.
-
-class CPythonFakeCode(eval.Code):
-    def __init__(self, cpy_callable):
-        eval.Code.__init__(self, getattr(cpy_callable, '__name__', '?'))
-        self.cpy_callable = cpy_callable
-        assert callable(cpy_callable), cpy_callable
-
-    def signature(self):
-        return argument.Signature([], 'args', 'kwds')
-
-    def funcrun(self, func, args):
-        frame = func.space.createframe(self, func.w_func_globals,
-                                       func)
-        sig = self.signature()
-        scope_w = args.parse_obj(None, func.name, sig, func.defs_w)
-        frame.setfastscope(scope_w)
-        return frame.run()
-
-
-class CPythonFakeFrame(eval.Frame):
-
-    def __init__(self, space, code, w_globals=None):
-        self.fakecode = code
-        eval.Frame.__init__(self, space, w_globals)
-
-    def getcode(self):
-        return self.fakecode
-
-    def setfastscope(self, scope_w):
-        w_args, w_kwds = scope_w
-        try:
-            self.unwrappedargs = self.space.unwrap(w_args)
-            self.unwrappedkwds = self.space.unwrap(w_kwds)
-        except UnwrapError, e:
-            code = self.fakecode
-            assert isinstance(code, CPythonFakeCode)
-            raise UnwrapError('calling %s: %s' % (code.cpy_callable, e))
-
-    def getfastscope(self):
-        raise OperationError(self.space.w_TypeError,
-          self.space.wrap("cannot get fastscope of a CPythonFakeFrame"))
-
-    def run(self):
-        code = self.fakecode
-        assert isinstance(code, CPythonFakeCode)
-        fn = code.cpy_callable
-        try:
-            result = fn(*self.unwrappedargs, **self.unwrappedkwds)
-        except:
-            wrap_exception(self.space)
-            raise
-        return self.space.wrap(result)
-
-
-class EvenMoreObscureWrapping(baseobjspace.Wrappable):
-    def __init__(self, val):
-        self.val = val
-    def __spacebind__(self, space):
-        return fake_builtin_callable(space, self.val)
-
-def fake_builtin_callable(space, val):
-    return Function(space, CPythonFakeCode(val))
-
-def fake_builtin_function(space, fn):
-    func = fake_builtin_callable(space, fn)
-    if fn.__self__ is None:
-        func = BuiltinFunction(func)
-    return func
-
-_fake_type_cache[type(len)] = fake_builtin_function
-_fake_type_cache[type(list.append)] = fake_builtin_callable
-_fake_type_cache[type(type(None).__repr__)] = fake_builtin_callable
-
-class W_FakeDescriptor(Wrappable):
-    # Mimics pypy.interpreter.typedef.GetSetProperty.
-
-    def __init__(self, space, d):
-        self.name = d.__name__
-
-    def descr_descriptor_get(self, space, w_obj, w_cls=None):
-        # XXX HAAAAAAAAAAAACK (but possibly a good one)
-        if (space.is_w(w_obj, space.w_None)
-            and not space.is_w(w_cls, space.type(space.w_None))):
-            #print self, w_obj, w_cls
-            return space.wrap(self)
-        else:
-            name = self.name
-            obj = space.unwrap(w_obj)
-            try:
-                val = getattr(obj, name)  # this gives a "not RPython" warning
-            except:
-                wrap_exception(space)
-                raise
-            return space.wrap(val)
-
-    def descr_descriptor_set(self, space, w_obj, w_value):
-        name = self.name
-        obj = space.unwrap(w_obj)
-        val = space.unwrap(w_value)
-        try:
-            setattr(obj, name, val)   # this gives a "not RPython" warning
-        except:
-            wrap_exception(space)
-
-    def descr_descriptor_del(self, space, w_obj):
-        name = self.name
-        obj = space.unwrap(w_obj)
-        try:
-            delattr(obj, name)
-        except:
-            wrap_exception(space)
-
-
-W_FakeDescriptor.typedef = TypeDef(
-    "FakeDescriptor",
-    __get__ = gateway.interp2app(W_FakeDescriptor.descr_descriptor_get),
-    __set__ = gateway.interp2app(W_FakeDescriptor.descr_descriptor_set),
-    __delete__ = gateway.interp2app(W_FakeDescriptor.descr_descriptor_del),
-    )
-
-if hasattr(file, 'softspace'):    # CPython only
-    _fake_type_cache[type(file.softspace)] = W_FakeDescriptor
-_fake_type_cache[type(type.__dict__['__dict__'])] = W_FakeDescriptor

File pypy/objspace/std/model.py

         from pypy.objspace.std import unicodeobject
         from pypy.objspace.std import dictproxyobject
         from pypy.objspace.std import proxyobject
-        from pypy.objspace.std import fake
         import pypy.objspace.std.default # register a few catch-all multimethods
 
         import pypy.objspace.std.marshal_impl # install marshal multimethods

File pypy/objspace/std/objspace.py

         ec._py_repr = None
         return ec
 
-    def createframe(self, code, w_globals, outer_func=None):
-        from pypy.objspace.std.fake import CPythonFakeCode, CPythonFakeFrame
-        if not we_are_translated() and isinstance(code, CPythonFakeCode):
-            return CPythonFakeFrame(self, code, w_globals)
-        else:
-            return ObjSpace.createframe(self, code, w_globals, outer_func)
-
     def gettypefor(self, cls):
         return self.gettypeobject(cls.typedef)
 
             # '__builtin__.Ellipsis' avoids confusion with special.Ellipsis
             return self.w_Ellipsis
 
-        if self.config.objspace.nofaking:
-            raise OperationError(self.w_RuntimeError,
-                                 self.wrap("nofaking enabled: refusing "
-                                           "to wrap cpython value %r" %(x,)))
-        if isinstance(x, type(Exception)) and issubclass(x, Exception):
-            w_result = self.wrap_exception_cls(x)
-            if w_result is not None:
-                return w_result
-        from pypy.objspace.std.fake import fake_object
-        return fake_object(self, x)
+        raise OperationError(self.w_RuntimeError,
+            self.wrap("refusing to wrap cpython value %r" % (x,))
+        )
 
     def wrap_exception_cls(self, x):
         """NOT_RPYTHON"""

File pypy/objspace/std/test/test_complexobject.py

 
 
 class AppTestAppComplexTest:
+    spaceconfig = {
+        "usemodules": ["binascii", "rctime"]
+    }
+
     def w_check_div(self, x, y):
         """Compute complex z=x*y, and check that z/x==y and z/y==x."""
         z = x * y

File pypy/objspace/std/test/test_floatobject.py

         else:
             assert False, 'did not raise'
 
+
 class AppTestFloatHex:
+    spaceconfig = {
+        "usemodules": ["binascii", "rctime"],
+    }
+
     def w_identical(self, x, y):
         import math
         # check that floats x and y are identical, or that both

File pypy/objspace/std/test/test_lengthhint.py

     def test_dict(self):
         space = self.space
         w_dict = space.call_function(space.w_dict,
-                                     space.wrap((i, None) for i in self.ITEMS))
+                                     space.wrap([(i, None) for i in self.ITEMS]))
         self._test_length_hint(w_dict)
 
     def test_dict_iterkeys(self):

File pypy/objspace/std/test/test_longobject.py

 import py
-import sys
 from pypy.objspace.std import longobject as lobj
-from pypy.objspace.std.multimethod import FailedToImplement
-from pypy.interpreter.error import OperationError
-from pypy.rlib.rarithmetic import r_uint
 from pypy.rlib.rbigint import rbigint
 
+
 class TestW_LongObject:
-    spaceconfig = {"objspace.nofaking": True}
-
     def test_bigint_w(self):
         space = self.space
         fromlong = lobj.W_LongObject.fromlong

File pypy/objspace/std/test/test_unicodeobject.py

         assert s != u
         assert not u == s
         assert u != s
-        
+
 
 class AppTestUnicodeString:
     spaceconfig = dict(usemodules=('unicodedata',))
 
-    def setup_class(cls):
-        cls.w_version_info = cls.space.wrap(sys.version_info)
-
     def test_addition(self):
         def check(a, b):
             assert a == b
         assert u'abcdefghiabc'.rfind(u'abcz') == -1
 
     def test_rfind_corner_case(self):
-        if self.version_info < (2, 5):
-            skip("fails on top of CPython <= 2.4")
         assert u'abc'.rfind('', 4) == -1
 
     def test_count(self):

File pypy/translator/goal/targetpypystandalone.py

             config.objspace.lonepycfiles = False
             config.objspace.usepycfiles = False
 
-        config.objspace.nofaking = True
         config.translating = True
 
         import translate
         translate.log_config(config.objspace, "PyPy config object")
- 
+
         # obscure hack to stuff the translation options into the translated PyPy
         import pypy.module.sys
         options = make_dict(config)