[pypy-svn] r9332 - in pypy/dist: lib-python-2.3.4/test pypy pypy/interpreter pypy/interpreter/test pypy/interpreter/test/mixedmodule pypy/module pypy/module/builtin pypy/module/sys2 pypy/module/test pypy/objspace pypy/objspace/flow pypy/objspace/std pypy/objspace/std/test pypy/objspace/test pypy/tool pypy/tool/test pypy/translator pypy/translator/test pypy/translator/tool

hpk at codespeak.net hpk at codespeak.net
Sat Feb 19 15:30:46 CET 2005


Author: hpk
Date: Sat Feb 19 15:30:45 2005
New Revision: 9332

Added:
   pypy/dist/pypy/interpreter/lazymodule.py
      - copied unchanged from r9330, pypy/branch/dist-interpapp/pypy/interpreter/lazymodule.py
   pypy/dist/pypy/interpreter/test/mixedmodule/   (props changed)
      - copied from r9330, pypy/branch/dist-interpapp/pypy/interpreter/test/mixedmodule/
   pypy/dist/pypy/interpreter/test/mixedmodule/__init__.py
      - copied unchanged from r9330, pypy/branch/dist-interpapp/pypy/interpreter/test/mixedmodule/__init__.py
   pypy/dist/pypy/interpreter/test/mixedmodule/file1.py
      - copied unchanged from r9330, pypy/branch/dist-interpapp/pypy/interpreter/test/mixedmodule/file1.py
   pypy/dist/pypy/interpreter/test/mixedmodule/file2_app.py
      - copied unchanged from r9330, pypy/branch/dist-interpapp/pypy/interpreter/test/mixedmodule/file2_app.py
   pypy/dist/pypy/interpreter/test/test_descrtypecheck.py   (props changed)
      - copied unchanged from r9330, pypy/branch/dist-interpapp/pypy/interpreter/test/test_descrtypecheck.py
   pypy/dist/pypy/module/builtin/   (props changed)
      - copied from r9330, pypy/branch/dist-interpapp/pypy/module/builtin/
   pypy/dist/pypy/module/builtin/__init__.py
      - copied unchanged from r9330, pypy/branch/dist-interpapp/pypy/module/builtin/__init__.py
   pypy/dist/pypy/module/builtin/app_complex.py   (props changed)
      - copied unchanged from r9330, pypy/branch/dist-interpapp/pypy/module/builtin/app_complex.py
   pypy/dist/pypy/module/builtin/app_descriptor.py   (props changed)
      - copied unchanged from r9330, pypy/branch/dist-interpapp/pypy/module/builtin/app_descriptor.py
   pypy/dist/pypy/module/builtin/app_functional.py   (props changed)
      - copied unchanged from r9330, pypy/branch/dist-interpapp/pypy/module/builtin/app_functional.py
   pypy/dist/pypy/module/builtin/app_help.py   (props changed)
      - copied unchanged from r9330, pypy/branch/dist-interpapp/pypy/module/builtin/app_help.py
   pypy/dist/pypy/module/builtin/app_inspect.py   (props changed)
      - copied unchanged from r9330, pypy/branch/dist-interpapp/pypy/module/builtin/app_inspect.py
   pypy/dist/pypy/module/builtin/app_io.py   (props changed)
      - copied unchanged from r9330, pypy/branch/dist-interpapp/pypy/module/builtin/app_io.py
   pypy/dist/pypy/module/builtin/app_misc.py   (props changed)
      - copied unchanged from r9330, pypy/branch/dist-interpapp/pypy/module/builtin/app_misc.py
   pypy/dist/pypy/module/builtin/compiling.py   (props changed)
      - copied unchanged from r9330, pypy/branch/dist-interpapp/pypy/module/builtin/compiling.py
   pypy/dist/pypy/module/builtin/importing.py   (props changed)
      - copied unchanged from r9330, pypy/branch/dist-interpapp/pypy/module/builtin/importing.py
   pypy/dist/pypy/module/builtin/operation.py   (props changed)
      - copied unchanged from r9330, pypy/branch/dist-interpapp/pypy/module/builtin/operation.py
   pypy/dist/pypy/module/sys2/   (props changed)
      - copied from r9330, pypy/branch/dist-interpapp/pypy/module/sys2/
   pypy/dist/pypy/module/sys2/__init__.py
      - copied unchanged from r9330, pypy/branch/dist-interpapp/pypy/module/sys2/__init__.py
   pypy/dist/pypy/module/sys2/app.py   (props changed)
      - copied unchanged from r9330, pypy/branch/dist-interpapp/pypy/module/sys2/app.py
   pypy/dist/pypy/module/sys2/hook.py
      - copied unchanged from r9330, pypy/branch/dist-interpapp/pypy/module/sys2/hook.py
   pypy/dist/pypy/module/sys2/state.py   (props changed)
      - copied unchanged from r9330, pypy/branch/dist-interpapp/pypy/module/sys2/state.py
   pypy/dist/pypy/module/sys2/vm.py   (props changed)
      - copied unchanged from r9330, pypy/branch/dist-interpapp/pypy/module/sys2/vm.py
   pypy/dist/pypy/tool/getpy.py
      - copied unchanged from r9330, pypy/branch/dist-interpapp/pypy/tool/getpy.py
Removed:
   pypy/dist/pypy/interpreter/extmodule.py
   pypy/dist/pypy/interpreter/test/foomodule.py
   pypy/dist/pypy/interpreter/test/test_extmodule.py
   pypy/dist/pypy/module/__builtin__interp.py
   pypy/dist/pypy/module/__builtin__module.py
   pypy/dist/pypy/module/sysinterp.py
   pypy/dist/pypy/module/sysmodule.py
Modified:
   pypy/dist/lib-python-2.3.4/test/conftest.py
   pypy/dist/pypy/TODO
   pypy/dist/pypy/conftest.py
   pypy/dist/pypy/interpreter/baseobjspace.py
   pypy/dist/pypy/interpreter/executioncontext.py
   pypy/dist/pypy/interpreter/gateway.py
   pypy/dist/pypy/interpreter/interactive.py
   pypy/dist/pypy/interpreter/main.py
   pypy/dist/pypy/interpreter/module.py
   pypy/dist/pypy/interpreter/py.py
   pypy/dist/pypy/interpreter/pycode.py
   pypy/dist/pypy/interpreter/pyframe.py
   pypy/dist/pypy/interpreter/pyopcode.py
   pypy/dist/pypy/interpreter/test/test_appinterp.py
   pypy/dist/pypy/interpreter/test/test_class.py
   pypy/dist/pypy/interpreter/test/test_function.py
   pypy/dist/pypy/interpreter/test/test_gateway.py
   pypy/dist/pypy/interpreter/test/test_interpreter.py
   pypy/dist/pypy/interpreter/test/test_main.py
   pypy/dist/pypy/interpreter/test/test_module.py
   pypy/dist/pypy/interpreter/test/test_objspace.py
   pypy/dist/pypy/interpreter/typedef.py
   pypy/dist/pypy/module/test/test_builtin.py
   pypy/dist/pypy/module/test/test_import.py
   pypy/dist/pypy/module/test/test_sysmodule.py
   pypy/dist/pypy/objspace/descroperation.py
   pypy/dist/pypy/objspace/flow/flowcontext.py
   pypy/dist/pypy/objspace/flow/objspace.py
   pypy/dist/pypy/objspace/flow/specialcase.py
   pypy/dist/pypy/objspace/std/dictproxyobject.py
   pypy/dist/pypy/objspace/std/dictproxytype.py
   pypy/dist/pypy/objspace/std/dicttype.py
   pypy/dist/pypy/objspace/std/listtype.py
   pypy/dist/pypy/objspace/std/longobject.py
   pypy/dist/pypy/objspace/std/model.py
   pypy/dist/pypy/objspace/std/multimethod.py
   pypy/dist/pypy/objspace/std/objecttype.py
   pypy/dist/pypy/objspace/std/objspace.py
   pypy/dist/pypy/objspace/std/slicetype.py
   pypy/dist/pypy/objspace/std/stdtypedef.py
   pypy/dist/pypy/objspace/std/test/test_typeobject.py
   pypy/dist/pypy/objspace/std/typeobject.py
   pypy/dist/pypy/objspace/std/typetype.py
   pypy/dist/pypy/objspace/test/test_traceobjspace.py
   pypy/dist/pypy/objspace/trivial.py
   pypy/dist/pypy/tool/pydis.py
   pypy/dist/pypy/tool/pytestsupport.py
   pypy/dist/pypy/tool/test/test_pytestsupport.py
   pypy/dist/pypy/tool/uid.py
   pypy/dist/pypy/translator/genc.py
   pypy/dist/pypy/translator/geninterplevel.py
   pypy/dist/pypy/translator/test/snippet.py
   pypy/dist/pypy/translator/test/test_annrpython.py
   pypy/dist/pypy/translator/tool/tointerplevel.py
Log:
merge of the dist-interpapp branch where Samuele
Armin and me worked for 9 days (summing up to a 
hundred commits, as you may have noticed in your inbox). 

Major results (apart from little stuff here and 
there) are: 

- a new app2interp mechanism that is now indepedent from 
  the interp2app implementation 

- a new way to do "mixed modules" which contain applevel 
  and interplevel definitions.  We also ported the builtin
  and sys module and they now live as packages/directory 
  structures.  in pypy/module/sys2/__init__.py 
  and pypy/module/builtin/__init__.py you'll find dictionaries
  which specify where attributes are loaded from (on demand). 

  The old very hacky code for interplevel/applevel modules
  is gone. 

- in the course, interp2app was cleaned up a bit 
  and we added more type information/checks for GetSetProperties 
  and other interp-level functions. 

One consequence of the finalized branch is that the startup
time for interactive usage of PyPy is reduced by some 50-70 %. 
This is mainly due to the now-lazy sys and builtin module. 
Btw, if you access "__builtin__.__dict__" or "sys.__dict__" 
then the lazyness ends: all attributes will be loaded and
you get a normal dictionary.  So from application level 
the module-lazyness is basically invisible. 

There are still bits and pieces to be further cleaned 
or fixed up but that can happen in the trunk now. 



Modified: pypy/dist/lib-python-2.3.4/test/conftest.py
==============================================================================
--- pypy/dist/lib-python-2.3.4/test/conftest.py	(original)
+++ pypy/dist/lib-python-2.3.4/test/conftest.py	Sat Feb 19 15:30:45 2005
@@ -62,9 +62,10 @@
     mod = PyPyModule(space, w_dottedname) 
     w_globals = mod.w_dict 
     w_filename = space.wrap(str(filepath)) 
-    space.builtin.execfile(w_filename, w_globals, w_globals) 
+    w_execfile = space.builtin.get('execfile') 
+    space.call_function(w_execfile, w_filename, w_globals, w_globals)
     w_mod = space.wrap(mod) 
-    w_modules = space.getitem(space.sys.w_dict, space.wrap('modules'))
+    w_modules = space.sys.get('modules') 
     space.setitem(w_modules, w_dottedname, w_mod) 
     return w_mod 
 

Modified: pypy/dist/pypy/TODO
==============================================================================
--- pypy/dist/pypy/TODO	(original)
+++ pypy/dist/pypy/TODO	Sat Feb 19 15:30:45 2005
@@ -20,21 +20,13 @@
 * (documentation) remove/retire all web-pages referencing e.g.
   AnnSpace or other deprecated stuff
 
-* Review, enhance the new mixed-level module mechanism
-  (e.g. the module/builtin*.py files comprise the builtin module)
-  and try to apply the same technique for the application level 
-  type definitions (types.py). Think about a way to split up
-  especially app-level definitions of __builtin__ into multiple
-  files. (like allowing __builtin__ to be a directory with files
-  comprising the complete definition of the builtin module etc.pp) 
-
 * review whatever you like 
 
 StdObjSpace
 ===========
 
-* find a way via hacking or elegance to run CPython's unit tests
-  against the StdObjSpace.
+* allow CPython's "output-checking" tests to run in a convenient
+  way over StdObjSpace
 
 * String formatting is agonizingly slow.
 

Modified: pypy/dist/pypy/conftest.py
==============================================================================
--- pypy/dist/pypy/conftest.py	(original)
+++ pypy/dist/pypy/conftest.py	Sat Feb 19 15:30:45 2005
@@ -37,11 +37,11 @@
         if name == 'std' and py.test.config.option.oldstyle:
             space.enable_old_style_classes_as_default_metaclass()
         if name != 'flow': # not sensible for flow objspace case
-            space.setitem(space.w_builtins, space.wrap('AssertionError'), 
+            space.setitem(space.builtin.w_dict, space.wrap('AssertionError'), 
                           pytestsupport.build_pytest_assertion(space))
-            space.setitem(space.w_builtins, space.wrap('raises'),
+            space.setitem(space.builtin.w_dict, space.wrap('raises'),
                           space.wrap(pytestsupport.app_raises))
-            space.setitem(space.w_builtins, space.wrap('skip'),
+            space.setitem(space.builtin.w_dict, space.wrap('skip'),
                           space.wrap(pytestsupport.app_skip))
             space.raises_w = pytestsupport.raises_w.__get__(space)
             space.eq_w = pytestsupport.eq_w.__get__(space) 
@@ -129,7 +129,7 @@
         assert not args 
         name = target.func_globals.get('objspacename', None) 
         space = gettestobjspace(name) 
-        func = app2interp_temp(target, target.__name__)
+        func = app2interp_temp(target)
         self.execute_appex(space, func, space)
 
 
@@ -137,7 +137,7 @@
     def execute(self, target, *args): 
         assert not args 
         space = target.im_self.space 
-        func = app2interp_temp(target.im_func, target.__name__) 
+        func = app2interp_temp(target.im_func) 
         self.execute_appex(space, func, space, space.w_None)
 
 class AppClassCollector(py.test.collect.Class): 

Modified: pypy/dist/pypy/interpreter/baseobjspace.py
==============================================================================
--- pypy/dist/pypy/interpreter/baseobjspace.py	(original)
+++ pypy/dist/pypy/interpreter/baseobjspace.py	Sat Feb 19 15:30:45 2005
@@ -13,6 +13,18 @@
     in a 'normal' object space like StdObjSpace."""
     def getdict(self):
         return None
+
+    def getdictvalue(self, space, attr):
+        w_dict = self.getdict()
+        if w_dict is not None:
+            try:
+                return space.getitem(w_dict, space.wrap(attr))
+            except OperationError, e:
+                if not e.match(space, space.w_KeyError):
+                    raise
+        return None
+
+    
     def getclass(self, space):
         return space.gettypeobject(self.typedef)
 
@@ -25,6 +37,7 @@
 class Wrappable(BaseWrappable, object):
     """Same as BaseWrappable, just new-style instead."""
 
+
 class ObjSpace(object):
     """Base class for the interpreter-level implementations of object spaces.
     http://codespeak.net/moin/pypy/moin.cgi/ObjectSpace"""
@@ -34,60 +47,36 @@
     def __init__(self):
         "NOT_RPYTHON: Basic initialization of objects."
         self._gatewaycache = Cache()
+        self._codecache = Cache()
         # set recursion limit
-        self.recursion_limit = 1000
         # sets all the internal descriptors
         self.initialize()
         
     def __repr__(self):
         return self.__class__.__name__
 
-    def make_builtins(self, for_builtins):
+    def make_builtins(self):
         "NOT_RPYTHON: only for initializing the space."
-        # initializing builtins may require creating a frame which in
-        # turn already accesses space.w_builtins, provide a dummy one ...
-        self.w_builtins = self.newdict([])
-
-        # insert stuff into the newly-made builtins
-        for key, w_value in for_builtins.items():
-            self.setitem(self.w_builtins, self.wrap(key), w_value)
-
-        assert not hasattr(self, 'builtin')
-        if not hasattr(self, 'sys'):
-            self.make_sys()
-
-        from pypy.interpreter.extmodule import BuiltinModule
-
-        # the builtins are iteratively initialized
-        self.builtin = BuiltinModule(self, '__builtin__', self.w_builtins)
-        self.w_builtin = self.wrap(self.builtin)
+
+        from pypy.module.sys2 import Module 
+        w_name = self.wrap('sys')
+        self.sys = Module(self, w_name) 
+        w_modules = self.sys.get('modules')
+        self.setitem(w_modules, w_name, self.wrap(self.sys))
+
+        from pypy.module.builtin import Module 
+        w_name = self.wrap('__builtin__')
+        self.builtin = Module(self, w_name) 
+        w_builtin = self.wrap(self.builtin)
+        self.setitem(w_modules, w_name, w_builtin) 
+        self.setitem(self.builtin.w_dict, self.wrap('__builtins__'), w_builtin) 
 
         # initialize with "bootstrap types" from objspace  (e.g. w_None)
         for name, value in self.__dict__.items():
             if name.startswith('w_'):
                 name = name[2:]
-                if name.startswith('builtin') or name.startswith('sys'):
-                    continue
                 #print "setitem: space instance %-20s into builtins" % name
-                self.setitem(self.w_builtins, self.wrap(name), value)
-
-        self.sys.setbuiltinmodule(self.w_builtin, '__builtin__')
-
-    def make_sys(self):
-        "NOT_RPYTHON: only for initializing the space."
-        from pypy.interpreter.extmodule import BuiltinModule
-        assert not hasattr(self, 'sys')
-        self.sys = BuiltinModule(self, 'sys')
-        self.w_sys = self.wrap(self.sys)
-        self.sys.setbuiltinmodule(self.w_sys, 'sys')
-        
-    def get_builtin_module(self, name):
-        if name not in self.sys.builtin_modules:
-            return None
-        module = self.sys.builtin_modules[name]
-        w_module = self.wrap(module)
-        self.sys.setbuiltinmodule(w_module, name)
-        return w_module
+                self.setitem(self.builtin.w_dict, self.wrap(name), value)
 
     def initialize(self):
         """NOT_RPYTHON: Abstract method that should put some minimal
@@ -279,36 +268,34 @@
             statement = PyCode(self)._from_code(statement)
         if not isinstance(statement, PyCode):
             raise TypeError, 'space.exec_(): expected a string, code or PyCode object'
+        w_key = self.wrap('__builtins__')
+        if not self.is_true(self.contains(w_globals, w_key)):
+            self.setitem(w_globals, w_key, self.wrap(self.builtin))
         return statement.exec_code(self, w_globals, w_locals)
 
-    def appexec(self, posargs, source): 
-        """ return value from executing given source at applevel with 
-            given name=wrapped value parameters as its starting scope.  
-            Note: EXPERIMENTAL. 
-        """ 
-        space = self
-        pypyco = pypycodecache.getorbuild((space,source), buildpypycode, posargs)
-        w_glob = space.newdict([])
-        frame = pypyco.create_frame(space, w_glob) 
-        frame.setfastscope(posargs)
-        return frame.run() 
+    def appexec(self, posargs_w, source): 
+        """ return value from executing given source at applevel.
+            EXPERIMENTAL. The source must look like
+               '''(x, y):
+                       do_stuff...
+                       return result
+               '''
+        """
+        w_func = self.loadfromcache(source, buildappexecfunc, self._codecache)
+        args = Arguments(self, posargs_w)
+        return self.call_args(w_func, args)
 
-pypycodecache = Cache() 
-def buildpypycode((space, source), posargs): 
+def buildappexecfunc(source, space):
     """ NOT_RPYTHON """ 
     # XXX will change once we have our own compiler 
     from pypy.interpreter.pycode import PyCode
     from pypy.tool.pytestsupport import py  # aehem
-    argdecl, source = source.split(':', 1)
-    argdecl = argdecl.strip()
-    if not argdecl.startswith('(') or not argdecl.endswith(')'): 
-        raise SyntaxError("incorrect exec_with header\n%s" % source)
-    source = py.code.Source(source) 
-    source = source.putaround("def anon%s:" % argdecl)
-    d = {}
-    exec source.compile() in d
-    newco = d['anon'].func_code 
-    return PyCode(space)._from_code(newco) 
+    source = source.lstrip()
+    assert source.startswith('('), "incorrect header in:\n%s" % (source,)
+    source = py.code.Source("def anonymous%s\n" % source)
+    w_glob = space.newdict([])
+    space.exec_(source.compile(), w_glob, w_glob)
+    return space.getitem(w_glob, space.wrap('anonymous'))
 
 ## Table describing the regular part of the interface of object spaces,
 ## namely all methods which only take w_ arguments and return a w_ result

Modified: pypy/dist/pypy/interpreter/executioncontext.py
==============================================================================
--- pypy/dist/pypy/interpreter/executioncontext.py	(original)
+++ pypy/dist/pypy/interpreter/executioncontext.py	Sat Feb 19 15:30:45 2005
@@ -12,7 +12,7 @@
         self.stateDict = {}
         
     def enter(self, frame):
-        if self.framestack.depth() > self.space.recursion_limit:
+        if self.framestack.depth() > self.space.sys.recursionlimit:
             raise OperationError(self.space.w_RuntimeError,
                                  self.space.wrap("maximum recursion depth exceeded"))
         locals = getthreadlocals()
@@ -26,16 +26,16 @@
         locals = getthreadlocals()
         locals.executioncontext = previous_ec
 
-    def get_w_builtins(self):
-        if self.framestack.empty():
-            return self.space.w_builtins
-        else:
-            return self.framestack.top().w_builtins
+    def get_builtin(self):
+        try:
+            return self.framestack.top().builtin
+        except IndexError:
+            return self.space.builtin
 
     def make_standard_w_globals(self):
         "Create a new empty 'globals' dictionary."
         w_key = self.space.wrap("__builtins__")
-        w_value = self.get_w_builtins()
+        w_value = self.space.wrap(self.get_builtin())
         w_globals = self.space.newdict([(w_key, w_value)])
         return w_globals
 

Deleted: /pypy/dist/pypy/interpreter/extmodule.py
==============================================================================
--- /pypy/dist/pypy/interpreter/extmodule.py	Sat Feb 19 15:30:45 2005
+++ (empty file)
@@ -1,180 +0,0 @@
-"""
-
-Helpers to build extension modules.
-
-"""
-
-from __future__ import generators   # for generators.compiler_flag
-import os, sys
-import autopath
-from pypy.interpreter import gateway
-from pypy.interpreter.error import OperationError
-from pypy.interpreter.pycode import PyCode
-from pypy.interpreter.function import Function
-from pypy.interpreter.module import Module
-
-class interplevelimport_interp2app(gateway.interp2app):
-
-    def __init__(self, f, w_globals):
-        "NOT_RPYTHON"
-        gateway.interp2app.__init__(self, f, ismethod=False, spacearg=False)
-        self.w_globals = w_globals
-
-    def getglobals(self, space):
-        "NOT_RPYTHON"
-        return self.w_globals
-
-
-class BuiltinModule(Module):
-    """A Module subclass specifically for built-in modules."""
-
-    # '__builtins__' is stored in self.__dict__ by
-    # self.interplevel{exec,eval,execfile}()
-    NOT_RPYTHON_ATTRIBUTES = ['__builtins__']
-
-    def __init__(self, space, modulename, w_dict=None, sourcefile=None):
-        """NOT_RPYTHON
-        Load the named built-in module, by default from the source file
-        'pypy/module/<name>module.py', which is app-level Python code
-        with a few special features that allow it to include interp-level
-        bits.  (See pypy/module/test/foomodule.py)
-
-        The module has two parts: the interp-level objects, stored as
-        attributes of 'self', and the app-level objects, stored in the
-        dictionary 'self.w_dict'.  The app-level definition of the module
-        runs with 'self.w_dict' as globals.  The interp-level bits are
-        executed with 'self.__dict__' as globals, i.e. they can read and
-        change the attributes of 'self' as global variables.
-        """
-        Module.__init__(self, space, space.wrap(modulename), w_dict)
-        w_dict = self.w_dict
-
-        # Compile the xxxmodule.py source file
-        self.__name__ = 'interpreter-level %s' % modulename
-        self.__file__ = sourcefile or os.path.join(autopath.pypydir, 'module',
-                                                   modulename+'module.py')
-        space.setitem(w_dict, space.wrap('__file__'),
-                              space.wrap(self.__file__))
-        f = open(self.__file__, 'r')
-        modulesource = f.read()
-        f.close()
-        code = compile(modulesource, self.__file__, 'exec',
-                       generators.compiler_flag)
-        pycode = PyCode(space)._from_code(code)
-
-        # Set the hooks that call back from app-level to interp-level
-        w_builtins = space.w_builtins
-        self.__saved_hooks = {}
-        newhooks = {}
-        
-        for name, impl in [
-            ('__interplevel__exec',     self.interplevelexec.im_func),
-            ('__interplevel__eval',     self.interpleveleval.im_func),
-            ('__interplevel__execfile', self.interplevelexecfile.im_func),
-            ('__import__',              self.interplevelimport.im_func)]:
-            hook = gateway.interp2app_temp(impl).get_method(self)
-            w_name = space.wrap(name)
-            try:
-                self.__saved_hooks[name] = space.getitem(w_builtins, w_name)
-            except OperationError:
-                pass
-            w_hook = space.wrap(hook)
-            space.setitem(w_builtins, w_name, w_hook)
-            newhooks[name] = w_hook
-        space.setitem(self.w_dict, space.wrap('__builtins__'),
-                      space.w_builtins)
-
-        # Temporarily install an '__applevel__' pseudo-module
-        sys.modules['__applevel__'] = AppModuleHack(self)
-
-        # Run the app-level module definition (xxxmodule.py)
-        pycode.exec_code(space, w_dict, w_dict)
-
-        # Remove the pseudo-module
-        del sys.modules['__applevel__']
-        try:
-            del self.__applevel__
-        except AttributeError:
-            pass
-
-        # Remove/restore the hooks unless they have been modified at app-level
-        for name, w_hook in newhooks.items():
-            w_name = space.wrap(name)
-            try:
-                w_current = space.getitem(w_builtins, w_name)
-            except OperationError:
-                pass
-            else:
-                if space.is_true(space.is_(w_current, w_hook)):
-                    if name in self.__saved_hooks:
-                        space.setitem(w_builtins, w_name,
-                                      self.__saved_hooks[name])
-                    else:
-                        space.delitem(w_builtins, w_name)
-        del self.__saved_hooks
-
-    def interplevelexec(self, w_codestring):
-        "NOT_RPYTHON: 'exec' a string at interp-level."
-        codestring = self.space.str_w(w_codestring)
-        exec codestring in self.__dict__
-        return self.space.w_None
-
-    def interpleveleval(self, w_codestring):
-        """NOT_RPYTHON: 'eval' a string at interp-level.  The result must
-        be None or a wrapped object, which is returned to the caller."""
-        space = self.space
-        codestring = space.str_w(w_codestring)
-        w_result = eval(codestring, self.__dict__)
-        if w_result is None:
-            w_result = space.w_None   # else assume that it is already wrapped
-        return w_result
-
-    def interplevelexecfile(self, w_filename):
-        """NOT_RPYTON: 'exec' a file at interp-level.  The file should be in
-        the same directory as the xxxmodule.py source file of the module."""
-        filename = self.space.str_w(w_filename)
-        filename = os.path.join(os.path.dirname(self.__file__), filename)
-        execfile(filename, self.__dict__)
-        return self.space.w_None
-
-    def interplevelimport(self, w_modulename, w_globals, w_locals, w_fromlist):
-        """NOT_RPYTHON: Hook for 'from __interplevel__ import something'.
-        If there is a wrapped interp-level object 'w_something', returns it.
-        If there is an interp-level function 'def something(w_x, w_y...)',
-        build an appropriate gateway and returns it.
-        """
-        space = self.space
-        w = space.wrap
-        if space.is_true(space.eq(w_modulename, w('__interplevel__'))):
-            if w_fromlist == space.w_None:
-                raise ImportError, "must use 'from __interplevel__ import xx'"
-            for w_name in space.unpacktuple(w_fromlist):
-                name = space.str_w(w_name)
-                if not hasattr(self, 'w_' + name):
-                    f = getattr(self, name)
-                    func = interplevelimport_interp2app(f, self.w_dict)
-                    w_result = space.wrap(func)
-                else:
-                    w_result = getattr(self, 'w_' + name)
-                space.setitem(self.w_dict, w_name, w_result)
-            return space.wrap(self)
-        else:
-            return space.call_function(self.__saved_hooks['__import__'],
-                                       w_modulename, w_globals,
-                                       w_locals, w_fromlist)
-
-class AppModuleHack:
-    """NOT_RPYTHON
-    For interp-level convenience: 'from __applevel__ import func'
-    imports the app-level function 'func' via an appropriate gateway.
-    """
-    def __init__(self, builtinmodule):
-        self.space = builtinmodule.space
-        self.w_dict = builtinmodule.w_dict
-    def __getattr__(self, name):
-        if name.startswith('__'):
-            raise AttributeError, name
-        w_func = self.space.getitem(self.w_dict, self.space.wrap(name))
-        def caller(*args):
-            return self.space.call_function(w_func, *args)
-        return caller

Modified: pypy/dist/pypy/interpreter/gateway.py
==============================================================================
--- pypy/dist/pypy/interpreter/gateway.py	(original)
+++ pypy/dist/pypy/interpreter/gateway.py	Sat Feb 19 15:30:45 2005
@@ -2,7 +2,6 @@
 
 Gateway between app-level and interpreter-level:
 * BuiltinCode (call interp-level code from app-level)
-* Gateway     (a space-independent gateway to a Code object)
 * app2interp  (embed an app-level function into an interp-level callable)
 * interp2app  (publish an interp-level object to be visible from app-level)
 * exportall   (mass-call interp2app on a whole dict of objects)
@@ -16,9 +15,11 @@
 from pypy.interpreter.error import OperationError 
 from pypy.interpreter import eval
 from pypy.interpreter.function import Function, Method
-from pypy.interpreter.baseobjspace import W_Root,ObjSpace,Wrappable
+from pypy.interpreter.baseobjspace import W_Root,ObjSpace, BaseWrappable, Wrappable
 from pypy.interpreter.argument import Arguments
 from pypy.tool.cache import Cache 
+# internal non-translatable parts: 
+from pypy.tool.getpy import py  # XXX from interpreter/ we get py.py 
 
 NoneNotWrapped = object()
 
@@ -35,16 +36,9 @@
         self.argnames = argnames
         self.varargname = varargname
         self.kwargname = kwargname
-        self.rewind()
 
-    def rewind(self):
-        self._iter = iter(self.argnames)
-        
-    def __iter__(self):
-        return self
-
-    def next(self):
-        return self._iter.next()
+    def next_arg(self):
+        return self._argiter.next()
 
     def append(self, argname):
         self.argnames.append(argname)
@@ -52,11 +46,188 @@
     def signature(self):
         return self.argnames, self.varargname, self.kwargname
 
-def apply_unwrap_spec(unwrap_spec, orig_sig, new_sig, recipes):
-    for el in unwrap_spec:
-        recipes[el](orig_sig, new_sig)
-    return new_sig
+    def apply_unwrap_spec(self, unwrap_spec, recipe, new_sig):
+        self._argiter = iter(self.argnames)
+        for el in unwrap_spec:
+            recipe(el, self, new_sig)
+        return new_sig
+
+
+class UnwrapSpecRecipe:
+
+    bases_order = [BaseWrappable, W_Root, ObjSpace, Arguments, object]
+
+    def dispatch(self, meth_family, el, orig_sig, new_sig):
+        if isinstance(el,str):
+            getattr(self, "%s_%s" % (meth_family, el))(el, orig_sig, new_sig)
+        else:
+            for typ in self.bases_order:
+                if issubclass(el, typ):
+                    getattr(self, "%s__%s" % (meth_family, typ.__name__))(el, orig_sig, new_sig)
+                    break
+            else:
+                assert False, "no match for unwrap_spec element: %s" % el
+
+    def check(self, el, orig_sig, new_sig):
+        self.dispatch("check", el, orig_sig, new_sig)
+
+    def emit(self, el, orig_sig, new_sig):
+        self.dispatch("emit", el, orig_sig, new_sig)
+
+
+    # checks for checking interp2app func argument names wrt unwrap_spec
+    # and synthetizing an app-level signature
+
+    def check__BaseWrappable(self, el, orig_sig, app_sig):
+        name = el.__name__
+        argname = orig_sig.next_arg()
+        assert not argname.startswith('w_'), (
+            "unwrapped %s argument %s of built-in function %r should "
+            "not start with 'w_'" % (name, argname, orig_sig.func))
+        app_sig.append(argname)
+        
+    def check__ObjSpace(self, el, orig_sig, app_sig):
+        orig_sig.next_arg()
+
+    def check__W_Root(self, el, orig_sig, app_sig):
+        assert el is W_Root, "oops"
+        argname = orig_sig.next_arg()
+        assert argname.startswith('w_'), (
+            "argument %s of built-in function %r should "
+            "start with 'w_'" % (argname, orig_sig.func))
+        app_sig.append(argname[2:])
+
+    def check__Arguments(self, el, orig_sig, app_sig):
+        argname = orig_sig.next_arg()
+        assert app_sig.varargname is None,(
+            "built-in function %r has conflicting rest args specs" % orig_sig.func)
+        app_sig.varargname = 'args'
+        app_sig.kwargname = 'keywords'
+
+    def check_starargs(self, el, orig_sig, app_sig):
+        varargname = orig_sig.varargname
+        assert varargname.endswith('_w'), (
+            "argument *%s of built-in function %r should end in '_w'" %
+            (varargname, orig_sig.func))
+        assert app_sig.varargname is None,(
+            "built-in function %r has conflicting rest args specs" % orig_sig.func)
+        app_sig.varargname = varargname[:-2]
+
+    def check_args_w(self, el, orig_sig, app_sig):
+        argname = orig_sig.next_arg()
+        assert argname.endswith('_w'), (
+            "rest arguments arg %s of built-in function %r should end in '_w'" %
+            (argname, orig_sig.func))
+        assert app_sig.varargname is None,(
+            "built-in function %r has conflicting rest args specs" % orig_sig.func)
+        app_sig.varargname = argname[:-2]    
+
+    def check_w_args(self, el, orig_sig, app_sig):
+        argname = orig_sig.next_arg()
+        assert argname.startswith('w_'), (
+            "rest arguments arg %s of built-in function %r should start 'w_'" %
+            (argname, orig_sig.func))
+        assert app_sig.varargname is None,(
+            "built-in function %r has conflicting rest args specs" % orig_sig.func)
+        app_sig.varargname = argname[2:]
+
+    def check__object(self, el, orig_sig, app_sig):
+        if el not in (int, str, float):
+            assert False, "unsupported basic type in uwnrap_spec"
+        name = el.__name__
+        argname = orig_sig.next_arg()
+        assert not argname.startswith('w_'), (
+            "unwrapped %s argument %s of built-in function %r should "
+            "not start with 'w_'" % (name, argname, orig_sig.func))
+        app_sig.append(argname)        
+
+    # collect code to emit for interp2app builtin frames based on unwrap_spec
+
+    def emit__BaseWrappable(self, el, orig_sig, emit_sig):
+        name = el.__name__
+        cur = emit_sig.through_scope_w
+        emit_sig.setfastscope.append(
+            "obj = self.space.interpclass_w(scope_w[%d])" % cur)
+        emit_sig.setfastscope.append(
+            "if obj is None or not isinstance(obj, %s):" % name)
+        emit_sig.setfastscope.append(
+            "    raise OperationError(self.space.w_TypeError,self.space.wrap('expected %%s' %% %s.typedef.name ))" % name) # xxx
+        emit_sig.miniglobals[name] = el
+        emit_sig.miniglobals['OperationError'] = OperationError
+        emit_sig.setfastscope.append(
+            "self.%s_arg%d = obj" % (name,cur))
+        emit_sig.through_scope_w += 1
+        emit_sig.run_args.append("self.%s_arg%d" % (name,cur))
+
+    def emit__ObjSpace(self, el, orig_sig, emit_sig):
+        emit_sig.run_args.append('self.space')
+
+    def emit__W_Root(self, el, orig_sig, emit_sig):
+        cur = emit_sig.through_scope_w
+        emit_sig.setfastscope.append(
+            "self.w_arg%d = scope_w[%d]" % (cur,cur))
+        emit_sig.through_scope_w += 1
+        emit_sig.run_args.append("self.w_arg%d" % cur)
+
+    def emit__Arguments(self, el, orig_sig, emit_sig):
+        cur = emit_sig.through_scope_w
+        emit_sig.through_scope_w += 2
+        emit_sig.miniglobals['Arguments'] = Arguments
+        emit_sig.setfastscope.append(
+            "self.arguments_arg = "
+            "Arguments.frompacked(self.space,scope_w[%d],scope_w[%d])"
+                % (cur, cur+1))
+        emit_sig.run_args.append("self.arguments_arg")
+
+    def emit_starargs(self, el, orig_sig, emit_sig):
+        emit_sig.setfastscope.append(
+            "self.starargs_arg_w = self.space.unpacktuple(scope_w[%d])" %
+                (emit_sig.through_scope_w))
+        emit_sig.through_scope_w += 1
+        emit_sig.run_args.append("*self.starargs_arg_w")
+
+    def emit_args_w(self, el, orig_sig, emit_sig):
+        emit_sig.setfastscope.append(
+            "self.args_w = self.space.unpacktuple(scope_w[%d])" %
+                 (emit_sig.through_scope_w))
+        emit_sig.through_scope_w += 1
+        emit_sig.run_args.append("self.args_w")
+
+    def emit_w_args(self, el, orig_sig, emit_sig):
+        cur = emit_sig.through_scope_w
+        emit_sig.setfastscope.append(
+            "self.w_args = scope_w[%d]" % cur)
+        emit_sig.through_scope_w += 1
+        emit_sig.run_args.append("self.w_args")
+
+    def emit__object(self, el, orig_sig, emit_sig):
+        if el not in (int, str, float):
+            assert False, "unsupported basic type in uwnrap_spec"
+        name = el.__name__
+        cur = emit_sig.through_scope_w
+        emit_sig.setfastscope.append(
+            "self.%s_arg%d = self.space.%s_w(scope_w[%d])" %
+                (name,cur,name,cur))
+        emit_sig.through_scope_w += 1
+        emit_sig.run_args.append("self.%s_arg%d" % (name,cur))
+
+class BuiltinFrame(eval.Frame):
+    "Frame emulation for BuiltinCode."
+    # Subclasses of this are defined with the function to delegate to attached through miniglobals.
+    # Initialization of locals is already done by the time run() is called,
+    # via the interface defined in eval.Frame.
+
+    def setfastscope(self, scope_w):
+        """Subclasses with behavior specific for an unwrap spec are generated"""
+        raise TypeError, "abstract"
+
+    def getfastscope(self):
+        raise OperationError(self.space.w_TypeError,
+            self.space.wrap("cannot get fastscope of a BuiltinFrame"))
 
+    def run(self):
+        """Subclasses with behavior specific for an unwrap spec are generated"""
+        raise TypeError, "abstract"
 
 class BuiltinCodeSignature(Signature):
 
@@ -65,8 +236,9 @@
         self.setfastscope = []
         self.run_args = []
         self.through_scope_w = 0
+        self.miniglobals = {}
 
-    def make_frame_class(self):
+    def make_frame_class(self, func):
         setfastscope = self.setfastscope
         if not setfastscope:
             setfastscope = ["pass"]
@@ -78,183 +250,37 @@
         # Python 2.2 SyntaxError without newline: Bug #501622
         setfastscope += '\n'
         d = {}
-        exec setfastscope in globals(),d
-        exec """
-def run(self):
-    try: 
-        w_result = self.code.func(%s)
-    except KeyboardInterrupt: 
-        raise OperationError(self.space.w_KeyboardInterrupt, self.space.w_None) 
-    except MemoryError: 
-        raise OperationError(self.space.w_MemoryError, self.space.w_None) 
-    except RuntimeError, e: 
-        raise OperationError(self.space.w_RuntimeError, 
-                             self.space.wrap("internal error" + str(e))) 
-    if w_result is None:
-        w_result = self.space.w_None
-    return w_result
-""" % ','.join(self.run_args) in globals(),d
+        exec compile(setfastscope, '', 'exec') in self.miniglobals, d
+
+        self.miniglobals['func'] = func
+        source = """if 1: 
+            def run(self):
+                try:
+                    w_result = func(%s)
+                except KeyboardInterrupt: 
+                    raise OperationError(self.space.w_KeyboardInterrupt, self.space.w_None) 
+                except MemoryError: 
+                    raise OperationError(self.space.w_MemoryError, self.space.w_None) 
+                except RuntimeError, e: 
+                    raise OperationError(self.space.w_RuntimeError, 
+                                         self.space.wrap("internal error" + str(e))) 
+                if w_result is None:
+                    w_result = self.space.w_None
+                return w_result
+            \n""" % ','.join(self.run_args) 
+        exec compile(source, '', 'exec') in self.miniglobals, d
         return type("BuiltinFrame_for_%s" % self.name,
                     (BuiltinFrame,),d)
         
-    
-def unwrap_spec_check_space(orig_sig, new_sig):
-    orig_sig.next()
-    
-def unwrap_spec_check_self(orig_sig, new_sig):
-    argname = orig_sig.next()
-    new_sig.append(argname)
-        
-        
-def unwrap_spec_check_wrapped(orig_sig, new_sig):
-    argname = orig_sig.next()
-    assert argname.startswith('w_'), (
-        "argument %s of built-in function %r should "
-        "start with 'w_'" % (argname, orig_sig.func))
-    new_sig.append(argname[2:])
-
-def unwrap_spec_check_arguments(orig_sig, new_sig):
-    argname = orig_sig.next()
-    assert new_sig.varargname is None,(
-        "built-in function %r has conflicting rest args specs" % orig_sig.func)
-    new_sig.varargname = 'args'
-    new_sig.kwargname = 'keywords'
-        
-def unwrap_spec_check_starargs(orig_sig, new_sig):
-    varargname = orig_sig.varargname
-    assert varargname.endswith('_w'), (
-        "argument *%s of built-in function %r should end in '_w'" %
-        (varargname, orig_sig.func))
-    assert new_sig.varargname is None,(
-        "built-in function %r has conflicting rest args specs" % orig_sig.func)
-    new_sig.varargname = varargname[:-2]
-
-def unwrap_spec_check_args_w(orig_sig, new_sig):
-    argname = orig_sig.next()
-    assert argname.endswith('_w'), (
-        "rest arguments arg %s of built-in function %r should end in '_w'" %
-        (argname, orig_sig.func))
-    assert new_sig.varargname is None,(
-        "built-in function %r has conflicting rest args specs" % orig_sig.func)
-    new_sig.varargname = argname[:-2]
-
-def unwrap_spec_check_w_args(orig_sig, new_sig):
-    argname = orig_sig.next()
-    assert argname.startswith('w_'), (
-        "rest arguments arg %s of built-in function %r should start 'w_'" %
-        (argname, orig_sig.func))
-    assert new_sig.varargname is None,(
-        "built-in function %r has conflicting rest args specs" % orig_sig.func)
-    new_sig.varargname = argname[2:]
-      
-# recipes for checking interp2app func argumes wrt unwrap_spec
-unwrap_spec_checks = {
-    ObjSpace: unwrap_spec_check_space,
-    'self': unwrap_spec_check_self,
-    W_Root: unwrap_spec_check_wrapped,
-    Arguments: unwrap_spec_check_arguments,
-    '*': unwrap_spec_check_starargs,
-    'args_w': unwrap_spec_check_args_w,
-    'w_args': unwrap_spec_check_w_args,    
-}
-
-def unwrap_spec_emit_space(orig_sig, new_sig):
-    new_sig.run_args.append('self.space')
-    
-def unwrap_spec_emit_self(orig_sig, new_sig):
-    new_sig.setfastscope.append(
-        "self.self_arg = self.space.interpclass_w(scope_w[%d])" %
-            (new_sig.through_scope_w))
-    new_sig.through_scope_w += 1
-    new_sig.run_args.append("self.self_arg")
-        
-def unwrap_spec_emit_wrapped(orig_sig, new_sig):
-    cur = new_sig.through_scope_w
-    new_sig.setfastscope.append(
-        "self.w_arg%d = scope_w[%d]" % (cur,cur))
-    new_sig.through_scope_w += 1
-    new_sig.run_args.append("self.w_arg%d" % cur)
-
-
-def unwrap_spec_emit_arguments(orig_sig, new_sig):
-    cur = new_sig.through_scope_w
-    new_sig.through_scope_w += 2
-    new_sig.setfastscope.append(
-        "self.arguments_arg = "
-        "Arguments.frompacked(self.space,scope_w[%d],scope_w[%d])"
-            % (cur, cur+1))
-    new_sig.run_args.append("self.arguments_arg")
-        
-def unwrap_spec_emit_starargs(orig_sig, new_sig):
-    new_sig.setfastscope.append(
-        "self.starargs_arg_w = self.space.unpacktuple(scope_w[%d])" %
-            (new_sig.through_scope_w))
-    new_sig.through_scope_w += 1
-    new_sig.run_args.append("*self.starargs_arg_w")
-
-def unwrap_spec_emit_args_w(orig_sig, new_sig):
-    new_sig.setfastscope.append(
-        "self.args_w = self.space.unpacktuple(scope_w[%d])" %
-             (new_sig.through_scope_w))
-    new_sig.through_scope_w += 1
-    new_sig.run_args.append("self.args_w")
-
-def unwrap_spec_emit_w_args(orig_sig, new_sig):
-    cur = new_sig.through_scope_w
-    new_sig.setfastscope.append(
-        "self.w_args = scope_w[%d]" % cur)
-    new_sig.through_scope_w += 1
-    new_sig.run_args.append("self.w_args")
-        
-# recipes for emitting unwrapping code for arguments of a interp2app func
-# wrt a unwrap_spec
-unwrap_spec_emit = {
-    ObjSpace: unwrap_spec_emit_space,
-    'self': unwrap_spec_emit_self,
-    W_Root: unwrap_spec_emit_wrapped,
-    Arguments: unwrap_spec_emit_arguments,
-    '*': unwrap_spec_emit_starargs,
-    'args_w': unwrap_spec_emit_args_w,
-    'w_args': unwrap_spec_emit_w_args,
-}
-
-# unwrap_spec_check/emit for str,int,float
-for basic_type in [str,int,float]:
-    name = basic_type.__name__
-    def unwrap_spec_check_basic(orig_sig, new_sig, name=name):
-        argname = orig_sig.next()
-        assert not argname.startswith('w_'), (
-            "unwrapped %s argument %s of built-in function %r should "
-            "not start with 'w_'" % (name, argname, orig_sig.func))
-        new_sig.append(argname)
-    def unwrap_spec_emit_basic(orig_sig, new_sig, name=name):
-        cur = new_sig.through_scope_w
-        new_sig.setfastscope.append(
-            "self.%s_arg%d = self.space.%s_w(scope_w[%d])" %
-                (name,cur,name,cur))
-        new_sig.through_scope_w += 1
-        new_sig.run_args.append("self.%s_arg%d" % (name,cur))
-    unwrap_spec_checks[basic_type] = hack.func_with_new_name(
-        unwrap_spec_check_basic, "unwrap_spec_check_%s" % name)
-    unwrap_spec_emit[basic_type] = hack.func_with_new_name(
-        unwrap_spec_emit_basic, "unwrap_spec_emit_%s" % name)    
-    
-
-
-def make_builtin_frame_class_for_unwrap_spec(unwrap_spec, cache={}):
+def make_builtin_frame_class(func, orig_sig, unwrap_spec):
     "NOT_RPYTHON"
-    key = tuple(unwrap_spec)
-    try:
-        return cache[key]
-    except KeyError:
-        name = '_'.join([getattr(k, "__name__", k) for k in key])
-        emit_sig = apply_unwrap_spec(unwrap_spec, None,
-                                     BuiltinCodeSignature(name=name),
-                                     unwrap_spec_emit)
+    name = (getattr(func, '__module__', None) or '')+'_'+func.__name__
+    emit_sig = orig_sig.apply_unwrap_spec(unwrap_spec, UnwrapSpecRecipe().emit,
+                                              BuiltinCodeSignature(name=name))
+    cls = emit_sig.make_frame_class(func)
+    return cls
+
 
-        cache[key] = cls = emit_sig.make_frame_class()
-        return cls
-    
 
 class BuiltinCode(eval.Code):
     "The code object implementing a built-in (interpreter-level) hook."
@@ -262,28 +288,19 @@
     # When a BuiltinCode is stored in a Function object,
     # you get the functionality of CPython's built-in function type.
 
-    def __init__(self, func, ismethod=None, spacearg=None, unwrap_spec = None):
+    def __init__(self, func, ismethod=None, spacearg=None, unwrap_spec = None, self_type = None):
         "NOT_RPYTHON"
         # 'implfunc' is the interpreter-level function.
         # Note that this uses a lot of (construction-time) introspection.
         eval.Code.__init__(self, func.__name__)
-        self.func = func
         self.docstring = func.__doc__
-        # signature-based hacks if unwrap_spec is not specified:
-        # renaming arguments from w_xyz to xyz.
-        # Currently we enforce the following signature tricks:
-        #  * the first arg must be either 'self' or 'space'
-        #  * 'w_' prefixes for the rest
-        #  * '_w' suffix for the optional '*' argument
-        #  * alternatively a final '__args__' means an Arguments()
-        # Not exactly a clean approach XXX.
-        # --
+
         # unwrap_spec can be passed to interp2app or
         # attached as an attribute to the function.
         # It is a list of types or singleton objects:
         #  baseobjspace.ObjSpace is used to specify the space argument
-        #  'self' is used to specify a self method argument
         #  baseobjspace.W_Root is for wrapped arguments to keep wrapped
+        #  baseobjspace.BaseWrappable subclasses imply interpclass_w and a typecheck
         #  argument.Arguments is for a final rest arguments Arguments object
         # 'args_w' for unpacktuple applied to rest arguments
         # 'w_args' for rest arguments passed as wrapped tuple
@@ -293,57 +310,33 @@
         from pypy.interpreter import pycode
         argnames, varargname, kwargname = pycode.cpython_code_signature(func.func_code)
 
+        assert not ismethod, ("ismethod is not expected anymore")
+        assert not spacearg, ("spacearg is not expected anymore")
+
         if unwrap_spec is None:
             unwrap_spec = getattr(func,'unwrap_spec',None)
-        
-        if unwrap_spec is None:
 
-            unwrap_spec = []
+        if unwrap_spec is None and argnames == ['space', '__args__']: #xxx for geninterp
+            #print sys._getframe(2).f_globals['__name__']
+            unwrap_spec = [ObjSpace, Arguments]
 
-            argnames = list(argnames)
-            lookslikemethod = argnames[:1] == ['self']
-            if ismethod is None:
-                ismethod = lookslikemethod
-            if spacearg is None:
-                spacearg = not lookslikemethod
-            self.ismethod = ismethod
-            self.spacearg = spacearg
-            assert kwargname is None, (
-                "built-in function %r should not take a ** argument" % func)
-
-            n = len(argnames)
-
-            if self.ismethod:
-                unwrap_spec.append('self')
-                n -= 1
-            if self.spacearg:
-                unwrap_spec.append(ObjSpace)
-                n -= 1
-
-            self.generalargs = argnames[-1:] == ['__args__']
-            self.starargs = varargname is not None
-
-            if self.generalargs:
-                unwrap_spec.extend([W_Root] * (n-1))
-                unwrap_spec.append(Arguments)
-            else:
-                unwrap_spec.extend([W_Root] * n)
+        if unwrap_spec is None:
+            unwrap_spec = [ObjSpace]+ [W_Root] * (len(argnames)-1)
 
-            if self.starargs:
-                unwrap_spec.append('*')
-        else:
-            assert not ismethod, ("if unwrap_spec is specified, "
-                                  "ismethod is not expected")
-            assert not spacearg, ("if unwrap_spec is specified, " 
-                                  "spacearg is not expected")
+            if self_type:
+                unwrap_spec = ['self'] + unwrap_spec[1:]
+            
+        if self_type:
+            assert unwrap_spec[0] == 'self',"self_type without 'self' spec element"
+            unwrap_spec = list(unwrap_spec)
+            unwrap_spec[0] = self_type
 
         orig_sig = Signature(func, argnames, varargname, kwargname)
 
-        new_sig = apply_unwrap_spec(unwrap_spec, orig_sig,
-                                    Signature(func),
-                                    unwrap_spec_checks)
+        app_sig = orig_sig.apply_unwrap_spec(unwrap_spec, UnwrapSpecRecipe().check,
+                                             Signature(func))
 
-        self.sig = argnames, varargname, kwargname = new_sig.signature()
+        self.sig = argnames, varargname, kwargname = app_sig.signature()
 
         self.minargs = len(argnames)
         if varargname:
@@ -351,7 +344,7 @@
         else:
             self.maxargs = self.minargs
 
-        self.framecls = make_builtin_frame_class_for_unwrap_spec(unwrap_spec)
+        self.framecls = make_builtin_frame_class(func, orig_sig, unwrap_spec)
 
     def create_frame(self, space, w_globals, closure=None):
         return self.framecls(space, self, w_globals)
@@ -363,183 +356,29 @@
         return self.docstring
 
 
-class BuiltinFrame(eval.Frame):
-    "Frame emulation for BuiltinCode."
-    # This is essentially just a delegation to the 'func' of the BuiltinCode.
-    # Initialization of locals is already done by the time run() is called,
-    # via the interface defined in eval.Frame.
-
-    def setfastscope(self, scope_w):
-        """Subclasses with behavior specific for an unwrap spec are generated"""
-        raise TypeError, "abstract"
+class interp2app(Wrappable):
+    """Build a gateway that calls 'f' at interp-level."""
 
-    def getfastscope(self):
-        raise OperationError(self.space.w_TypeError,
-            self.space.wrap("cannot get fastscope of a BuiltinFrame"))
-
-    def run(self):
-        """Subclasses with behavior specific for an unwrap spec are generated"""
-        raise TypeError, "abstract"        
-
-
-class Gateway(Wrappable):
-    """General-purpose utility for the interpreter-level to create callables
-    that transparently invoke code objects (and thus possibly interpreted
-    app-level code)."""
-
-    # This is similar to a Function object, but not bound to a particular
-    # object space. During the call, the object space is either given
-    # explicitly as the first argument (for plain function), or is read
-    # from 'self.space' for methods.
-
-        # after initialization the following attributes should be set
-        #   name
-        #   _staticglobals 
-        #   _staticdefs
-        #
-        #  getcode is called lazily to get the code object to construct
-        #  the space-bound function
-
-    NOT_RPYTHON_ATTRIBUTES = ['_staticglobals', '_staticdefs']
-
-    def getcode(self, space):
-        # needs to be implemented by subclasses
-        raise TypeError, "abstract"
-        
-    def __spacebind__(self, space):
-        # to wrap a Gateway, we first make a real Function object out of it
-        # and the result is a wrapped version of this Function.
-        return self.get_function(space)
-
-    def get_function(self, space):
-        return space.loadfromcache(self, 
-                                   Gateway.build_all_functions, 
-                                   self.getcache(space))
-
-    def getglobals(self, space):
-        "NOT_RPYTHON"
-        if self._staticglobals is None:
-            w_globals = None
-        else:
-            # is there another Gateway in _staticglobals for which we
-            # already have a w_globals for this space ?
-            cache = self.getcache(space) 
-            for value in self._staticglobals.itervalues():
-                if isinstance(value, Gateway):
-                    if value in cache.content: 
-                        # yes, we share its w_globals
-                        fn = cache.content[value] 
-                        w_globals = fn.w_func_globals
-                        break
-            else:
-                # no, we build all Gateways in the _staticglobals now.
-                w_globals = build_dict(self._staticglobals, space)
-            return w_globals
-                
-    def build_all_functions(self, space):
-        "NOT_RPYTHON"
-        # the construction is supposed to be done only once in advance,
-        # but must be done lazily when needed only, because
-        #   1) it depends on the object space
-        #   2) the w_globals must not be built before the underlying
-        #      _staticglobals is completely initialized, because
-        #      w_globals must be built only once for all the Gateway
-        #      instances of _staticglobals
-        return self._build_function(space, self.getglobals(space))
-
-    def getcache(self, space):
-        return space._gatewaycache 
-
-    def _build_function(self, space, w_globals):
-        "NOT_RPYTHON"
-        cache = self.getcache(space) 
-        try: 
-            return cache.content[self] 
-        except KeyError: 
-            defs = self.getdefaults(space)  # needs to be implemented by subclass
-            code = self.getcode(space)
-            fn = Function(space, code, w_globals, defs, forcename = self.name)
-            cache.content[self] = fn 
-            return fn
-
-    def get_method(self, obj):
-        # to get the Gateway as a method out of an instance, we build a
-        # Function and get it.
-        # the object space is implicitely fetched out of the instance
-        space = obj.space
-        fn = self.get_function(space)
-        w_obj = space.wrap(obj)
-        return Method(space, space.wrap(fn),
-                      w_obj, space.type(w_obj))
-
-
-class app2interp(Gateway):
-    """Build a Gateway that calls 'app' at app-level."""
-
-    NOT_RPYTHON_ATTRIBUTES = ['_staticcode'] + Gateway.NOT_RPYTHON_ATTRIBUTES
-    
-    def __init__(self, app, app_name=None):
-        "NOT_RPYTHON"
-        Gateway.__init__(self)
-        # app must be a function whose name starts with 'app_'.
-        if not isinstance(app, types.FunctionType):
-            raise TypeError, "function expected, got %r instead" % app
-        if app_name is None:
-            if not app.func_name.startswith('app_'):
-                raise ValueError, ("function name must start with 'app_'; "
-                                   "%r does not" % app.func_name)
-            app_name = app.func_name[4:]
-        self.__name__ = app.func_name
-        self.name = app_name
-        self._staticcode = app.func_code
-        self._staticglobals = app.func_globals
-        self._staticdefs = list(app.func_defaults or ())
-
-    def getcode(self, space):
-        "NOT_RPYTHON"
-        from pypy.interpreter import pycode
-        code = pycode.PyCode(space)
-        code._from_code(self._staticcode)
-        return code
-
-    def getdefaults(self, space):
-        "NOT_RPYTHON"
-        return [space.wrap(val) for val in self._staticdefs]
-
-    def __call__(self, space, *args_w):
-        # to call the Gateway as a non-method, 'space' must be explicitly
-        # supplied. We build the Function object and call it.
-        fn = self.get_function(space)
-        return space.call_function(space.wrap(fn), *args_w)
-
-    def __get__(self, obj, cls=None):
-        "NOT_RPYTHON"
-        if obj is None:
-            return self
-        else:
-            space = obj.space
-            w_method = space.wrap(self.get_method(obj))
-            def helper_method_caller(*args_w):
-                return space.call_function(w_method, *args_w)
-            return helper_method_caller
-
-class interp2app(Gateway):
-    """Build a Gateway that calls 'f' at interp-level."""
-
-    # NOTICE even interp2app defaults are stored and passed as
+    # NOTICE interp2app defaults are stored and passed as
     # wrapped values, this to avoid having scope_w be of mixed
-    # wrapped and unwrapped types,
-    # an exception is made for None which is passed around as default
-    # as an unwrapped None, unwrapped None and wrapped types are
-    # compatible
+    # wrapped and unwrapped types;
+    # an exception is made for the NoneNotWrapped special value
+    # which is passed around as default as an unwrapped None,
+    # unwrapped None and wrapped types are compatible
     #
     # Takes optionally an unwrap_spec, see BuiltinCode
+
+    NOT_RPYTHON_ATTRIBUTES = ['_staticdefs']
     
     def __init__(self, f, app_name=None,
                  ismethod=None, spacearg=None, unwrap_spec = None):
         "NOT_RPYTHON"
-        Gateway.__init__(self)
+        Wrappable.__init__(self)
         # f must be a function whose name does NOT starts with 'app_'
+        self_type = None
+        if hasattr(f, 'im_func'):
+            self_type = f.im_class
+            f = f.im_func
         if not isinstance(f, types.FunctionType):
             raise TypeError, "function expected, got %r instead" % f
         if app_name is None:
@@ -549,18 +388,13 @@
             app_name = f.func_name
         self._code = BuiltinCode(f, ismethod=ismethod,
                                   spacearg=spacearg,
-                                  unwrap_spec=unwrap_spec)
+                                  unwrap_spec=unwrap_spec,
+                                  self_type = self_type)
         self.__name__ = f.func_name
         self.name = app_name
         self._staticdefs = list(f.func_defaults or ())
-        #if self._staticdefs:
-        #    print f.__module__,f.__name__,"HAS NON TRIVIAL DEFLS",self._staticdefs
-        self._staticglobals = None
 
-    def getcode(self, space):
-        return self._code
-
-    def getdefaults(self, space):
+    def _getdefaults(self, space):
         "NOT_RPYTHON"
         defs_w = []
         for val in self._staticdefs:
@@ -570,13 +404,48 @@
                 defs_w.append(space.wrap(val))
         return defs_w
 
+    # lazy binding to space
+
+    def __spacebind__(self, space):
+        # we first make a real Function object out of it
+        # and the result is a wrapped version of this Function.
+        return self.get_function(space)
+
+    def get_function(self, space):
+        return space.loadfromcache(self, 
+                                   interp2app.build_function, 
+                                   self.getcache(space))
+
+    def getcache(self, space):
+        return space._gatewaycache 
+
     def get_method(self, obj):
-       assert self._code.ismethod, (
-           'global built-in function %r used as method' %
-           self._code.func)
-       return Gateway.get_method(self, obj)
+        # to bind this as a method out of an instance, we build a
+        # Function and get it.
+        # the object space is implicitely fetched out of the instance
+        assert self._code.ismethod, (
+            'global built-in function %r used as method' %
+            self._code.func)
+
+        space = obj.space
+        fn = self.get_function(space)
+        w_obj = space.wrap(obj)
+        return Method(space, space.wrap(fn),
+                      w_obj, space.type(w_obj))
 
 
+    def build_function(self, space):
+        "NOT_RPYTHON"
+        cache = self.getcache(space) 
+        try: 
+            return cache.content[self] 
+        except KeyError: 
+            defs = self._getdefaults(space)  # needs to be implemented by subclass
+            code = self._code
+            fn = Function(space, code, None, defs, forcename = self.name)
+            cache.content[self] = fn 
+            return fn
+        
 def exportall(d, temporary=False):
     """NOT_RPYTHON: Publish every function from a dict."""
     if temporary:
@@ -618,34 +487,89 @@
     for name, obj in d.items():
         if name.startswith('app_') and name[4:] not in d:
             if isinstance(obj, types.FunctionType):
-                d[name[4:]] = a2i(obj, name[4:])
-
-def build_dict(d, space):
-    """NOT_RPYTHON:
-    Search all Gateways and put them into a wrapped dictionary."""
-    w_globals = space.newdict([])
-    for value in d.itervalues():
-        if isinstance(value, Gateway):
-            fn = value._build_function(space, w_globals)
-            w_name = space.wrap(value.name)
-            w_object = space.wrap(fn)
-            space.setitem(w_globals, w_name, w_object)
-    if hasattr(space, 'w_sys'):  # give them 'sys' if it exists already
-        space.setitem(w_globals, space.wrap('sys'), space.w_sys)
-    return w_globals
-
+                d[name[4:]] = a2i(obj)
 
 # 
 # the next gateways are to be used only for 
 # temporary/initialization purposes 
-class app2interp_temp(app2interp):
-    "NOT_RPYTHON"
-    def getcache(self, space): 
-        return self.__dict__.setdefault(space, Cache())
-        #                               ^^^^^
-        #                          armin suggested this 
      
 class interp2app_temp(interp2app): 
     "NOT_RPYTHON"
     def getcache(self, space): 
         return self.__dict__.setdefault(space, Cache())
+
+
+# and now for something completly different ... 
+#
+
+class applevel:
+    """A container for app-level source code that should be executed
+    as a module in the object space;  interphook() builds a static
+    interp-level function that invokes the callable with the given
+    name at app-level."""
+
+    NOT_RPYTHON_ATTRIBUTES = ['code']
+
+    def __init__(self, source):
+        "NOT_RPYTHON"
+        self.code = py.code.Source(source).compile()
+
+    def getwdict(self, space):
+        return space.loadfromcache(self, applevel._builddict,
+                                   space._gatewaycache)
+
+    def buildmodule(self, space, name='applevel'):
+        from pypy.interpreter.module import Module
+        return Module(space, space.wrap(name), self.getwdict(space))
+
+    def _builddict(self, space):
+        "NOT_RPYTHON"
+        w_glob = space.newdict([])
+        space.exec_(self.code, w_glob, w_glob)
+        return w_glob
+    
+    def wget(self, space, name): 
+        w_globals = self.getwdict(space) 
+        return space.getitem(w_globals, space.wrap(name))
+
+    def interphook(self, name):
+        "NOT_RPYTHON"
+        def appcaller(space, *args_w):
+            args = Arguments(space, args_w)
+            w_func = self.wget(space, name) 
+            return space.call_args(w_func, args)
+        def get_function(space):
+            w_func = self.wget(space, name) 
+            return space.unwrap(w_func)
+        appcaller = hack.func_with_new_name(appcaller, name)
+        appcaller.get_function = get_function
+        return appcaller
+
+def appdef(source, applevel=applevel):
+    """ NOT_RPYTHON: build an app-level helper function, like for example:
+    myfunc = appdef('''myfunc(x, y):
+                           return x+y
+                    ''')
+    """ 
+    from pypy.interpreter.pycode import PyCode
+    if not isinstance(source, str): 
+        source = str(py.code.Source(source).strip())
+        assert source.startswith("def "), "can only transform functions" 
+        source = source[4:]
+    p = source.find('(')
+    assert p >= 0
+    funcname = source[:p].strip()
+    source = source[p:]
+    return applevel("def %s%s\n" % (funcname, source)).interphook(funcname)
+
+app2interp = appdef   # backward compatibility
+
+
+# app2interp_temp is used for testing mainly
+class applevel_temp(applevel):
+    def getwdict(self, space):
+        return self._builddict(space)   # no cache
+
+def app2interp_temp(func):
+    """ NOT_RPYTHON """
+    return appdef(func, applevel_temp)

Modified: pypy/dist/pypy/interpreter/interactive.py
==============================================================================
--- pypy/dist/pypy/interpreter/interactive.py	(original)
+++ pypy/dist/pypy/interpreter/interactive.py	Sat Feb 19 15:30:45 2005
@@ -4,6 +4,7 @@
 from pypy.interpreter import executioncontext, baseobjspace
 import sys
 import code
+import time
 
 
 class PyPyConsole(code.InteractiveConsole):
@@ -22,8 +23,9 @@
             #banner = "Python %s in pypy\n%s / %s" % (
             #    sys.version, self.__class__.__name__,
             #    self.space.__class__.__name__)
-            banner = "PyPy in %s on top of Python %s" % (
-                self.space.__class__.__name__, sys.version.split()[0])
+            elapsed = time.time() - self.space._starttime
+            banner = "PyPy in %s on top of Python %s (startupttime: %.2f secs)" % (
+                self.space.__class__.__name__, sys.version.split()[0], elapsed)
         code.InteractiveConsole.interact(self, banner)
 
     def raw_input(self, prompt=""):

Modified: pypy/dist/pypy/interpreter/main.py
==============================================================================
--- pypy/dist/pypy/interpreter/main.py	(original)
+++ pypy/dist/pypy/interpreter/main.py	Sat Feb 19 15:30:45 2005
@@ -14,15 +14,17 @@
             from pypy.objspace.std import StdObjSpace
             space = StdObjSpace()
 
-        compile = space.builtin.compile
+        w_compile = space.builtin.get('compile') 
         w = space.wrap
-        w_code = compile(w(source), filename, cmd, 0, 0)
-
+        w_code = space.call_function(w_compile, 
+                 w(source), w(filename), w(cmd), w(0), w(0))
         w_main = space.wrap('__main__')
         mainmodule = module.Module(space, w_main)
-        space.setitem(space.sys.w_modules, w_main, mainmodule)
+        w_modules = space.sys.get('modules')
+        space.setitem(w_modules, w_main, mainmodule)
 
         w_globals = mainmodule.w_dict
+        space.setitem(w_globals, w('__builtins__'), space.builtin)
 
         pycode = space.interpclass_w(w_code)
         retval = pycode.exec_code(space, w_globals, w_globals)

Modified: pypy/dist/pypy/interpreter/module.py
==============================================================================
--- pypy/dist/pypy/interpreter/module.py	(original)
+++ pypy/dist/pypy/interpreter/module.py	Sat Feb 19 15:30:45 2005
@@ -10,20 +10,16 @@
 
     def __init__(self, space, w_name, w_dict=None):
         self.space = space
-        if w_dict is None:
+        if w_dict is None: 
             w_dict = space.newdict([])
-        self.w_dict = w_dict
-        self.w_name = w_name
-        space.setitem(w_dict, space.wrap('__name__'), w_name)
-        if not space.is_true(space.contains(w_dict, space.wrap('__doc__'))):
-            space.setitem(w_dict, space.wrap('__doc__'), space.w_None)
+        self.w_dict = w_dict 
+        self.w_name = w_name 
+        if w_name is not None:
+            space.setitem(w_dict, space.wrap('__name__'), w_name) 
 
     def getdict(self):
         return self.w_dict
 
-    def setdict(self, w_dict):
-        self.w_dict = w_dict
-
     def descr_module__new__(space, w_subtype, __args__):
         module = space.allocate_instance(Module, w_subtype)
         module.__init__(space, space.wrap('?'))
@@ -32,37 +28,8 @@
     def descr_module__init__(self, w_name, w_doc=None):
         space = self.space
         self.w_name = w_name
-        space.setitem(self.w_dict, space.wrap('__name__'), w_name)
-        if w_doc is not None:
-            space.setitem(self.w_dict, space.wrap('__doc__'), w_doc)
-
-    def descr_module__getattr__(self, w_attr):
-        space = self.space
-        attr = space.str_w(w_attr)
-        # ______ for the 'sys' module only _____ XXX generalize
-        if self is space.sys:
-            if attr == 'exc_type':
-                operror = space.getexecutioncontext().sys_exc_info()
-                if operror is None:
-                    return space.w_None
-                else:
-                    return operror.w_type
-            if attr == 'exc_value':
-                operror = space.getexecutioncontext().sys_exc_info()
-                if operror is None:
-                    return space.w_None
-                else:
-                    return operror.w_value
-            if attr == 'exc_traceback':
-                operror = space.getexecutioncontext().sys_exc_info()
-                if operror is None:
-                    return space.w_None
-                else:
-                    return space.wrap(operror.application_traceback)
-        # produce a nice error message that shows the name of the module
-        try:
-            name = space.str_w(self.w_name)
-        except OperationError:
-            name = '?'
-        msg = "'%s' module has no attribute '%s'" % (name, attr)
-        raise OperationError(space.w_AttributeError, space.wrap(msg))
+        if w_doc is None:  
+            w_doc = space.w_None
+        w_dict = self.getdict()
+        space.setitem(w_dict, space.wrap('__name__'), w_name)
+        space.setitem(w_dict, space.wrap('__doc__'), w_doc)

Modified: pypy/dist/pypy/interpreter/py.py
==============================================================================
--- pypy/dist/pypy/interpreter/py.py	(original)
+++ pypy/dist/pypy/interpreter/py.py	Sat Feb 19 15:30:45 2005
@@ -5,10 +5,14 @@
 except ImportError:
     pass
 
+from pypy.tool.getpy import py
+#py.magic.invoke(compile=1)
+
 from pypy.tool import option
 from pypy.tool.optik import make_option
 from pypy.interpreter import main, interactive, error
 import os, sys
+import time
 
 class Options(option.Options):
     verbose = os.getenv('PYPY_TB')
@@ -42,11 +46,13 @@
     return options
 
 def main_(argv=None):
+    starttime = time.time() 
     from pypy.tool import tb_server
     args = option.process_options(get_main_options(), Options, argv[1:])
     space = None
     try:
         space = option.objspace()
+        space._starttime = starttime
         assert 'pypy.tool.udir' not in sys.modules, (
             "running py.py should not import pypy.tool.udir, which is\n"
             "only for testing or translating purposes.")
@@ -56,14 +62,14 @@
         if Options.command:
             args = ['-c'] + Options.command[1:]
         for arg in args:
-            space.call_method(space.sys.w_argv, 'append', space.wrap(arg))
+            space.call_method(space.sys.get('argv'), 'append', space.wrap(arg))
         try:
             if Options.command:
                 main.run_string(Options.command[0], '<string>', space)
             elif args:
                 main.run_file(args[0], space)
             else:
-                space.call_method(space.sys.w_argv, 'append', space.wrap(''))
+                space.call_method(space.sys.get('argv'), 'append', space.wrap(''))
                 go_interactive = 1
                 banner = None
         except error.OperationError, operationerr:

Modified: pypy/dist/pypy/interpreter/pycode.py
==============================================================================
--- pypy/dist/pypy/interpreter/pycode.py	(original)
+++ pypy/dist/pypy/interpreter/pycode.py	Sat Feb 19 15:30:45 2005
@@ -6,7 +6,8 @@
 
 import dis
 from pypy.interpreter import eval
-from pypy.interpreter.gateway import NoneNotWrapped
+from pypy.interpreter.gateway import NoneNotWrapped 
+from pypy.interpreter.baseobjspace import ObjSpace, W_Root 
 from pypy.tool.cache import Cache 
 
 # helper
@@ -55,7 +56,7 @@
         self.co_flags = 0            # CO_..., see above
         self.co_code = None          # string: instruction opcodes
         self.co_consts_w = []        # list of constants used (wrapped!)
-        self.co_names_w = []         # list of wrapped strs: names (for attrs..)
+        self.co_names = []           # list of strings: names (for attrs..)
         self.co_varnames = ()        # tuple of strings: local variable names
         self.co_freevars = ()        # tuple of strings: free variable names
         self.co_cellvars = ()        # tuple of strings: cell variable names
@@ -88,7 +89,7 @@
         self.co_code = x
         #self.co_consts = <see below>
         x = code.co_names; assert isinstance(x, tuple)
-        self.co_names_w = [ self.space.wrap(i) for i in x ] 
+        self.co_names = list(x)
         x = code.co_varnames; assert isinstance(x, tuple)
         self.co_varnames = x
         x = code.co_freevars; assert isinstance(x, tuple)
@@ -157,10 +158,10 @@
     
     def fget_co_names(space, w_self):
         self = space.interpclass_w(w_self)
-        return space.newtuple(self.co_names_w)
+        return space.newtuple([space.wrap(name) for name in self.co_names])
 
-    def descr_code__eq__(space, w_self, w_other):
-        self = space.interpclass_w(w_self)
+    def descr_code__eq__(self, w_other):
+        space = self.space
         other = space.interpclass_w(w_other)
         if not isinstance(other, PyCode):
             return space.w_False
@@ -170,7 +171,11 @@
                     self.co_flags == other.co_flags and
                     self.co_firstlineno == other.co_firstlineno and
                     self.co_code == other.co_code and
-                    len(self.co_consts_w) == len(other.co_consts_w))
+                    len(self.co_consts_w) == len(other.co_consts_w) and
+                    self.co_names == other.co_names and
+                    self.co_varnames == other.co_varnames and
+                    self.co_freevars == other.co_freevars and
+                    self.co_cellvars == other.co_cellvars)
         if not areEqual:
             return space.w_False
 
@@ -178,45 +183,40 @@
             if not space.eq_w(self.co_consts_w[i], other.co_consts_w[i]):
                 return space.w_False
 
-        if len(self.co_names_w) != len(other.co_names_w):
-            return space.w_False
-        
-        for i in range(len(self.co_names_w)):
-            if not space.eq_w(self.co_names_w[i], other.co_names_w[i]):
-                return space.w_False
-        if (self.co_varnames == other.co_varnames and
-            self.co_freevars == other.co_freevars and
-            self.co_cellvars == other.co_cellvars):
-            return space.w_True
-
         return space.w_True
-    
+   
+    unwrap_spec =        [ObjSpace, W_Root, 
+                          int, int, int, int,
+                          str, W_Root, W_Root, 
+                          W_Root, str, str, int, 
+                          str, W_Root, 
+                          W_Root]
     def descr_code__new__(space, w_subtype,
-                          w_argcount, w_nlocals, w_stacksize, w_flags,
-                          w_codestring, w_constants, w_names,
-                          w_varnames, w_filename, w_name, w_firstlineno,
-                          w_lnotab, w_freevars=NoneNotWrapped,
+                          argcount, nlocals, stacksize, flags,
+                          codestring, w_constants, w_names,
+                          w_varnames, filename, name, firstlineno,
+                          lnotab, w_freevars=NoneNotWrapped,
                           w_cellvars=NoneNotWrapped):
         code = space.allocate_instance(PyCode, w_subtype)
         code.__init__(space)
-        # XXX typechecking everywhere!
-        code.co_argcount   = space.int_w(w_argcount)
-        code.co_nlocals    = space.int_w(w_nlocals)
-        code.co_stacksize  = space.int_w(w_stacksize)
-        code.co_flags      = space.int_w(w_flags)
-        code.co_code       = space.str_w(w_codestring)
+        code.co_argcount   = argcount 
+        code.co_nlocals    = nlocals 
+        code.co_stacksize  = stacksize 
+        code.co_flags      = flags 
+        code.co_code       = codestring 
         code.co_consts_w   = space.unpacktuple(w_constants)
-        code.co_names_w    = space.unpacktuple(w_names)
+        code.co_names      = unpack_str_tuple(space, w_names)
         code.co_varnames   = unpack_str_tuple(space, w_varnames)
-        code.co_filename   = space.str_w(w_filename)
-        code.co_name       = space.str_w(w_name)
-        code.co_firstlineno= space.int_w(w_firstlineno)
-        code.co_lnotab     = space.str_w(w_lnotab)
+        code.co_filename   = filename 
+        code.co_name       = name 
+        code.co_firstlineno= firstlineno 
+        code.co_lnotab     = lnotab 
         if w_freevars is not None:
             code.co_freevars = unpack_str_tuple(space, w_freevars)
         if w_cellvars is not None:
             code.co_cellvars = unpack_str_tuple(space, w_cellvars)
         return space.wrap(code)
+    descr_code__new__.unwrap_spec = unwrap_spec 
 
     
 def _really_enhanceclass(key, stuff):

Modified: pypy/dist/pypy/interpreter/pyframe.py
==============================================================================
--- pypy/dist/pypy/interpreter/pyframe.py	(original)
+++ pypy/dist/pypy/interpreter/pyframe.py	Sat Feb 19 15:30:45 2005
@@ -23,7 +23,7 @@
      * 'code' is the PyCode object this frame runs
      * 'w_locals' is the locals dictionary to use
      * 'w_globals' is the attached globals dictionary
-     * 'w_builtins' is the attached built-ins dictionary
+     * 'builtin' is the attached built-in module
      * 'valuestack', 'blockstack', 'next_instr' control the interpretation
     """
 
@@ -33,7 +33,7 @@
         self.blockstack = Stack()
         self.last_exception = None
         self.next_instr = 0
-        self.w_builtins = self.space.w_builtins
+        self.builtin = space.builtin.pick_builtin(w_globals)
         # regular functions always have CO_OPTIMIZED and CO_NEWLOCALS.
         # class bodies only have CO_NEWLOCALS.
         if code.dictscope_needed():
@@ -74,14 +74,17 @@
                         # catch asynchronous exceptions and turn them
                         # into OperationErrors
                         except KeyboardInterrupt:
-                            raise OperationError(self.space.w_KeyboardInterrupt,
-                                                 self.space.w_None)
+                            import sys; tb = sys.exc_info()[2]
+                            raise OperationError, (self.space.w_KeyboardInterrupt,
+                                                   self.space.w_None), tb
                         except MemoryError:
-                            raise OperationError(self.space.w_MemoryError,
-                                                 self.space.w_None)
+                            import sys; tb = sys.exc_info()[2]
+                            raise OperationError, (self.space.w_MemoryError,
+                                                   self.space.w_None), tb
                         except RuntimeError, e:
-                            raise OperationError(self.space.w_RuntimeError,
-                                self.space.wrap("internal error: " + str(e)))
+                            import sys; tb = sys.exc_info()[2]
+                            raise OperationError, (self.space.w_RuntimeError,
+                                self.space.wrap("internal error: " + str(e))), tb
 
                     except OperationError, e:
                         pytraceback.record_application_traceback(
@@ -130,6 +133,10 @@
         "Returns the line number of the next instruction to execute."
         return pytraceback.offset2lineno(self.code, self.next_instr)
 
+    def fget_f_builtins(space, w_self):
+        self = space.interpclass_w(w_self)
+        return self.builtin.getdict()
+
 
 ### Frame Blocks ###
 
@@ -216,44 +223,46 @@
             return True  # stop unrolling
         return False
 
-def app_normalize_exception(etype, value, tb):
-    """Normalize an (exc_type, exc_value) pair:
-    exc_value will be an exception instance and exc_type its class.
-    """
-    # mistakes here usually show up as infinite recursion, which is fun.
-    while isinstance(etype, tuple):
-        etype = etype[0]
-    if isinstance(etype, (type, _classobj)):
-        if not isinstance(value, etype):
-            if value is None:
-                # raise Type: we assume we have to instantiate Type
-                value = etype()
-            elif isinstance(value, tuple):
-                # raise Type, Tuple: assume Tuple contains the constructor args
-                value = etype(*value)
-            else:
-                # raise Type, X: assume X is the constructor argument
-                value = etype(value)
-        # raise Type, Instance: let etype be the exact type of value
-        etype = value.__class__
-    elif type(etype) is str:
-        # XXX warn -- deprecated
-        if value is not None and type(value) is not str:
-            raise TypeError("string exceptions can only have a string value")
-    else:
-        # raise X: we assume that X is an already-built instance
-        if value is not None:
-            raise TypeError("instance exception may not have a separate value")
-        value = etype
-        etype = value.__class__
-        # for the sake of language consistency we should not allow
-        # things like 'raise 1', but it's probably fine (i.e.
-        # not ambiguous) to allow them in the explicit form 'raise int, 1'
-        if not hasattr(value, '__dict__') and not hasattr(value, '__slots__'):
-            raise TypeError("raising built-in objects can be ambiguous, "
-                            "use 'raise type, value' instead")
-    return etype, value, tb
-normalize_exception = gateway.app2interp(app_normalize_exception)
+app = gateway.applevel('''
+    def normalize_exception(etype, value, tb):
+        """Normalize an (exc_type, exc_value) pair:
+        exc_value will be an exception instance and exc_type its class.
+        """
+        # mistakes here usually show up as infinite recursion, which is fun.
+        while isinstance(etype, tuple):
+            etype = etype[0]
+        if isinstance(etype, (type, _classobj)):
+            if not isinstance(value, etype):
+                if value is None:
+                    # raise Type: we assume we have to instantiate Type
+                    value = etype()
+                elif isinstance(value, tuple):
+                    # raise Type, Tuple: assume Tuple contains the constructor args
+                    value = etype(*value)
+                else:
+                    # raise Type, X: assume X is the constructor argument
+                    value = etype(value)
+            # raise Type, Instance: let etype be the exact type of value
+            etype = value.__class__
+        elif type(etype) is str:
+            # XXX warn -- deprecated
+            if value is not None and type(value) is not str:
+                raise TypeError("string exceptions can only have a string value")
+        else:
+            # raise X: we assume that X is an already-built instance
+            if value is not None:
+                raise TypeError("instance exception may not have a separate value")
+            value = etype
+            etype = value.__class__
+            # for the sake of language consistency we should not allow
+            # things like 'raise 1', but it is probably fine (i.e.
+            # not ambiguous) to allow them in the explicit form 'raise int, 1'
+            if not hasattr(value, '__dict__') and not hasattr(value, '__slots__'):
+                raise TypeError("raising built-in objects can be ambiguous, "
+                                "use 'raise type, value' instead")
+        return etype, value, tb
+''')
+normalize_exception = app.interphook("normalize_exception")
 
 
 class FinallyBlock(FrameBlock):

Modified: pypy/dist/pypy/interpreter/pyopcode.py
==============================================================================
--- pypy/dist/pypy/interpreter/pyopcode.py	(original)
+++ pypy/dist/pypy/interpreter/pyopcode.py	Sat Feb 19 15:30:45 2005
@@ -71,9 +71,11 @@
     def getconstant_w(self, index):
         return self.code.co_consts_w[index]
 
+    def getname(self, index):
+        return self.code.co_names[index]
+
     def getname_w(self, index):
-        w_varname = self.code.co_names_w[index]
-        return w_varname
+        return self.space.wrap(self.code.co_names[index])
 
 
     ################################################################
@@ -345,8 +347,8 @@
         w_globals = f.valuestack.pop()
         w_prog    = f.valuestack.pop()
         w_compile_flags = f.space.wrap(f.get_compile_flags())
-        w_resulttuple = f.prepare_exec(w_prog, w_globals, w_locals,
-                                       w_compile_flags)
+        w_resulttuple = prepare_exec(f.space, f.space.wrap(f), w_prog, w_globals, w_locals,
+                                       w_compile_flags, f.space.wrap(f.builtin))
         w_prog, w_globals, w_locals = f.space.unpacktuple(w_resulttuple, 3)
 
         plain = f.space.is_true(f.space.is_(w_locals, f.w_locals))
@@ -357,44 +359,6 @@
         if plain:
             f.setdictscope(w_locals)
 
-    def app_prepare_exec(f, prog, globals, locals, compile_flags):
-        """Manipulate parameters to exec statement to (codeobject, dict, dict).
-        """
-        # XXX INCOMPLETE
-        if (globals is None and locals is None and
-            isinstance(prog, tuple) and
-            (len(prog) == 2 or len(prog) == 3)):
-            globals = prog[1]
-            if len(prog) == 3:
-                locals = prog[2]
-            prog = prog[0]
-        if globals is None:
-            globals = f.f_globals
-            if locals is None:
-                locals = f.f_locals
-        if locals is None:
-            locals = globals
-        if not isinstance(globals, dict):
-            raise TypeError("exec: arg 2 must be a dictionary or None")
-        elif not globals.has_key('__builtins__'):
-            globals['__builtins__'] = f.f_builtins
-        if not isinstance(locals, dict):
-            raise TypeError("exec: arg 3 must be a dictionary or None")
-        # XXX - HACK to check for code object
-        co = compile('1','<string>','eval')
-        if isinstance(prog, type(co)):
-            return (prog, globals, locals)
-        if not isinstance(prog, str):
-    ##     if not (isinstance(prog, types.StringTypes) or
-    ##             isinstance(prog, types.FileType)):
-            raise TypeError("exec: arg 1 must be a string, file, or code object")
-    ##     if isinstance(prog, types.FileType):
-    ##         co = compile(prog.read(),prog.name,'exec',comple_flags,1)
-    ##         return (co,globals,locals)
-        else: # prog is a string
-            co = compile(prog,'<string>','exec', compile_flags, 1)
-            return (co, globals, locals)
-
     def POP_BLOCK(f):
         block = f.blockstack.pop()
         block.cleanup(f)  # the block knows how to clean up the value stack
@@ -417,7 +381,8 @@
         w_bases       = f.valuestack.pop()
         w_name        = f.valuestack.pop()
         w_metaclass = find_metaclass(f.space, w_bases,
-                                     w_methodsdict, f.w_globals, f.w_builtins)
+                                     w_methodsdict, f.w_globals,
+                                     f.space.wrap(f.builtin)) 
         w_newclass = f.space.call_function(w_metaclass, w_name,
                                            w_bases, w_methodsdict)
         f.valuestack.push(w_newclass)
@@ -471,38 +436,19 @@
         f.space.delitem(f.w_globals, w_varname)
 
     def LOAD_NAME(f, nameindex):
-        w_varname = f.getname_w(nameindex)
-
-        if f.w_globals is f.w_locals:
-            try_list_w = [f.w_globals, f.w_builtins]
-
-        else:
-            try_list_w = [f.w_locals, f.w_globals, f.w_builtins]
-
-        w_value = None
-        for wrapped in try_list_w:
+        if f.w_locals is not f.w_globals:
+            w_varname = f.getname_w(nameindex)
             try:
-                w_value = f.space.getitem(wrapped, w_varname)
-                f.valuestack.push(w_value)
-                return
-
+                w_value = f.space.getitem(f.w_locals, w_varname)
             except OperationError, e:
                 if not e.match(f.space, f.space.w_KeyError):
                     raise
-        message = "name '%s' is not defined" % f.space.str_w(w_varname)
-        w_exc_type = f.space.w_NameError
-        w_exc_value = f.space.wrap(message)
-        raise OperationError(w_exc_type, w_exc_value)
-
-
-        # XXX the implementation can be pushed back into app-space as an
-        # when exception handling begins to behave itself.  For now, it
-        # was getting on my nerves -- mwh
-        #    w_value = f.load_name(w_varname)
-        #    f.valuestack.push(w_value)
+            else:
+                f.valuestack.push(w_value)
+                return
+        f.LOAD_GLOBAL(nameindex)    # fall-back
 
     def LOAD_GLOBAL(f, nameindex):
-        assert f.w_globals is not None
         w_varname = f.getname_w(nameindex)
         try:
             w_value = f.space.getitem(f.w_globals, w_varname)
@@ -511,16 +457,12 @@
             if not e.match(f.space, f.space.w_KeyError):
                 raise
             # we got a KeyError, now look in the built-ins
-            try:
-                w_value = f.space.getitem(f.w_builtins, w_varname)
-            except OperationError, e:
-                # catch KeyErrors again
-                if not e.match(f.space, f.space.w_KeyError):
-                    raise
-                message = "global name '%s' is not defined" % f.space.str_w(w_varname)
-                w_exc_type = f.space.w_NameError
-                w_exc_value = f.space.wrap(message)
-                raise OperationError(w_exc_type, w_exc_value)
+            varname = f.getname(nameindex)
+            w_value = f.builtin.getdictvalue(f.space, varname)
+            if w_value is None:
+                message = "global name '%s' is not defined" % varname
+                raise OperationError(f.space.w_NameError,
+                                     f.space.wrap(message))
         f.valuestack.push(w_value)
 
     def DELETE_FAST(f, varindex):
@@ -601,11 +543,8 @@
         w_modulename = f.getname_w(nameindex)
         modulename = f.space.str_w(w_modulename)
         w_fromlist = f.valuestack.pop()
-        try:
-            w_import = space.getitem(f.w_builtins, space.wrap("__import__"))
-        except OperationError, e:
-            if not e.match(space, space.w_KeyError):
-                raise
+        w_import = f.builtin.getdictvalue(f.space, '__import__')
+        if w_import is None:
             raise OperationError(space.w_ImportError,
                                  space.wrap("__import__ not found"))
         w_locals = f.w_locals
@@ -774,9 +713,6 @@
         cls.dispatch_table = dispatch_table
 
 
-    gateway.importall(locals())   # app_xxx() -> xxx()
-
-
 ### helpers written at the application-level ###
 # Some of these functions are expected to be generally useful if other
 # parts of the code needs to do the same thing as a non-trivial opcode,
@@ -785,78 +721,130 @@
 # There are also a couple of helpers that are methods, defined in the
 # class above.
 
-def app_print_expr(x):
-    try:
-        displayhook = sys.displayhook
-    except AttributeError:
-        raise RuntimeError("lost sys.displayhook")
-    displayhook(x)
-
-def app_file_softspace(file, newflag):
-    try:
-        softspace = file.softspace
-    except AttributeError:
-        softspace = 0
-    try:
-        file.softspace = newflag
-    except AttributeError:
-        pass
-    return softspace
+app = gateway.applevel(r'''
 
-def app_sys_stdout():
-    try:
-        return sys.stdout
-    except AttributeError:
-        raise RuntimeError("lost sys.stdout")
-
-def app_print_item_to(x, stream):
-    if file_softspace(stream, False):
-        stream.write(" ")
-    stream.write(str(x))
-    # add a softspace unless we just printed a string which ends in a '\t'
-    # or '\n' -- or more generally any whitespace character but ' '
-    if isinstance(x, str) and len(x) and x[-1].isspace() and x[-1]!=' ':
-        return
-    # XXX add unicode handling
-    file_softspace(stream, True)
-
-def app_print_newline_to(stream):
-    stream.write("\n")
-    file_softspace(stream, False)
-
-def app_find_metaclass(bases, namespace, globals, builtins):
-    if '__metaclass__' in namespace:
-        return namespace['__metaclass__']
-    elif len(bases) > 0:
-        base = bases[0]
-        if hasattr(base, '__class__'):
-            return base.__class__
-        else:
-            return type(base)
-    elif '__metaclass__' in globals:
-        return globals['__metaclass__']
-    elif '__metaclass__' in builtins:
-        return builtins['__metaclass__']
-    else:
-        return type
-
-def app_import_all_from(module, into_locals):
-    try:
-        all = module.__all__
-    except AttributeError:
+    import sys
+
+    def sys_stdout(): 
+        try: 
+            return sys.stdout
+        except AttributeError:
+            raise RuntimeError("lost sys.stdout")
+
+    def print_expr(obj):
+        try:
+            displayhook = sys.displayhook
+        except AttributeError:
+            raise RuntimeError("lost sys.displayhook")
+        displayhook(obj)
+
+    def print_item_to(x, stream):
+        if file_softspace(stream, False):
+           stream.write(" ")
+        stream.write(str(x))
+
+        # add a softspace unless we just printed a string which ends in a '\t'
+        # or '\n' -- or more generally any whitespace character but ' '
+        if isinstance(x, str) and x and x[-1].isspace() and x[-1]!=' ':
+            return 
+        # XXX add unicode handling
+        file_softspace(stream, True)
+
+    def print_newline_to(stream):
+        stream.write("\n")
+        file_softspace(stream, False)
+
+    def file_softspace(file, newflag):
+        try:
+            softspace = file.softspace
+        except AttributeError:
+            softspace = 0
         try:
-            dict = module.__dict__
+            file.softspace = newflag
         except AttributeError:
-            raise ImportError("from-import-* object has no __dict__ "
-                              "and no __all__")
-        all = dict.keys()
-        skip_leading_underscores = True
-    else:
-        skip_leading_underscores = False
-    for name in all:
-        if skip_leading_underscores and name[0]=='_':
-            continue
-        into_locals[name] = getattr(module, name)
+            pass
+        return softspace
 
+    def find_metaclass(bases, namespace, globals, builtin):
+        if '__metaclass__' in namespace:
+            return namespace['__metaclass__']
+        elif len(bases) > 0:
+            base = bases[0]
+            if hasattr(base, '__class__'):
+                return base.__class__
+            else:
+                return type(base)
+        elif '__metaclass__' in globals:
+            return globals['__metaclass__']
+        else: 
+            try: 
+                return builtin.__metaclass__ 
+            except AttributeError: 
+                return type
+
+    def import_all_from(module, into_locals):
+        try:
+            all = module.__all__
+        except AttributeError:
+            try:
+                dict = module.__dict__
+            except AttributeError:
+                raise ImportError("from-import-* object has no __dict__ "
+                                  "and no __all__")
+            all = dict.keys()
+            skip_leading_underscores = True
+        else:
+            skip_leading_underscores = False
+        for name in all:
+            if skip_leading_underscores and name[0]=='_':
+                continue
+            into_locals[name] = getattr(module, name)
+
+    def prepare_exec(f, prog, globals, locals, compile_flags, builtin):
+        """Manipulate parameters to exec statement to (codeobject, dict, dict).
+        """
+        # XXX INCOMPLETE
+        if (globals is None and locals is None and
+            isinstance(prog, tuple) and
+            (len(prog) == 2 or len(prog) == 3)):
+            globals = prog[1]
+            if len(prog) == 3:
+                locals = prog[2]
+            prog = prog[0]
+        if globals is None:
+            globals = f.f_globals
+            if locals is None:
+                locals = f.f_locals
+        if locals is None:
+            locals = globals
+        if not isinstance(globals, dict):
+            raise TypeError("exec: arg 2 must be a dictionary or None")
+        elif not globals.has_key('__builtins__'):
+            globals['__builtins__'] = builtin
+        if not isinstance(locals, dict):
+            raise TypeError("exec: arg 3 must be a dictionary or None")
+        # XXX - HACK to check for code object
+        co = compile('1','<string>','eval')
+        if isinstance(prog, type(co)):
+            return (prog, globals, locals)
+        if not isinstance(prog, str):
+    ##     if not (isinstance(prog, types.StringTypes) or
+    ##             isinstance(prog, types.FileType)):
+            raise TypeError("exec: arg 1 must be a string, file, "
+                            "or code object")
+    ##     if isinstance(prog, types.FileType):
+    ##         co = compile(prog.read(),prog.name,'exec',comple_flags,1)
+    ##         return (co,globals,locals)
+        else: # prog is a string
+            co = compile(prog,'<string>','exec', compile_flags, 1)
+            return (co, globals, locals)
+''')
 
-gateway.importall(globals())   # app_xxx() -> xxx()
+sys_stdout      = app.interphook('sys_stdout')
+print_expr      = app.interphook('print_expr')
+print_item_to   = app.interphook('print_item_to')
+print_newline_to= app.interphook('print_newline_to')
+file_softspace  = app.interphook('file_softspace')
+find_metaclass  = app.interphook('find_metaclass')
+import_all_from = app.interphook('import_all_from')
+prepare_exec    = app.interphook('prepare_exec')

Deleted: /pypy/dist/pypy/interpreter/test/foomodule.py
==============================================================================
--- /pypy/dist/pypy/interpreter/test/foomodule.py	Sat Feb 19 15:30:45 2005
+++ (empty file)
@@ -1,13 +0,0 @@
-
-__interplevel__exec("w_foo = space.w_Ellipsis")
-foo1 = __interplevel__eval("w_foo")  # foo1 is Ellipsis
-from __interplevel__ import foo      # Ellipsis too
-
-def bar(a, b):  # visible from interp-level code
-    return a * b
-
-__interplevel__execfile("foointerp.py")  # defines w_foo2 and foobuilder()
-
-from __interplevel__ import foo2   # from w_foo2, gives "hello"
-from __interplevel__ import foobuilder
-foo3 = foobuilder("guido")         # gives "hi, guido!"

Modified: pypy/dist/pypy/interpreter/test/test_appinterp.py
==============================================================================
--- pypy/dist/pypy/interpreter/test/test_appinterp.py	(original)
+++ pypy/dist/pypy/interpreter/test/test_appinterp.py	Sat Feb 19 15:30:45 2005
@@ -1,5 +1,6 @@
 
 import py
+from pypy.interpreter.gateway import appdef, applevel
 
 def test_execwith_novars(space): 
     val = space.appexec([], """ 
@@ -23,4 +24,104 @@
     """)
     assert str(excinfo).find('y y') != -1 
 
-    
+def test_simple_applevel(space):
+    app = appdef("""app(x,y): 
+        return x + y
+    """)
+    assert app.func_name == 'app'
+    w_result = app(space, space.wrap(41), space.wrap(1))
+    assert space.eq_w(w_result, space.wrap(42))
+
+def test_applevel_with_one_default(space):
+    app = appdef("""app(x,y=1): 
+        return x + y
+    """)
+    assert app.func_name == 'app'
+    w_result = app(space, space.wrap(41)) 
+    assert space.eq_w(w_result, space.wrap(42))
+
+def test_applevel_with_two_defaults(space):
+    app = appdef("""app(x=1,y=2): 
+        return x + y
+    """)
+    w_result = app(space, space.wrap(41), space.wrap(1))
+    assert space.eq_w(w_result, space.wrap(42))
+
+    w_result = app(space, space.wrap(15))
+    assert space.eq_w(w_result, space.wrap(17))
+
+    w_result = app(space)
+    assert space.eq_w(w_result, space.wrap(3))
+
+
+def test_applevel_noargs(space):
+    app = appdef("""app(): 
+        return 42 
+    """)
+    assert app.func_name == 'app'
+    w_result = app(space) 
+    assert space.eq_w(w_result, space.wrap(42))
+
+def somefunc(arg2=42): 
+    return arg2 
+
+def test_app2interp_somefunc(space): 
+    app = appdef(somefunc) 
+    w_result = app(space) 
+    assert space.eq_w(w_result, space.wrap(42))
+
+def test_applevel_functions(space):
+    app = applevel('''
+        def f(x, y):
+            return x-y
+        def g(x, y):
+            return f(y, x)
+    ''')
+    g = app.interphook('g')
+    w_res = g(space, space.wrap(10), space.wrap(1))
+    assert space.eq_w(w_res, space.wrap(-9))
+
+def test_applevel_class(space):
+    app = applevel('''
+        class C: 
+            clsattr = 42 
+            def __init__(self, x=13): 
+                self.attr = x 
+    ''')
+    C = app.interphook('C')
+    c = C(space, space.wrap(17)) 
+    w_attr = space.getattr(c, space.wrap('clsattr'))
+    assert space.eq_w(w_attr, space.wrap(42))
+    w_clsattr = space.getattr(c, space.wrap('attr'))
+    assert space.eq_w(w_clsattr, space.wrap(17))
+
+def app_test_something_at_app_level(): 
+    x = 2
+    assert x/2 == 1
+
+class AppTestMethods: 
+    def test_some_app_test_method(self): 
+        assert 2 == 2
+
+class TestMixedModule: 
+    def test_accesses(self): 
+        space = self.space 
+        import mixedmodule 
+        w_module = mixedmodule.Module(space, space.wrap('mixedmodule'))
+        space.appexec([w_module], """
+            (module): 
+                assert module.value is None 
+                assert module.__doc__ == 'mixedmodule doc'
+
+                assert module.somefunc is module.somefunc 
+                result = module.somefunc() 
+                assert result == True 
+
+                assert module.someappfunc is module.someappfunc 
+                appresult = module.someappfunc(41) 
+                assert appresult == 42 
+
+                assert module.__dict__ is module.__dict__
+                for name in ('somefunc', 'someappfunc', '__doc__', '__name__'): 
+                    assert name in module.__dict__
+        """)

Modified: pypy/dist/pypy/interpreter/test/test_class.py
==============================================================================
--- pypy/dist/pypy/interpreter/test/test_class.py	(original)
+++ pypy/dist/pypy/interpreter/test/test_class.py	Sat Feb 19 15:30:45 2005
@@ -30,15 +30,14 @@
 
     def test_metaclass_global(self):
         d = {}
-        metatest_text = """
-class M(type):
-    pass
-
-__metaclass__ = M
-
-class C:
-    pass
-"""
+        metatest_text = """if 1: 
+            class M(type):
+                pass
+
+            __metaclass__ = M
+
+            class C:
+                pass\n"""
         exec metatest_text in d
         C = d['C']
         M = d['M']

Deleted: /pypy/dist/pypy/interpreter/test/test_extmodule.py
==============================================================================
--- /pypy/dist/pypy/interpreter/test/test_extmodule.py	Sat Feb 19 15:30:45 2005
+++ (empty file)
@@ -1,25 +0,0 @@
-
-import autopath
-import os
-from pypy.interpreter.extmodule import BuiltinModule
-
-class TestBuiltinModule: 
-    def test_foomodule(self):
-        space = self.space
-        sourcefile = os.path.join(autopath.this_dir, 'foomodule.py')
-        m = BuiltinModule(space, 'foo', sourcefile=sourcefile)
-        w = space.wrap
-        w_m = space.wrap(m)
-        assert self.space.eq_w(space.getattr(w_m, w('__name__')), w('foo'))
-        assert self.space.eq_w(space.getattr(w_m, w('__file__')), w(sourcefile))
-        # check app-level definitions
-        assert self.space.eq_w(m.w_foo, space.w_Ellipsis)
-        assert self.space.eq_w(space.getattr(w_m, w('foo1')), space.w_Ellipsis)
-        assert self.space.eq_w(space.getattr(w_m, w('foo')), space.w_Ellipsis)
-        assert self.space.eq_w(space.call_method(w_m, 'bar', w(4), w(3)), w(12))
-        assert self.space.eq_w(space.getattr(w_m, w('foo2')), w('hello'))
-        assert self.space.eq_w(space.getattr(w_m, w('foo3')), w('hi, guido!'))
-        # check interp-level definitions
-        assert self.space.eq_w(m.w_foo2, w('hello'))
-        assert self.space.eq_w(m.foobuilder(w('xyzzy')), w('hi, xyzzy!'))
-        assert self.space.eq_w(m.fortytwo, w(42))

Modified: pypy/dist/pypy/interpreter/test/test_function.py
==============================================================================
--- pypy/dist/pypy/interpreter/test/test_function.py	(original)
+++ pypy/dist/pypy/interpreter/test/test_function.py	Sat Feb 19 15:30:45 2005
@@ -176,7 +176,7 @@
         def c(self, bar):
             return bar
         code = PyCode(self.space)._from_code(c.func_code)
-        self.fn = Function(self.space, code)
+        self.fn = Function(self.space, code, self.space.newdict([]))
         
     def test_get(self):
         space = self.space
@@ -202,7 +202,8 @@
         space = self.space
         # Create some function for this test only
         def m(self): return self
-        func = Function(space, PyCode(self.space)._from_code(m.func_code))
+        func = Function(space, PyCode(self.space)._from_code(m.func_code),
+                        space.newdict([]))
         # Some shorthands
         obj1 = space.wrap(23)
         obj2 = space.wrap(42)

Modified: pypy/dist/pypy/interpreter/test/test_gateway.py
==============================================================================
--- pypy/dist/pypy/interpreter/test/test_gateway.py	(original)
+++ pypy/dist/pypy/interpreter/test/test_gateway.py	Sat Feb 19 15:30:45 2005
@@ -1,20 +1,28 @@
 
 import autopath
 from pypy.interpreter import gateway
+import py
 
 class TestBuiltinCode: 
     def test_signature(self):
         def c(space, w_x, w_y, *hello_w):
             pass
-        code = gateway.BuiltinCode(c)
+        code = gateway.BuiltinCode(c, unwrap_spec=[gateway.ObjSpace,
+                                                   gateway.W_Root,
+                                                   gateway.W_Root,
+                                                   'starargs'])
         assert code.signature() == (['x', 'y'], 'hello', None)
         def d(self, w_boo):
             pass
-        code = gateway.BuiltinCode(d)
+        code = gateway.BuiltinCode(d, unwrap_spec= ['self',
+                                                   gateway.W_Root], self_type=gateway.BaseWrappable)
         assert code.signature() == (['self', 'boo'], None, None)
         def e(space, w_x, w_y, __args__):
             pass
-        code = gateway.BuiltinCode(e)
+        code = gateway.BuiltinCode(e, unwrap_spec=[gateway.ObjSpace,
+                                                   gateway.W_Root,
+                                                   gateway.W_Root,
+                                                   gateway.Arguments])
         assert code.signature() == (['x', 'y'], 'args', 'keywords')
 
     def test_call(self):
@@ -25,7 +33,10 @@
             assert u(hello_w[0]) == 0
             assert u(hello_w[1]) == True
             return w((u(w_x) - u(w_y) + len(hello_w)))
-        code = gateway.BuiltinCode(c)
+        code = gateway.BuiltinCode(c, unwrap_spec=[gateway.ObjSpace,
+                                                   gateway.W_Root,
+                                                   gateway.W_Root,
+                                                   'starargs'])
         w = self.space.wrap
         w_dict = self.space.newdict([
             (w('x'), w(123)),
@@ -42,7 +53,10 @@
             w = space.wrap
             return w((u(w_x) - u(w_y) + len(args_w))
                      * u(kwds_w['boo']))
-        code = gateway.BuiltinCode(c)
+        code = gateway.BuiltinCode(c, unwrap_spec=[gateway.ObjSpace,
+                                                   gateway.W_Root,
+                                                   gateway.W_Root,
+                                                   gateway.Arguments])
         w = self.space.wrap
         w_dict = self.space.newdict([
             (w('x'), w(123)),
@@ -55,6 +69,7 @@
 
 
 class TestGateway: 
+
     def test_app2interp(self):
         w = self.space.wrap
         def app_g3(a, b):
@@ -189,26 +204,14 @@
 
     def test_importall(self):
         w = self.space.wrap
-        g = {}
-        exec """
-def app_g3(a, b):
-    return a+b
-def app_g1(x):
-    return g3('foo', x)
-""" in g
+        g = {'app_g3': app_g3}
         gateway.importall(g, temporary=True)
-        g1 = g['g1']
-        assert self.space.eq_w(g1(self.space, w('bar')), w('foobar'))
+        g3 = g['g3']
+        assert self.space.eq_w(g3(self.space, w('bar')), w('foobar'))
 
-    def test_exportall(self):
-        w = self.space.wrap
-        g = {}
-        exec """
-def g3(space, w_a, w_b):
-    return space.add(w_a, w_b)
-def app_g1(x):
-    return g3('foo', x)
-""" in g
-        gateway.exportall(g, temporary=True)
-        g1 = gateway.app2interp_temp(g['app_g1'])
-        assert self.space.eq_w(g1(self.space, w('bar')), w('foobar'))
+##    def test_exportall(self):
+##        not used any more
+
+
+def app_g3(b):
+    return 'foo'+b

Modified: pypy/dist/pypy/interpreter/test/test_interpreter.py
==============================================================================
--- pypy/dist/pypy/interpreter/test/test_interpreter.py	(original)
+++ pypy/dist/pypy/interpreter/test/test_interpreter.py	Sat Feb 19 15:30:45 2005
@@ -10,15 +10,16 @@
 
         source = str(py.code.Source(source).strip()) + '\n'
 
-        compile = space.builtin.compile
+        #from pypy.module.builtin.compiling import compile 
+        w_compile = space.builtin.get('compile')
         w = space.wrap
-        w_code = compile(w(source), '<string>', 'exec', 0, 0)
-
+        w_code = space.call_function(w_compile, 
+                w(source), w('<string>'), w('exec'), w(0), w(0))
         ec = executioncontext.ExecutionContext(space)
 
         tempmodule = module.Module(space, w("__temp__"))
         w_glob = tempmodule.w_dict
-        space.setitem(w_glob, w("__builtins__"), space.w_builtins)
+        space.setitem(w_glob, w("__builtins__"), space.builtin)
 
         code = space.unwrap(w_code)
         code.exec_code(space, w_glob, w_glob)

Modified: pypy/dist/pypy/interpreter/test/test_main.py
==============================================================================
--- pypy/dist/pypy/interpreter/test/test_main.py	(original)
+++ pypy/dist/pypy/interpreter/test/test_main.py	Sat Feb 19 15:30:45 2005
@@ -17,10 +17,10 @@
 testresultoutput = '11\n'
 
 def checkoutput(space, expected_output,f,*args):
-    w_sys = space.get_builtin_module("sys")
-    w_oldout = space.getattr(w_sys, space.wrap("stdout"))
+    w_oldout = space.sys.get('stdout') 
     capturefn = udir.join('capturefile')
     capturefile = capturefn.open('w') 
+    w_sys = space.sys.getmodule('sys')
     space.setattr(w_sys, space.wrap("stdout"), space.wrap(capturefile))
     try:
         f(*(args + (space,)))
@@ -29,7 +29,6 @@
     capturefile.close() 
     assert capturefn.read(mode='rU') == expected_output
 
-
 testfn = 'tmp_hello_world.py'
 
 class TestMain: 

Modified: pypy/dist/pypy/interpreter/test/test_module.py
==============================================================================
--- pypy/dist/pypy/interpreter/test/test_module.py	(original)
+++ pypy/dist/pypy/interpreter/test/test_module.py	Sat Feb 19 15:30:45 2005
@@ -37,6 +37,8 @@
         delattr(m, 'x')
         raises(AttributeError, getattr, m, 'x')
         raises(AttributeError, delattr, m, 'x')
+        raises(TypeError, setattr, m, '__dict__', {})
+
     def test_docstring(self):
         import sys
         foo = type(sys)('foo')

Modified: pypy/dist/pypy/interpreter/test/test_objspace.py
==============================================================================
--- pypy/dist/pypy/interpreter/test/test_objspace.py	(original)
+++ pypy/dist/pypy/interpreter/test/test_objspace.py	Sat Feb 19 15:30:45 2005
@@ -89,15 +89,14 @@
 
 class TestModuleMinimal: 
     def test_sys_exists(self):
-        w_sys = self.space.get_builtin_module('sys')
-        assert self.space.is_true(w_sys)
+        assert self.space.sys 
 
     def test_import_exists(self):
         space = self.space
-        w_builtin = space.get_builtin_module('__builtin__')
-        assert space.is_true(w_builtin)
+        assert space.builtin 
         w_name = space.wrap('__import__')
-        w_import = self.space.getattr(w_builtin, w_name)
+        w_builtin = space.sys.getmodule('__builtin__')
+        w_import = self.space.getattr(w_builtin, w_name) 
         assert space.is_true(w_import)
 
     def test_sys_import(self):

Modified: pypy/dist/pypy/interpreter/typedef.py
==============================================================================
--- pypy/dist/pypy/interpreter/typedef.py	(original)
+++ pypy/dist/pypy/interpreter/typedef.py	Sat Feb 19 15:30:45 2005
@@ -2,8 +2,8 @@
 
 
 """
-from pypy.interpreter.gateway import interp2app 
-from pypy.interpreter.baseobjspace import Wrappable
+from pypy.interpreter.gateway import interp2app, ObjSpace, Arguments, W_Root 
+from pypy.interpreter.baseobjspace import BaseWrappable, Wrappable
 from pypy.interpreter.error import OperationError
 from pypy.tool.cache import Cache
 import new
@@ -92,63 +92,117 @@
     else:
         return new.instance(cls)
 
+def make_descr_typecheck_wrapper(func, extraargs=(), cls=None):
+    if func is None:
+        return None
+    if hasattr(func, 'im_func'):
+        assert not cls or cls is func.im_class
+        cls = func.im_class
+        func = func.im_func
+    if not cls:
+        #print "UNCHECKED", func.__module__ or '?', func.__name__
+        return func
+
+    miniglobals = {
+         func.__name__: func,
+        'OperationError': OperationError
+        }
+    if isinstance(cls, str):
+        #print "<CHECK", func.__module__ or '?', func.__name__
+        assert cls.startswith('<'),"pythontype typecheck should begin with <"
+        unwrap = "w_obj"
+        cls_name = cls[1:]
+        expected = repr(cls_name)
+        check = "space.is_true(space.isinstance(obj, space.w_%s))" % cls_name
+    else:
+        cls_name = cls.__name__
+        if issubclass(cls, BaseWrappable):
+            unwrap =  "space.interpclass_w(w_obj)"
+        else:
+            unwrap = "w_obj"
+        miniglobals[cls_name] = cls
+        check = "isinstance(obj, %s)" % cls_name
+        expected = "%s.typedef.name" % cls_name
+   
+    source = """if 1: 
+        def descr_typecheck_%(name)s(space, w_obj, %(extra)s):
+            obj = %(unwrap)s
+            if obj is None or not %(check)s:
+                # xxx improve msg
+                msg =  "descriptor is for '%%s'" %% %(expected)s
+                raise OperationError(space.w_TypeError, space.wrap(msg))
+            return %(name)s(space, obj, %(extra)s)
+        \n""" % {'name': func.__name__, 
+                 'check': check,
+                 'expected': expected,
+                 'unwrap': unwrap,
+                 'extra': ', '.join(extraargs)} 
+    exec compile(source, '', 'exec') in miniglobals 
+    return miniglobals['descr_typecheck_%s' % func.__name__]    
+
+
 class GetSetProperty(Wrappable):
-    def __init__(self, fget, fset=None, fdel=None, doc=None):
+    def __init__(self, fget, fset=None, fdel=None, doc=None, cls=None):
         "NOT_RPYTHON: initialization-time only"
-        fget = getattr(fget, 'im_func', fget) 
-        fset = getattr(fset, 'im_func', fset) 
-        fdel = getattr(fdel, 'im_func', fdel) 
+        fget = make_descr_typecheck_wrapper(fget, cls=cls) 
+        fset = make_descr_typecheck_wrapper(fset, ('w_value',), cls=cls)
+        fdel = make_descr_typecheck_wrapper(fdel, cls=cls) 
         self.fget = fget
         self.fset = fset
         self.fdel = fdel
         self.doc = doc
 
-    def descr_property_get(space, w_property, w_obj, w_cls=None):
+    def descr_property_get(space, property, w_obj, w_cls=None):
         # XXX HAAAAAAAAAAAACK (but possibly a good one)
         if w_obj == space.w_None and not space.is_true(space.is_(w_cls, space.type(space.w_None))):
-            #print w_property, w_obj, w_cls
-            return w_property
+            #print property, w_obj, w_cls
+            return space.wrap(property)
         else:
-            return space.interpclass_w(w_property).fget(space, w_obj)
+            return property.fget(space, w_obj)
 
-    def descr_property_set(space, w_property, w_obj, w_value):
-        fset = space.interpclass_w(w_property).fset
+    def descr_property_set(space, property, w_obj, w_value):
+        fset = property.fset
         if fset is None:
-            raise OperationError(space.w_AttributeError,
+            raise OperationError(space.w_TypeError,
                                  space.wrap("read-only attribute"))
         fset(space, w_obj, w_value)
 
-    def descr_property_del(space, w_property, w_obj):
-        fdel = space.interpclass_w(w_property).fdel
+    def descr_property_del(space, property, w_obj):
+        fdel = property.fdel
         if fdel is None:
             raise OperationError(space.w_AttributeError,
                                  space.wrap("cannot delete attribute"))
         fdel(space, w_obj)
 
-    typedef = TypeDef("GetSetProperty",
-        __get__ = interp2app(descr_property_get),
-        __set__ = interp2app(descr_property_set),
-        __delete__ = interp2app(descr_property_del),
-        )
+GetSetProperty.typedef = TypeDef(
+    "GetSetProperty",
+    __get__ = interp2app(GetSetProperty.descr_property_get.im_func,
+                         unwrap_spec = [ObjSpace,
+                                        GetSetProperty, W_Root, W_Root]),
+    __set__ = interp2app(GetSetProperty.descr_property_set.im_func,
+                         unwrap_spec = [ObjSpace,
+                                        GetSetProperty, W_Root, W_Root]),
+    __delete__ = interp2app(GetSetProperty.descr_property_del.im_func,
+                            unwrap_spec = [ObjSpace,
+                                           GetSetProperty, W_Root]),
+    )
 
-def interp_attrproperty(name):
+def interp_attrproperty(name, cls):
     "NOT_RPYTHON: initialization-time only"
-    def fget(space, w_obj):
-        obj = space.interpclass_w(w_obj)
+    def fget(space, obj):
         return space.wrap(getattr(obj, name))
-    return GetSetProperty(fget)
+    return GetSetProperty(fget, cls=cls)
 
-def interp_attrproperty_w(name):
+def interp_attrproperty_w(name, cls):
     "NOT_RPYTHON: initialization-time only"
-    def fget(space, w_obj):
-        obj = space.interpclass_w(w_obj)
+    def fget(space, obj):
         w_value = getattr(obj, name)
         if w_value is None:
             return space.w_None
         else:
             return w_value 
 
-    return GetSetProperty(fget)
+    return GetSetProperty(fget, cls=cls)
 
 class Member(Wrappable):
     """For slots."""
@@ -156,30 +210,37 @@
         self.index = index
         self.name = name
 
-    def descr_member_get(space, w_member, w_obj, w_cls=None):
+    def descr_member_get(space, member, w_obj, w_cls=None):
         if space.is_w(w_obj, space.w_None):
-            return w_member
+            return space.wrap(member)
         else:
-            self = space.interpclass_w(w_member)
+            self = member
             w_result = w_obj.slots_w[self.index]
             if w_result is None:
                 raise OperationError(space.w_AttributeError,
                                      space.wrap(self.name)) # XXX better message
             return w_result
 
-    def descr_member_set(space, w_member, w_obj, w_value):
-        self = space.interpclass_w(w_member)
-        w_obj.slots_w[self.index] = w_value
-
-    def descr_member_del(space, w_member, w_obj):
-        self = space.interpclass_w(w_member)
-        w_obj.slots_w[self.index] = None
-
-    typedef = TypeDef("member",
-        __get__ = interp2app(descr_member_get),
-        __set__ = interp2app(descr_member_set),
-        __delete__ = interp2app(descr_member_del),
-        )
+    def descr_member_set(space, member, w_obj, w_value):
+        self = member
+        w_obj.slots_w[self.index] = w_value # xxx typecheck
+
+    def descr_member_del(space, member, w_obj):
+        self = member
+        w_obj.slots_w[self.index] = None # xxx typecheck
+
+Member.typedef = TypeDef(
+    "Member",
+    __get__ = interp2app(Member.descr_member_get.im_func,
+                         unwrap_spec = [ObjSpace,
+                                        Member, W_Root, W_Root]),
+    __set__ = interp2app(Member.descr_member_set.im_func,
+                         unwrap_spec = [ObjSpace,
+                                        Member, W_Root, W_Root]),
+    __delete__ = interp2app(Member.descr_member_del.im_func,
+                            unwrap_spec = [ObjSpace,
+                                           Member, W_Root]),
+    )
 
 # ____________________________________________________________
 #
@@ -195,19 +256,14 @@
 from pypy.interpreter.nestedscope import Cell
 from pypy.interpreter.special import NotImplemented, Ellipsis
 
-def descr_get_dict(space, w_obj):
-    obj = space.interpclass_w(w_obj)
+def descr_get_dict(space, obj):
     w_dict = obj.getdict()
     assert w_dict is not None, repr(obj)
     return w_dict
 
-def descr_set_dict(space, w_obj, w_dict):
-    obj = space.interpclass_w(w_obj)
+def descr_set_dict(space, obj, w_dict):
     obj.setdict(w_dict)
 
-interp_dict_descr = GetSetProperty(descr_get_dict, descr_set_dict)
-
-
 # co_xxx interface emulation for built-in code objects
 def fget_co_varnames(space, w_code):
     code = space.interpclass_w(w_code)
@@ -232,48 +288,48 @@
     return space.newtuple([w_docstring])
 
 Code.typedef = TypeDef('internal-code',
-    co_name = interp_attrproperty('co_name'),
-    co_varnames = GetSetProperty(fget_co_varnames),
-    co_argcount = GetSetProperty(fget_co_argcount),
-    co_flags = GetSetProperty(fget_co_flags),
-    co_consts = GetSetProperty(fget_co_consts),
+    co_name = interp_attrproperty('co_name', cls=Code),
+    co_varnames = GetSetProperty(fget_co_varnames, cls=Code),
+    co_argcount = GetSetProperty(fget_co_argcount, cls=Code),
+    co_flags = GetSetProperty(fget_co_flags, cls=Code),
+    co_consts = GetSetProperty(fget_co_consts, cls=Code),
     )
 
 Frame.typedef = TypeDef('internal-frame',
-    f_code = interp_attrproperty('code'),
-    f_locals = GetSetProperty(Frame.fget_getdictscope.im_func),
-    f_globals = interp_attrproperty_w('w_globals'),
+    f_code = interp_attrproperty('code', cls=Frame),
+    f_locals = GetSetProperty(Frame.fget_getdictscope),
+    f_globals = interp_attrproperty_w('w_globals', cls=Frame),
     )
 
 PyCode.typedef = TypeDef('code',
     __new__ = interp2app(PyCode.descr_code__new__.im_func),
-    __eq__ = interp2app(PyCode.descr_code__eq__.im_func),
-    co_argcount = interp_attrproperty('co_argcount'),
-    co_nlocals = interp_attrproperty('co_nlocals'),
-    co_stacksize = interp_attrproperty('co_stacksize'),
-    co_flags = interp_attrproperty('co_flags'),
-    co_code = interp_attrproperty('co_code'),
+    __eq__ = interp2app(PyCode.descr_code__eq__),
+    co_argcount = interp_attrproperty('co_argcount', cls=PyCode),
+    co_nlocals = interp_attrproperty('co_nlocals', cls=PyCode),
+    co_stacksize = interp_attrproperty('co_stacksize', cls=PyCode),
+    co_flags = interp_attrproperty('co_flags', cls=PyCode),
+    co_code = interp_attrproperty('co_code', cls=PyCode),
     co_consts = GetSetProperty(PyCode.fget_co_consts),
     co_names = GetSetProperty(PyCode.fget_co_names),
-    co_varnames = interp_attrproperty('co_varnames'),
-    co_freevars = interp_attrproperty('co_freevars'),
-    co_cellvars = interp_attrproperty('co_cellvars'),
-    co_filename = interp_attrproperty('co_filename'),
-    co_name = interp_attrproperty('co_name'),
-    co_firstlineno = interp_attrproperty('co_firstlineno'),
-    co_lnotab = interp_attrproperty('co_lnotab'),
+    co_varnames = interp_attrproperty('co_varnames', cls=PyCode),
+    co_freevars = interp_attrproperty('co_freevars', cls=PyCode),
+    co_cellvars = interp_attrproperty('co_cellvars', cls=PyCode),
+    co_filename = interp_attrproperty('co_filename', cls=PyCode),
+    co_name = interp_attrproperty('co_name', cls=PyCode),
+    co_firstlineno = interp_attrproperty('co_firstlineno', cls=PyCode),
+    co_lnotab = interp_attrproperty('co_lnotab', cls=PyCode),
     )
 
 PyFrame.typedef = TypeDef('frame',
-    f_builtins = interp_attrproperty_w('w_builtins'),
-    f_lineno = GetSetProperty(PyFrame.fget_f_lineno.im_func),
+    f_builtins = GetSetProperty(PyFrame.fget_f_builtins),
+    f_lineno = GetSetProperty(PyFrame.fget_f_lineno),
     **Frame.typedef.rawdict)
 
 Module.typedef = TypeDef("module",
-    __new__ = interp2app(Module.descr_module__new__.im_func),
-    __init__ = interp2app(Module.descr_module__init__.im_func),
-    __dict__ = GetSetProperty(descr_get_dict), # module dictionaries are readonly attributes
-    __getattr__ = interp2app(Module.descr_module__getattr__.im_func),
+    __new__ = interp2app(Module.descr_module__new__.im_func,
+                         unwrap_spec=[ObjSpace, W_Root, Arguments]),
+    __init__ = interp2app(Module.descr_module__init__),
+    __dict__ = GetSetProperty(descr_get_dict, cls=Module), # module dictionaries are readonly attributes
     )
 
 getset_func_doc = GetSetProperty(Function.fget_func_doc,
@@ -295,20 +351,21 @@
 getset_func_code = GetSetProperty(Function.fget_func_code,
                                   Function.fset_func_code)
 
-getset_func_dict = GetSetProperty(descr_get_dict, descr_set_dict)
+getset_func_dict = GetSetProperty(descr_get_dict, descr_set_dict, cls=Function)
 
 Function.typedef = TypeDef("function",
-    __call__ = interp2app(Function.descr_function_call.im_func),
-    __get__ = interp2app(Function.descr_function_get.im_func),
+    __call__ = interp2app(Function.descr_function_call,
+                          unwrap_spec=['self', Arguments]),
+    __get__ = interp2app(Function.descr_function_get),
     func_code = getset_func_code, 
     func_doc = getset_func_doc,
-    func_name = interp_attrproperty('name'), 
+    func_name = interp_attrproperty('name', cls=Function), 
     func_dict = getset_func_dict, 
     func_defaults = getset_func_defaults,
-    func_globals = interp_attrproperty_w('w_func_globals'),
+    func_globals = interp_attrproperty_w('w_func_globals', cls=Function),
     func_closure = GetSetProperty( Function.fget_func_closure ),
     __doc__ = getset_func_doc,
-    __name__ = interp_attrproperty('name'),
+    __name__ = interp_attrproperty('name', cls=Function),
     __dict__ = getset_func_dict,
     __module__ = getset___module__,
     # XXX func_closure, etc.pp
@@ -316,42 +373,43 @@
 
 Method.typedef = TypeDef("method",
     __new__ = interp2app(Method.descr_method__new__.im_func),
-    __call__ = interp2app(Method.descr_method_call.im_func),
-    __get__ = interp2app(Method.descr_method_get.im_func),
-    im_func  = interp_attrproperty_w('w_function'), 
-    im_self  = interp_attrproperty_w('w_instance'), 
-    im_class = interp_attrproperty_w('w_class'),
-    __getattribute__ = interp2app(Method.descr_method_getattribute.im_func),
+    __call__ = interp2app(Method.descr_method_call,
+                          unwrap_spec=['self', Arguments]),
+    __get__ = interp2app(Method.descr_method_get),
+    im_func  = interp_attrproperty_w('w_function', cls=Method), 
+    im_self  = interp_attrproperty_w('w_instance', cls=Method), 
+    im_class = interp_attrproperty_w('w_class', cls=Method),
+    __getattribute__ = interp2app(Method.descr_method_getattribute),
     # XXX getattribute/setattribute etc.pp 
     )
 
 StaticMethod.typedef = TypeDef("staticmethod",
-    __get__ = interp2app(StaticMethod.descr_staticmethod_get.im_func),
+    __get__ = interp2app(StaticMethod.descr_staticmethod_get),
     # XXX getattribute etc.pp
     )
 
 PyTraceback.typedef = TypeDef("traceback",
-    tb_frame  = interp_attrproperty('frame'),
-    tb_lasti  = interp_attrproperty('lasti'),
-    tb_lineno = interp_attrproperty('lineno'),
-    tb_next   = interp_attrproperty('next'),
+    tb_frame  = interp_attrproperty('frame', cls=PyTraceback),
+    tb_lasti  = interp_attrproperty('lasti', cls=PyTraceback),
+    tb_lineno = interp_attrproperty('lineno', cls=PyTraceback),
+    tb_next   = interp_attrproperty('next', cls=PyTraceback),
     )
 
 GeneratorIterator.typedef = TypeDef("generator",
-    next       = interp2app(GeneratorIterator.descr_next.im_func),
-    __iter__   = interp2app(GeneratorIterator.descr__iter__.im_func),
-    gi_running = interp_attrproperty('running'), 
-    gi_frame   = interp_attrproperty('frame'), 
+    next       = interp2app(GeneratorIterator.descr_next),
+    __iter__   = interp2app(GeneratorIterator.descr__iter__),
+    gi_running = interp_attrproperty('running', cls=GeneratorIterator), 
+    gi_frame   = interp_attrproperty('frame', cls=GeneratorIterator), 
 )
 
 Cell.typedef = TypeDef("cell")
 
 Ellipsis.typedef = TypeDef("Ellipsis", 
-    __repr__   = interp2app(Ellipsis.descr__repr__.im_func),
+    __repr__   = interp2app(Ellipsis.descr__repr__),
 )
 
 NotImplemented.typedef = TypeDef("NotImplemented", 
-    __repr__   = interp2app(NotImplemented.descr__repr__.im_func), 
+    __repr__   = interp2app(NotImplemented.descr__repr__), 
 )
 
 ControlFlowException.typedef = TypeDef("ControlFlowException")

Deleted: /pypy/dist/pypy/module/__builtin__interp.py
==============================================================================
--- /pypy/dist/pypy/module/__builtin__interp.py	Sat Feb 19 15:30:45 2005
+++ (empty file)
@@ -1,336 +0,0 @@
-"""
-Implementation of interpreter-level builtins.
-"""
-from pypy.interpreter.module import Module
-from pypy.interpreter.pycode import PyCode
-from pypy.interpreter.error import OperationError
-from pypy.interpreter.baseobjspace import BaseWrappable, W_Root
-from pypy.interpreter.gateway import NoneNotWrapped
-
-import __builtin__ as cpy_builtin
-
-# import useful app-level functions
-from __applevel__ import execfile, callable, _iter_generator
-
-
-def _actframe(position=0):
-    return space.getexecutioncontext().framestack.top(position)
-
-def globals():
-    return _actframe().w_globals
-
-def locals():
-    return _actframe().getdictscope()
-
-def _caller_globals(position=1):
-    return _actframe(position).w_globals
-#
-_caller_globals.unwrap_spec = [int]
-
-def _caller_locals(position=1):
-    return _actframe(position).getdictscope()
-#
-_caller_locals.unwrap_spec = [int]
-
-
-def try_import_mod(w_modulename, f, w_parent, w_name, pkgdir=None):
-    import os
-    w = space.wrap
-    if os.path.exists(f):
-        w_mod = space.wrap(Module(space, w_modulename))
-        space.sys.setmodule(w_mod)
-        space.setattr(w_mod, w('__file__'), w(f))
-        if pkgdir is not None:
-            space.setattr(w_mod, w('__path__'), space.newlist([w(pkgdir)]))
-        w_dict = space.getattr(w_mod, w('__dict__'))
-        execfile(w(f), w_dict, w_dict)
-        w_mod = check_sys_modules(w_modulename)
-        if w_mod is not None and w_parent is not None:
-            space.setattr(w_parent, w_name, w_mod)
-        return w_mod
-    else:
-        return None
-
-def try_getattr(w_obj,w_name):
-    try:
-        return space.getattr(w_obj, w_name)
-    except OperationError, e:
-        # ugh, but blame CPython :-/ this is supposed to emulate
-        # hasattr, which eats all exceptions.
-        return None
-
-def try_getitem(w_obj,w_key):
-    try:
-        return space.getitem(w_obj, w_key)
-    except OperationError, e:
-        if not e.match(space, space.w_KeyError):
-            raise
-        return None
-
-
-def check_sys_modules(w_modulename):
-    try:
-        w_mod = space.getitem(space.sys.w_modules, w_modulename)
-    except OperationError, e:
-        pass
-    else:
-        return w_mod
-    if not e.match(space, space.w_KeyError):
-        raise
-    return None
-
-il_len = len
-
-def __import__(modulename, w_globals=None,
-               w_locals=None, w_fromlist=None):
-    if not isinstance(modulename, str):
-        try:
-            helper = ', not ' + modulename.__class__.__name__
-        except AttributeError:
-            helper = ''
-        raise OperationError(space.w_TypeError,
-              space.wrap("__import__() argument 1 must be string" + helper))
-    w = space.wrap
-
-    if w_globals is not None and not space.is_true(space.is_(w_globals, space.w_None)):
-        ctxt_w_name = try_getitem(w_globals,w('__name__'))
-        ctxt_w_path = try_getitem(w_globals,w('__path__'))
-    else:
-        ctxt_w_name = None
-        ctxt_w_path = None
-
-    rel_modulename = None
-    if ctxt_w_name is not None:
-
-        ctxt_name_prefix_parts = space.str_w(ctxt_w_name).split('.')
-        if ctxt_w_path is None: # context is a plain module
-            ctxt_name_prefix_parts = ctxt_name_prefix_parts[:-1]
-            if ctxt_name_prefix_parts:
-                rel_modulename = '.'.join(ctxt_name_prefix_parts+[modulename])
-        else: # context is a package module
-            rel_modulename = space.str_w(ctxt_w_name)+'.'+modulename
-        if rel_modulename is not None:
-            w_mod = check_sys_modules(w(rel_modulename))
-            if (w_mod is None or
-                not space.is_true(space.is_(w_mod,space.w_None))):
-                
-                w_mod = absolute_import(rel_modulename,
-                                        il_len(ctxt_name_prefix_parts),
-                                        w_fromlist, tentative=1)
-                if w_mod is not None:
-                    return w_mod
-            else:
-                rel_modulename = None
-
-    w_mod = absolute_import(modulename,0,w_fromlist, tentative=0)
-    if rel_modulename is not None:
-        space.setitem(space.sys.w_modules, w(rel_modulename),space.w_None)
-    return w_mod
-#
-__import__.unwrap_spec = [str,W_Root,W_Root,W_Root]
-
-def absolute_import(modulename, baselevel, w_fromlist, tentative):
-    w = space.wrap
-    
-    w_mod = None
-    parts = modulename.split('.')
-    prefix = []
-    # it would be nice if we could do here: w_path = space.sys.w_path
-    # instead:
-    w_path = space.getitem(space.sys.w_dict, space.wrap('path'))
-
-    first = None
-    level = 0
-
-    for part in parts:
-        w_mod = load_part(w_path, prefix, part, w_mod, tentative=tentative)
-        if w_mod is None:
-            return None
-
-        if baselevel == level:
-            first = w_mod
-            tentative = 0
-        prefix.append(part)
-        w_path = try_getattr(w_mod,w('__path__'))
-        level += 1
-
-    if w_fromlist is not None and space.is_true(w_fromlist):
-        if w_path is not None:
-            for w_name in space.unpackiterable(w_fromlist):
-                load_part(w_path, prefix, space.str_w(w_name), w_mod,
-                          tentative=1)
-        return w_mod
-    else:
-        return first
-
-def load_part(w_path, prefix, partname, w_parent, tentative):
-    w = space.wrap
-    modulename = '.'.join(prefix+[partname])
-    w_modulename = w(modulename)
-    w_mod = check_sys_modules(w_modulename)
-    if w_mod is not None:
-        if not space.is_true(space.is_(w_mod,space.w_None)):
-            return w_mod
-    else:
-        w_mod = space.get_builtin_module(modulename)
-        if w_mod is not None:
-            return w_mod
-        import os
-        for path in space.unpackiterable(w_path):
-            dir = os.path.join(space.str_w(path), partname)
-            if os.path.isdir(dir):
-                f = os.path.join(dir,'__init__.py')
-                w_mod = try_import_mod(w_modulename, f, w_parent, w(partname),
-                                       pkgdir=dir)
-                if w_mod is not None:
-                    return w_mod
-            f = os.path.join(space.str_w(path), partname + '.py')
-            w_mod = try_import_mod(w_modulename, f, w_parent, w(partname))
-            if w_mod is not None:
-                return w_mod
-
-    if tentative:
-        return None
-    else:
-        # ImportError
-        w_failing = w_modulename
-        w_exc = space.call_function(space.w_ImportError, w_failing)
-        raise OperationError(space.w_ImportError, w_exc)
-
-def compile(w_str_, filename, startstr,
-            supplied_flags=0, dont_inherit=0):
-    if space.is_true(space.isinstance(w_str_, space.w_unicode)):
-        str_ = space.unwrap(w_str_) # xxx generic unwrap
-    else:
-        str_ = space.str_w(w_str_)
-    #print (str_, filename, startstr, supplied_flags, dont_inherit)
-    # XXX we additionally allow GENERATORS because compiling some builtins
-    #     requires it. doesn't feel quite right to do that here.
-    supplied_flags |= 4096 
-    if not dont_inherit:
-        try:
-            frame = _actframe()
-        except IndexError:
-            pass
-        else:
-            supplied_flags |= frame.get_compile_flags()
-    try:
-        c = cpy_builtin.compile(str_, filename, startstr, supplied_flags, 1)
-    # It would be nice to propagate all exceptions to app level,
-    # but here we only propagate the 'usual' ones, until we figure
-    # out how to do it generically.
-    except SyntaxError,e:
-        raise OperationError(space.w_SyntaxError,space.wrap(str(e)))
-    except ValueError,e:
-        raise OperationError(space.w_ValueError,space.wrap(str(e)))
-    except TypeError,e:
-        raise OperationError(space.w_TypeError,space.wrap(str(e)))
-    return space.wrap(PyCode(space)._from_code(c))
-#
-compile.unwrap_spec = [W_Root,str,str,int,int]
-
-
-def eval(w_source, w_globals=NoneNotWrapped, w_locals=NoneNotWrapped):
-    w = space.wrap
-
-    if (space.is_true(space.isinstance(w_source, space.w_str)) or
-        space.is_true(space.isinstance(w_source, space.w_unicode))):
-        w_codeobj = compile(space.call_method(w_source, 'lstrip', space.wrap(' \t')), "<string>", "eval")
-    elif isinstance(space.interpclass_w(w_source), PyCode):
-        w_codeobj = w_source
-    else:
-        raise OperationError(space.w_TypeError,
-              w('eval() arg 1 must be a string or code object'))
-
-    if w_globals is None:
-        w_globals = globals()
-        w_locals = locals()
-    elif w_locals is None:
-        w_locals = w_globals
-
-    return space.interpclass_w(w_codeobj).exec_code(space, w_globals, w_locals)
-
-def abs(w_val):
-    "abs(number) -> number\n\nReturn the absolute value of the argument."
-    return space.abs(w_val)
-
-def chr(w_ascii):
-    w_character = space.newstring([w_ascii])
-    return w_character
-
-def len(w_obj):
-    return space.len(w_obj)
-
-def delattr(w_object, w_name):
-    space.delattr(w_object, w_name)
-    return space.w_None
-
-def getattr(w_object, w_name, w_defvalue=NoneNotWrapped):
-    if space.is_true(space.isinstance(w_name, space.w_unicode)): # xxx collect this logic somewhere
-        w_name = space.call_method(w_name, 'encode')
-    try:
-        return space.getattr(w_object, w_name)
-    except OperationError, e:
-        if e.match(space, space.w_AttributeError):
-            if w_defvalue is not None:
-                return w_defvalue
-        raise
-
-def hash(w_object):
-    return space.hash(w_object)
-
-def oct(w_val):
-    # XXX does this need to be a space operation?
-    return space.oct(w_val)
-
-def hex(w_val):
-    return space.hex(w_val)
-
-def round(w_val, w_n=0):
-    return space.round(w_val, w_n)
-
-def id(w_object):
-    return space.id(w_object)
-
-def cmp(w_x, w_y):
-    """return 0 when x == y, -1 when x < y and 1 when x > y """
-    return space.cmp(w_x, w_y)
-
-def coerce(w_x, w_y):
-    """coerce(x, y) -> (x1, y1)
-
-    Return a tuple consisting of the two numeric arguments converted to
-    a common type, using the same rules as used by arithmetic operations.
-    If coercion is not possible, raise TypeError."""
-    return space.coerce(w_x, w_y)
-
-
-#XXX works only for new-style classes.
-#So we have to fix it, when we add support for old-style classes
-def _issubtype(w_cls1, w_cls2):
-    return space.issubtype(w_cls1, w_cls2)
-
-def iter(w_collection_or_callable, w_sentinel=NoneNotWrapped):
-    if w_sentinel is None:
-        return space.iter(w_collection_or_callable)
-    else:
-        if not space.is_true(callable(w_collection_or_callable)):
-            raise OperationError(space.w_TypeError,
-                    space.wrap('iter(v, w): w must be callable'))
-        return _iter_generator(w_collection_or_callable, w_sentinel)
-
-def _seqiter(w_obj):
-    return space.newseqiter(w_obj)
-
-def ord(w_val):
-    return space.ord(w_val)
-
-def pow(w_base, w_exponent, w_modulus=None):
-    return space.pow(w_base, w_exponent, w_modulus)
-
-def repr(w_object):
-    return space.repr(w_object)
-
-def setattr(w_object, w_name, w_val):
-    space.setattr(w_object, w_name, w_val)
-    return space.w_None

Deleted: /pypy/dist/pypy/module/__builtin__module.py
==============================================================================
--- /pypy/dist/pypy/module/__builtin__module.py	Sat Feb 19 15:30:45 2005
+++ (empty file)
@@ -1,1049 +0,0 @@
-"""Built-in functions, exceptions, and other objects.
-
-Noteworthy: None is the `nil' object; Ellipsis represents `...' in slices.
-"""
-
-__builtins__['None']       = __interplevel__eval('space.w_None')
-__builtins__['False']      = __interplevel__eval('space.w_False')
-__builtins__['True']       = __interplevel__eval('space.w_True')
-__builtins__['type']       = __interplevel__eval('space.w_type')
-__builtins__['__debug__']  = True
-
-object = __interplevel__eval('space.w_object')
-# XXX these are faked:
-unicode = __interplevel__eval('space.wrap(unicode)')
-file = __interplevel__eval('space.wrap(file)')
-open = file
-
-# old-style classes dummy support
-__builtins__['_classobj'] = __interplevel__eval('space.w_classobj')
-__builtins__['_instance'] = __interplevel__eval('space.w_instance')
-
-
-# TODO Fix this later to show Ctrl-D on Unix
-quit = exit = "Use Ctrl-Z (i.e. EOF) to exit."
-
-def execfile(filename, glob=None, loc=None):
-    if glob is None:
-        glob = _caller_globals()
-        if loc is None:
-            loc = _caller_locals()
-    elif loc is None:
-        loc = glob
-    f = file(filename)
-    try:
-        source = f.read()
-    finally:
-        f.close()
-    #Don't exec the source directly, as this loses the filename info
-    co = compile(source, filename, 'exec')
-    exec co in glob, loc
-
-def raw_input(prompt=None):
-    import sys
-    try:
-        sys.stdin
-    except AttributeError:
-        raise RuntimeError("[raw_]input: lost sys.stdin");
-    try:
-        sys.stdout
-    except AttributeError:
-        raise RuntimeError("[raw_]input: lost sys.stdout");
-    if prompt is not None:
-        sys.stdout.write(prompt)
-        try:
-            flush = sys.stdout.flush
-        except AttributeError:
-            pass
-        else:
-            flush()
-    line = sys.stdin.readline()
-    if not line:    # inputting an empty line gives line == '\n'
-        raise EOFError
-    if line[-1] == '\n':
-        return line[:-1]
-    return line
-
-def input(prompt=None):
-    return eval(raw_input(prompt))
-
-
-def sum(sequence, total=0):
-    # must forbid "summing" strings, per specs of built-in 'sum'
-    if isinstance(total, str): raise TypeError
-    for item in sequence:
-        total = total + item
-    return total
-
-def _iter_generator(callable_, sentinel):
-    """ This generator implements the __iter__(callable,sentinel) protocol """
-    while 1:
-        result = callable_()
-        if result == sentinel:
-            return
-        yield result
-
-
-def apply(function, args, kwds={}):
-    """call a function (or other callable object) and return its result"""
-    return function(*args, **kwds)
-
-def map(function, *collections):
-    """does 3 separate things, hence this enormous docstring.
-       1.  if function is None, return a list of tuples, each with one
-           item from each collection.  If the collections have different
-           lengths,  shorter ones are padded with None.
-
-       2.  if function is not None, and there is only one collection,
-           apply function to every item in the collection and return a
-           list of the results.
-
-       3.  if function is not None, and there are several collections,
-           repeatedly call the function with one argument from each
-           collection.  If the collections have different lengths,
-           shorter ones are padded with None
-    """
-
-    if len(collections) == 0:
-        raise TypeError, "map() requires at least one sequence"
-
-    if len(collections) == 1:
-        #it's the most common case, so make it faster
-        if function is None:
-            return list(collections[0])
-        return [function(x) for x in collections[0]]
-
-    iterators = [ iter(collection) for collection in collections ]
-    res = []
-    while 1:
-        cont = False     #is any collection not empty?
-        args = []
-        for iterator in iterators:
-            try:
-                elem = iterator.next()
-                cont = True
-            except StopIteration:
-                elem = None
-            args.append(elem)
-        if cont:
-            if function is None:
-                res.append(tuple(args))
-            else:
-                res.append(function(*args))
-        else:
-            return res
-
-def filter(function, collection):
-    """construct a list of those elements of collection for which function
-       is True.  If function is None, then return the items in the sequence
-       which are True."""
-    str_type = None
-    if isinstance(collection, str):
-        str_type = str
-    elif isinstance(collection, unicode):
-        str_type = unicode
-
-    if str_type is not None:
-        if function is None and type(collection) is str_type:
-            return collection
-        res = []
-        for i in xrange(len(collection)):
-            c = collection[i]
-            if function is None or function(c):
-                if not isinstance(c, str_type):
-                    raise TypeError("can't filter %s to %s: __getitem__ returned different type", str_type.__name__, str_type.__name__)
-                res.append(c)
-        return str_type().join(res)
-        
-    if function is None:
-        res = [item for item in collection if item]
-    else:
-        res = [item for item in collection if function(item)]
-
-    if isinstance(collection, tuple):
-       return tuple(res)
-    else:
-       return res
-
-def zip(*collections):
-    """return a list of tuples, where the nth tuple contains every
-       nth item of each collection.  If the collections have different
-       lengths, zip returns a list as long as the shortest collection,
-       ignoring the trailing items in the other collections."""
-
-    if len(collections) == 0:
-        import sys
-        if sys.version_info < (2,4):
-            raise TypeError("zip() requires at least one sequence")
-        return []
-    res = []
-    iterators = [ iter(collection) for collection in collections ]
-    while 1:
-        try:
-            elems = []
-            for iterator in iterators:
-                elems.append(iterator.next())
-            res.append(tuple(elems))
-        except StopIteration:
-            return res
-
-def reduce(function, seq, *initialt):
-    """ Apply function of two arguments cumulatively to the items of
-        sequence, from left to right, so as to reduce the sequence to a
-        single value.  Optionally begin with an initial value."""
-
-    seqiter = iter(seq)
-    if initialt:
-       initial, = initialt
-    else:
-       try:
-          initial = seqiter.next()
-       except StopIteration:
-          raise TypeError, "reduce() of empty sequence with no initial value"
-    while 1:
-        try:
-            arg = seqiter.next()
-        except StopIteration:
-            break
-        initial = function(initial, arg)
-
-    return initial
-
-def _recursive_issubclass(cls, klass_or_tuple):
-    if cls is klass_or_tuple:
-        return True
-    for base in cls.__bases__:
-        if _recursive_issubclass(base, klass_or_tuple):
-            return True
-    return False
-
-def issubclass(cls, klass_or_tuple):
-    if _issubtype(type(klass_or_tuple), tuple):
-        for klass in klass_or_tuple:
-            if issubclass(cls, klass):
-                return True
-        return False
-    try:
-        return _issubtype(cls, klass_or_tuple)
-    except TypeError:
-        if not hasattr(cls, '__bases__'):
-            raise TypeError, "arg 1 must be a class or type"
-        if not hasattr(klass_or_tuple, '__bases__'):
-            raise TypeError, "arg 2 must be a class or type or a tuple thereof"
-        return _recursive_issubclass(cls, klass_or_tuple)
-        
-
-def isinstance(obj, klass_or_tuple):
-    if issubclass(type(obj), klass_or_tuple):
-        return True
-    try:
-        objcls = obj.__class__
-    except AttributeError:
-        return False
-    else:
-        return objcls is not type(obj) and issubclass(objcls, klass_or_tuple)
-
-def range(x, y=None, step=1):
-    """ returns a list of integers in arithmetic position from start (defaults
-        to zero) to stop - 1 by step (defaults to 1).  Use a negative step to
-        get a list in decending order."""
-
-
-    if y is None: 
-            start = 0
-            stop = x
-    else:
-            start = x
-            stop = y
-
-    if not isinstance(start, (int, long)):
-        raise TypeError('range() interger start argument expected, got %s' % type(start))
-    if not isinstance(stop, (int, long)):
-        raise TypeError('range() interger stop argument expected, got %s' % type(stop))
-    if not isinstance(step, (int, long)):
-        raise TypeError('range() interger step argument expected, got %s' % type(step))
-
-    if step == 0:
-        raise ValueError, 'range() arg 3 must not be zero'
-
-    elif step > 0:
-        if stop <= start: # no work for us
-            return []
-        howmany = (stop - start + step - 1)/step
-
-    else:  # step must be < 0, or we would have raised ValueError
-        if stop >= start: # no work for us
-            return []
-        howmany = (start - stop - step  - 1)/-step
-
-    arr = [None] * howmany  # this is to avoid using append.
-
-    i = start
-    n = 0
-    while n < howmany:
-        arr[n] = i
-        i += step
-        n += 1
-
-    return arr
-
-# min and max could be one function if we had operator.__gt__ and
-# operator.__lt__  Perhaps later when we have operator.
-
-def min(*arr):
-    """return the smallest number in a list"""
-
-    if not arr:
-        raise TypeError, 'min() takes at least one argument'
-
-    if len(arr) == 1:
-        arr = arr[0]
-
-    iterator = iter(arr)
-    try:
-        min = iterator.next()
-    except StopIteration:
-        raise ValueError, 'min() arg is an empty sequence'
-
-    for i in iterator:
-        if min > i:
-            min = i
-    return min
-
-def max(*arr):
-    """return the largest number in a list"""
-
-    if not arr:
-        raise TypeError, 'max() takes at least one argument'
-
-    if len(arr) == 1:
-        arr = arr[0]
-
-    iterator = iter(arr)
-    try:
-        max = iterator.next()
-    except StopIteration:
-        raise ValueError, 'max() arg is an empty sequence'
-
-    for i in iterator:
-        if max < i:
-            max = i
-    return max
-
-def divmod(x, y):
-    return x//y, x%y
-
-def vars(*obj):
-    """return a dictionary of all the attributes currently bound in obj.  If
-    called with no argument, return the variables bound in local scope."""
-
-    if len(obj) == 0:
-        return _caller_locals()
-    elif len(obj) != 1:
-        raise TypeError, "vars() takes at most 1 argument."
-    else:
-        try:
-            return obj[0].__dict__
-        except AttributeError:
-            raise TypeError, "vars() argument must have __dict__ attribute"
-
-def hasattr(ob, attr):
-    try:
-        getattr(ob, attr)
-        return True
-    except AttributeError:
-        return False
-
-def callable(ob):
-    for c in type(ob).__mro__:
-        if '__call__' in c.__dict__:
-            return True
-    else:
-        return False
-
-def dir(*args):
-    """dir([object]) -> list of strings
-
-    Return an alphabetized list of names comprising (some of) the attributes
-    of the given object, and of attributes reachable from it:
-
-    No argument:  the names in the current scope.
-    Module object:  the module attributes.
-    Type or class object:  its attributes, and recursively the attributes of
-        its bases.
-    Otherwise:  its attributes, its class's attributes, and recursively the
-        attributes of its class's base classes.
-    """
-    if len(args) > 1:
-        raise TypeError("dir expected at most 1 arguments, got %d"
-                        % len(args))
-    if len(args) == 0:
-        local_names = _caller_locals().keys() # 2 stackframes away
-        local_names.sort()
-        return local_names
-
-    import types
-    def _classdir(klass):
-        """Return a dict of the accessible attributes of class/type klass.
-
-        This includes all attributes of klass and all of the
-        base classes recursively.
-
-        The values of this dict have no meaning - only the keys have
-        meaning.  
-        """
-        Dict = {}
-        try:
-            Dict.update(klass.__dict__)
-        except AttributeError: pass 
-        try:
-            # XXX - Use of .__mro__ would be suggested, if the existance
-            #   of that attribute could be guarranted.
-            bases = klass.__bases__
-        except AttributeError: pass
-        else:
-            try:
-                #Note that since we are only interested in the keys,
-                #  the order we merge classes is unimportant
-                for base in bases:
-                    Dict.update(_classdir(base))
-            except TypeError: pass
-        return Dict
-    #End _classdir
-
-    obj = args[0]
-
-    if isinstance(obj, types.ModuleType):
-        try:
-            result = obj.__dict__.keys()
-            result.sort()
-            return result
-        except AttributeError:
-            return []
-
-    elif isinstance(obj, (types.TypeType, types.ClassType)):
-        #Don't look at __class__, as metaclass methods would be confusing.
-        result = _classdir(obj).keys()
-        result.sort()
-        return result
-
-    else: #(regular item)
-        Dict = {}
-        try:
-            Dict.update(obj.__dict__)
-        except AttributeError: pass
-        try:
-            Dict.update(_classdir(obj.__class__))
-        except AttributeError: pass
-
-        ## Comment from object.c:
-        ## /* Merge in __members__ and __methods__ (if any).
-        ## XXX Would like this to go away someday; for now, it's
-        ## XXX needed to get at im_self etc of method objects. */
-        for attr in ['__members__','__methods__']:
-            try:
-                for item in getattr(obj, attr):
-                    if isinstance(item, types.StringTypes):
-                        Dict[item] = None
-            except (AttributeError, TypeError): pass
-
-        result = Dict.keys()
-        result.sort()
-        return result
-
-_stringtable = {}
-def intern(s):
-    # XXX CPython has also non-immortal interned strings
-    if not isinstance(s, str):
-        raise TypeError("intern() argument 1 must be string.")
-    return _stringtable.setdefault(s,s)
-
-def copyright():
-    print 'Copyright 2003-2004 Pypy development team.\nAll rights reserved.\nFor further information see http://www.codespaek.net/pypy.\nSome materials may have a different copyright.\nIn these cases, this is explicitly noted in the source code file.'
-
-def license():
-    print \
-"""
-Copyright (c) <2003-2004> <Pypy development team>
-
-Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
-
-The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
-
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-"""
-
-def help():
-    print "You must be joking."
-
-def unichr(code):
-    import sys
-    if (code < 0 or code > sys.maxunicode):
-        raise ValueError('unichr() arg not in range(%#x)'%(sys.maxunicode + 1))
-    return unicode('\\U%08x' %(code), 'unicode-escape')
-# ______________________________________________________________________
-#
-#   Interpreter-level function definitions
-#
-
-__interplevel__execfile('__builtin__interp.py')
-
-from __interplevel__ import abs, chr, len, ord, pow, repr
-from __interplevel__ import hash, oct, hex, round, cmp, coerce
-from __interplevel__ import getattr, setattr, delattr, iter, hash, id
-from __interplevel__ import _issubtype, _seqiter
-from __interplevel__ import compile, eval
-from __interplevel__ import globals, locals, _caller_globals, _caller_locals
-
-# The following must be the last import from __interplevel__ because it
-# overwrites the special __import__ hook with the normal one.
-
-from __interplevel__ import __import__
-
-
-# ________________________________________________________________________
-def enumerate(collection):
-    'Generates an indexed series:  (0,coll[0]), (1,coll[1]) ...'
-    it = iter(collection)   # raises a TypeError early
-    def do_enumerate(it):
-        index = 0
-        for value in it:
-            yield index, value
-            index += 1
-    return do_enumerate(it)
-
-class xrange(object):
-    def __init__(self, start, stop=None, step=1):
-        if not isinstance(start, (int, long, float)):
-            raise TypeError('an integer is required')
-        start = int(start)
-        if stop is None:
-            self.start = 0
-            self.stop = start
-        else:
-            if not isinstance(stop, (int, long, float)):
-                raise TypeError('an integer is required')
-            stop = int(stop)
-            self.start = start
-            self.stop = stop
-        if not isinstance(step, (int, long, float)):
-            raise TypeError('an integer is required')
-        step = int(step)
-        if step == 0:
-            raise ValueError, 'xrange() step-argument (arg 3) must not be zero'
-        self.step = step
-
-    def __len__(self):
-        if not hasattr(self, '_len'):
-            slicelength = self.stop - self.start
-            lengthsign = cmp(slicelength, 0)
-            stepsign = cmp(self.step, 0)
-            if stepsign == lengthsign:
-                self._len = (slicelength - lengthsign) // self.step + 1
-            else:
-                self._len = 0
-        return self._len
-
-    def __getitem__(self, index):
-        # xrange does NOT support slicing
-        if not isinstance(index, int):
-            raise TypeError, "sequence index must be integer"
-        len = self.__len__()
-        if index<0:
-            index += len
-        if 0 <= index < len:
-            return self.start + index * self.step
-        raise IndexError, "xrange object index out of range"
-
-    def __iter__(self):
-        start, stop, step = self.start, self.stop, self.step
-        i = start
-        if step > 0:
-            while i < stop:
-                yield i
-                i+=step
-        else:
-            while i > stop:
-                yield i
-                i+=step
-
-
-# Descriptor code, shamelessly stolen to Raymond Hettinger:
-#    http://users.rcn.com/python/download/Descriptor.htm
-class property(object):
-
-    def __init__(self, fget=None, fset=None, fdel=None, doc=None):
-        self.fget = fget
-        self.fset = fset
-        self.fdel = fdel
-        self.__doc__ = doc or ""   # XXX why:  or ""  ?
-
-    def __get__(self, obj, objtype=None):
-        if obj is None:
-            return self         
-        if self.fget is None:
-            raise AttributeError, "unreadable attribute"
-        return self.fget(obj)
-
-    def __set__(self, obj, value):
-        if self.fset is None:
-            raise AttributeError, "can't set attribute"
-        self.fset(obj, value)
-
-    def __delete__(self, obj):
-        if self.fdel is None:
-            raise AttributeError, "can't delete attribute"
-        self.fdel(obj)
-
-
-# XXX there is an interp-level pypy.interpreter.function.StaticMethod
-# XXX because __new__ needs to be a StaticMethod early.
-class staticmethod(object):
-
-    def __init__(self, f):
-        self.f = f
-
-    def __get__(self, obj, objtype=None):
-        return self.f
-
-
-class classmethod(object):
-
-    def __init__(self, f):
-        self.f = f
-
-    def __get__(self, obj, klass=None):
-        if klass is None:
-            klass = type(obj)
-        def newfunc(*args, **kwargs):
-            return self.f(klass, *args, **kwargs)
-        return newfunc
-
-if not hasattr(dict, 'fromkeys'):
-    def _fromkeys(cls, seq, value=None):
-        r = cls()
-        for s in seq:
-            r[s] = value
-        return r
-
-    try:
-        dict.fromkeys = classmethod(_fromkeys)
-    except TypeError:
-        pass   # Python2.2 with trivial object space
-
-    del _fromkeys
-
-
-# super is a modified version from Guido's tutorial
-#     http://www.python.org/2.2.3/descrintro.html
-# it exposes the same special attributes as CPython's.
-class super(object):
-    def __init__(self, typ, obj=None):
-        if obj is None:
-            objcls = None        # unbound super object
-        elif _issubtype(type(obj), type) and _issubtype(obj, type):
-            objcls = obj         # special case for class methods
-        elif _issubtype(type(obj), typ):
-            objcls = type(obj)   # normal case
-        else:
-            objcls = getattr(obj, '__class__', type(obj))
-            if not _issubtype(objcls, typ):
-                raise TypeError, ("super(type, obj): "
-                                  "obj must be an instance or subtype of type")
-        self.__thisclass__ = typ
-        self.__self__ = obj
-        self.__self_class__ = objcls
-    def __get__(self, obj, type=None):
-        ga = object.__getattribute__
-        if ga(self, '__self__') is None and obj is not None:
-            return super(ga(self, '__thisclass__'), obj)
-        else:
-            return self
-    def __getattribute__(self, attr):
-        d = object.__getattribute__(self, '__dict__')
-        if attr != '__class__' and d['__self_class__'] is not None:
-            # we want super().__class__ to be the real class
-            # and we don't do anything for unbound type objects
-            mro = iter(d['__self_class__'].__mro__)
-            for cls in mro:
-                if cls is d['__thisclass__']:
-                    break
-            # Note: mro is an iterator, so the second loop
-            # picks up where the first one left off!
-            for cls in mro:
-                try:                
-                    x = cls.__dict__[attr]
-                except KeyError:
-                    continue
-                if hasattr(x, '__get__'):
-                    x = x.__get__(d['__self__'], type(d['__self__']))
-                return x
-        return object.__getattribute__(self, attr)     # fall-back
-    
-class complex(object):
-    """complex(real[, imag]) -> complex number
-
-    Create a complex number from a real part and an optional imaginary part.
-    This is equivalent to (real + imag*1j) where imag defaults to 0."""
-    PREC_REPR = 17
-    PREC_STR = 12
-
-    # XXX this class is not well tested
-
-    def __init__(self, real=0.0, imag=None):
-        if isinstance(real, str) and imag is not None:
-            msg = "complex() can't take second arg if first is a string"
-            raise TypeError, msg
-
-        if isinstance(imag, str): 
-            msg = "complex() second arg can't be a string"
-            raise TypeError, msg
-
-        if isinstance(real, str): 
-            real, imag = self._makeComplexFromString(real)
-            self.__dict__['real'] = real
-            self.__dict__['imag'] = imag
-        else:
-            if imag is None:
-               imag = 0.
-            self.__dict__['real'] = float(real)
-            self.__dict__['imag'] = float(imag)
-        
-
-    def __setattr__(self, name, value):
-        if name in ('real', 'imag'):
-            raise AttributeError, "readonly attribute"
-        else:
-            raise AttributeError, "'complex' object has no attribute %s" % name
-
-    def _makeComplexFromString(self, string):
-        import re
-        pat = re.compile(" *([\+\-]?\d*\.?\d*)([\+\-]?\d*\.?\d*)[jJ] *")
-        m = pat.match(string)
-        x, y = m.groups()
-        if len(y) == 1 and y in '+-':
-            y = y + '1.0'
-        x, y = map(float, [x, y])
-        return x, y
-
-
-    def __description(self, precision):
-        if self.real != 0.:
-            return "(%.*g%+.*gj)"%(precision, self.real, precision, self.imag)
-        else:
-            return "%.*gj"%(precision, self.imag)
-
-
-    def __repr__(self):
-        return self.__description(self.PREC_REPR)
-
-
-    def __str__(self):
-        return self.__description(self.PREC_STR)
-
-        
-    def __hash__(self):
-        hashreal = hash(self.real)
-        hashimag = hash(self.imag)
-
-        # Note:  if the imaginary part is 0, hashimag is 0 now,
-        # so the following returns hashreal unchanged.  This is
-        # important because numbers of different types that
-        # compare equal must have the same hash value, so that
-        # hash(x + 0*j) must equal hash(x).
-
-        return hashreal + 1000003 * hashimag
-
-
-    def __add__(self, other):
-        result = self.__coerce__(other)
-        if result is NotImplemented:
-            return result
-        self, other = result
-        real = self.real + other.real
-        imag = self.imag + other.imag
-        return complex(real, imag)
-
-    __radd__ = __add__
-
-    def __sub__(self, other):
-        result = self.__coerce__(other)
-        if result is NotImplemented:
-            return result
-        self, other = result
-        real = self.real - other.real
-        imag = self.imag - other.imag
-        return complex(real, imag)
-    
-    def __rsub__(self, other):
-        result = self.__coerce__(other)
-        if result is NotImplemented:
-            return result
-        self, other = result
-        return other.__sub__(self)
-
-    def __mul__(self, other):
-        result = self.__coerce__(other)
-        if result is NotImplemented:
-            return result
-        self, other = result
-        real = self.real*other.real - self.imag*other.imag
-        imag = self.real*other.imag + self.imag*other.real
-        return complex(real, imag)
-
-    __rmul__ = __mul__
-
-    def __div__(self, other):
-        result = self.__coerce__(other)
-        if result is NotImplemented:
-            return result
-        self, other = result
-        if abs(other.real) >= abs(other.imag):
-            # divide tops and bottom by other.real
-            try:
-                ratio = other.imag / other.real
-            except ZeroDivisionError:
-                raise ZeroDivisionError, "complex division"
-            denom = other.real + other.imag * ratio
-            real = (self.real + self.imag * ratio) / denom
-            imag = (self.imag - self.real * ratio) / denom
-        else:
-            # divide tops and bottom by other.imag
-            assert other.imag != 0.0
-            ratio = other.real / other.imag
-            denom = other.real * ratio + other.imag
-            real = (self.real * ratio + self.imag) / denom
-            imag = (self.imag * ratio - self.real) / denom
-
-        return complex(real, imag)
-
-    def __rdiv__(self, other):
-        result = self.__coerce__(other)
-        if result is NotImplemented:
-            return result
-        self, other = result
-        return other.__div__(self)
-
-    def __floordiv__(self, other):
-        result = self.__divmod__(other)
-        if result is NotImplemented:
-            return result
-        div, mod = result
-        return div
-
-    def __rfloordiv__(self, other):
-        result = self.__coerce__(other)
-        if result is NotImplemented:
-            return result
-        self, other = result
-        return other.__floordiv__(self)
-
-    __truediv__ = __div__
-    __rtruediv__ = __rdiv__
-
-    def __mod__(self, other):
-        result = self.__divmod__(other)
-        if result is NotImplemented:
-            return result
-        div, mod = result
-        return mod
-
-    def __rmod__(self, other):
-        result = self.__coerce__(other)
-        if result is NotImplemented:
-            return result
-        self, other = result
-        return other.__mod__(self)
-
-    def __divmod__(self, other):
-        result = self.__coerce__(other)
-        if result is NotImplemented:
-            return result
-        self, other = result
-
-        import warnings, math
-        warnings.warn("complex divmod(), // and % are deprecated", DeprecationWarning)
-
-        try:
-            div = self/other # The raw divisor value.
-        except ZeroDivisionError:
-            raise ZeroDivisionError, "complex remainder"
-        div = complex(math.floor(div.real), 0.0)
-        mod = self - div*other
-        return div, mod
-
-
-    def __pow__(self, other, mod=None):
-        if mod is not None:
-            raise ValueError("complex modulo")
-        result = self.__coerce__(other)
-        if result is NotImplemented:
-            return result
-        a, b = result
-        import math
-
-        if b.real == 0. and b.imag == 0.:
-            real = 1.
-            imag = 0.
-        elif a.real == 0. and a.imag == 0.:
-            real = 0.
-            imag = 0.
-        else:
-            vabs = math.hypot(a.real,a.imag)
-            len = math.pow(vabs,b.real)
-            at = math.atan2(a.imag, a.real)
-            phase = at*b.real
-            if b.imag != 0.0:
-                len /= math.exp(at*b.imag)
-                phase += b.imag*math.log(vabs)
-            real = len*math.cos(phase)
-            imag = len*math.sin(phase)
-
-        result = complex(real, imag)
-        return result
-
-    def __rpow__(self, other, mod=None):
-        result = self.__coerce__(other)
-        if result is NotImplemented:
-            return result
-        self, other = result
-        return other.__pow__(self, mod)
-
-    def __neg__(self):
-        return complex(-self.real, -self.imag)
-
-
-    def __pos__(self):
-        return complex(self.real, self.imag)
-
-
-    def __abs__(self):
-        import math
-        result = math.hypot(self.real, self.imag)
-        return float(result)
-
-
-    def __nonzero__(self):
-        return self.real != 0.0 or self.imag != 0.0
-
-
-    def __coerce__(self, other):
-        if isinstance(other, complex):
-            return self, other
-        if isinstance(other, (int, long, float)):
-            return self, complex(other)
-        return NotImplemented
-
-    def conjugate(self):
-        return complex(self.real, -self.imag)
-
-    def __eq__(self, other):
-        result = self.__coerce__(other)
-        if result is NotImplemented:
-            return result
-        self, other = result
-        return self.real == other.real and self.imag == other.imag
-
-    def __ne__(self, other):
-        result = self.__coerce__(other)
-        if result is NotImplemented:
-            return result
-        self, other = result
-        return self.real != other.real or self.imag != other.imag
-
-
-    # unsupported operations
-    
-    def __lt__(self, other):
-        raise TypeError, "cannot compare complex numbers using <, <=, >, >="
-
-        
-    def __le__(self, other):
-        raise TypeError, "cannot compare complex numbers using <, <=, >, >="
-
-        
-    def __gt__(self, other):
-        raise TypeError, "cannot compare complex numbers using <, <=, >, >="
-
-        
-    def __ge__(self, other):
-        raise TypeError, "cannot compare complex numbers using <, <=, >, >="
-
-
-    def __int__(self):
-        raise TypeError, "can't convert complex to int; use e.g. int(abs(z))"
-
-
-    def __long__(self):
-        raise TypeError, "can't convert complex to long; use e.g. long(abs(z))"
-
-
-    def __float__(self):
-        raise TypeError, "can't convert complex to float; use e.g. float(abs(z))"
-
-
-# ________________________________________________________________________
-
-class buffer(object):
-    def __init__(self, object, offset=None, size=None):
-        raise NotImplementedError, "XXX nobody needs this anyway"
-
-def sorted(lst, cmp=None, key=None, reverse=None):
-    "sorted(iterable, cmp=None, key=None, reverse=False) --> new sorted list"
-    sorted_lst = list(lst)
-    sorted_lst.sort(cmp, key, reverse)
-    return sorted_lst
-
-def reversed(iterable):
-    """reversed(sequence) -> reverse iterator over values of the sequence
-
-    Return a reverse iterator
-    """
-    if hasattr(iterable, '__reversed__'):
-        return iterable.__reversed__()
-    seq = list(iterable)
-    def reversed_gen(local_iterable):
-        len_iterable = len(local_iterable)
-        for index in range(len_iterable-1, -1, -1):
-            yield local_iterable[index]
-    return reversed_gen(seq)
-
-def reload(module):
-    import imp, sys, errno
-
-    if type(module) not in (type(imp), type(errno)):
-        raise TypeError("reload() argument must be module")
-
-    name = module.__name__
-    if module is not sys.modules[name]:
-        raise ImportError("reload(): module %.200s not in sys.modules" % name)
-
-    namepath = name.split('.')
-    subname = namepath[-1]
-    parent_name = '.'.join(namepath[:-1])
-    parent = None
-    path = None
-    if parent_name:
-        try:
-            parent = sys.modules[parent_name]
-        except KeyError:
-            raise ImportError("reload(): parent %.200s not in sys.modules" %
-                              parent_name)
-        path = parent.__path__
-
-    f, filename, description = imp.find_module(subname, path)
-    try:
-        new_module = imp.load_module(name, f, filename, description)
-    finally:
-        sys.modules[name] = module
-        if f is not None:
-            f.close()
-
-    return new_module
-
-#from _file import file
-#open = file
-
-#default __metaclass__
-# XXX can use _classobj when we have a working one integrated
-__metaclass__ = type

Deleted: /pypy/dist/pypy/module/sysinterp.py
==============================================================================
--- /pypy/dist/pypy/module/sysinterp.py	Sat Feb 19 15:30:45 2005
+++ (empty file)
@@ -1,202 +0,0 @@
-"""
-Implementation of interpreter-level 'sys' routines.
-"""
-#from pypy.interpreter.module import Module
-from pypy.interpreter.error import OperationError
-
-import sys as cpy_sys
-
-def hack_cpython_module(modname):
-    "NOT_RPYTHON. Steal a module from CPython."
-    cpy_module = __import__(modname, globals(), locals(), None)
-    return cpy_module
-##    # to build the dictionary of the module, we get all the objects
-##    # accessible as 'self.xxx'. Methods are bound.
-##    contents = []
-##    for name in cpy_module.__dict__:
-##        # ignore names in '_xyz'
-##        if not name.startswith('_') or name.endswith('_'):
-##            value = cpy_module.__dict__[name]
-##            contents.append((space.wrap(name), space.wrap(value)))
-##    w_contents = space.newdict(contents)
-##    return Module(space, space.wrap(modname), w_contents)
-
-# ____________________________________________________________
-#
-# List of built-in modules.
-# It should contain the name of all the files 'module/*module.py'.
-builtin_module_names = ['__builtin__', 'sys', 'exceptions'
-                        ]
-
-# Create the builtin_modules dictionary, mapping names to Module instances
-builtin_modules = {}
-for fn in builtin_module_names:
-    builtin_modules[fn] = None
-
-# The following built-in modules are not written in PyPy, so we
-# steal them from Python.
-for fn in ['posix', 'nt', 'os2', 'mac', 'ce', 'riscos',
-           'math', '_codecs', 'array',
-           '_random', '_sre', 'time', '_socket', 'errno',
-           'marshal', 'binascii', 'parser']:
-    if fn not in builtin_modules:
-        try:
-            builtin_modules[fn] = hack_cpython_module(fn)
-        except ImportError:
-            pass
-        else:
-            builtin_module_names.append(fn)
-
-# ____________________________________________________________
-#
-# Common data structures
-w_modules              = space.newdict([])
-w_warnoptions          = space.newlist([])
-w_argv                 = space.newlist([])
-builtin_module_names.sort()
-w_builtin_module_names = space.newtuple([space.wrap(fn)
-                                         for fn in builtin_module_names])
-
-# Initialize the default path
-import os
-from pypy.interpreter import autopath
-srcdir = os.path.dirname(autopath.pypydir)
-python_std_lib = os.path.normpath(
-        os.path.join(autopath.pypydir, os.pardir,'lib-python-2.3.4'))
-pypy_override_lib = os.path.join(autopath.pypydir, 'lib') 
-assert os.path.exists(python_std_lib) 
-del os, autopath # XXX for the translator. Something is very wrong around here.
-
-w_initialpath = space.newlist([space.wrap(''), 
-                       space.wrap(pypy_override_lib), 
-                       space.wrap(python_std_lib), 
-                       ] +
-                       [space.wrap(p) for p in cpy_sys.path if p!= srcdir])
-
-# XXX - Replace with appropriate PyPy version numbering
-w_platform   = space.wrap(cpy_sys.platform)
-w_maxint     = space.wrap(cpy_sys.maxint)
-w_byteorder  = space.wrap(cpy_sys.byteorder)
-w_exec_prefix = space.wrap(cpy_sys.exec_prefix)
-w_prefix = space.wrap(cpy_sys.prefix)
-w_maxunicode = space.wrap(cpy_sys.maxunicode)
-w_stdin  = space.wrap(cpy_sys.stdin)
-w_stdout = space.wrap(cpy_sys.stdout)
-w_stderr = space.wrap(cpy_sys.stderr)
-
-w_pypy_objspaceclass = space.wrap(space.__class__.__name__)
-
-# ____________________________________________________________
-
-def setmodule(w_module):
-    """ put a module into the modules dict """
-    w_name = space.getattr(w_module, space.wrap('__name__'))
-    space.setitem(w_modules, w_name, w_module)
-
-def setbuiltinmodule(w_module, name):
-    """ put a module into the modules builtin_modules dicts """
-    if builtin_modules[name] is None:
-        builtin_modules[name] = space.unwrap(w_module)
-    else:
-        assert builtin_modules[name] is space.unwrap(w_module), (
-            "trying to change the builtin-in module %r" % (name,))
-    space.setitem(w_modules, space.wrap(name), w_module)
-
-##def displayhook(w_x):
-##    w = space.wrap
-##    if not space.is_true(space.is_(w_x, space.w_None)):
-##        w_stdout = space.getattr(space.w_sys, space.wrap('stdout'))
-##        try:
-##            w_repr = space.repr(w_x)
-##        except OperationError:
-##            w_repr = space.wrap("! __repr__ raised an exception")
-##        w_repr = space.add(w_repr, space.wrap("\n"))
-##        space.call_method(w_stdout, 'write', 
-##        space.setitem(space.w_builtins, w('_'), w_x)
-
-def _getframe(w_depth=0):
-    depth = space.int_w(w_depth)
-    try:
-        f = space.getexecutioncontext().framestack.top(depth)
-    except IndexError:
-        raise OperationError(space.w_ValueError,
-                             space.wrap("call stack is not deep enough"))
-    except ValueError:
-        raise OperationError(space.w_ValueError,
-                             space.wrap("frame index must not be negative"))
-    return space.wrap(f)
-
-# directly from the C code in ceval.c, might be moved somewhere else.
-
-def setrecursionlimit(w_new_limit):
-    """setrecursionlimit(n)
-
-Set the maximum depth of the Python interpreter stack to n.  This
-limit prevents infinite recursion from causing an overflow of the C
-stack and crashing Python.  The highest possible limit is platform
-dependent."""
-    new_limit = space.int_w(w_new_limit)
-    if new_limit <= 0:
-        raise OperationError(space.w_ValueError,
-                             space.wrap("recursion limit must be positive"))
-    # global recursion_limit
-    # we need to do it without writing globals.
-    space.recursion_limit = new_limit
-
-def getrecursionlimit():
-    """getrecursionlimit()
-
-Return the current value of the recursion limit, the maximum depth
-of the Python interpreter stack.  This limit prevents infinite
-recursion from causing an overflow of the C stack and crashing Python."""
-
-    return space.newint(space.recursion_limit)
-
-checkinterval = 100
-
-def setcheckinterval(w_interval):
-    """setcheckinterval(n)
-
-Tell the Python interpreter to check for asynchronous events every
-n instructions.  This also affects how often thread switches occur."""
-
-    space.sys.checkinterval = space.int_w(w_interval)
-
-def getcheckinterval():
-    """getcheckinterval() -> current check interval; see setcheckinterval()."""
-    return space.newint(checkinterval)
-
-
-def exc_info():
-    operror = space.getexecutioncontext().sys_exc_info()
-    if operror is None:
-        return space.newtuple([space.w_None,space.w_None,space.w_None])
-    else:
-        return space.newtuple([operror.w_type,operror.w_value,
-                               space.wrap(operror.application_traceback)])
-
-def exc_clear():
-    operror = space.getexecutioncontext().sys_exc_info()
-    if operror is not None:
-        operror.clear(space)
-
-def pypy_getudir():
-    """NOT_RPYTHON"""
-    from pypy.tool.udir import udir
-    return space.wrap(str(udir))
-
-def getdefaultencoding():
-    """getdefaultencoding() -> return the default encoding used for UNICODE"""
-    return space.wrap(cpy_sys.getdefaultencoding())
-
-def getrefcount(w_obj):
-    """getrefcount(object) -> integer
-
-Return the reference count of object.  The count returned is generally
-one higher than you might expect, because it includes the (temporary)
-reference as an argument to getrefcount().
-"""
-    # From the results i get when using this i need to apply a fudge
-    # value of 6 to get results comparable to cpythons. /Arre
-    return space.wrap(cpy_sys.getrefcount(w_obj) - 6)
-

Deleted: /pypy/dist/pypy/module/sysmodule.py
==============================================================================
--- /pypy/dist/pypy/module/sysmodule.py	Sat Feb 19 15:30:45 2005
+++ (empty file)
@@ -1,70 +0,0 @@
-"""
-The 'sys' module.
-"""
-
-__interplevel__execfile('sysinterp.py')
-
-# Common data structures
-from __interplevel__ import initialpath as path
-from __interplevel__ import modules, argv
-from __interplevel__ import warnoptions, builtin_module_names
-from __interplevel__ import maxunicode
-
-# Objects from interpreter-level
-from __interplevel__ import stdin, stdout, stderr, maxint
-from __interplevel__ import platform, byteorder
-from __interplevel__ import pypy_objspaceclass
-from __interplevel__ import exec_prefix, prefix
-
-# Functions from interpreter-level
-from __interplevel__ import _getframe, exc_info, exc_clear, pypy_getudir
-from __interplevel__ import getrecursionlimit, setrecursionlimit
-from __interplevel__ import getcheckinterval, setcheckinterval
-from __interplevel__ import getdefaultencoding, getrefcount
-
-# Dummy
-executable = 'py.py'
-api_version = 0
-copyright = ''
-version = '2.3a0 (pypy build)'
-version_info = (2, 3, 0, 'alpha', 0)
-hexversion = 0x020300a0
-ps1 = '>>>> '
-ps2 = '.... '
-
-
-# XXX not called by the core yet
-def excepthook(exctype, value, traceback):
-    from traceback import print_exception
-    print_exception(exctype, value, traceback)
-
-__excepthook__ = excepthook  # this is exactly like in CPython
-
-def exit(exitcode=0):
-    # note that we cannot use SystemExit(exitcode) here.
-    # The comma version leads to an extra de-tupelizing
-    # in normalize_exception, which is exactlylike CPython.
-    raise SystemExit, exitcode
-
-def displayhook(obj):
-    if obj is not None:
-        __builtins__['_'] = obj
-        # NB. this is slightly more complicated in CPython,
-        # see e.g. the difference with  >>> print 5,; 8
-        print `obj`
-
-__displayhook__ = displayhook  # this is exactly like in CPython
-
-def getfilesystemencoding():
-    """getfilesystemencoding() -> string
-
-Return the encoding used to convert Unicode filenames in
-operating system filenames."""
-    
-    if platform == "win32":
-        encoding = "mbcs"
-    elif platform == "darwin":
-        encoding = "utf-8"
-    else:
-        encoding = None
-    return encoding

Modified: pypy/dist/pypy/module/test/test_builtin.py
==============================================================================
--- pypy/dist/pypy/module/test/test_builtin.py	(original)
+++ pypy/dist/pypy/module/test/test_builtin.py	Sat Feb 19 15:30:45 2005
@@ -381,10 +381,7 @@
         space = self.space
 
     def get_builtin(self, name):
-        w = self.space.wrap
-        w_builtins = self.space.w_builtins
-        w_obj = self.space.getitem(w_builtins, w(name))
-        return w_obj
+        return self.space.builtin.get(name) 
 
     def test_execfile(self):
         from pypy.tool.udir import udir

Modified: pypy/dist/pypy/module/test/test_import.py
==============================================================================
--- pypy/dist/pypy/module/test/test_import.py	(original)
+++ pypy/dist/pypy/module/test/test_import.py	Sat Feb 19 15:30:45 2005
@@ -2,21 +2,23 @@
 from pypy.interpreter import gateway
 import os
 
-
-def _setup(dn=os.path.abspath(os.path.join(os.path.dirname(__file__), 'impsubdir'))):
-    import sys
-    sys.path.append(dn)
-    return sys.modules.copy()
-
-_setup = gateway.app2interp_temp(_setup,'setup')
-
-def _teardown(saved_modules):
-    import sys
-    sys.path.pop()
-    sys.modules.clear()
-    sys.modules.update(saved_modules)
-
-_teardown = gateway.app2interp_temp(_teardown,'teardown')
+def _setup(space): 
+    dn=os.path.abspath(os.path.join(os.path.dirname(__file__), 'impsubdir'))
+    return space.appexec([space.wrap(dn)], """
+        (dn): 
+            import sys
+            sys.path.append(dn)
+            return sys.modules.copy()
+    """)
+
+def _teardown(space, w_saved_modules):
+    space.appexec([w_saved_modules], """
+        (saved_modules): 
+            import sys
+            sys.path.pop()
+            sys.modules.clear()
+            sys.modules.update(saved_modules)
+    """)
 
 class AppTestImport:
 

Modified: pypy/dist/pypy/module/test/test_sysmodule.py
==============================================================================
--- pypy/dist/pypy/module/test/test_sysmodule.py	(original)
+++ pypy/dist/pypy/module/test/test_sysmodule.py	Sat Feb 19 15:30:45 2005
@@ -9,12 +9,8 @@
     b.cStringIO = cStringIO
     b.sys = sys
 
-class TestSysTests:
-    def setup_method(self,method):
-        self.sys_w = self.space.get_builtin_module("sys")
-    def test_stdout_exists(self):
-        s = self.space
-        assert s.is_true(s.getattr(self.sys_w, s.wrap("stdout")))
+def test_stdout_exists(space):
+    assert space.sys.get('stdout') 
 
 class AppTestAppSysTests:
     def test_path_exists(self):
@@ -119,9 +115,9 @@
         dh(None)
         assert out.getvalue() == ""
         assert not hasattr(__builtin__, "_")
-        dh(42)
-        assert out.getvalue() == "42\n"
-        assert __builtin__._ == 42
+        dh("hello")
+        assert out.getvalue() == "'hello'\n"
+        assert __builtin__._ == "hello"
 
         del sys.stdout
         raises(RuntimeError, dh, 42)

Modified: pypy/dist/pypy/objspace/descroperation.py
==============================================================================
--- pypy/dist/pypy/objspace/descroperation.py	(original)
+++ pypy/dist/pypy/objspace/descroperation.py	Sat Feb 19 15:30:45 2005
@@ -5,6 +5,11 @@
 from pypy.interpreter.gateway import BuiltinCode
 from pypy.interpreter.argument import Arguments
 
+def raiseattrerror(space, w_obj, name): 
+    w_type = space.type(w_obj) 
+    msg = "'%s' object has no attribute '%s'" %(w_type.name, name)
+    raise OperationError(space.w_AttributeError, space.wrap(msg))
+
 class Object:
     def descr__getattribute__(space, w_obj, w_name):
         name = space.str_w(w_name)
@@ -12,16 +17,12 @@
         if w_descr is not None:
             if space.is_data_descr(w_descr):
                 return space.get(w_descr, w_obj)
-        w_dict = space.getdict(w_obj)
-        if w_dict is not None:  
-            try:
-                return space.getitem(w_dict, w_name)
-            except OperationError, e:
-                if not e.match(space, space.w_KeyError):
-                    raise
+        w_value = space.getdictvalue(w_obj, name)
+        if w_value is not None:
+            return w_value
         if w_descr is not None:
             return space.get(w_descr, w_obj)
-        raise OperationError(space.w_AttributeError, w_name)
+        raiseattrerror(space, w_obj, name) 
 
     def descr__setattr__(space, w_obj, w_name, w_value):
         name = space.str_w(w_name)
@@ -32,7 +33,7 @@
         w_dict = space.getdict(w_obj)
         if w_dict is not None:
             return space.setitem(w_dict, w_name, w_value)
-        raise OperationError(space.w_AttributeError, w_name)
+        raiseattrerror(space, w_obj, name) 
 
     def descr__delattr__(space, w_obj, w_name):
         name = space.str_w(w_name)
@@ -47,7 +48,7 @@
             except OperationError, ex:
                 if not ex.match(space, space.w_KeyError):
                     raise
-        raise OperationError(space.w_AttributeError, w_name)
+        raiseattrerror(space, w_obj, name) 
 
     def descr__init__(space, w_obj, __args__):
         pass   # XXX some strange checking maybe
@@ -57,6 +58,9 @@
     def getdict(space, w_obj):
         return w_obj.getdict()
 
+    def getdictvalue(space, w_obj, attr):
+        return w_obj.getdictvalue(space, attr)
+
     def is_data_descr(space, w_obj):
         return space.lookup(w_obj, '__set__') is not None
 
@@ -566,24 +570,25 @@
     l = ["space.is_true(space.isinstance(w_result, %s))" % x 
                 for x in checkerspec]
     checker = " or ".join(l) 
-    exec """
-def %(targetname)s(space, w_obj):
-    w_impl = space.lookup(w_obj, %(specialname)r) 
-    if w_impl is None:
-        raise OperationError(space.w_TypeError,
-               space.wrap("operand does not support unary %(targetname)s"))
-    w_result = space.get_and_call_function(w_impl, w_obj)
+    source = """if 1: 
+        def %(targetname)s(space, w_obj):
+            w_impl = space.lookup(w_obj, %(specialname)r) 
+            if w_impl is None:
+                raise OperationError(space.w_TypeError,
+                       space.wrap("operand does not support unary %(targetname)s"))
+            w_result = space.get_and_call_function(w_impl, w_obj)
 
-    if %(checker)s: 
-        return w_result
-    typename = space.str_w(space.getattr(space.type(w_result), 
-                           space.wrap('__name__')))
-    msg = '%(specialname)s returned non-%(targetname)s (type %%s)' %% (typename,) 
-    raise OperationError(space.w_TypeError, space.wrap(msg)) 
-assert not hasattr(DescrOperation, %(targetname)r)
-DescrOperation.%(targetname)s = %(targetname)s
-del %(targetname)s 
-""" % locals() 
+            if %(checker)s: 
+                return w_result
+            typename = space.str_w(space.getattr(space.type(w_result), 
+                                   space.wrap('__name__')))
+            msg = '%(specialname)s returned non-%(targetname)s (type %%s)' %% (typename,) 
+            raise OperationError(space.w_TypeError, space.wrap(msg)) 
+        assert not hasattr(DescrOperation, %(targetname)r)
+        DescrOperation.%(targetname)s = %(targetname)s
+        del %(targetname)s 
+        \n""" % locals() 
+    exec compile(source, '', 'exec')
 
 
 # add default operation implementations for all still missing ops 

Modified: pypy/dist/pypy/objspace/flow/flowcontext.py
==============================================================================
--- pypy/dist/pypy/objspace/flow/flowcontext.py	(original)
+++ pypy/dist/pypy/objspace/flow/flowcontext.py	Sat Feb 19 15:30:45 2005
@@ -83,8 +83,11 @@
                  name=None):
         ExecutionContext.__init__(self, space)
         self.code = code
+        
         self.w_globals = w_globals = space.wrap(globals)
+        
         self.crnt_offset = -1
+        self.crnt_frame = None
         if closure is None:
             self.closure = None
         else:
@@ -113,6 +116,7 @@
     def bytecode_trace(self, frame):
         if not isinstance(self.crnt_ops, list):
             return
+        assert frame is self.crnt_frame, "seeing an unexpected frame!"
         next_instr = frame.next_instr
         self.crnt_offset = next_instr # save offset for opcode
         varnames = frame.code.getvarnames()
@@ -213,7 +217,11 @@
             except ExitFrame:
                 continue   # restarting a dead SpamBlock
             try:
-                w_result = frame.resume()
+                self.crnt_frame = frame
+                try:
+                    w_result = frame.resume()
+                finally:
+                    self.crnt_frame = None
             except OperationThatShouldNotBePropagatedError, e:
                 raise Exception(
                     'found an operation that always raises %s: %s' % (

Modified: pypy/dist/pypy/objspace/flow/objspace.py
==============================================================================
--- pypy/dist/pypy/objspace/flow/objspace.py	(original)
+++ pypy/dist/pypy/objspace/flow/objspace.py	Sat Feb 19 15:30:45 2005
@@ -2,6 +2,7 @@
 import sys, operator, types
 from pypy.interpreter.baseobjspace import ObjSpace, BaseWrappable
 from pypy.interpreter.pycode import PyCode
+from pypy.interpreter.module import Module
 from pypy.interpreter.error import OperationError
 from pypy.objspace.flow.model import *
 from pypy.objspace.flow import flowcontext
@@ -35,7 +36,12 @@
     def initialize(self):
         import __builtin__
         self.concrete_mode = 0
-        self.w_builtins = Constant(__builtin__.__dict__)
+        self.builtin    = Module(self, Constant('__builtin__'), Constant(__builtin__.__dict__))
+        def pick_builtin(w_globals):
+            return self.builtin
+        self.builtin.pick_builtin = pick_builtin
+        self.sys        = Module(self, Constant('sys'), Constant(sys.__dict__))
+        self.sys.recursionlimit = 100
         self.w_None     = Constant(None)
         self.w_False    = Constant(False)
         self.w_True     = Constant(True)

Modified: pypy/dist/pypy/objspace/flow/specialcase.py
==============================================================================
--- pypy/dist/pypy/objspace/flow/specialcase.py	(original)
+++ pypy/dist/pypy/objspace/flow/specialcase.py	Sat Feb 19 15:30:45 2005
@@ -82,6 +82,7 @@
     opname = fn.__name__.replace('__', '')
     return space.do_operation(opname, *args_w)
 
+
 def setup(space):
     fn = pyframe.normalize_exception.get_function(space)
     space.specialcases[fn] = sc_normalize_exception

Modified: pypy/dist/pypy/objspace/std/dictproxyobject.py
==============================================================================
--- pypy/dist/pypy/objspace/std/dictproxyobject.py	(original)
+++ pypy/dist/pypy/objspace/std/dictproxyobject.py	Sat Feb 19 15:30:45 2005
@@ -4,8 +4,6 @@
 def descr_get_dictproxy(space, w_obj):
     return W_DictProxyObject(space, w_obj.getdict())
 
-dictproxy_descr = GetSetProperty(descr_get_dictproxy)
-
 class W_DictProxyObject(W_Object):
     from pypy.objspace.std.dictproxytype import dictproxy_typedef as typedef
     

Modified: pypy/dist/pypy/objspace/std/dictproxytype.py
==============================================================================
--- pypy/dist/pypy/objspace/std/dictproxytype.py	(original)
+++ pypy/dist/pypy/objspace/std/dictproxytype.py	Sat Feb 19 15:30:45 2005
@@ -4,34 +4,38 @@
 
 # ____________________________________________________________
 
-def proxymethod(name):
+def _proxymethod(name):
     def fget(space, w_obj):
+        from pypy.objspace.std.dictproxyobject import W_DictProxyObject
+        if not isinstance(w_obj, W_DictProxyObject):
+            raise OperationError(space.w_TypeError,
+                                 space.wrap("expected dictproxy"))
         return space.getattr(w_obj.w_dict, space.wrap(name))
     return GetSetProperty(fget)
 
 # ____________________________________________________________
 
 dictproxy_typedef = StdTypeDef("dictproxy",
-    has_key = proxymethod('has_key'),
-    get = proxymethod('get'),
-    keys = proxymethod('keys'),
-    values = proxymethod('values'),
-    items = proxymethod('items'),
-    iterkeys = proxymethod('iterkeys'),
-    itervalues = proxymethod('itervalues'),
-    iteritems = proxymethod('iteritems'),
-    copy = proxymethod('copy'),
-    __len__ = proxymethod('__len__'),
-    __getitem__ = proxymethod('__getitem__'),
-    __contains__ = proxymethod('__contains__'),
-    __str__ = proxymethod('__str__'),
-    __iter__ = proxymethod('__iter__'),
-    __cmp__ = proxymethod('__cmp__'),
-    __lt__ = proxymethod('__lt__'),
-    __le__ = proxymethod('__le__'),
-    __eq__ = proxymethod('__eq__'),
-    __ne__ = proxymethod('__ne__'),
-    __gt__ = proxymethod('__gt__'),
-    __ge__ = proxymethod('__ge__'),
+    has_key = _proxymethod('has_key'),
+    get = _proxymethod('get'),
+    keys = _proxymethod('keys'),
+    values = _proxymethod('values'),
+    items = _proxymethod('items'),
+    iterkeys = _proxymethod('iterkeys'),
+    itervalues = _proxymethod('itervalues'),
+    iteritems = _proxymethod('iteritems'),
+    copy = _proxymethod('copy'),
+    __len__ = _proxymethod('__len__'),
+    __getitem__ = _proxymethod('__getitem__'),
+    __contains__ = _proxymethod('__contains__'),
+    __str__ = _proxymethod('__str__'),
+    __iter__ = _proxymethod('__iter__'),
+    __cmp__ = _proxymethod('__cmp__'),
+    __lt__ = _proxymethod('__lt__'),
+    __le__ = _proxymethod('__le__'),
+    __eq__ = _proxymethod('__eq__'),
+    __ne__ = _proxymethod('__ne__'),
+    __gt__ = _proxymethod('__gt__'),
+    __ge__ = _proxymethod('__ge__'),
 )
 dictproxy_typedef.registermethods(globals())

Modified: pypy/dist/pypy/objspace/std/dicttype.py
==============================================================================
--- pypy/dist/pypy/objspace/std/dicttype.py	(original)
+++ pypy/dist/pypy/objspace/std/dicttype.py	Sat Feb 19 15:30:45 2005
@@ -20,75 +20,69 @@
 #dict_str        = StdObjSpace.str
 
 # default application-level implementations for some operations
+# gateway is imported in the stdtypedef module
+app = gateway.applevel('''
 
-def app_dict_update__ANY_ANY(d, o):
-    for k in o.keys():
-        d[k] = o[k]
-
-def app_dict_popitem__ANY(d):
-    k = d.keys()
-    if not k:
-        raise KeyError("popitem(): dictionary is empty")
-    k = k[0]
-    v = d[k]
-    del d[k]
-    return k, v
-
-def app_dict_get__ANY_ANY_ANY(d, k, v=None):
-    if d.has_key(k):
-        return d[k]
-    return v
-
-def app_dict_setdefault__ANY_ANY_ANY(d, k, v):
-    if d.has_key(k):
-        return d[k]
-    d[k] = v
-    return v
-
-def app_dict_pop__ANY_ANY(d, k, default):
-    if len(default) > 1:
-        raise TypeError, "pop expected at most 2 arguments, got %d" % (
-            1 + len(default))
-    try:
+    def update(d, o):
+        for k in o.keys():
+            d[k] = o[k]
+
+    def popitem(d):
+        k = d.keys()
+        if not k:
+            raise KeyError("popitem(): dictionary is empty")
+        k = k[0]
         v = d[k]
         del d[k]
-    except KeyError, e:
-        if default:
-            return default[0]
+        return k, v
+
+    def get(d, k, v=None):
+        if k in d:
+            return d[k]
         else:
-            raise e
-    return v
+            return v
 
-def app_dict_iteritems__ANY(d):
-    return iter(d.items())
+    def setdefault(d, k, v=None):
+        if k in d:
+            return d[k]
+        else:
+            d[k] = v
+            return v
 
-def app_dict_iterkeys__ANY(d):
-    return iter(d.keys())
+    def pop(d, k, defaults):     # XXX defaults is actually *defaults
+        if len(defaults) > 1:
+            raise TypeError, "pop expected at most 2 arguments, got %d" % (
+                1 + len(defaults))
+        try:
+            v = d[k]
+            del d[k]
+        except KeyError, e:
+            if defaults:
+                return defaults[0]
+            else:
+                raise e
+        return v
+
+    def iteritems(d):
+        return iter(d.items())
+
+    def iterkeys(d):
+        return iter(d.keys())
+
+    def itervalues(d):
+        return iter(d.values())
+''')
+#XXX what about dict.fromkeys()?
+
+dict_update__ANY_ANY         = app.interphook("update")
+dict_popitem__ANY            = app.interphook("popitem")
+dict_get__ANY_ANY_ANY        = app.interphook("get")
+dict_setdefault__ANY_ANY_ANY = app.interphook("setdefault")
+dict_pop__ANY_ANY            = app.interphook("pop")
+dict_iteritems__ANY          = app.interphook("iteritems")
+dict_iterkeys__ANY           = app.interphook("iterkeys")
+dict_itervalues__ANY         = app.interphook("itervalues")
 
-def app_dict_itervalues__ANY(d):
-    return iter(d.values())
-
-#def app_dict_fromkeys__ANY_List(d, seq, value):
-#    d = {}
-#    if value:
-#        value = value[0]
-#    else:
-#        value = None
-#    for item in seq:
-#        d[item] = value
-#    return d
-#XXX implement dict.fromkeys() which must be a static method
-#XXX accepting any iterable
-
-# This can return when multimethods have been fixed
-"""
-def app_dict_str__ANY(d):
-    items = []
-    for k, v in d.iteritems():
-        items.append("%r: %r" % (k, v))
-    return "{%s}" % ', '.join(items)
-"""
-gateway.importall(globals())
 register_all(vars(), globals())
 
 # ____________________________________________________________
@@ -102,6 +96,7 @@
 # ____________________________________________________________
 
 dict_typedef = StdTypeDef("dict",
-    __new__ = newmethod(descr__new__),
+    __new__ = newmethod(descr__new__,
+                        unwrap_spec=[gateway.ObjSpace,gateway.W_Root,gateway.Arguments]),
     )
 dict_typedef.registermethods(globals())

Modified: pypy/dist/pypy/objspace/std/listtype.py
==============================================================================
--- pypy/dist/pypy/objspace/std/listtype.py	(original)
+++ pypy/dist/pypy/objspace/std/listtype.py	Sat Feb 19 15:30:45 2005
@@ -14,15 +14,16 @@
 list_sort     = MultiMethod('sort',   4, defaults=(None, None, False), argnames=['cmp', 'key', 'reverse'])
 list_reversed = MultiMethod('__reversed__', 1)
 
-def app_list_reversed__ANY(lst):
-    def reversed_gen(local_iterable):
-        len_iterable = len(local_iterable)
-        for index in range(len_iterable-1, -1, -1):
-            yield local_iterable[index]
-    return reversed_gen(lst)
-
 # gateway is imported in the stdtypedef module
-gateway.importall(globals())
+app = gateway.applevel('''
+
+    def reversed(lst):
+        for index in range(len(lst)-1, -1, -1):
+            yield lst[index]
+
+''')
+
+list_reversed__ANY = app.interphook('reversed')
 register_all(vars(), globals())
 
 # ____________________________________________________________
@@ -36,6 +37,8 @@
 # ____________________________________________________________
 
 list_typedef = StdTypeDef("list",
-    __new__ = newmethod(descr__new__),
+    __new__ = newmethod(descr__new__, unwrap_spec=[gateway.ObjSpace,
+                                                   gateway.W_Root,
+                                                   gateway.Arguments]),
     )
 list_typedef.registermethods(globals())

Modified: pypy/dist/pypy/objspace/std/longobject.py
==============================================================================
--- pypy/dist/pypy/objspace/std/longobject.py	(original)
+++ pypy/dist/pypy/objspace/std/longobject.py	Sat Feb 19 15:30:45 2005
@@ -253,12 +253,12 @@
 
 # binary ops
 for opname in ['add', 'sub', 'mul', 'div', 'floordiv', 'truediv', 'mod', 'divmod', 'lshift']:
-    exec """
+    exec compile("""
 def %(opname)s_ovr__Int_Int(space, w_int1, w_int2):
     w_long1 = delegate_Int2Long(w_int1)
     w_long2 = delegate_Int2Long(w_int2)
     return %(opname)s__Long_Long(space, w_long1, w_long2)
-""" % {'opname': opname}
+""" % {'opname': opname}, '', 'exec')
 
     getattr(StdObjSpace.MM, opname).register(globals()['%s_ovr__Int_Int' %opname], W_IntObject, W_IntObject, order=1)
 

Modified: pypy/dist/pypy/objspace/std/model.py
==============================================================================
--- pypy/dist/pypy/objspace/std/model.py	(original)
+++ pypy/dist/pypy/objspace/std/model.py	Sat Feb 19 15:30:45 2005
@@ -26,6 +26,7 @@
             from pypy.objspace.std.slicetype  import slice_typedef
             from pypy.objspace.std.longtype   import long_typedef
             from pypy.objspace.std.unicodetype import unicode_typedef
+            from pypy.objspace.std.dictproxytype import dictproxy_typedef
         self.pythontypes = [value for key, value in result.__dict__.items()
                             if not key.startswith('_')]   # don't look
 

Modified: pypy/dist/pypy/objspace/std/multimethod.py
==============================================================================
--- pypy/dist/pypy/objspace/std/multimethod.py	(original)
+++ pypy/dist/pypy/objspace/std/multimethod.py	Sat Feb 19 15:30:45 2005
@@ -252,7 +252,7 @@
         source = '\n'.join(bodylines)
         #print source
         #print "*"*60
-        exec source in miniglobals
+        exec compile(source, '', 'exec') in miniglobals
         func = miniglobals[funcname]
         self.to_install.append((target, funcname, func, source, fallback))
         return func

Modified: pypy/dist/pypy/objspace/std/objecttype.py
==============================================================================
--- pypy/dist/pypy/objspace/std/objecttype.py	(original)
+++ pypy/dist/pypy/objspace/std/objecttype.py	Sat Feb 19 15:30:45 2005
@@ -3,12 +3,14 @@
 from pypy.objspace.std.stdtypedef import *
 from pypy.objspace.std.register_all import register_all
 from pypy.objspace.std.objspace import StdObjSpace
+from pypy.tool.uid import fixid
 
 
 def descr__repr__(space, w_obj):
     w = space.wrap
     classname = space.str_w(space.getattr(space.type(w_obj), w("__name__")))
     id = space.int_w(space.id(w_obj))# xxx ids could be long
+    id = fixid(id)
     return w("<%s object at 0x%x>" % (classname, id))
 
 def descr__str__(space, w_obj):
@@ -45,6 +47,8 @@
     __str__ = gateway.interp2app(descr__str__),
     __repr__ = gateway.interp2app(descr__repr__),
     __class__ = GetSetProperty(descr__class__),
-    __new__ = newmethod(descr__new__),
-    __init__ = gateway.interp2app(descr__init__),
+    __new__ = newmethod(descr__new__,
+                        unwrap_spec = [gateway.ObjSpace,gateway.W_Root,gateway.Arguments]),
+    __init__ = gateway.interp2app(descr__init__,
+                                  unwrap_spec=[gateway.ObjSpace,gateway.W_Root,gateway.Arguments]),
     )

Modified: pypy/dist/pypy/objspace/std/objspace.py
==============================================================================
--- pypy/dist/pypy/objspace/std/objspace.py	(original)
+++ pypy/dist/pypy/objspace/std/objspace.py	Sat Feb 19 15:30:45 2005
@@ -55,40 +55,39 @@
         self.w_None  = W_NoneObject(self)
         self.w_False = W_BoolObject(self, False)
         self.w_True  = W_BoolObject(self, True)
-        from pypy.interpreter.special import NotImplemented, Ellipsis 
+        from pypy.interpreter.special import NotImplemented, Ellipsis
         self.w_NotImplemented = self.wrap(NotImplemented(self))  
         self.w_Ellipsis = self.wrap(Ellipsis(self))  
 
-        for_builtins = {"False": self.w_False,
-                        "True" : self.w_True,
-                        "None" : self.w_None,
-                        "NotImplemented": self.w_NotImplemented,
-                        "Ellipsis": self.w_Ellipsis,
-                        }
-
         # types
         self.types_w = {}
         for typedef in self.model.pythontypes:
             w_type = self.gettypeobject(typedef)
             setattr(self, 'w_' + typedef.name, w_type)
-            for_builtins[typedef.name] = w_type
+
+        # exceptions & builtins
+        mod = self.setup_exceptions()
+        self.make_builtins()
+        self.sys.setmodule(self.wrap(mod))
 
         # dummy old-style classes types
         self.w_classobj = W_TypeObject(self, 'classobj', [self.w_object], {})
         self.w_instance = W_TypeObject(self, 'instance', [self.w_object], {})
 
-        # exceptions
-        mod = self.setup_exceptions(for_builtins)
-
+        # fix up a problem where multimethods apparently don't 
+        # like to define this at interp-level 
+        self.appexec([self.w_dict], """
+            (dict): 
+                def fromkeys(cls, seq, value=None):
+                    r = cls()
+                    for s in seq:
+                        r[s] = value
+                    return r
+                dict.fromkeys = classmethod(fromkeys)
+        """) 
         # old-style classes
         self.setup_old_style_classes()
 
-        # install things in the __builtin__ module
-        self.make_builtins(for_builtins)
-
-        w_exceptions = self.wrap(mod)
-        self.sys.setbuiltinmodule(w_exceptions, 'exceptions')
-
     def enable_old_style_classes_as_default_metaclass(self):
         self.setitem(self.builtin.w_dict, self.wrap('__metaclass__'), self.w_classobj)
 
@@ -101,7 +100,7 @@
         self.w_classobj = w_classobj
         self.w_instance = w_instance
 
-    def setup_exceptions(self, for_builtins):
+    def setup_exceptions(self):
         """NOT_RPYTHON"""
         ## hacking things in
         from pypy.module import exceptionsinterp as ex
@@ -136,8 +135,6 @@
                 w_exc = self.getitem(w_dic, w_name)
                 setattr(self, "w_"+excname, w_exc)
                         
-                for_builtins[excname] = w_exc
-
         # XXX refine things, clean up, create a builtin module...
         # but for now, we do a regular one.
         from pypy.interpreter.module import Module
@@ -181,7 +178,7 @@
         if isinstance(x, complex):
             # XXX is this right?   YYY no, this is wrong right now  (CT)
             # ZZZ hum, seems necessary for complex literals in co_consts (AR)
-            c = self.getitem(self.w_builtins, self.wrap("complex"))
+            c = self.builtin.get('complex') 
             return self.call_function(c,
                                       self.wrap(x.real), 
                                       self.wrap(x.imag))

Modified: pypy/dist/pypy/objspace/std/slicetype.py
==============================================================================
--- pypy/dist/pypy/objspace/std/slicetype.py	(original)
+++ pypy/dist/pypy/objspace/std/slicetype.py	Sat Feb 19 15:30:45 2005
@@ -6,64 +6,69 @@
 slice_indices = MultiMethod('indices', 2)
 
 # default application-level implementations for some operations
+# gateway is imported in the stdtypedef module
+app = gateway.applevel("""
 
-def app_slice_indices3(slice, length):
-    # this is used internally, analogous to CPython's PySlice_GetIndicesEx
-    step = slice.step
-    if step is None:
-        step = 1
-    elif step == 0:
-        raise ValueError, "slice step cannot be zero"
-    if step < 0:
-        defstart = length - 1
-        defstop = -1
-    else:
-        defstart = 0
-        defstop = length
-
-    start = slice.start
-    if start is None:
-        start = defstart
-    else:
-        if start < 0:
-            start += length
+    def indices(slice, length):
+        # this is used internally, analogous to CPython's PySlice_GetIndicesEx
+        step = slice.step
+        if step is None:
+            step = 1
+        elif step == 0:
+            raise ValueError, "slice step cannot be zero"
+        if step < 0:
+            defstart = length - 1
+            defstop = -1
+        else:
+            defstart = 0
+            defstop = length
+
+        start = slice.start
+        if start is None:
+            start = defstart
+        else:
             if start < 0:
+                start += length
+                if start < 0:
+                    if step < 0:
+                        start = -1
+                    else:
+                        start = 0
+            elif start >= length:
                 if step < 0:
-                    start = -1
+                    start = length - 1
                 else:
-                    start = 0
-        elif start >= length:
-            if step < 0:
-                start = length - 1
-            else:
-                start = length
-
-    stop = slice.stop
-    if stop is None:
-        stop = defstop
-    else:
-        if stop < 0:
-            stop += length
-            if stop < 0:
-                stop = -1
-        elif stop > length:
-            stop = length
-
-    return start, stop, step
-slice_indices__ANY_ANY = slice_indices3 = gateway.app2interp(app_slice_indices3)
-
-def app_slice_indices4(slice, sequencelength):
-    start, stop, step = slice_indices3(slice, sequencelength)
-    slicelength = stop - start
-    lengthsign = cmp(slicelength, 0)
-    stepsign = cmp(step, 0)
-    if stepsign == lengthsign:
-        slicelength = (slicelength - lengthsign) // step + 1
-    else:
-        slicelength = 0
+                    start = length
 
-    return start, stop, step, slicelength
-slice_indices4 = gateway.app2interp(app_slice_indices4)
+        stop = slice.stop
+        if stop is None:
+            stop = defstop
+        else:
+            if stop < 0:
+                stop += length
+                if stop < 0:
+                    stop = -1
+            elif stop > length:
+                stop = length
+
+        return start, stop, step
+
+    def slice_indices4(slice, sequencelength):
+        start, stop, step = indices(slice, sequencelength)
+        slicelength = stop - start
+        lengthsign = cmp(slicelength, 0)
+        stepsign = cmp(step, 0)
+        if stepsign == lengthsign:
+            slicelength = (slicelength - lengthsign) // step + 1
+        else:
+            slicelength = 0
+
+        return start, stop, step, slicelength
+""")
+
+slice_indices__ANY_ANY = app.interphook("indices")
+slice_indices3         = slice_indices__ANY_ANY
+slice_indices4         = app.interphook("slice_indices4")
 
 # utility functions
 def indices3(space, w_slice, length):
@@ -120,10 +125,20 @@
 
 # ____________________________________________________________
 
+def slicewprop(name):
+    def fget(space, w_obj):
+        from pypy.objspace.std.sliceobject import W_SliceObject
+        if not isinstance(w_obj, W_SliceObject):
+            raise OperationError(space.w_TypeError,
+                                 space.wrap("descriptor is for 'slice'"))
+        return getattr(w_obj, name)
+    return GetSetProperty(fget)
+
+
 slice_typedef = StdTypeDef("slice",
     __new__ = newmethod(descr__new__),
-    start = attrproperty_w('w_start'),
-    stop  = attrproperty_w('w_stop'),
-    step  = attrproperty_w('w_step'),
+    start = slicewprop('w_start'),
+    stop  = slicewprop('w_stop'),
+    step  = slicewprop('w_step'),
     )
 slice_typedef.registermethods(globals())

Modified: pypy/dist/pypy/objspace/std/stdtypedef.py
==============================================================================
--- pypy/dist/pypy/objspace/std/stdtypedef.py	(original)
+++ pypy/dist/pypy/objspace/std/stdtypedef.py	Sat Feb 19 15:30:45 2005
@@ -4,7 +4,7 @@
 from pypy.objspace.std.model import MultiMethod, FailedToImplement
 
 __all__ = ['StdTypeDef', 'newmethod', 'gateway',
-           'GetSetProperty', 'Member', 'attrproperty', 'attrproperty_w',
+           'GetSetProperty', 'Member',
            'MultiMethod']
 
 
@@ -29,36 +29,20 @@
         a = a.base
     return True
 
-def attrproperty(name):
-    "NOT_RPYTHON: initialization-time only"
-    def fget(space, w_obj):
-        return space.wrap(getattr(w_obj, name))
-    return GetSetProperty(fget)
-
-def attrproperty_w(name):
-    "NOT_RPYTHON: initialization-time only"
-    def fget(space, w_obj):
-        w_value = getattr(w_obj, name)
-        if w_value is None:
-            return space.w_None
-        else:
-            return w_value 
-    return GetSetProperty(fget)
-
-def descr_get_dict(space, w_obj):
+def descr_get_dict(space, w_obj): # xxx typecheck
     w_dict = w_obj.getdict()
     assert w_dict is not None, repr(w_obj)
     return w_dict
 
-def descr_set_dict(space, w_obj, w_dict):
+def descr_set_dict(space, w_obj, w_dict): # xxx typecheck
     w_obj.setdict(w_dict)
 
 std_dict_descr = GetSetProperty(descr_get_dict, descr_set_dict)
 
-def newmethod(descr_new):
+def newmethod(descr_new, unwrap_spec=None):
     "NOT_RPYTHON: initialization-time only."
     # this is turned into a static method by the constructor of W_TypeObject.
-    return gateway.interp2app(descr_new)
+    return gateway.interp2app(descr_new, unwrap_spec=unwrap_spec)
 
 # ____________________________________________________________
 #
@@ -73,15 +57,19 @@
     from pypy.objspace.std.objecttype import object_typedef
 
     w = space.wrap
-    rawdict = typedef.rawdict.copy()
+    rawdict = typedef.rawdict
+    lazyloaders = {}
 
     if isinstance(typedef, StdTypeDef):
         # get all the sliced multimethods
         multimethods = slicemultimethods(space, typedef)
-        for name, gateway in multimethods.items():
-            assert name not in rawdict, 'name clash: %s in %s_typedef' % (
-                name, typedef.name)
-            rawdict[name] = gateway
+        for name, loader in multimethods.items():
+            if name in rawdict:
+                # the name specified in the rawdict has priority
+                continue
+            assert name not in lazyloaders, (
+                'name clash: %s in %s.lazyloaders' % (name, typedef.name))
+            lazyloaders[name] = loader
 
     # compute the bases
     if typedef is object_typedef:
@@ -95,8 +83,10 @@
     for descrname, descrvalue in rawdict.items():
         dict_w[descrname] = w(descrvalue)
 
-    return W_TypeObject(space, typedef.name, bases_w, dict_w,
-                        overridetypedef=typedef)
+    w_type = W_TypeObject(space, typedef.name, bases_w, dict_w,
+                          overridetypedef=typedef)
+    w_type.lazyloaders = lazyloaders
+    return w_type
 
 def hack_out_multimethods(ns):
     "NOT_RPYTHON: initialization-time only."
@@ -247,7 +237,7 @@
                       return w_res
 """        % (prefix, wrapper_sig, renaming, expr,
               multimethod.operatorsymbol, ', '.join(solid_arglist))
-    exec code in miniglobals
+    exec compile(code, '', 'exec') in miniglobals 
     return miniglobals["%s_perform_call" % prefix]
 
 def wrap_trampoline_in_gateway(func, methname, multimethod):
@@ -261,29 +251,30 @@
     return gateway.interp2app(func, app_name=methname, unwrap_spec=unwrap_spec)
 
 def slicemultimethod(space, multimethod, typedef, result, local=False):
-    from pypy.objspace.std.objecttype import object_typedef
     for i in range(len(multimethod.specialnames)):
-        # each MultimethodCode embeds a multimethod
         methname = multimethod.specialnames[i]
         if methname in result:
             # conflict between e.g. __lt__ and
             # __lt__-as-reversed-version-of-__gt__
-            gw = result[methname]
-            if gw.bound_position < i:
+            loader = result[methname]
+            if loader.bound_position < i:
                 continue
 
-        prefix, list_of_typeorders = sliced_typeorders(
-            space.model.typeorder, multimethod, typedef, i, local=local)
-        exprargs, expr, miniglobals, fallback = multimethod.install(prefix, list_of_typeorders,
-                                                                    baked_perform_call=False)
-        if fallback:
-            continue   # skip empty multimethods
-        trampoline = make_perform_trampoline(prefix, exprargs, expr, miniglobals,
-                                             multimethod, i,
-                                             allow_NotImplemented_results=True)
-        gw = wrap_trampoline_in_gateway(trampoline, methname, multimethod)
-        gw.bound_position = i   # for the check above
-        result[methname] = gw
+        def multimethod_loader(i=i, methname=methname):
+            prefix, list_of_typeorders = sliced_typeorders(
+                space.model.typeorder, multimethod, typedef, i, local=local)
+            exprargs, expr, miniglobals, fallback = multimethod.install(prefix, list_of_typeorders,
+                                                                        baked_perform_call=False)
+            if fallback:
+                return None   # skip empty multimethods
+            trampoline = make_perform_trampoline(prefix, exprargs, expr, miniglobals,
+                                                 multimethod, i,
+                                                 allow_NotImplemented_results=True)
+            gw = wrap_trampoline_in_gateway(trampoline, methname, multimethod)
+            return space.wrap(gw)
+
+        multimethod_loader.bound_position = i   # for the check above
+        result[methname] = multimethod_loader
 
 def slicemultimethods(space, typedef):
     result = {}

Modified: pypy/dist/pypy/objspace/std/test/test_typeobject.py
==============================================================================
--- pypy/dist/pypy/objspace/std/test/test_typeobject.py	(original)
+++ pypy/dist/pypy/objspace/std/test/test_typeobject.py	Sat Feb 19 15:30:45 2005
@@ -232,7 +232,11 @@
         assert type(D1) is T1
         assert type(C) is T1
         assert type(G) is T1
-            
+    
+    def test_descr_typecheck(self):
+        raises(TypeError,type.__dict__['__name__'].__get__,1)
+        raises(TypeError,type.__dict__['__mro__'].__get__,1)
+
 
         
         

Modified: pypy/dist/pypy/objspace/std/typeobject.py
==============================================================================
--- pypy/dist/pypy/objspace/std/typeobject.py	(original)
+++ pypy/dist/pypy/objspace/std/typeobject.py	Sat Feb 19 15:30:45 2005
@@ -8,6 +8,8 @@
 class W_TypeObject(W_Object):
     from pypy.objspace.std.typetype import type_typedef as typedef
 
+    lazyloaders = None   # can be overridden by specific instances
+
     def __init__(w_self, space, name, bases_w, dict_w,
                  overridetypedef=None):
         W_Object.__init__(w_self, space)
@@ -106,21 +108,26 @@
             if isinstance(w_new, Function):
                 w_self.dict_w['__new__'] = StaticMethod(w_new)
 
+    def getdictvalue(w_self, space, attr):
+        try:
+            return w_self.dict_w[attr]
+        except KeyError:
+            if w_self.lazyloaders and attr in w_self.lazyloaders:
+                loader = w_self.lazyloaders[attr]
+                del w_self.lazyloaders[attr]
+                w_value = loader()
+                if w_value is not None:   # None means no such attribute
+                    w_self.dict_w[attr] = w_value
+                return w_value
+            return None
+
     def lookup(w_self, key):
         # note that this doesn't call __get__ on the result at all
         space = w_self.space
         for w_class in w_self.mro_w:
-            try:
-                if isinstance(w_class, W_TypeObject):
-                    return w_class.dict_w[key]
-                else:
-                    try:
-                        return space.getitem(space.getdict(w_class),space.wrap(key))
-                    except OperationError,e:
-                        if not e.match(space, space.w_KeyError):
-                            raise
-            except KeyError:
-                pass
+            w_value = space.getdictvalue(w_class, key)
+            if w_value is not None:
+                return w_value
         return None
 
     def lookup_where(w_self, key):
@@ -128,17 +135,9 @@
         # attribute was found
         space = w_self.space
         for w_class in w_self.mro_w:
-            try:
-                if isinstance(w_class, W_TypeObject):
-                    return w_class, w_class.dict_w[key]
-                else:
-                    try:
-                        return w_class, space.getitem(space.getdict(w_class),space.wrap(key))
-                    except OperationError,e:
-                        if not e.match(space, space.w_KeyError):
-                            raise                
-            except KeyError:
-                pass
+            w_value = space.getdictvalue(w_class, key)
+            if w_value is not None:
+                return w_class, w_value
         return None, None
 
     def check_user_subclass(w_self, w_subtype):
@@ -158,6 +157,10 @@
 
     def getdict(w_self):
         # XXX should return a <dictproxy object>
+        if w_self.lazyloaders:
+            for attr in w_self.lazyloaders.keys():
+                w_self.getdictvalue(w_self.space, attr)
+            del w_self.lazyloaders
         space = w_self.space
         dictspec = []
         for key, w_value in w_self.dict_w.items():
@@ -213,7 +216,8 @@
         return space.get(w_value, space.w_None, w_type)
     if w_descr is not None:
         return space.get(w_descr,w_type)
-    raise OperationError(space.w_AttributeError,w_name)
+    msg = "type object '%s' has no attribute '%s'" %(w_type.name, name)
+    raise OperationError(space.w_AttributeError, space.wrap(msg))
 
 def setattr__Type_ANY_ANY(space, w_type, w_name, w_value):
     name = space.str_w(w_name)
@@ -224,6 +228,8 @@
     w_type.dict_w[name] = w_value
 
 def delattr__Type_ANY(space, w_type, w_name):
+    if w_type.lazyloaders:
+        w_type.getdict()    # force un-lazification
     name = space.str_w(w_name)
     w_descr = space.lookup(w_type, name)
     if w_descr is not None:
@@ -237,7 +243,8 @@
 # ____________________________________________________________
 
 
-def app_abstract_mro(klass): # abstract/classic mro
+def app_abstract_mro(klass):
+    # abstract/classic mro
     mro = []
     def fill_mro(klass):
         if klass not in mro:

Modified: pypy/dist/pypy/objspace/std/typetype.py
==============================================================================
--- pypy/dist/pypy/objspace/std/typetype.py	(original)
+++ pypy/dist/pypy/objspace/std/typetype.py	Sat Feb 19 15:30:45 2005
@@ -1,6 +1,6 @@
 from pypy.interpreter.error import OperationError
 from pypy.objspace.std.stdtypedef import *
-from pypy.objspace.std.dictproxyobject import dictproxy_descr
+from pypy.objspace.std.dictproxyobject import descr_get_dictproxy
 
 
 def descr__new__(space, w_typetype, w_name, w_bases, w_dict):
@@ -42,17 +42,37 @@
     w_type.__init__(space, name, bases_w or [space.w_object], dict_w)
     return w_type
 
+def _check(space, w_type, msg=None):
+    from pypy.objspace.std.typeobject import W_TypeObject
+    if not isinstance(w_type, W_TypeObject):
+        raise OperationError(space.w_TypeError, 
+                             space.wrap(msg or "descriptor is for 'type'"))
+    return w_type
+
+
+def descr_get__name__(space, w_type):
+    w_type = _check(space, w_type)
+    return space.wrap(w_type.name)
+
 def descr_get__mro__(space, w_type):
+    w_type = _check(space, w_type)
     # XXX this should be inside typeobject.py
     return space.newtuple(w_type.mro_w)
 
 def descr_mro(space, w_type):
+    w_type = _check(space, w_type,"expected type")
     return space.newlist(w_type.compute_mro())
 
 def descr__bases(space, w_type):
+    w_type = _check(space, w_type)
+    from pypy.objspace.std.typeobject import W_TypeObject
+    if not isinstance(w_type, W_TypeObject):
+        raise OperationError(space.w_TypeError, 
+                             space.wrap("descriptor is for 'type'"))
     return space.newtuple(w_type.bases_w)
 
 def descr__base(space, w_type):
+    w_type = _check(space, w_type)
     if w_type is space.w_object:
         return space.w_None
     b = w_type.instancetypedef.base
@@ -62,17 +82,22 @@
         return space.w_object
 
 def descr__doc(space, w_type):
-    return w_type.dict_w.get('__doc__')
+    w_type = _check(space, w_type)
+    w_result = w_type.getdictvalue(space, '__doc__')
+    if w_result is None:
+        return space.w_None
+    else:
+        return w_result
 
 # ____________________________________________________________
 
 type_typedef = StdTypeDef("type",
     __new__ = newmethod(descr__new__),
-    __name__ = attrproperty('name'),
+    __name__ = GetSetProperty(descr_get__name__),
     __bases__ = GetSetProperty(descr__bases),
     __base__ = GetSetProperty(descr__base),
     __mro__ = GetSetProperty(descr_get__mro__),
-    __dict__ = dictproxy_descr,
+    __dict__ = GetSetProperty(descr_get_dictproxy),
     __doc__ = GetSetProperty(descr__doc),
-    mro = newmethod(descr_mro),
+    mro = gateway.interp2app(descr_mro),
     )

Modified: pypy/dist/pypy/objspace/test/test_traceobjspace.py
==============================================================================
--- pypy/dist/pypy/objspace/test/test_traceobjspace.py	(original)
+++ pypy/dist/pypy/objspace/test/test_traceobjspace.py	Sat Feb 19 15:30:45 2005
@@ -22,7 +22,7 @@
 
     def test_traceobjspace_basic(self):
         tspace = self.space
-        assert tspace.is_true(tspace.w_builtins)
+        assert tspace.is_true(tspace.builtin)
         #for name, value in vars(self.space).items():
         #    if not name.startswith('_'):
         #        self.assert_(value is getattr(t, name))

Modified: pypy/dist/pypy/objspace/trivial.py
==============================================================================
--- pypy/dist/pypy/objspace/trivial.py	(original)
+++ pypy/dist/pypy/objspace/trivial.py	Sat Feb 19 15:30:45 2005
@@ -12,7 +12,8 @@
 import __builtin__ as cpy_builtin
 
 class CPyWrapper(object):
-    pass
+    def getdictvalue(self, space, name): 
+        return self.__dict__.get(name, None)
 
 class TrivialObjSpace(ObjSpace, DescrOperation):
 
@@ -122,7 +123,10 @@
                 setattr(self, 'w_' + c.__name__, c)
                 newstuff[c.__name__] = c
         newstuff.update(self.clone_exception_hierarchy())
-        self.make_builtins(newstuff)
+        self.make_builtins() 
+        # XXX Do we need the following still? 
+        #for name, value in newstuff.items(): 
+        #    self.builtin.w_dict[name] = value 
 
     # general stuff
     def wrap(self, x):

Modified: pypy/dist/pypy/tool/pydis.py
==============================================================================
--- pypy/dist/pypy/tool/pydis.py	(original)
+++ pypy/dist/pypy/tool/pydis.py	Sat Feb 19 15:30:45 2005
@@ -28,8 +28,7 @@
                 self.index == other.index and
                 self.op == other.op and
                 self.name == other.name and
-                self.oparg == other.oparg and
-                self.lineno == other.lineno)
+                self.oparg == other.oparg)
 
     def __ne__(self, other):
         return not (self == other)
@@ -44,7 +43,12 @@
         
         s = repr(oparg).rjust(5) + " "
         if op in hasconst:
-            s += '(' + `co.co_consts_w[oparg]` + ')'
+            # support both real code objects and PyCode objects
+            try:
+                consts = co.co_consts
+            except AttributeError:
+                consts = co.co_consts_w
+            s += '(' + `consts[oparg]` + ')'
         elif op in hasname:
             s +=  '(' + co.co_names[oparg] + ')'
         elif op in hasjrel:

Modified: pypy/dist/pypy/tool/pytestsupport.py
==============================================================================
--- pypy/dist/pypy/tool/pytestsupport.py	(original)
+++ pypy/dist/pypy/tool/pytestsupport.py	Sat Feb 19 15:30:45 2005
@@ -2,7 +2,7 @@
 import autopath
 import py
 from py.__impl__.magic import exprinfo
-from pypy.interpreter.gateway import interp2app_temp
+from pypy.interpreter import gateway
 from pypy.interpreter.error import OperationError
 
 # ____________________________________________________________
@@ -85,7 +85,7 @@
         frame = framestack.top(0)
         # Argh! we may see app-level helpers in the frame stack!
         #       that's very probably very bad...
-        if frame.code.co_name == 'app_normalize_exception': 
+        if frame.code.co_name == 'normalize_exception': 
             frame = framestack.top(1)
         
         runner = AppFrame(frame)
@@ -104,10 +104,13 @@
         space.setattr(w_self, space.wrap('msg'), w_msg)
 
     # build a new AssertionError class to replace the original one.
-    w_BuiltinAssertionError = space.getitem(space.w_builtins,
+    w_BuiltinAssertionError = space.getitem(space.builtin.w_dict, 
                                             space.wrap('AssertionError'))
     w_metaclass = space.type(w_BuiltinAssertionError)
-    w_init = space.wrap(interp2app_temp(my_init))
+    w_init = space.wrap(gateway.interp2app_temp(my_init,
+                                                unwrap_spec=[gateway.ObjSpace,
+                                                             gateway.W_Root,
+                                                             gateway.Arguments]))
     w_dict = space.newdict([])
     space.setitem(w_dict, space.wrap('__init__'), w_init)
     return space.call_function(w_metaclass,
@@ -137,26 +140,30 @@
                               w_locals)
         except OperationError, e:
             if e.match(space, w_ExpectedException):
-                return space.sys.exc_info()
+                return space.call_function(space.sys.get('exc_info'))
             raise
     else:
         try:
             space.call_args(w_expr, __args__)
         except OperationError, e:
             if e.match(space, w_ExpectedException):
-                return space.sys.exc_info()
+                return space.call_function(space.sys.get('exc_info'))
             raise
     raise OperationError(space.w_AssertionError,
                          space.wrap("DID NOT RAISE"))
 
-app_raises = interp2app_temp(pypyraises)
+app_raises = gateway.interp2app_temp(pypyraises,
+                                     unwrap_spec=[gateway.ObjSpace,
+                                                  gateway.W_Root,
+                                                  gateway.W_Root,
+                                                  gateway.Arguments])
 
 def pypyskip(space, w_message): 
     """skip a test at app-level. """ 
     msg = space.unwrap(w_message) 
     py.test.skip(msg)
 
-app_skip = interp2app_temp(pypyskip)
+app_skip = gateway.interp2app_temp(pypyskip)
 
 def raises_w(space, w_ExpectedException, *args, **kwds):
     try:

Modified: pypy/dist/pypy/tool/test/test_pytestsupport.py
==============================================================================
--- pypy/dist/pypy/tool/test/test_pytestsupport.py	(original)
+++ pypy/dist/pypy/tool/test/test_pytestsupport.py	Sat Feb 19 15:30:45 2005
@@ -28,7 +28,7 @@
         assert x == 43
     t = app2interp_temp(app_test_func)
     f = t.get_function(space)
-    space.setitem(space.w_builtins, space.wrap('AssertionError'), 
+    space.setitem(space.builtin.w_dict, space.wrap('AssertionError'), 
                   build_pytest_assertion(space))
     try:
         f.call_args(Arguments([]))

Modified: pypy/dist/pypy/tool/uid.py
==============================================================================
--- pypy/dist/pypy/tool/uid.py	(original)
+++ pypy/dist/pypy/tool/uid.py	Sat Feb 19 15:30:45 2005
@@ -1,12 +1,16 @@
-import sys
-HUGEINT = (sys.maxint + 1L) * 2L
+import struct
+
+HUGEVAL = 256 ** struct.calcsize('P')
+
+
+def fixid(result):
+    if result < 0:
+        result += HUGEVAL
+    return result
 
 def uid(obj):
     """
     Return the id of an object as an unsigned number so that its hex
     representation makes sense
     """
-    rval = id(obj)
-    if rval < 0:
-        rval += HUGEINT
-    return rval
+    return fixid(id(obj))

Modified: pypy/dist/pypy/translator/genc.py
==============================================================================
--- pypy/dist/pypy/translator/genc.py	(original)
+++ pypy/dist/pypy/translator/genc.py	Sat Feb 19 15:30:45 2005
@@ -35,6 +35,11 @@
 #    return 'PyRun_String("%s", Py_eval_input, PyEval_GetGlobals(), NULL)' % (
 #        source, )
 
+def builtin_base(obj):
+    typ = type(obj)
+    while typ.__module__ != '__builtin__':
+        typ = typ.__base__
+    return typ
 
 class GenC:
     MODNAMES = {}
@@ -75,8 +80,8 @@
             else:
                 stackentry = obj
             self.debugstack = (self.debugstack, stackentry)
-            if (type(obj).__module__ != '__builtin__' and
-                not isinstance(obj, type)):   # skip user-defined metaclasses
+            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:
@@ -310,6 +315,8 @@
                 if isinstance(value, staticmethod) and value.__get__(1) not in self.translator.flowgraphs and self.translator.frozen:
                     print value
                     continue
+                if isinstance(value, classmethod) and value.__get__(cls).__doc__.lstrip().startswith("NOT_RPYTHON"):
+                    continue
                 if isinstance(value, FunctionType) and value not in self.translator.flowgraphs and self.translator.frozen:
                     print value
                     continue

Modified: pypy/dist/pypy/translator/geninterplevel.py
==============================================================================
--- pypy/dist/pypy/translator/geninterplevel.py	(original)
+++ pypy/dist/pypy/translator/geninterplevel.py	Sat Feb 19 15:30:45 2005
@@ -543,10 +543,10 @@
                 #self.initcode.append('m.%s = space.getattr(space.w_builtin, %s)'% (
                 #    name, self.nameof(func.__name__)))
                 # be lazy
-                return "(space.getattr(space.w_builtin, %s))" % self.nameof(func.__name__)
+                return "(space.builtin.get(space.str_w(%s)))" % self.nameof(func.__name__)
             elif modname == 'sys':
                 # be lazy
-                return "(space.getattr(space.w_sys, %s))" % self.nameof(func.__name__)                
+                return "(space.sys.get(space.str_w(%s)))" % self.nameof(func.__name__)                
             else:
                 print ("WARNING: accessing builtin modules different from sys or __builtin__"
                        " is likely producing non-sense")

Modified: pypy/dist/pypy/translator/test/snippet.py
==============================================================================
--- pypy/dist/pypy/translator/test/snippet.py	(original)
+++ pypy/dist/pypy/translator/test/snippet.py	Sat Feb 19 15:30:45 2005
@@ -764,3 +764,52 @@
   return (a,a1,b,b1)
 
 
+# reorg
+
+class BltinCodeReorg:
+  def __init__(self, framecls):
+    self.framecls = framecls
+
+  def call(self, x):
+     frame = self.framecls()
+     frame.set(x)
+     return frame.run()
+
+class BltinFrameReorg:
+  def __init__(self):
+      pass
+
+  def set(self,x):
+      pass
+
+  def run(self):
+      pass
+
+class FBltinFrameReorg(BltinFrameReorg):
+
+  def set(self, x):
+      self.arg = int(x)
+
+  def run(self):
+     return bltin_code_frame_f(self.arg)
+
+class GBltinFrameReorg(BltinFrameReorg):
+
+  def set(self, x):
+      self.arg = str(x)
+
+  def run(self):
+     return bltin_code_frame_g(self.arg)
+
+
+bltin_code_for_f_reorg = BltinCodeReorg(FBltinFrameReorg)
+bltin_code_for_g_reorg = BltinCodeReorg(GBltinFrameReorg)
+
+def bltin_code_frame_reorg():
+  a = bltin_code_for_f_reorg.call(0)
+  a1 = bltin_code_for_f_reorg.call(1)
+  b = bltin_code_for_g_reorg.call("a")
+  b1 = bltin_code_for_g_reorg.call("b")
+  return (a,a1,b,b1)
+
+

Modified: pypy/dist/pypy/translator/test/test_annrpython.py
==============================================================================
--- pypy/dist/pypy/translator/test/test_annrpython.py	(original)
+++ pypy/dist/pypy/translator/test/test_annrpython.py	Sat Feb 19 15:30:45 2005
@@ -494,10 +494,17 @@
         a.build_types(snippet.bltin_code_frame_confusion,[])
         f_flowgraph = a.translator.getflowgraph(snippet.bltin_code_frame_f)
         g_flowgraph = a.translator.getflowgraph(snippet.bltin_code_frame_g)
-        is_int = isinstance(a.binding(f_flowgraph.getreturnvar()),
+        # annotator confused by original bltin code/frame setup, we just get SomeObject here
+        assert a.binding(f_flowgraph.getreturnvar()).__class__ is annmodel.SomeObject
+        assert a.binding(g_flowgraph.getreturnvar()).__class__ is annmodel.SomeObject
+
+    def test_bltin_code_frame_reorg(self):
+        a = RPythonAnnotator()
+        a.build_types(snippet.bltin_code_frame_reorg,[])
+        f_flowgraph = a.translator.getflowgraph(snippet.bltin_code_frame_f)
+        g_flowgraph = a.translator.getflowgraph(snippet.bltin_code_frame_g)
+        assert isinstance(a.binding(f_flowgraph.getreturnvar()),
                             annmodel.SomeInteger)
-        if not is_int:
-            py.test.skip("annotator confused with bltin code/frame setup")
         assert isinstance(a.binding(g_flowgraph.getreturnvar()),
                           annmodel.SomeString)
 

Modified: pypy/dist/pypy/translator/tool/tointerplevel.py
==============================================================================
--- pypy/dist/pypy/translator/tool/tointerplevel.py	(original)
+++ pypy/dist/pypy/translator/tool/tointerplevel.py	Sat Feb 19 15:30:45 2005
@@ -30,6 +30,7 @@
     as = options.as or name
 
     mod = new.module(as)
+    mod.__dict__['__file__'] = modfile
     execfile(modfile, mod.__dict__)
 
     del mod.__dict__['__builtins__']



More information about the Pypy-commit mailing list