Commits

Justin Peel committed c0562be Merge

merge in default

Comments (0)

Files changed (42)

+#!/usr/bin/env pypy
+
+"""RPython translation usage:
+
+rpython <translation options> target <targetoptions>
+
+run with --help for more information
+"""
+
+import sys
+from pypy.translator.goal.translate import main
+
+# no implicit targets
+if len(sys.argv) == 1:
+    print __doc__
+    sys.exit(1)
+
+main()

pypy/config/pypyoption.py

                cmdline="--translationmodules",
                suggests=[("objspace.allworkingmodules", False)]),
 
-    BoolOption("geninterp", "specify whether geninterp should be used",
-               default=False),
-
     BoolOption("logbytecodes",
                "keep track of bytecode usage",
                default=False),
             config.objspace.std.suggest(withsmalllong=True)
         # xxx other options? ropes maybe?
 
-    # completely disable geninterp in a level 0 translation
-    if level == '0':
-        config.objspace.suggest(geninterp=False)
-
     # some optimizations have different effects depending on the typesystem
     if type_system == 'ootype':
         config.objspace.std.suggest(multimethods="doubledispatch")

pypy/config/translationoption.py

 
     # Flags of the TranslationContext:
     BoolOption("simplifying", "Simplify flow graphs", default=True),
-    BoolOption("builtins_can_raise_exceptions",
-               "When true, assume any call to a 'simple' builtin such as "
-               "'hex' can raise an arbitrary exception",
-               default=False,
-               cmdline=None),
     BoolOption("list_comprehension_operations",
                "When true, look for and special-case the sequence of "
                "operations that results from a list comprehension and "

pypy/interpreter/gateway.py

         self.filename = filename
         self.source = str(py.code.Source(source).deindent())
         self.modname = modname
-        # look at the first three lines for a NOT_RPYTHON tag
-        first = "\n".join(source.split("\n", 3)[:3])
-        if "NOT_RPYTHON" in first:
-            self.can_use_geninterp = False
-        else:
-            self.can_use_geninterp = True
         # make source code available for tracebacks
         lines = [x + "\n" for x in source.split("\n")]
         py.std.linecache.cache[filename] = (1, None, lines, filename)
 
     def __repr__(self):
-        return "<ApplevelClass filename=%r can_use_geninterp=%r>" % (self.filename, self.can_use_geninterp)
+        return "<ApplevelClass filename=%r>" % (self.filename,)
 
     def getwdict(self, space):
         return space.fromcache(ApplevelCache).getorbuild(self)
 
     def build(self, app):
         "NOT_RPYTHON.  Called indirectly by Applevel.getwdict()."
-        if self.space.config.objspace.geninterp and app.can_use_geninterp:
-            return PyPyCacheDir.build_applevelinterp_dict(app, self.space)
-        else:
-            return build_applevel_dict(app, self.space)
+        return build_applevel_dict(app, self.space)
 
 
 # __________ pure applevel version __________
                 filename=self.filename)
     return w_glob
 
-# __________ geninterplevel version __________
-
-class PyPyCacheDir:
-    "NOT_RPYTHON"
-    # similar to applevel, but using translation to interp-level.
-    # This version maintains a cache folder with single files.
-
-    def build_applevelinterp_dict(cls, self, space):
-        "NOT_RPYTHON"
-        # N.B. 'self' is the ApplevelInterp; this is a class method,
-        # just so that we have a convenient place to store the global state.
-        if not cls._setup_done:
-            cls._setup()
-
-        from pypy.translator.geninterplevel import translate_as_module
-        import marshal
-        scramble = md5(cls.seed)
-        scramble.update(marshal.dumps(self.source))
-        key = scramble.hexdigest()
-        initfunc = cls.known_code.get(key)
-        if not initfunc:
-            # try to get it from file
-            name = key
-            if self.filename:
-                prename = os.path.splitext(os.path.basename(self.filename))[0]
-            else:
-                prename = 'zznoname'
-            name = "%s_%s" % (prename, name)
-            try:
-                __import__("pypy._cache."+name)
-            except ImportError, x:
-                # print x
-                pass
-            else:
-                initfunc = cls.known_code[key]
-        if not initfunc:
-            # build it and put it into a file
-            initfunc, newsrc = translate_as_module(
-                self.source, self.filename, self.modname)
-            fname = cls.cache_path.join(name+".py").strpath
-            f = file(get_tmp_file_name(fname), "w")
-            print >> f, """\
-# self-destruct on double-click:
-if __name__ == "__main__":
-    from pypy import _cache
-    import os
-    namestart = os.path.join(os.path.split(_cache.__file__)[0], '%s')
-    for ending in ('.py', '.pyc', '.pyo'):
-        try:
-            os.unlink(namestart+ending)
-        except os.error:
-            pass""" % name
-            print >> f
-            print >> f, newsrc
-            print >> f, "from pypy._cache import known_code"
-            print >> f, "known_code[%r] = %s" % (key, initfunc.__name__)
-            f.close()
-            rename_tmp_to_eventual_file_name(fname)
-        w_glob = initfunc(space)
-        return w_glob
-    build_applevelinterp_dict = classmethod(build_applevelinterp_dict)
-
-    _setup_done = False
-
-    def _setup(cls):
-        """NOT_RPYTHON"""
-        lp = py.path.local
-        import pypy, os
-        p = lp(pypy.__file__).new(basename='_cache').ensure(dir=1)
-        cls.cache_path = p
-        ini = p.join('__init__.py')
-        try:
-            if not ini.check():
-                raise ImportError  # don't import if only a .pyc file left!!!
-            from pypy._cache import known_code, \
-                 GI_VERSION_RENDERED
-        except ImportError:
-            GI_VERSION_RENDERED = 0
-        from pypy.translator.geninterplevel import GI_VERSION
-        cls.seed = md5(str(GI_VERSION)).digest()
-        if GI_VERSION != GI_VERSION_RENDERED or GI_VERSION is None:
-            for pth in p.listdir():
-                if pth.check(file=1):
-                    try:
-                        pth.remove()
-                    except: pass
-            f = file(get_tmp_file_name(str(ini)), "w")
-            f.write("""\
-# This folder acts as a cache for code snippets which have been
-# compiled by compile_as_module().
-# It will get a new entry for every piece of code that has
-# not been seen, yet.
-#
-# Caution! Only the code snippet is checked. If something
-# is imported, changes are not detected. Also, changes
-# to geninterplevel or gateway are also not checked.
-# Exception: There is a checked version number in geninterplevel.py
-#
-# If in doubt, remove this file from time to time.
-
-GI_VERSION_RENDERED = %r
-
-known_code = {}
-
-# self-destruct on double-click:
-def harakiri():
-    import pypy._cache as _c
-    import py
-    lp = py.path.local
-    for pth in lp(_c.__file__).dirpath().listdir():
-        try:
-            pth.remove()
-        except: pass
-
-if __name__ == "__main__":
-    harakiri()
-
-del harakiri
-""" % GI_VERSION)
-            f.close()
-            rename_tmp_to_eventual_file_name(str(ini))
-        import pypy._cache
-        cls.known_code = pypy._cache.known_code
-        cls._setup_done = True
-    _setup = classmethod(_setup)
-
-
-def gethostname(_cache=[]):
-    if not _cache:
-        try:
-            import socket
-            hostname = socket.gethostname()
-        except:
-            hostname = ''
-        _cache.append(hostname)
-    return _cache[0]
-
-def get_tmp_file_name(fname):
-    return '%s~%s~%d' % (fname, gethostname(), os.getpid())
-
-def rename_tmp_to_eventual_file_name(fname):
-    # generated files are first written to the host- and process-specific
-    # file 'tmpname', and then atomically moved to their final 'fname'
-    # to avoid problems if py.py is started several times in parallel
-    tmpname = get_tmp_file_name(fname)
-    try:
-        os.rename(tmpname, fname)
-    except (OSError, IOError):
-        os.unlink(fname)    # necessary on Windows
-        os.rename(tmpname, fname)
-
 # ____________________________________________________________
 
 def appdef(source, applevel=ApplevelClass, filename=None):
         return build_applevel_dict(self, space)
 
 
-class applevelinterp_temp(ApplevelClass):
-    hidden_applevel = False
-    def getwdict(self, space):   # no cache
-        return PyPyCacheDir.build_applevelinterp_dict(self, space)
-
 # app2interp_temp is used for testing mainly
 def app2interp_temp(func, applevel_temp=applevel_temp, filename=None):
     """ NOT_RPYTHON """

pypy/interpreter/pyopcode.py

             if lastchar.isspace() and lastchar != ' ':
                 return
         file_softspace(stream, True)
-    print_item_to._annspecialcase_ = "specialize:argtype(0)"
 
     def print_item(x):
         print_item_to(x, sys_stdout())
-    print_item._annspecialcase_ = "flowspace:print_item"
 
     def print_newline_to(stream):
         stream.write("\n")
 
     def print_newline():
         print_newline_to(sys_stdout())
-    print_newline._annspecialcase_ = "flowspace:print_newline"
 
     def file_softspace(file, newflag):
         try:

pypy/interpreter/test/test_appinterp.py

 
 import py
-from pypy.interpreter.gateway import appdef, ApplevelClass, applevel_temp, applevelinterp_temp
+from pypy.interpreter.gateway import appdef, ApplevelClass, applevel_temp
 from pypy.interpreter.error import OperationError
 
 def test_execwith_novars(space): 
     w_res = g(space, space.wrap(10), space.wrap(1))
     assert space.eq_w(w_res, space.wrap(-9))
 
-def test_applevelinterp_functions(space):
-    test_applevel_functions(space, applevel_temp = applevelinterp_temp)
-
 def test_applevel_class(space, applevel_temp = applevel_temp):
     app = applevel_temp('''
         class C(object):
     w_clsattr = space.getattr(c, space.wrap('attr'))
     assert space.eq_w(w_clsattr, space.wrap(17))
 
-def test_applevelinterp_class(space):
-    test_applevel_class(space, applevel_temp = applevelinterp_temp)
-
 def app_test_something_at_app_level(): 
     x = 2
     assert x/2 == 1
         w_str = space1.getattr(w_mymod1, space1.wrap("hi"))
         assert space1.str_w(w_str) == "hello"
 
-    def test_geninterp_can_unfreeze(self):
+    def test_random_stuff_can_unfreeze(self):
         # When a module contains an "import" statement in applevel code, the
         # imported module is initialized, possibly after it has been already
         # frozen.

pypy/interpreter/test/test_compiler.py

     def test_tuple_constants(self):
         ns = {}
         exec "x = (1, 0); y = (1L, 0L)" in ns
-        assert isinstance(ns["x"][0], (int, long))
+        assert isinstance(ns["x"][0], int)
         assert isinstance(ns["y"][0], long)
 
     def test_division_folding(self):

pypy/interpreter/test/test_gateway.py

         g3 = gateway.app2interp_temp(noapp_g3, gateway.applevel_temp)
         assert self.space.eq_w(g3(self.space, w('foo'), w('bar')), w('foobar'))
 
-    def test_app2interp2(self):
-        """same but using transformed code"""
-        w = self.space.wrap
-        def noapp_g3(a, b):
-            return a+b
-        g3 = gateway.app2interp_temp(noapp_g3, gateway.applevelinterp_temp)
-        assert self.space.eq_w(g3(self.space, w('foo'), w('bar')), w('foobar'))
-
     def test_app2interp_general_args(self):
         w = self.space.wrap
         def app_general(x, *args, **kwds):

pypy/jit/metainterp/blackhole.py

     def bhimpl_getinteriorfield_gc_f(cpu, array, index, descr):
         return cpu.bh_getinteriorfield_gc_f(array, index, descr)
 
-    @arguments("cpu", "r", "i", "d", "i")
-    def bhimpl_setinteriorfield_gc_i(cpu, array, index, descr, value):
+    @arguments("cpu", "r", "i", "i", "d")
+    def bhimpl_setinteriorfield_gc_i(cpu, array, index, value, descr):
         cpu.bh_setinteriorfield_gc_i(array, index, descr, value)
-    @arguments("cpu", "r", "i", "d", "r")
-    def bhimpl_setinteriorfield_gc_r(cpu, array, index, descr, value):
+    @arguments("cpu", "r", "i", "r", "d")
+    def bhimpl_setinteriorfield_gc_r(cpu, array, index, value, descr):
         cpu.bh_setinteriorfield_gc_r(array, index, descr, value)
-    @arguments("cpu", "r", "i", "d", "f")
-    def bhimpl_setinteriorfield_gc_f(cpu, array, index, descr, value):
+    @arguments("cpu", "r", "i", "f", "d")
+    def bhimpl_setinteriorfield_gc_f(cpu, array, index, value, descr):
         cpu.bh_setinteriorfield_gc_f(array, index, descr, value)
 
     @arguments("cpu", "r", "d", returns="i")

pypy/jit/metainterp/test/test_ajit.py

         assert res == 11 * 12 * 13
         self.check_operations_history(int_add=3, int_mul=2)
 
+    def test_setinteriorfield(self):
+        A = lltype.GcArray(lltype.Struct('S', ('x', lltype.Signed)))
+        a = lltype.malloc(A, 5, immortal=True)
+        def g(n):
+            a[n].x = n + 2
+            return a[n].x
+        res = self.interp_operations(g, [1])
+        assert res == 3
+
 
 class TestLLtype(BaseLLtypeTests, LLJitMixin):
     def test_tagged(self):

pypy/jit/metainterp/test/test_list.py

     def test_newlist_hint(self):
         def f(i):
             l = newlist_hint(i)
+            l[0] = 55
             return len(l)
 
         r = self.interp_operations(f, [3])

pypy/module/__builtin__/app_inspect.py

 from __pypy__ import lookup_special
 
 def _caller_locals(): 
-    # note: the reason why this is working is because the functions in here are
-    # compiled by geninterp, so they don't have a frame
     return sys._getframe(0).f_locals 
 
 def vars(*obj):
         except AttributeError:
             raise TypeError, "vars() argument must have __dict__ attribute"
 
-# Replaced by the interp-level helper space.callable(): 
-##def callable(ob):
-##    import __builtin__ # XXX this is insane but required for now for geninterp
-##    for c in type(ob).__mro__:
-##        if '__call__' in c.__dict__:
-##            if isinstance(ob, __builtin__._instance): # old style instance!
-##                return getattr(ob, '__call__', None) is not None
-##            return True
-##    else:
-##        return False
-
 def dir(*args):
     """dir([object]) -> list of strings
 

pypy/module/_ffi/test/test__ffi.py

 from pypy.module._rawffi.interp_rawffi import TYPEMAP
 from pypy.module._rawffi.tracker import Tracker
 from pypy.translator.platform import platform
-from pypy.rlib.rarithmetic import is_valid_int
-
 
 import os, sys, py
 
                                         types.void)
         assert get_dummy() == 0
         ptr = get_dummy_ptr()
-        assert is_valid_int(ptr)
+        assert type(ptr) in (int, long)
         ptr2 = MyPointerWrapper(ptr)
         set_val_to_ptr(ptr2, 123)
         assert get_dummy() == 123

pypy/module/_multiprocessing/test/test_semaphore.py

 from pypy.conftest import gettestobjspace
 from pypy.module._multiprocessing.interp_semaphore import (
     RECURSIVE_MUTEX, SEMAPHORE)
-from pypy.rlib.rarithmetic import is_valid_int
 
 
 class AppTestSemaphore:
         sem = SemLock(kind, value, maxvalue)
         assert sem.kind == kind
         assert sem.maxvalue == maxvalue
-        assert is_valid_int(sem.handle)
+        assert isinstance(sem.handle, (int, long))
 
         assert sem._count() == 0
         if sys.platform == 'darwin':

pypy/module/cpyext/api.py

     pypy_decls.append("#ifdef __cplusplus")
     pypy_decls.append("extern \"C\" {")
     pypy_decls.append("#endif\n")
+    pypy_decls.append('#define Signed   long           /* xxx temporary fix */\n')
+    pypy_decls.append('#define Unsigned unsigned long  /* xxx temporary fix */\n')
 
     for decl in FORWARD_DECLS:
         pypy_decls.append("%s;" % (decl,))
             typ = 'PyObject*'
         pypy_decls.append('PyAPI_DATA(%s) %s;' % (typ, name))
 
+    pypy_decls.append('#undef Signed    /* xxx temporary fix */\n')
+    pypy_decls.append('#undef Unsigned  /* xxx temporary fix */\n')
     pypy_decls.append("#ifdef __cplusplus")
     pypy_decls.append("}")
     pypy_decls.append("#endif")

pypy/module/cpyext/stringobject.py

 
 @cpython_api([PyObject], rffi.CCHARP, error=0)
 def PyString_AsString(space, ref):
+    if from_ref(space, rffi.cast(PyObject, ref.c_ob_type)) is space.w_str:
+        pass    # typecheck returned "ok" without forcing 'ref' at all
+    elif not PyString_Check(space, ref):   # otherwise, use the alternate way
+        raise OperationError(space.w_TypeError, space.wrap(
+            "PyString_AsString only support strings"))
     ref_str = rffi.cast(PyStringObject, ref)
     if not ref_str.c_buffer:
         # copy string buffer

pypy/module/cpyext/test/test_longobject.py

                                   space.wrap((2, 7)))):
             py.test.skip("unsupported before Python 2.7")
 
-        assert api._PyLong_Sign(space.wrap(0L)) == 0
-        assert api._PyLong_Sign(space.wrap(2L)) == 1
-        assert api._PyLong_Sign(space.wrap(-2L)) == -1
+        assert api._PyLong_Sign(space.wraplong(0L)) == 0
+        assert api._PyLong_Sign(space.wraplong(2L)) == 1
+        assert api._PyLong_Sign(space.wraplong(-2L)) == -1
 
         assert api._PyLong_NumBits(space.wrap(0)) == 0
         assert api._PyLong_NumBits(space.wrap(1)) == 1

pypy/module/cpyext/test/test_number.py

 class TestIterator(BaseApiTest):
     def test_check(self, space, api):
         assert api.PyIndex_Check(space.wrap(12))
-        assert api.PyIndex_Check(space.wrap(-12L))
+        assert api.PyIndex_Check(space.wraplong(-12L))
         assert not api.PyIndex_Check(space.wrap(12.1))
         assert not api.PyIndex_Check(space.wrap('12'))
 
         assert api.PyNumber_Check(space.wrap(12))
-        assert api.PyNumber_Check(space.wrap(-12L))
+        assert api.PyNumber_Check(space.wraplong(-12L))
         assert api.PyNumber_Check(space.wrap(12.1))
         assert not api.PyNumber_Check(space.wrap('12'))
         assert not api.PyNumber_Check(space.wrap(1+3j))
         assert api.PyLong_CheckExact(w_l)
 
     def test_number_int(self, space, api):
-        w_l = api.PyNumber_Int(space.wrap(123L))
+        w_l = api.PyNumber_Int(space.wraplong(123L))
         assert api.PyInt_CheckExact(w_l)
         w_l = api.PyNumber_Int(space.wrap(2 << 65))
         assert api.PyLong_CheckExact(w_l)
         assert api.PyInt_CheckExact(w_l)
 
     def test_number_index(self, space, api):
-        w_l = api.PyNumber_Index(space.wrap(123L))
+        w_l = api.PyNumber_Index(space.wraplong(123L))
         assert api.PyLong_CheckExact(w_l)
         w_l = api.PyNumber_Index(space.wrap(42.3))
         assert w_l is None

pypy/module/pypyjit/policy.py

 
         if mod == 'pypy.rlib.rbigint' or mod == 'pypy.rlib.rlocale' or mod == 'pypy.rlib.rsocket':
             return False
-        if '_geninterp_' in func.func_globals: # skip all geninterped stuff
-            return False
         if mod.startswith('pypy.interpreter.astcompiler.'):
             return False
         if mod.startswith('pypy.interpreter.pyparser.'):

pypy/module/pypyjit/test/test_policy.py

     from pypy.rlib.rlocale import setlocale
     assert not pypypolicy.look_inside_function(setlocale)
 
-def test_geninterp():
-    d = {'_geninterp_': True}
-    exec """def f():
-        pass""" in d
-    assert not pypypolicy.look_inside_function(d['f'])
-
 def test_astcompiler():
     from pypy.interpreter.astcompiler import ast
     assert not pypypolicy.look_inside_function(ast.AST.walkabout)

pypy/module/rbench/__init__.py

-# Package initialisation
-from pypy.interpreter.mixedmodule import MixedModule
-
-class Module(MixedModule):
-    """geninterpreted benchmarks"""
-
-    appleveldefs = {
-        'pystone': 'app_bench.pystone',
-        'richards': 'app_bench.richards',
-        }
-    
-    interpleveldefs = {}

pypy/module/rbench/app_bench.py

-from pypy.translator.test.rpystone import main as pystone
-from pypy.translator.goal.richards import main as richards

pypy/objspace/flow/objspace.py

     is_ = None     # real version added by add_operations()
     id  = None     # real version added by add_operations()
 
-    def newdict(self):
+    def newdict(self, module="ignored"):
         if self.concrete_mode:
             return Constant({})
         return self.do_operation('newdict')
         except UnwrapException:
             raise Exception, "non-constant except guard"
         if check_class in (NotImplementedError, AssertionError):
-            # if we are in geninterp, we cannot catch these exceptions
-            if not self.config.translation.builtins_can_raise_exceptions:
-                raise error.FlowingError("Catching %s is not valid in RPython" %
-                                         check_class.__name__)
+            raise error.FlowingError("Catching %s is not valid in RPython" %
+                                     check_class.__name__)
         if not isinstance(check_class, tuple):
             # the simple case
             return ObjSpace.exception_match(self, w_exc_type, w_check_class)
         exceptions = [Exception]   # *any* exception by default
         if isinstance(w_callable, Constant):
             c = w_callable.value
-            if not self.config.translation.builtins_can_raise_exceptions:
-                if (isinstance(c, (types.BuiltinFunctionType,
-                                   types.BuiltinMethodType,
-                                   types.ClassType,
-                                   types.TypeType)) and
-                      c.__module__ in ['__builtin__', 'exceptions']):
-                    exceptions = operation.implicit_exceptions.get(c)
+            if (isinstance(c, (types.BuiltinFunctionType,
+                               types.BuiltinMethodType,
+                               types.ClassType,
+                               types.TypeType)) and
+                  c.__module__ in ['__builtin__', 'exceptions']):
+                exceptions = operation.implicit_exceptions.get(c)
         self.handle_implicit_exceptions(exceptions)
         return w_res
 
     def handle_implicit_exceptions(self, exceptions):
         if not exceptions:
             return
-        if not self.config.translation.builtins_can_raise_exceptions:
-            # clean up 'exceptions' by removing the non-RPythonic exceptions
-            # which might be listed for geninterp.
-            exceptions = [exc for exc in exceptions
-                              if exc is not TypeError and
-                                 exc is not AttributeError]
-        if exceptions:
-            # catch possible exceptions implicitly.  If the OperationError
-            # below is not caught in the same function, it will produce an
-            # exception-raising return block in the flow graph.  Note that
-            # even if the interpreter re-raises the exception, it will not
-            # be the same ImplicitOperationError instance internally.
-            context = self.getexecutioncontext()
-            outcome, w_exc_cls, w_exc_value = context.guessexception(*exceptions)
-            if outcome is not None:
-                # we assume that the caught exc_cls will be exactly the
-                # one specified by 'outcome', and not a subclass of it,
-                # unless 'outcome' is Exception.
-                #if outcome is not Exception:
-                    #w_exc_cls = Constant(outcome) Now done by guessexception itself
-                    #pass
-                 raise operation.ImplicitOperationError(w_exc_cls, w_exc_value)
+        # catch possible exceptions implicitly.  If the OperationError
+        # below is not caught in the same function, it will produce an
+        # exception-raising return block in the flow graph.  Note that
+        # even if the interpreter re-raises the exception, it will not
+        # be the same ImplicitOperationError instance internally.
+        context = self.getexecutioncontext()
+        outcome, w_exc_cls, w_exc_value = context.guessexception(*exceptions)
+        if outcome is not None:
+            # we assume that the caught exc_cls will be exactly the
+            # one specified by 'outcome', and not a subclass of it,
+            # unless 'outcome' is Exception.
+            #if outcome is not Exception:
+                #w_exc_cls = Constant(outcome) Now done by guessexception itself
+                #pass
+             raise operation.ImplicitOperationError(w_exc_cls, w_exc_value)
 
     def w_KeyboardInterrupt(self):
         # the reason to do this is: if you interrupt the flowing of a function

pypy/objspace/flow/operation.py

     OverflowError: 'ovf',
     IndexError: 'idx',
     KeyError: 'key',
-    AttributeError: 'att',
-    TypeError: 'typ',
     ZeroDivisionError: 'zer',
     ValueError: 'val',
     }
         lis.append(OverflowError)
         implicit_exceptions[name+"_ovf"] = lis
 
-for _name in 'getattr', 'delattr':
-    _add_exceptions(_name, AttributeError)
-for _name in 'iter', 'coerce':
-    _add_exceptions(_name, TypeError)
-del _name
-
 _add_exceptions("""div mod divmod truediv floordiv pow
                    inplace_div inplace_mod inplace_divmod inplace_truediv
                    inplace_floordiv inplace_pow""", ZeroDivisionError)

pypy/objspace/flow/specialcase.py

         else:
             raise Exception, "should call %r with exactly %d arguments" % (
                 fn, Arity[opname])
-    if space.config.translation.builtins_can_raise_exceptions:
-        # in this mode, avoid constant folding and raise an implicit Exception
-        w_result = space.do_operation(opname, *args_w)
-        space.handle_implicit_exceptions([Exception])
-        return w_result
-    else:
-        # in normal mode, completely replace the call with the underlying
-        # operation and its limited implicit exceptions semantic
-        return getattr(space, opname)(*args_w)
-
-
-# This is not a space cache.
-# It is just collecting the compiled functions from all the source snippets.
-
-class FunctionCache(Cache):
-    """A cache mapping applevel instances to dicts with simple functions"""
-
-    def _build(app):
-        """NOT_RPYTHON.
-        Called indirectly by ApplevelClass.interphook().appcaller()."""
-        dic = {}
-        if not app.can_use_geninterp:
-            return None
-        if app.filename is not None:
-            dic['__file__'] = app.filename
-        dic['__name__'] = app.modname
-        exec py.code.Source(app.source).compile() in dic
-        return dic
-    _build = staticmethod(_build)
+    # completely replace the call with the underlying
+    # operation and its limited implicit exceptions semantic
+    return getattr(space, opname)(*args_w)
 
 # _________________________________________________________________________
 # a simplified version of the basic printing routines, for RPython programs
         s = '\n'
     import os
     os.write(1, s)
-# _________________________________________________________________________
-
-compiled_funcs = FunctionCache()
 
 def sc_applevel(space, app, name, args_w):
-    dic = compiled_funcs.getorbuild(app)
-    if not dic:
-        return None # signal that this is not RPython
-    func = dic[name]
-    if getattr(func, '_annspecialcase_', '').startswith('flowspace:'):
-        # a hack to replace specific app-level helpers with simplified
-        # RPython versions
-        name = func._annspecialcase_[len('flowspace:'):]
-        if name == 'print_item':    # more special cases...
-            w_s = space.do_operation('str', *args_w)
-            args_w = (w_s,)
-        func = globals()['rpython_' + name]
+    # special case only for print_item and print_newline
+    if 'pyopcode' in app.filename and name == 'print_item':
+        w_s = space.do_operation('str', *args_w)
+        args_w = (w_s,)
+    elif 'pyopcode' in app.filename and name == 'print_newline':
+        pass
     else:
-        # otherwise, just call the app-level helper and hope that it
-        # is RPython enough
-        pass
+        raise Exception("not RPython: calling %r from %r" % (name, app))
+    func = globals()['rpython_' + name]
     return space.do_operation('simple_call', Constant(func), *args_w)
 
+# _________________________________________________________________________
+
 def sc_r_uint(space, r_uint, args):
     args_w, kwds_w = args.unpack()
     assert not kwds_w

pypy/objspace/flow/test/test_objspace.py

         g = self.codetest(f)
 
 
-class TestGenInterpStyle(Base):
-    def setup_class(cls):
-        cls.space = FlowObjSpace()
-        cls.space.config.translation.builtins_can_raise_exceptions = True
-
-    def reraiseAttributeError(v):
-        try:
-            x = getattr(v, "y")
-        except AttributeError:
-            raise
-
-    def test_reraiseAttributeError(self):
-        x = self.codetest(self.reraiseAttributeError)
-        simplify_graph(x)
-        self.show(x)
-        excfound = []
-        for link in x.iterlinks():
-            if link.target is x.exceptblock:
-                excfound.append(link.exitcase)
-        assert len(excfound) == 2
-        excfound.sort()
-        expected = [Exception, AttributeError]
-        expected.sort()
-        assert excfound == expected
-
-    def reraiseTypeError(dic):
-        try:
-            x = dic[5]
-        except TypeError:
-            raise
-
-    def test_reraiseTypeError(self):
-        x = self.codetest(self.reraiseTypeError)
-        simplify_graph(x)
-        self.show(x)
-        excfound = []
-        for link in x.iterlinks():
-            if link.target is x.exceptblock:
-                excfound.append(link.exitcase)
-        assert len(excfound) == 2
-        excfound.sort()
-        expected = [Exception, TypeError]
-        expected.sort()
-        assert excfound == expected
-
-    def test_can_catch_special_exceptions(self):
-        def f():
-            try:
-                f()
-            except NotImplementedError:
-                pass
-        graph = self.codetest(f)
-        # assert did not crash
-
-
 DATA = {'x': 5,
         'y': 6}
 

pypy/objspace/std/intobject.py

 from pypy.objspace.std.noneobject import W_NoneObject
 from pypy.objspace.std.register_all import register_all
 from pypy.rlib import jit
-from pypy.rlib.rarithmetic import ovfcheck, LONG_BIT, r_uint
+from pypy.rlib.rarithmetic import ovfcheck, LONG_BIT, r_uint, is_valid_int
 from pypy.rlib.rbigint import rbigint
 
 """
     from pypy.objspace.std.inttype import int_typedef as typedef
 
     def __init__(w_self, intval):
+        assert is_valid_int(intval)
         w_self.intval = intval
 
     def __repr__(w_self):

pypy/objspace/std/objspace.py

 from pypy.objspace.descroperation import DescrOperation, raiseattrerror
 from pypy.rlib.objectmodel import instantiate, r_dict, specialize, is_annotation_constant
 from pypy.rlib.debug import make_sure_not_resized
-from pypy.rlib.rarithmetic import base_int, widen, maxint
+from pypy.rlib.rarithmetic import base_int, widen, maxint, is_valid_int
 from pypy.rlib.objectmodel import we_are_translated
 from pypy.rlib import jit
 
                 return self.newbool(x)
             else:
                 return self.newint(x)
-        # this is an inlined 'is_valid_int' which cannot be used
-        # due to the special annotation nature of 'wrap'.
-        if isinstance(x, long) and (-maxint - 1 <= x <= maxint):
-            return self.newint(x)
         if isinstance(x, str):
             return wrapstr(self, x)
         if isinstance(x, unicode):
         "NOT_RPYTHON"
         # _____ this code is here to support testing only _____
 
+        # we might get there in non-translated versions if 'x' is
+        # a long that fits the correct range.
+        if is_valid_int(x):
+            return self.newint(x)
+
         # wrap() of a container works on CPython, but the code is
         # not RPython.  Don't use -- it is kept around mostly for tests.
         # Use instead newdict(), newlist(), newtuple().
         # The following cases are even stranger.
         # Really really only for tests.
         if type(x) is long:
-            if self.config.objspace.std.withsmalllong:
-                from pypy.rlib.rarithmetic import r_longlong
-                try:
-                    rx = r_longlong(x)
-                except OverflowError:
-                    pass
-                else:
-                    from pypy.objspace.std.smalllongobject import \
-                                                   W_SmallLongObject
-                    return W_SmallLongObject(rx)
-            return W_LongObject.fromlong(x)
+            return self.wraplong(x)
         if isinstance(x, slice):
             return W_SliceObject(self.wrap(x.start),
                                  self.wrap(x.stop),
             return w_result
         return None
 
+    def wraplong(self, x):
+        "NOT_RPYTHON"
+        if self.config.objspace.std.withsmalllong:
+            from pypy.rlib.rarithmetic import r_longlong
+            try:
+                rx = r_longlong(x)
+            except OverflowError:
+                pass
+            else:
+                from pypy.objspace.std.smalllongobject import \
+                                               W_SmallLongObject
+                return W_SmallLongObject(rx)
+        return W_LongObject.fromlong(x)
+
     def unwrap(self, w_obj):
         """NOT_RPYTHON"""
         if isinstance(w_obj, Wrappable):

pypy/objspace/std/test/test_stringobject.py

         # Need default encoding utf-8, but sys.setdefaultencoding
         # is removed after startup.
         import sys
+        if not hasattr(sys, 'setdefaultencoding'):
+            skip("sys.setdefaultencoding() not available")
         old_encoding = sys.getdefaultencoding()
         # Duplicate unittest.test_support.CleanImport logic because it won't
         # import.

pypy/rlib/rarithmetic.py

 maxint = int(LONG_TEST - 1)
 
 def is_valid_int(r):
-    return isinstance(r, (int, long)) and (
+    if objectmodel.we_are_translated():
+        return isinstance(r, int)
+    return type(r) in (int, long, bool) and (
         -maxint - 1 <= r <= maxint)
+is_valid_int._annspecialcase_ = 'specialize:argtype(0)'
 
 def ovfcheck(r):
     "NOT_RPYTHON"

pypy/rlib/test/test_rarithmetic.py

             return a == b
         py.test.raises(MissingRTypeOperation, "self.interpret(f, [42.0])")
 
+    def test_is_valid_int(self):
+        def f(x):
+            return (is_valid_int(x)     * 4 +
+                    is_valid_int(x > 0) * 2 +
+                    is_valid_int(x + 0.5))
+        assert f(123) == 4 + 2
+        res = self.interpret(f, [123])
+        assert res == 4 + 2
+
 class TestLLtype(BaseTestRarithmetic, LLRtypeMixin):
     pass
 

pypy/rpython/test/test_llinterp.py

         try:
             return ovfcheck((-sys.maxint - 1) % x)
         except OverflowError:
-            return 1
+            return 43
         except ZeroDivisionError:
-            return 0
+            return 42
     res = interpret(f, [0])
-    assert res == 0
+    assert res == 42
+    # the following test doesn't work any more before translation,
+    # but "too bad" is the best answer I suppose
     res = interpret(f, [-1])
-    assert res == 1
+    if 0:
+        assert res == 43
     res = interpret(f, [30])
     assert res == (-sys.maxint - 1) % 30
 

pypy/translator/c/src/debug_print.c

 #define WIN32_LEAN_AND_MEAN
 #include <windows.h>
 #endif
+#include "common_header.h"
 #include "src/profiling.h"
 #include "src/debug_print.h"
 

pypy/translator/c/test/test_database.py

     B = Signed
     db = LowLevelDatabase()
     assert db.gettype(A) == "int @"
-    assert db.gettype(B) == "long @"
+    assert db.gettype(B) == "Signed @"
 
 
 def test_recursive_struct():

pypy/translator/geninterplevel.py

-"""
-Implementation of a translator from application Python to
-interpreter level RPython.
-
-The idea is that we can automatically transform application level
-implementations of methods into some equivalent representation at
-interpreter level. Then, the RPython to C translation might
-hopefully spit out some more efficient code than always interpreting
-these methods.
-
-Note that the application level functions are treated as rpythonic,
-in a sense that globals are constants, for instance. This definition
-is not exact and might change.
-
-The interface for this module is
-
-    (initfunc, newsrc) = translate_as_module(
-                                sourcetext,
-                                filename=None,
-                                modname="app2interpexec",
-                                tmpname=None)
-
-If filename is given, it is used as a reference where
-this sourcetext can be literally found, to produce
-real line numbers. It cannot be just any name but
-must exist and contain the source code somewhere.
-
-modname is optional and will be put into the dictionary
-to be created.
-
-tmpname is optional. If given, a temporary file will
-be created for debugging purposes.
-
-The returned newsrc is the generated source text.
-It is used in gateway.py's caching mechanism.
-The initfunc result is a function named "init"+modname
-It must be called with a space instance and returns
-a wrapped dict which is suitable to use as a module dict,
-containing all trnaslatedobjects with their originalname.
-
-Integration of this module is finished.
-There are no longer hand-generated source
-pieces in pypy svn.
-"""
-
-import autopath, os, sys, types
-import inspect
-import cPickle as pickle, __builtin__
-from copy_reg import _HEAPTYPE
-from pypy.objspace.flow.model import Variable, Constant, SpaceOperation
-from pypy.objspace.flow.model import c_last_exception, checkgraph
-from pypy.interpreter.pycode import CO_VARARGS, CO_VARKEYWORDS
-from types import FunctionType, CodeType, ModuleType, MethodType
-from pypy.interpreter.error import OperationError
-from pypy.interpreter.argument import ArgumentsForTranslation, Arguments
-from pypy.translator.backendopt.ssa import SSI_to_SSA
-
-from pypy.translator.translator import TranslationContext
-from pypy.objspace.flow.objspace import FlowObjSpace
-
-from pypy.tool.sourcetools import render_docstr, NiceCompile
-
-from pypy.translator.gensupp import ordered_blocks, UniqueList, builtin_base, \
-     uniquemodulename, C_IDENTIFIER, NameManager
-from pypy.tool.identity_dict import identity_dict
-
-import pypy # __path__
-import py.path
-from pypy.tool.ansi_print import ansi_log
-
-log = py.log.Producer("geninterp")
-py.log.setconsumer("geninterp", ansi_log)
-
-GI_VERSION = '1.2.9'  # bump this for substantial changes
-# ____________________________________________________________
-
-try:
-    set
-except NameError:
-    class fake_set(object):
-        pass
-    class fake_frozenset(object):
-        pass
-    builtin_set = fake_set
-    builtin_frozenset = fake_frozenset
-    faked_set = True
-else:
-    builtin_set = set
-    builtin_frozenset = frozenset
-    faked_set = False
-
-def eval_helper(self, typename, expr):
-    name = self.uniquename("gtype_%s" % typename)
-    unique = self.uniquenameofprebuilt("eval_helper", eval_helper)
-    self.initcode.append1(
-        'def %s(expr):\n'
-        '    dic = space.newdict()\n'
-        '    if "types." in expr:\n'
-        '        space.exec_("import types", dic, dic, hidden_applevel=True)\n'
-        '    else:\n'
-        '        space.exec_("", dic, dic, hidden_applevel=True)\n'
-        '    return space.eval(expr, dic, dic, hidden_applevel=True)' % (unique, ))
-    self.initcode.append1('%s = %s(%r)' % (name, unique, expr))
-    return name
-
-def unpickle_helper(self, name, value):
-    unique = self.uniquenameofprebuilt("unpickle_helper", unpickle_helper)
-    self.initcode.append1(
-        'def %s(value):\n'
-        '    dic = space.newdict()\n'
-        '    space.exec_("import cPickle as pickle", dic, dic, hidden_applevel=True)\n'
-        '    return space.eval("pickle.loads(%%r)" %% value, dic, dic, hidden_applevel=True)' % unique)
-    self.initcode.append1('%s = %s(%r)' % (
-        name, unique, pickle.dumps(value, 2)) )
-
-# hey, for longs we can do even easier:
-def long_helper(self, name, value):
-    unique = self.uniquenameofprebuilt("long_helper", long_helper)
-    self.initcode.append1(
-        'def %s(value):\n'
-        '    dic = space.newdict()\n'
-        '    space.exec_("", dic, dic, hidden_applevel=True) # init __builtins__\n'
-        '    return space.eval(value, dic, dic, hidden_applevel=True)' % unique)
-    self.initcode.append1('%s = %s(%r)' % (
-        name, unique, repr(value) ) )
-
-def bltinmod_helper(self, mod):
-    name = self.uniquename("mod_%s" % mod.__name__)
-    unique = self.uniquenameofprebuilt("bltinmod_helper", bltinmod_helper)
-    self.initcode.append1(
-        'def %s(name):\n'
-        '    dic = space.newdict()\n'
-        '    space.exec_("import %%s" %% name, dic, dic, hidden_applevel=True)\n'
-        '    return space.eval("%%s" %% name, dic, dic, hidden_applevel=True)' % (unique, ))
-    self.initcode.append1('%s = %s(%r)' % (name, unique, mod.__name__))
-    return name
-
-class GenRpy:
-    def __init__(self, translator, entrypoint=None, modname=None, moddict=None):
-        self.translator = translator
-        if entrypoint is None:
-            entrypoint = translator.entrypoint
-        self.entrypoint = entrypoint
-        self.modname = self.trans_funcname(modname or
-                        uniquemodulename(entrypoint))
-        self.moddict = moddict # the dict if we translate a module
-
-        def late_OperationError():
-            self.initcode.append1(
-                'from pypy.interpreter.error import OperationError as gOperationError')
-            return 'gOperationError'
-        def late_Arguments():
-            self.initcode.append1('from pypy.interpreter import gateway')
-            return 'gateway.Arguments'
-
-        self.rpynames = {Constant(None).key:  'space.w_None',
-                         Constant(False).key: 'space.w_False',
-                         Constant(True).key:  'space.w_True',
-                         Constant(Ellipsis).key: 'space.w_Ellipsis',
-                         Constant(NotImplemented).key: 'space.w_NotImplemented',
-                         Constant(OperationError).key: late_OperationError,
-                         Constant(Arguments).key: late_Arguments,
-                       }
-        self.initcode = UniqueList() # list of lines for the module's initxxx()
-        self.latercode = UniqueList()
-        # list of generators generating extra lines
-        #   for later in initxxx() -- for recursive
-        #   objects
-        self.namespace = NameManager()
-        self.namespace.make_reserved_names('__doc__ __args__ space goto')
-        self.globaldecl = []
-        self.globalobjects = []
-        self.pendingfunctions = []
-        self.currentfunc = None
-        self.debugstack = ()  # linked list of nested nameof()
-
-        # special constructors:
-        self.has_listarg = {}
-        for name in "newtuple newlist".split():
-            self.has_listarg[name] = name
-
-        # catching all builtins in advance, to avoid problems
-        # with modified builtins
-
-        # add a dummy _issubtype() to builtins
-        if not hasattr(__builtin__, '_issubtype'):
-            def _issubtype(cls1, cls2):
-                raise TypeError, "this dummy should *not* be reached"
-            __builtin__._issubtype = _issubtype
-
-        class bltinstub:
-            def __init__(self, name):
-                self.__name__ = name
-            def __repr__(self):
-                return '<%s>' % self.__name__
-
-        self.ibuiltin_ids = identity_dict()
-        self.ibuiltin_ids.update([
-            (value, bltinstub(key))
-            for key, value in __builtin__.__dict__.items()
-            if callable(value) and type(value) not in [types.ClassType, type] ] )
-
-        self.space = FlowObjSpace() # for introspection
-
-        self.use_fast_call = True
-        self.specialize_goto = False
-        self._labeltable = {} # unique label names, reused per func
-
-        self._space_arities = None
-
-        self._signature_cache = {}
-        self._defaults_cache = {}
-
-    def expr(self, v, localscope, wrapped = True):
-        if isinstance(v, Variable):
-            return localscope.localname(v.name, wrapped)
-        elif isinstance(v, Constant):
-            return self.nameof(v.value,
-                               debug=('Constant in the graph of', self.currentfunc))
-        else:
-            raise TypeError, "expr(%r)" % (v,)
-
-    def arglist(self, args, localscope):
-        res = [self.expr(arg, localscope) for arg in args]
-        return ", ".join(res)
-
-    def oper(self, op, localscope):
-        if op.opname in ('issubtype', 'isinstance'):
-            arg = op.args[1]
-            if (not isinstance(arg, Constant)
-                or not isinstance(arg.value, (type, types.ClassType))):
-                func = issubclass if op.opname == 'issubtype' else isinstance
-                op = SpaceOperation("simple_call",
-                                    [Constant(func)]+op.args,
-                                    op.result)
-        if op.opname == "simple_call":
-            v = op.args[0]
-            space_shortcut = self.try_space_shortcut_for_builtin(v, len(op.args)-1,
-                                                                 op.args[1:])
-            if space_shortcut is not None:
-                # space method call
-                exv = space_shortcut
-                fmt = "%(res)s = %(func)s(%(args)s)"
-            else:
-                # import sys|__builtin__|_codecs avoid going through __import__
-                if isinstance(v, Constant) and v.value is __builtin__.__import__:
-                    name, glb, loc, frm_lst = op.args[1:]
-                    if (isinstance(name, Constant) and name.value in ('sys', '__builtin__', '_codecs') and
-                        isinstance(loc, Constant) and loc.value is None and
-                        isinstance(frm_lst, Constant) and frm_lst.value is None):
-                        return "%s = space.getbuiltinmodule(%r)" % (self.expr(op.result, localscope),
-                                                                    name.value)
-                exv = self.expr(v, localscope)
-                # default for a spacecall:
-                fmt = "%(res)s = space.call_function(%(func)s, %(args)s)"
-                # see if we can optimize for a fast call.
-                # we just do the very simple ones.
-                if self.use_fast_call and (isinstance(v, Constant)
-                                           and exv.startswith('gfunc_')):
-                    func = v.value
-                    if (not func.func_code.co_flags & CO_VARARGS) and (
-                        func.func_defaults is None):
-                        fmt = "%(res)s = fastf_%(func)s(space, %(args)s)"
-                        exv = exv[6:]
-            return fmt % {"res" : self.expr(op.result, localscope),
-                          "func": exv,
-                          "args": self.arglist(op.args[1:], localscope) }
-        if op.opname == "call_args":
-            v = op.args[0]
-            exv = self.expr(v, localscope)
-            fmt = (
-                "_args = %(Arg)s(space, [%(args_w)s], %(keywords)s, [%(keywords_w)s], %(w_stararg)s, %(w_starstararg)s)\n"
-                "%(res)s = space.call_args(%(func)s, _args)")
-            assert isinstance(op.args[1], Constant)
-            shape = op.args[1].value
-            # make a list out of the second shape elt.
-            shape = shape[0], list(shape[1]), shape[2], shape[3]
-            arglist = [self.expr(arg, localscope) for arg in op.args[2:]]
-            args = ArgumentsForTranslation.fromshape(None, shape, arglist)
-            return fmt % {"res": self.expr(op.result, localscope),
-                          "func": exv,
-                          "args_w": ", ".join(args.arguments_w),
-                          "keywords": args.keywords,
-                          "keywords_w": ", ".join(args.keywords_w),
-                          "w_stararg": args.w_stararg,
-                          "w_starstararg": args.w_starstararg,
-                          'Arg': self.nameof(Arguments) }
-        if op.opname == "hint":
-            return "%s = %s" % (self.expr(op.result, localscope),
-                                self.expr(op.args[0], localscope))
-        if op.opname in self.has_listarg:
-            fmt = "%s = %s([%s])"
-        else:
-            fmt = "%s = %s(%s)"
-        # special case is_true
-        opname = op.opname
-        if opname.startswith('getitem_'):
-            opname = 'getitem'
-        wrapped = opname != "is_true"
-        oper = "space.%s" % opname
-        return fmt % (self.expr(op.result, localscope, wrapped), oper,
-                      self.arglist(op.args, localscope))
-
-    def large_assignment(self, left, right, margin=65):
-        expr = "(%s) = (%s)" % (", ".join(left), ", ".join(right))
-        pieces = expr.split(",")
-        res = [pieces.pop(0)]
-        for piece in pieces:
-            if len(res[-1])+len(piece)+1 > margin:
-                res[-1] += ","
-                res.append(piece)
-            else:
-                res[-1] += (","+piece)
-        return res
-
-    def large_initialize(self, vars, margin=65):
-        res = []
-        nonestr = "None"
-        margin -= len(nonestr)
-        for var in vars:
-            ass = var+"="
-            if not res or len(res[-1]) >= margin:
-                res.append(ass)
-            else:
-                res[-1] += ass
-        res = [line + nonestr for line in res]
-        return res
-
-    def mklabel(self, blocknum):
-        if self.specialize_goto:
-            lbname = self._labeltable.get(blocknum)
-            if not lbname:
-                self.initcode.append1(
-                    'from pypy.objspace.flow.framestate import SpecTag')
-                lbname = self.uniquename("glabel_%d" % blocknum)
-                self._labeltable[blocknum] = lbname
-                self.initcode.append1('%s = SpecTag()' % lbname)
-            return lbname
-        else:
-            return repr(blocknum)
-
-    def gen_link(self, link, localscope, blocknum, block, linklocalvars=None):
-        "Generate the code to jump across the given Link."
-        linklocalvars = linklocalvars or {}
-        left, right = [], []
-        for a1, a2 in zip(link.args, link.target.inputargs):
-            if a1 in linklocalvars:
-                src = linklocalvars[a1]
-            else:
-                src = self.expr(a1, localscope)
-            dest = self.expr(a2, localscope)
-            if src != dest:
-                left.append(dest)
-                right.append(src)
-        if left: # anything at all?
-            txt = "%s = %s" % (", ".join(left), ", ".join(right))
-            if len(txt) <= 65: # arbitrary
-                yield txt
-            else:
-                for line in self.large_assignment(left, right):
-                    yield line
-        goto = blocknum[link.target]
-        yield 'goto = %s' % self.mklabel(goto)
-        if goto <= blocknum[block]:
-            yield 'continue'
-
-    def register_early(self, obj, name):
-        # this was needed for recursive lists.
-        # note that self.latercode led to too late initialization.
-        key = Constant(obj).key
-        self.rpynames[key] = name
-
-    def nameof(self, obj, debug=None, namehint=None):
-        key = Constant(obj).key
-        try:
-            txt = self.rpynames[key]
-            if type(txt) is not str:
-                # this is a predefined constant, initialized on first use
-                func = txt
-                txt = func()
-                self.rpynames[key] = txt
-            return txt
-
-        except KeyError:
-            if debug:
-                stackentry = debug, obj
-            else:
-                stackentry = obj
-            self.debugstack = (self.debugstack, stackentry)
-            obj_builtin_base = builtin_base(obj)
-            if obj_builtin_base in (object, int, long) and type(obj) is not obj_builtin_base:
-                # assume it's a user defined thingy
-                name = self.nameof_instance(obj)
-            else:
-                # shortcutting references to __builtin__
-                if obj in self.ibuiltin_ids:
-                    func = self.ibuiltin_ids[obj]
-                    #name = self.get_nameof_builtin_func(func)
-                    # the above is quicker in principle, but pulls more
-                    # stuff in, so it is slower right now.
-                    name = "(space.builtin.get(space.str_w(%s)))" % self.nameof(func.__name__)
-                else:
-                    for cls in type(obj).__mro__:
-                        meth = getattr(self,
-                                       'nameof_' + cls.__name__.replace(' ', ''),
-                                       None)
-                        if meth:
-                            break
-                    else:
-                        raise Exception, "nameof(%r)" % (obj,)
-
-                    code = meth.im_func.func_code
-                    if namehint and 'namehint' in code.co_varnames[:code.co_argcount]:
-                        name = meth(obj, namehint=namehint)
-                    else:
-                        name = meth(obj)
-            self.debugstack, x = self.debugstack
-            assert x is stackentry
-            self.rpynames[key] = name
-            return name
-
-    def get_nameof_builtin_func(self, func):
-        # this is a hack!
-        # in some cases, like exceptions, we don't have space.builtin available,
-        #so we crate a fall-back...
-        name = self.uniquename('gbltin_' + func.__name__)
-        self.initcode.append1('''\
-try:
-    # see if we have space.builtin in this context
-    space.builtin
-except AttributeError:
-    print "didn\'t get", %(bltin)r
-    def %(name)s(space, __args__):
-        w_func = space.builtin.get(%(bltin)r)
-        return space.call_args(w_func, __args__)
-    %(name)s = space.wrap(gateway.interp2app(%(name)s, unwrap_spec=[gateway.ObjSpace, gateway.Arguments]))
-else:
-        print "got it:", %(bltin)r
-        %(name)s = space.builtin.get(%(bltin)r)'''
-        % {'name': name, 'bltin': func.__name__} )
-        return name
-
-    def uniquename(self, basename):
-        name = self.namespace.uniquename(basename)
-        self.globalobjects.append(name)
-        self.globaldecl.append('# global object %s' % (name,))
-        return name
-
-    def uniquenameofprebuilt(self, basename, obj):
-        # identifying an object and giving it a name,
-        # without the attempt to render it.
-        key = Constant(obj).key
-        try:
-            txt = self.rpynames[key]
-        except KeyError:
-            self.rpynames[key] = txt = self.uniquename(basename)
-        return txt
-
-    def nameof_object(self, value):
-        if type(value) is not object:
-            # try to just wrap it?
-            name = self.uniquename('g_%sinst_%r' % (type(value).__name__, value))
-            self.initcode.append1('%s = space.wrap(%r)' % (name, value))
-            return name
-        name = self.uniquename('g_object')
-        self.initcode.append('_tup = space.newtuple([])\n'
-                                '%s = space.call(space.w_object, _tup)'
-                                % name)
-        return name
-
-    def is_module_builtin(self, mod):
-        if not hasattr(mod, "__file__") or mod.__file__ is None:
-            return True
-        if not (mod.__file__.endswith('.pyc') or
-                mod.__file__.endswith('.py') or
-                mod.__file__.endswith('.pyo')):
-            return True
-        if mod.__file__.endswith('*.py'):  # on top of PyPy, a mixed module
-            return True
-        return False
-
-    def nameof_module(self, value):
-        if value is os or self.is_module_builtin(value):
-            return bltinmod_helper(self, value)
-
-        # we might have createda reference to a module
-        # that is non-standard.
-
-        # SKIPPING
-        return "space.w_None"
-
-        # check whether we can import
-        try:
-            import value
-            need_extra_path = False
-        except ImportError:
-            need_extra_path = True
-        name = self.uniquename('mod_%s' % value.__name__)
-        if need_extra_path:
-            assert False
-            ## self.initcode.append1('import pypy')
-            ## self.initcode.append1('import sys')
-            ## self.initcode.append1('import os')
-            ## self.initcode.append1('for pkgdir in pypy.__path__:\n'
-            ##                       '    libdir = os.path.join(pkgdir, "lib")\n'
-            ##                       '    if os.path.isdir(libdir):\n'
-            ##                       '        break\n'
-            ##                       'else:\n'
-            ##                       '    raise Exception, "cannot find pypy/lib directory"\n'
-            ##                       'sys.path.insert(0, libdir)\n')
-            ## self.initcode.append1('try:\n'
-            ##                       '    import %s as _tmp\n'
-            ##                       'finally:\n'
-            ##                       '    if libdir in sys.path:\n'
-            ##                       '        sys.path.remove(libdir)\n' % value.__name__)
-        else:
-            self.initcode.append1('import %s as _tmp' % value.__name__)
-        self.initcode.append1('%s = space.wrap(_tmp)' % (name))
-        return name
-
-
-    def nameof_int(self, value):
-        if value >= 0:
-            name = 'gi_%d' % value
-        else:
-            # make sure that the type ident is completely described by
-            # the prefixbefore the initial '_' for easy postprocessing
-            name = 'gi_minus_%d' % abs(value)
-        name = self.uniquename(name)
-        self.initcode.append1('%s = space.wrap(%d)' % (name, value))
-        return name
-
-    def nameof_long(self, value):
-        # assume we want them in hex most of the time
-        if value < 256L:
-            s = "%dL" % value
-        else:
-            s = "0x%08xL" % value
-        if value >= 0:
-            name = 'glong_%s' % s
-        else:
-            # mae sure that the type ident is completely described by
-            # the prefix  before the initial '_'
-            name = 'glong_minus_%d' % abs(value)
-        name = self.uniquename(name)
-        # allow literally short longs only, meaning they
-        # must fit into a machine word.
-        if (sys.maxint*2+1)&value == value:
-            self.initcode.append1('%s = space.wrap(%s) # XXX implement long!' % (name, s))
-        else:
-            long_helper(self, name, value)
-        return name
-
-    def nameof_float(self, value):
-        name = 'gfloat_%s' % value
-        name = (name.replace('-', 'minus')
-                    .replace('.', 'dot'))
-        name = self.uniquename(name)
-        # handle overflows
-        if value != 0.0 and 2*value == value:
-            self.initcode.append1('float_inf = 1e200\nfloat_inf *= float_inf')
-            sign = '-+'[value >= 0]
-            self.initcode.append('%s = space.wrap(%sfloat_inf)' % (name, sign))
-        else:
-            self.initcode.append('%s = space.wrap(%r)' % (name, value))
-        return name
-
-    def nameof_str(self, value):
-        if [c for c in value if c<' ' or c>'~' or c=='"' or c=='\\']:
-            # non-printable string
-            namestr = repr(value)[1:-1]
-        else:
-            # printable string
-            namestr = value
-        if not namestr:
-            namestr = "_emptystr_"
-        name = self.uniquename('gs_' + namestr[:32])
-        if len(value) < 30 and "\n" not in value:
-            txt = '%s = space.new_interned_str(%r)' % (name, value)
-        else:
-            txt = render_docstr(value, '%s = space.new_interned_str(\n' % name, ')')
-            txt = txt,  # not splitted
-        self.initcode.append(txt)
-        return name
-
-    def skipped_function(self, func):
-        # debugging only!  Generates a placeholder for missing functions
-        # that raises an exception when called.
-        name = self.uniquename('gskippedfunc_' + func.__name__)
-        self.globaldecl.append('# global decl %s' % (name, ))
-        self.initcode.append('# build func %s' % name)
-        return name
-
-    def skipped_class(self, cls):
-        # debugging only!  Generates a placeholder for missing classes
-        # that raises an exception when called.
-        name = self.uniquename('gskippedclass_' + cls.__name__)
-        self.globaldecl.append('# global decl %s' % (name, ))
-        self.initcode.append1('# build class %s' % name)
-        return name
-
-    def trans_funcname(self, s):
-        return s.translate(C_IDENTIFIER)
-
-    def nameof_function(self, func, namehint=''):
-        if hasattr(func, 'geninterplevel_name'):
-            return func.geninterplevel_name(self)
-        if func.func_globals is None:
-            # built-in functions on top of PyPy
-            return self.nameof_builtin_function(func)
-
-        printable_name = '(%s:%d) %s' % (
-            self.trans_funcname(func.func_globals.get('__name__', '?')),
-            func.func_code.co_firstlineno,
-            func.__name__)
-        if (func.func_doc and
-            func.func_doc.lstrip().startswith('NOT_RPYTHON')):
-            log.WARNING("skipped %s" % printable_name)
-            return self.skipped_function(func)
-        name = self.uniquename('gfunc_' + self.trans_funcname(
-            namehint + func.__name__))
-
-        positional, varargs, varkwds, defs = inspect.getargspec(func)
-        if varargs is varkwds is defs is None:
-            unwrap = ', '.join(['gateway.W_Root']*len(positional))
-            interp_name = 'fastf_' + name[6:]
-        else:
-            unwrap = 'gateway.Arguments'
-            interp_name = 'f_' + name[6:]
-
-        self.initcode.append1('from pypy.interpreter import gateway')
-        self.initcode.append1('%s = space.wrap(gateway.interp2app(%s, unwrap_spec=[gateway.ObjSpace, %s]))' %
-                              (name, interp_name, unwrap))
-        self.pendingfunctions.append(func)
-        return name
-
-    def nameof_staticmethod(self, sm):
-        # XXX XXX XXXX
-        func = sm.__get__(42.5)
-        name = self.uniquename('gsm_' + func.__name__)
-        functionname = self.nameof(func)
-        self.initcode.append1('%s = space.wrap(%s)' % (name, functionname))
-        return name
-
-    def nameof_instancemethod(self, meth):
-        if (not hasattr(meth.im_func, 'func_globals') or
-            meth.im_func.func_globals is None):
-            # built-in methods (bound or not) on top of PyPy or possibly 2.4
-            return self.nameof_builtin_method(meth)
-        if meth.im_self is None:
-            # no error checking here
-            return self.nameof(meth.im_func, namehint="%s_" % meth.im_class.__name__)
-        else:
-            ob = self.nameof(meth.im_self)
-            func = self.nameof(meth.im_func)
-            typ = self.nameof(meth.im_class)
-            name = self.uniquename('gmeth_' + meth.im_func.__name__)
-            funcname = self.nameof(meth.im_func.__name__)
-            self.initcode.append1(
-                '%s = space.getattr(%s, %s)' % (name, ob, funcname))
-            return name
-
-    nameof_method = nameof_instancemethod   # when run on top of PyPy
-
-    def should_translate_attr(self, pbc, attr):
-        ignore = getattr(pbc.__class__, 'NOT_RPYTHON_ATTRIBUTES', [])
-        if attr in ignore:
-            return False
-        else:
-            return "probably"   # True
-
-    def later(self, gen):
-        self.latercode.append1((gen, self.debugstack))
-
-    def nameof_instance(self, instance):
-        klass = instance.__class__
-        name = self.uniquename('ginst_' + klass.__name__)
-        cls = self.nameof(klass)
-        if hasattr(klass, '__base__'):
-            base_class = builtin_base(instance)
-            base = self.nameof(base_class)
-        else:
-            base_class = None
-            base = cls
-        def initinstance():
-            content = instance.__dict__.items()
-            content.sort()
-            for key, value in content:
-                if self.should_translate_attr(instance, key):
-                    try:
-                            yield 'space.setattr(%s, %s, %s)' % (
-                                name, self.nameof(key), self.nameof(value))
-                    except:
-                        log.ERROR("Problem while generating %s of %r" % (
-                                name, instance))
-                        raise
-        self.initcode.append1("%s = space.call_method(%s, '__new__', %s)" % (
-                             name, cls, cls))
-        self.later(initinstance())
-        return name
-
-    def space_arities(self):
-        if self._space_arities is None:
-            arities = self._space_arities = {}
-            for name, sym, arity, specnames in self.space.MethodTable:
-                arities[name] = arity
-            del arities["isinstance"]
-        return self._space_arities
-
-    def try_space_shortcut_for_builtin(self, v, nargs, args):
-        if isinstance(v, Constant) and v.value in self.ibuiltin_ids:
-            name = self.ibuiltin_ids[v.value].__name__
-            if (hasattr(self.space, name) and
-                self.space_arities().get(name, -1) == nargs):
-                return "space.%s" % name
-        return None
-
-    def nameof_builtin_function_or_method(self, func):
-        if func.__self__ is None:
-            return self.nameof_builtin_function(func)
-        else:
-            return self.nameof_builtin_method(func)
-
-    def nameof_builtin_function(self, func):
-        # builtin function
-        if func in self.ibuiltin_ids:
-            func = self.ibuiltin_ids[func]
-            return "(space.builtin.get(space.str_w(%s)))" % self.nameof(func.__name__)
-        # where does it come from? Python2.2 doesn't have func.__module__
-        for modname, module in sys.modules.items():
-            if not self.is_module_builtin(module):
-                continue    # skip non-builtin modules
-            if func is getattr(module, func.__name__, None):
-                break
-        else:
-            raise Exception, '%r not found in any built-in module' % (func,)
-        #if modname == '__builtin__':
-        #    # be lazy
-        #    return "(space.builtin.get(space.str_w(%s)))" % self.nameof(func.__name__)
-        if modname == 'sys':
-            # be lazy
-            return "(space.sys.get(space.str_w(%s)))" % self.nameof(func.__name__)
-        else:
-            name = self.uniquename('gbltin_' + func.__name__)
-            self.initcode.append1('%s = space.getattr(%s, %s)' % (
-                name, self.nameof(module), self.nameof(func.__name__)))
-        return name
-
-    def nameof_builtin_method(self, meth):
-        try:
-            im_self = meth.__self__
-        except AttributeError:
-            im_self = meth.im_self    # on top of PyPy
-        if im_self is None:
-            # builtin unbound method (only on top of PyPy)
-            name = self.nameof_wrapper_descriptor(meth)
-        else:
-            # builtin (bound) method
-            name = self.uniquename('gbltinmethod_' + meth.__name__)
-            self.initcode.append1('%s = space.getattr(%s, %s)' % (
-                name, self.nameof(im_self), self.nameof(meth.__name__)))
-        return name
-
-    def nameof_classobj(self, cls):
-        initcode = []
-        printable_name = cls.__name__
-        if cls.__doc__ and cls.__doc__.lstrip().startswith('NOT_RPYTHON'):
-            #raise Exception, "%r should never be reached" % (cls,)
-            log.WARNING("skipped class %s" % printable_name)
-            return self.skipped_class(cls)
-
-        metaclass = "space.w_type"
-        name = self.uniquename('gcls_' + cls.__name__)
-
-        if issubclass(cls, py.builtin.BaseException):
-            # if cls.__module__ == 'exceptions':
-            # don't rely on this, py.magic redefines AssertionError
-            if getattr(__builtin__,cls.__name__,None) is cls:
-                # exception are defined on the space
-                return 'space.w_%s' % cls.__name__
-
-        if not isinstance(cls, type):
-            assert type(cls) is types.ClassType
-            # do *not* change metaclass, but leave the
-            # decision to what PyPy thinks is correct.
-            # metaclass = 'space.w_classobj'
-
-        basenames = [self.nameof(base) for base in cls.__bases__]
-
-        def initclassobj():
-            content = cls.__dict__.items()
-            content.sort()
-            for key, value in content:
-                if key.startswith('__'):
-                    if key in ['__module__', '__doc__', '__dict__',
-                               '__weakref__', '__metaclass__', '__slots__',
-                               '__new__', '__del__']:
-                        continue
-
-                # redirect value through class interface, in order to
-                # get methods instead of functions.
-                value = getattr(cls, key)
-
-                if isinstance(value, staticmethod) and value.__get__(1) not in self.translator.flowgraphs and self.translator.frozen:
-                    log.WARNING("skipped staticmethod: %s" % value)
-                    continue
-                if isinstance(value, MethodType) and value.im_self is cls:
-                    log.WARNING("skipped classmethod: %s" % value)
-                    continue
-
-                yield 'space.setattr(%s, %s, %s)' % (
-                    name, self.nameof(key), self.nameof(value))
-
-        baseargs = ", ".join(basenames)
-        initcode.append('_dic = space.newdict()')
-        for key, value in cls.__dict__.items():
-            if key.startswith('__'):
-                if key in ['__module__', '__metaclass__', '__slots__',
-                           '__new__', '__del__']:
-                    keyname = self.nameof(key)
-                    valname = self.nameof(value)
-                    initcode.append("space.setitem(_dic, %s, %s)" % (
-                        keyname, valname))
-
-        if cls.__doc__ is not None:
-            sdoc = self.nameof("__doc__")
-            docobj = cls.__dict__["__doc__"]
-            if type(docobj) in (str, unicode):
-                docstr = render_docstr(cls, "_doc = space.wrap(", ")")
-                initcode.append((docstr,)) # not splitted
-            else:
-                initcode.append("_doc = %s" % self.nameof(docobj) )
-            initcode.append("space.setitem(_dic, %s, _doc)" % (sdoc,))
-        cls_name = self.nameof(cls.__name__)
-        for l in initcode:
-            self.initcode.append(l)
-        self.initcode.append1('_bases = space.newtuple([%(bases)s])\n'
-                             '_args = space.newtuple([%(name)s, _bases, _dic])\n'
-                             '%(klass)s = space.call(%(meta)s, _args)'
-                             % {"bases": baseargs,
-                                "klass": name,
-                                "name" : cls_name,
-                                "meta" : metaclass} )
-
-        self.later(initclassobj())
-        return name
-
-    nameof_class = nameof_classobj   # for Python 2.2
-
-    typename_mapping = {
-        object: 'space.w_object',
-        int:    'space.w_int',
-        long:   'space.w_long',
-        bool:   'space.w_bool',
-        list:   'space.w_list',
-        tuple:  'space.w_tuple',
-        dict:   'space.w_dict',
-        str:    'space.w_str',
-        float:  'space.w_float',
-        slice:  'space.w_slice',
-        types.InstanceType: (eval_helper, 'InstanceType', 'types.InstanceType'),
-        type:   'space.w_type',
-        complex: (eval_helper, 'complex', 'types.ComplexType'),
-        unicode:'space.w_unicode',
-        basestring: (eval_helper, 'basestring', 'basestring'),
-        file:   (eval_helper, 'file', 'file'),
-        type(None): (eval_helper, 'NoneType', 'type(None)'),
-        CodeType: (eval_helper, 'code', 'type((lambda:42).func_code)'),
-        ModuleType: (eval_helper, 'ModuleType', 'types.ModuleType'),
-        xrange: (eval_helper, 'xrange', 'xrange'),
-
-        ##r_int:  'space.w_int',
-        ##r_uint: 'space.w_int',
-
-        type(len): (eval_helper, 'FunctionType', 'type(lambda:42)'),
-        # type 'method_descriptor':
-        # XXX small problem here:
-        # XXX with space.eval, we get <W_TypeObject(method)>
-        # XXX but with wrap, we get <W_TypeObject(instancemethod)>
-        type(list.append): (eval_helper, "method_descriptor", "type(list.append)"),
-        # type 'wrapper_descriptor':
-        type(type(None).__repr__): (eval_helper, "wrapper_descriptor",
-                                    "type(type(None).__repr__)"),
-        # type 'getset_descriptor':
-        # XXX here we get <W_TypeObject(FakeDescriptor)>,
-        # while eval gives us <W_TypeObject(GetSetProperty)>
-        type(type.__dict__['__dict__']): (eval_helper, "getset_descriptor",
-            "type(type.__dict__[\'__dict__\'])"),
-        # type 'member_descriptor':
-        # XXX this does not work in eval!
-        # type(type.__dict__['__basicsize__']): "cannot eval type(type.__dict__['__basicsize__'])",
-        # XXX there seems to be no working support for member descriptors ???
-        type(types.GeneratorType.gi_frame):
-            (eval_helper, "member_descriptor", 'type(property.fdel)'),
-        types.ClassType: 'space.w_classobj',
-        types.MethodType: (eval_helper, "instancemethod",
-            "type((lambda:42).__get__(42))"),
-        type(Ellipsis): (eval_helper, 'EllipsisType', 'types.EllipsisType'),
-        builtin_set: (eval_helper, "set", "set"),
-        builtin_frozenset: (eval_helper, "frozenset", "frozenset"),
-        buffer: (eval_helper, "buffer", "buffer"),
-    }
-
-    def nameof_type(self, cls):
-        if cls in self.typename_mapping:
-            ret = self.typename_mapping[cls]
-            if type(ret) is tuple:
-                ret = ret[0](self, ret[1], ret[2])
-            return ret
-        if issubclass(cls, py.builtin.BaseException):   # Python 2.5 only
-            # if cls.__module__ == 'exceptions':
-            # don't rely on this, py.magic redefines AssertionError
-            if getattr(__builtin__,cls.__name__,None) is cls:
-                # exception are defined on the space
-                return 'space.w_%s' % cls.__name__
-        assert cls.__module__ != '__builtin__' or cls.__flags__&_HEAPTYPE, (
-            "built-in class %r not found in typename_mapping "
-            "while compiling %s" % (cls, self.currentfunc and
-                                    self.currentfunc.__name__ or "*no function at all*"))
-        return self.nameof_classobj(cls)
-
-    def nameof_tuple(self, tup):
-        name = self.uniquename('g%dtuple' % len(tup))
-        args = [self.nameof(x) for x in tup]
-        args = ', '.join(args)
-        self.initcode.append1('%s = space.newtuple([%s])' % (name, args))
-        return name
-
-    def nameof_list(self, lis):
-        name = self.uniquename('g%dlist' % len(lis))
-        # note that self.latercode led to too late initialization.
-        self.register_early(lis, name)
-        # try to save at least one assignment.
-        if lis and lis[0] is not lis:
-            default = lis[0]
-        else:
-            default = None
-        self.initcode.append('%s = space.newlist([%s])' % (name, self.nameof(default)))
-        self.initcode.append('%s = space.mul(%s, %s)' % (name, name, self.nameof(len(lis))))