[pypy-svn] r10389 - in pypy/dist/pypy: . annotation annotation/test documentation interpreter objspace objspace/flow objspace/flow/test objspace/std tool translator translator/test

pedronis at codespeak.net pedronis at codespeak.net
Thu Apr 7 02:01:09 CEST 2005


Author: pedronis
Date: Thu Apr  7 02:01:08 2005
New Revision: 10389

Removed:
   pypy/dist/pypy/TODO
   pypy/dist/pypy/annotation/binaryop.py
   pypy/dist/pypy/annotation/bookkeeper.py
   pypy/dist/pypy/annotation/builtin.py
   pypy/dist/pypy/annotation/model.py
   pypy/dist/pypy/annotation/test/test_model.py
   pypy/dist/pypy/annotation/unaryop.py
   pypy/dist/pypy/documentation/controlflow.txt
   pypy/dist/pypy/interpreter/baseobjspace.py
   pypy/dist/pypy/interpreter/error.py
   pypy/dist/pypy/interpreter/pyframe.py
   pypy/dist/pypy/interpreter/pyopcode.py
   pypy/dist/pypy/objspace/dummy.py
   pypy/dist/pypy/objspace/flow/objspace.py
   pypy/dist/pypy/objspace/flow/test/test_objspace.py
   pypy/dist/pypy/objspace/std/objspace.py
   pypy/dist/pypy/tool/pytestsupport.py
   pypy/dist/pypy/translator/annrpython.py
   pypy/dist/pypy/translator/geninterplevel.py
   pypy/dist/pypy/translator/test/test_annrpython.py
Log:
pypy-normalize-exception merge:
remove files that will be copied in from the branch




Deleted: /pypy/dist/pypy/TODO
==============================================================================
--- /pypy/dist/pypy/TODO	Thu Apr  7 02:01:08 2005
+++ (empty file)
@@ -1,90 +0,0 @@
-General
-=======
-
-* missing pieces currently borrowed from CPython: the bytecode
-  compiler, a number of C modules, and some types -- as printed
-  when running py.py:  "faking <type xyz>".
-
-* mark debugging variables to make our code more readable 
-
-* extend the testing mechanisms to specifically allow: 
-  - running plain CPython regrtests (including outputtests, 
-    unittests, doctests, ...)  
-  - running modified CPython regrtests againat CPython 
-    as well as against PyPy 
-  - running pure app-level py-test style regrtests 
-  - running interp-level py-test style regrtests 
-  - running doctests with py.test modules 
-
-* not all of CPython's exceptions use the same __init__!
-
-* refactor the cmdline-entrypoints to PyPy aka py.py main.py 
-  interactive.py and traceinteractive.py towards a unified 
-  cmdline tool (py.py) possibly including translator-related
-  things too. 
-
-* cleanup the contents of the tool directory 
-
-* an oldie: move interpreter/unittest_w.py somewhere more appropriate
-  and give it a better name.
-
-* (documentation) remove/retire all web-pages referencing e.g.
-  AnnSpace or other deprecated stuff
-
-* review whatever you like 
-
-StdObjSpace
-===========
-
-* allow CPython's "output-checking" tests to run in a convenient
-  way over StdObjSpace
-
-* String formatting is agonizingly slow.
-
-* Provide an importer that can import packages. (we have a 
-  limited __import__ builtin defined)  <---- done now?
-
-  Consider PEP 302, new import hooks.
-  Try to write as much as possible in app-level.
-  How would PyPy import CPython extensions?
-
-* (documentation) generate a nice dot-graph from the structure of PyPy
-
-* port pypy's testing framework to py.test (probably a sprint topic, 
-  as some discussion how to do it is required) 
-
-* clear out and do a clean implementation of multimethod delegation.
-  The idea is to give 'kinds' to arguments according to their use,
-  e.g. 'numeric argument' or 'object whose identity is preserved'.
-  A 'kind' encapsulates a set of delegation functions. Armin has
-  already written documentation for the envisioned new multimethod 
-  implementation:
-
-  http://codespeak.net/pypy/index.cgi?doc/objspace/multimethod
-
-  (now irrelevant?  not sure... (nowadays, we have the descriptor 
-  mechanism implemented right before EuroPython 2004 for both the 
-  trivial and the stdobjspace))
-
-Translator
-==========
-
-* enhance the translator components to accept more of PyPy ...
-
-Tools
-=====
-
-* add web server thread (!) that allows inspection of e.g.
-  interpreter-level tracebacks (and stop clogging the user's terminal
-  with them).  --> there is some preliminary working code in
-  tool/tb_server
-
-* Interpreter level tracebacks are spectacular in their uselessness,
-  especially since the advent of descroperation.  It should be
-  possible to construct something like an app-level traceback even
-  when there's no OperationError.
-
-* improve traceobjectspace! currently it only catches 
-  calls from outside the space into the space but not
-  the ones where space operations involve calling more space 
-  operations (the latter are not traced)!  (fixed?)

Deleted: /pypy/dist/pypy/annotation/binaryop.py
==============================================================================
--- /pypy/dist/pypy/annotation/binaryop.py	Thu Apr  7 02:01:08 2005
+++ (empty file)
@@ -1,364 +0,0 @@
-"""
-Binary operations between SomeValues.
-"""
-
-from pypy.annotation.pairtype import pair, pairtype
-from pypy.annotation.model import SomeObject, SomeInteger, SomeBool
-from pypy.annotation.model import SomeString, SomeChar, SomeList, SomeDict
-from pypy.annotation.model import SomeTuple, SomeImpossibleValue
-from pypy.annotation.model import SomeInstance, SomeBuiltin, SomeIterator
-from pypy.annotation.model import SomePBC, SomeSlice
-from pypy.annotation.model import unionof, set, setunion, missing_operation
-from pypy.annotation.factory import generalize
-from pypy.annotation.bookkeeper import getbookkeeper
-from pypy.annotation.classdef import isclassdef
-from pypy.objspace.flow.model import Constant
-
-# convenience only!
-def immutablevalue(x):
-    return getbookkeeper().immutablevalue(x)
-
-# XXX unify this with ObjSpace.MethodTable
-BINARY_OPERATIONS = set(['add', 'sub', 'mul', 'div', 'mod',
-                         'and_', 'or_', 'xor',
-                         'getitem', 'setitem',
-                         'inplace_add', 'inplace_sub',
-                         'lt', 'le', 'eq', 'ne', 'gt', 'ge', 'is_',
-                         'union', 'issubtype',
-                         'lshift',
-                         ])
-
-for opname in BINARY_OPERATIONS:
-    missing_operation(pairtype(SomeObject, SomeObject), opname)
-
-class __extend__(pairtype(SomeObject, SomeObject)):
-
-    def union((obj1, obj2)):
-        if obj1 == obj2:
-            return obj1
-        else:
-            result = SomeObject()
-            is_type_of1 = getattr(obj1, 'is_type_of', None)
-            is_type_of2 = getattr(obj2, 'is_type_of', None)
-            if is_type_of1 and is_type_of1 == is_type_of2:
-                result.is_type_of = is_type_of1
-            # try to preserve the origin of SomeObjects
-            if obj1 == result:
-                return obj1
-            elif obj2 == result:
-                return obj2
-            else:
-                return result
-
-    def inplace_add((obj1, obj2)):
-        return pair(obj1, obj2).add()   # default
-
-    def inplace_sub((obj1, obj2)):
-        return pair(obj1, obj2).sub()   # default
-
-    def lt((obj1, obj2)):
-        if obj1.is_constant() and obj2.is_constant():
-            return immutablevalue(obj1.const < obj2.const)
-        else:
-            return SomeBool()
-
-    def le((obj1, obj2)):
-        if obj1.is_constant() and obj2.is_constant():
-            return immutablevalue(obj1.const <= obj2.const)
-        else:
-            return SomeBool()
-
-    def eq((obj1, obj2)):
-        if obj1.is_constant() and obj2.is_constant():
-            return immutablevalue(obj1.const == obj2.const)
-        else:
-            return SomeBool()
-
-    def ne((obj1, obj2)):
-        if obj1.is_constant() and obj2.is_constant():
-            return immutablevalue(obj1.const != obj2.const)
-        else:
-            return SomeBool()
-
-    def gt((obj1, obj2)):
-        if obj1.is_constant() and obj2.is_constant():
-            return immutablevalue(obj1.const > obj2.const)
-        else:
-            return SomeBool()
-
-    def ge((obj1, obj2)):
-        if obj1.is_constant() and obj2.is_constant():
-            return immutablevalue(obj1.const >= obj2.const)
-        else:
-            return SomeBool()
-
-    def is_((obj1, obj2)):
-        # XXX assumption: for "X is Y" we for simplification 
-        #     assume that X is possibly variable and Y constant 
-        #     (and not the other way round) 
-        r = SomeBool()
-        if obj2.is_constant():
-            if obj1.is_constant(): 
-                r.const = obj1.const is obj2.const
-        # XXX HACK HACK HACK
-        # XXX HACK HACK HACK
-        # XXX HACK HACK HACK
-        bk = getbookkeeper()
-        if hasattr(obj1,'is_type_of') and obj2.is_constant():
-            r.knowntypedata = (obj1.is_type_of, bk.valueoftype(obj2.const))
-            return r
-        fn, block, i = bk.position_key
-        annotator = bk.annotator
-        op = block.operations[i]
-        assert op.opname == "is_" 
-        assert len(op.args) == 2
-        assert annotator.binding(op.args[0]) == obj1 
-        r.knowntypedata = ([op.args[0]], obj2)
-        return r
-
-class __extend__(pairtype(SomeInteger, SomeInteger)):
-    # unsignedness is considered a rare and contagious disease
-
-    def union((int1, int2)):
-        return SomeInteger(nonneg = int1.nonneg and int2.nonneg,
-                           unsigned = int1.unsigned or int2.unsigned)
-
-    add = mul = div = mod = or_ = xor = union
-
-    def sub((int1, int2)):
-        return SomeInteger(unsigned = int1.unsigned or int2.unsigned)
-
-    def and_((int1, int2)):
-        return SomeInteger(nonneg = int1.nonneg or int1.nonneg,
-                           unsigned = int1.unsigned or int2.unsigned)
-
-    def lshift((int1, int2)):
-        if int1.unsigned:
-            return SomeInteger(unsigned=True)
-        return SomeInteger()
-
-class __extend__(pairtype(SomeBool, SomeBool)):
-
-    def union((boo1, boo2)):
-        s = SomeBool() 
-        if getattr(boo1, 'const', -1) == getattr(boo2, 'const', -2): 
-            s.const = boo1.const 
-        if hasattr(boo1, 'knowntypedata') and \
-           hasattr(boo2, 'knowntypedata') and \
-           boo1.knowntypedata[0] == boo2.knowntypedata[0]: 
-            s.knowntypedata = (
-                boo1.knowntypedata[0], 
-                unionof(boo1.knowntypedata[1], boo2.knowntypedata[1]))
-        return s 
-
-class __extend__(pairtype(SomeString, SomeString)):
-
-    def union((str1, str2)):
-        return SomeString()
-
-    def add((str1, str2)):
-        return SomeString()
-
-
-class __extend__(pairtype(SomeString, SomeObject)):
-
-    def mod((str, args)):
-        return SomeString()
-
-
-class __extend__(pairtype(SomeList, SomeList)):
-
-    def union((lst1, lst2)):
-        return SomeList(setunion(lst1.factories, lst2.factories),
-                        s_item = unionof(lst1.s_item, lst2.s_item))
-
-    add = union
-
-
-class __extend__(pairtype(SomeList, SomeObject)):
-
-    def inplace_add((lst1, obj2)):
-        s_iter = obj2.iter()
-        pair(lst1, SomeInteger()).setitem(s_iter.next())
-        return lst1
-
-
-class __extend__(pairtype(SomeTuple, SomeTuple)):
-
-    def union((tup1, tup2)):
-        if len(tup1.items) != len(tup2.items):
-            return SomeObject()
-        else:
-            unions = [unionof(x,y) for x,y in zip(tup1.items, tup2.items)]
-            return SomeTuple(items = unions)
-
-    def add((tup1, tup2)):
-        return SomeTuple(items = tup1.items + tup2.items)
-
-
-class __extend__(pairtype(SomeDict, SomeDict)):
-
-    def union((dic1, dic2)):
-        return SomeDict(setunion(dic1.factories, dic2.factories),
-                        unionof(dic1.s_key, dic2.s_key),
-                        unionof(dic1.s_value, dic2.s_value))
-
-
-class __extend__(pairtype(SomeDict, SomeObject)):
-
-    def getitem((dic1, obj2)):
-        return dic1.s_value
-
-    def setitem((dic1, obj2), s_value):
-        generalize(dic1.factories, obj2, s_value)
-
-
-class __extend__(pairtype(SomeSlice, SomeSlice)):
-
-    def union((slic1, slic2)):
-        return SomeSlice(unionof(slic1.start, slic2.start),
-                         unionof(slic1.stop, slic2.stop),
-                         unionof(slic1.step, slic2.step))
-
-
-class __extend__(pairtype(SomeTuple, SomeInteger)):
-    
-    def getitem((tup1, int2)):
-        if int2.is_constant():
-            try:
-                return tup1.items[int2.const]
-            except IndexError:
-                return SomeImpossibleValue()
-        else:
-            return unionof(*tup1.items)
-
-
-class __extend__(pairtype(SomeList, SomeInteger)):
-    
-    def mul((lst1, int2)):
-        return lst1
-
-    def getitem((lst1, int2)):
-        return lst1.s_item
-
-    def setitem((lst1, int2), s_value):
-        generalize(lst1.factories, s_value)
-
-
-class __extend__(pairtype(SomeList, SomeSlice)):
-
-    def getitem((lst, slic)):
-        return SomeList(lst.factories, lst.s_item)
-
-
-class __extend__(pairtype(SomeString, SomeInteger)):
-
-    def getitem((str1, int2)):
-        return SomeChar()
-
-
-class __extend__(pairtype(SomeInteger, SomeList)):
-    
-    def mul((int1, lst2)):
-        return lst2
-
-
-class __extend__(pairtype(SomeInstance, SomeInstance)):
-
-    def union((ins1, ins2)):
-        basedef = ins1.classdef.commonbase(ins2.classdef)
-        if basedef is None:
-            # print warning?
-            return SomeObject()
-        return SomeInstance(basedef)
-
-class __extend__(pairtype(SomeIterator, SomeIterator)):
-
-    def union((iter1, iter2)):
-        return SomeIterator(unionof(iter1.s_item, iter2.s_item))
-
-
-class __extend__(pairtype(SomeBuiltin, SomeBuiltin)):
-
-    def union((bltn1, bltn2)):
-        if bltn1.analyser != bltn2.analyser:
-            assert False, "merging incompatible builtins == BAD!"
-            return SomeObject()
-        else:
-            s_self = unionof(bltn1.s_self, bltn2.s_self)
-            return SomeBuiltin(bltn1.analyser, s_self)
-
-class __extend__(pairtype(SomePBC, SomePBC)):
-    def union((pbc1, pbc2)):       
-        if len(pbc2.prebuiltinstances) > len(pbc1.prebuiltinstances):
-            pbc1, pbc2 = pbc2, pbc1
-        d = pbc1.prebuiltinstances.copy()
-        for x, classdef in pbc2.prebuiltinstances.items():
-            if x in d:
-                if bool(isclassdef(classdef)) ^ bool(isclassdef(d[x])):
-                    raise Exception(
-                        "union failed for %r with classdefs %r and %r" % 
-                        (x, classdef, d[x]))
-                if isclassdef(classdef):
-                    classdef2 = classdef
-                    if classdef != d[x]:
-                        classdef = classdef.commonbase(d[x])
-                        for cand in classdef.getmro():
-                            if x in cand.cls.__dict__.values():
-                                break
-                        else:
-                            assert False, ("confused pbc union trying unwarranted"
-                                           "moving up of method %s from pair %s %s" %
-                                           (x, d[x], classdef2))
-            d[x] = classdef
-        result =  SomePBC(d)
-        return result
-
-class __extend__(pairtype(SomeImpossibleValue, SomeImpossibleValue)):
-    def union((imp1, imp2)):
-        return SomeImpossibleValue(benign=imp1.benign and imp2.benign)
-
-class __extend__(pairtype(SomeImpossibleValue, SomeObject)):
-    def union((imp1, obj2)):
-        return obj2
-
-class __extend__(pairtype(SomeObject, SomeImpossibleValue)):
-    def union((obj1, imp2)):
-        return obj1
-
-class __extend__(pairtype(SomeInstance, SomePBC)):
-    def union((ins, pbc)):
-        if pbc.isNone():
-            return ins
-        classdef = ins.classdef.superdef_containing(pbc.knowntype)
-        if classdef is None:
-            # print warning?
-            return SomeObject()
-        return SomeInstance(classdef)
-
-class __extend__(pairtype(SomePBC, SomeInstance)):
-    def union((pbc, ins)):
-        return pair(ins, pbc).union()
-
-# let mix lists and None for now
-class __extend__(pairtype(SomeList, SomePBC)):
-    def union((lst, pbc)):
-        if pbc.isNone():
-            return lst
-        return SomeObject()
-
-class __extend__(pairtype(SomePBC, SomeList    )):
-    def union((pbc, lst)):
-        return pair(lst, pbc).union()
-
-
-class __extend__(pairtype(SomeObject, SomePBC)):
-    def issubtype((obj, pbc)):
-        s = SomeBool()
-        if obj.is_constant() and pbc.is_constant():
-            s.const = issubclass(obj.const, pbc.const)
-        if hasattr(obj,'is_type_of') and pbc.is_constant():
-            bk = getbookkeeper()
-            s.knowntypedata = (obj.is_type_of, bk.valueoftype(pbc.const))
-        return s
-

Deleted: /pypy/dist/pypy/annotation/bookkeeper.py
==============================================================================
--- /pypy/dist/pypy/annotation/bookkeeper.py	Thu Apr  7 02:01:08 2005
+++ (empty file)
@@ -1,343 +0,0 @@
-"""
-The Bookkeeper class.
-"""
-
-from types import FunctionType, ClassType, MethodType
-from types import BuiltinMethodType
-from pypy.tool.ansi_print import ansi_print
-from pypy.annotation.model import *
-from pypy.annotation.classdef import ClassDef
-from pypy.interpreter.miscutils import getthreadlocals
-from pypy.tool.hack import func_with_new_name
-from pypy.interpreter.pycode import CO_VARARGS
-from pypy.interpreter.pycode import cpython_code_signature
-from pypy.interpreter.argument import ArgErr
-
-import inspect, new
-
-class Bookkeeper:
-    """The log of choices that have been made while analysing the operations.
-    It ensures that the same 'choice objects' will be returned if we ask
-    again during reflowing.  Like ExecutionContext, there is an implicit
-    Bookkeeper that can be obtained from a thread-local variable.
-
-    Currently used for factories and user-defined classes."""
-
-    def __init__(self, annotator):
-        self.annotator = annotator
-        self.creationpoints = {} # map position-in-a-block to its Factory
-        self.userclasses = {}    # map classes to ClassDefs
-        self.userclasseslist = []# userclasses.keys() in creation order
-        self.cachespecializations = {}
-        self.pbccache = {}
-        self.pbctypes = {}
-        self.seen_mutable = {}
-        # import ordering hack
-        global BUILTIN_ANALYZERS
-        from pypy.annotation.builtin import BUILTIN_ANALYZERS
-
-    def enter(self, position_key):
-        """Start of an operation.
-        The operation is uniquely identified by the given key."""
-        self.position_key = position_key
-        getthreadlocals().bookkeeper = self
-
-    def leave(self):
-        """End of an operation."""
-        del getthreadlocals().bookkeeper
-        del self.position_key
-
-    def getfactory(self, factorycls):
-        """Get the Factory associated with the current position,
-        or build it if it doesn't exist yet."""
-        try:
-            factory = self.creationpoints[self.position_key]
-        except KeyError:
-            factory = factorycls()
-            factory.bookkeeper = self
-            factory.position_key = self.position_key
-            self.creationpoints[self.position_key] = factory
-        assert isinstance(factory, factorycls)
-        return factory
-
-    def getclassdef(self, cls):
-        """Get the ClassDef associated with the given user cls."""
-        if cls is object:
-            return None
-        try:
-            return self.userclasses[cls]
-        except KeyError:
-            if cls in self.pbctypes:
-                self.warning("%r gets a ClassDef, but is the type of some PBC"
-                             % (cls,))
-            cdef = ClassDef(cls, self)
-            self.userclasses[cls] = cdef
-            self.userclasseslist.append(cdef)
-            return self.userclasses[cls]
-
-
-    def immutablevalue(self, x):
-        """The most precise SomeValue instance that contains the
-        immutable value x."""
-        tp = type(x)
-        if tp is bool:
-            result = SomeBool()
-        elif tp is int:
-            result = SomeInteger(nonneg = x>=0)
-        elif tp is str:
-            result = SomeString()
-        elif tp is tuple:
-            result = SomeTuple(items = [self.immutablevalue(e) for e in x])
-        elif tp is list:
-            items_s = [self.immutablevalue(e) for e in x]
-            result = SomeList({}, unionof(*items_s))
-        elif tp is dict:   # exactly a dict
-            keys_s   = [self.immutablevalue(e) for e in x.keys()]
-            values_s = [self.immutablevalue(e) for e in x.values()]
-            result = SomeDict({}, unionof(*keys_s), unionof(*values_s))
-        elif ishashable(x) and x in BUILTIN_ANALYZERS:
-            result = SomeBuiltin(BUILTIN_ANALYZERS[x])
-        elif callable(x) or isinstance(x, staticmethod): # XXX
-            # maybe 'x' is a method bound to a not-yet-frozen cache?
-            # fun fun fun.
-            if hasattr(x, 'im_self') and hasattr(x.im_self, '_freeze_'):
-                x.im_self._freeze_()
-            if hasattr(x, '__self__') and x.__self__ is not None:
-                s_self = self.immutablevalue(x.__self__)
-                try:
-                    result = s_self.find_method(x.__name__)
-                except AttributeError:
-                    result = SomeObject()
-            else:
-                return self.getpbc(x)
-        elif hasattr(x, '__class__') \
-                 and x.__class__.__module__ != '__builtin__':
-            # user-defined classes can define a method _freeze_(), which
-            # is called when a prebuilt instance is found.  If the method
-            # returns True, the instance is considered immutable and becomes
-            # a SomePBC().  Otherwise it's just SomeInstance().
-            frozen = hasattr(x, '_freeze_') and x._freeze_()
-            if frozen:
-                return self.getpbc(x)
-            else:
-                clsdef = self.getclassdef(x.__class__)
-                
-                if x not in self.seen_mutable: # avoid circular reflowing, 
-                                               # see for example test_circular_mutable_getattr
-                    for attr in x.__dict__:
-                        clsdef.add_source_for_attribute(attr, x) # can trigger reflowing
-                    self.seen_mutable[x] = True
-                return SomeInstance(clsdef)
-        elif x is None:
-            return self.getpbc(None)
-        else:
-            result = SomeObject()
-        result.const = x
-        return result
-
-    def getpbc(self, x):
-        try:
-            # this is not just an optimization, but needed to avoid
-            # infinitely repeated calls to add_source_for_attribute()
-            return self.pbccache[x]
-        except KeyError:
-            result = SomePBC({x: True}) # pre-built inst
-            #clsdef = self.getclassdef(new_or_old_class(x))
-            #for attr in getattr(x, '__dict__', {}):
-            #    clsdef.add_source_for_attribute(attr, x)
-            self.pbccache[x] = result
-            cls = new_or_old_class(x)
-            if cls not in self.pbctypes:
-                self.pbctypes[cls] = True
-                if cls in self.userclasses:
-                    self.warning("making some PBC of type %r, which has "
-                                 "already got a ClassDef" % (cls,))
-            return result
-
-    def valueoftype(self, t):
-        """The most precise SomeValue instance that contains all
-        objects of type t."""
-        assert isinstance(t, (type, ClassType))
-        if t is bool:
-            return SomeBool()
-        elif t is int:
-            return SomeInteger()
-        elif t is str:
-            return SomeString()
-        elif t is list:
-            return SomeList(factories={})
-        # can't do dict, tuple
-        elif t.__module__ != '__builtin__':
-            classdef = self.getclassdef(t)
-            return SomeInstance(classdef)
-        else:
-            o = SomeObject()
-            o.knowntype = t
-            return o
-
-    def pycall(self, func, args):
-        if func is None:   # consider None as a NULL function pointer
-            return SomeImpossibleValue()
-        if isinstance(func, (type, ClassType)) and \
-            func.__module__ != '__builtin__':
-            cls = func
-            x = getattr(cls, "_specialize_", False)
-            if x:
-                if x == "location":
-                    cls = self.specialize_by_key(cls, self.position_key)
-                else:
-                    raise Exception, \
-                          "unsupported specialization type '%s'"%(x,)
-
-            classdef = self.getclassdef(cls)
-            s_instance = SomeInstance(classdef)
-            # flow into __init__() if the class has got one
-            init = getattr(cls, '__init__', None)
-            if init is not None and init != object.__init__:
-                # don't record the access of __init__ on the classdef
-                # because it is not a dynamic attribute look-up, but
-                # merely a static function call
-                if hasattr(init, 'im_func'):
-                    init = init.im_func
-                else:
-                    assert isinstance(init, BuiltinMethodType)
-                s_init = self.immutablevalue(init)
-                s_init.call(args.prepend(s_instance))
-            else:
-                try:
-                    args.fixedunpack(0)
-                except ValueError:
-                    raise Exception, "no __init__ found in %r" % (cls,)
-            return s_instance
-        if hasattr(func, '__call__') and \
-           isinstance(func.__call__, MethodType):
-            func = func.__call__
-        if hasattr(func, 'im_func'):
-            if func.im_self is not None:
-                s_self = self.immutablevalue(func.im_self)
-                args = args.prepend(s_self)
-            # for debugging only, but useful to keep anyway:
-            try:
-                func.im_func.class_ = func.im_class
-            except AttributeError:
-                # probably a builtin function, we don't care to preserve
-                # class information then
-                pass
-            func = func.im_func
-        assert isinstance(func, FunctionType), "[%s] expected function, got %r" % (self.whereami(), func)
-        # do we need to specialize this function in several versions?
-        x = getattr(func, '_specialize_', False)
-        #if not x: 
-        #    x = 'argtypes'
-        if x:
-            if x == 'argtypes':
-                key = short_type_name(args)
-                func = self.specialize_by_key(func, key,
-                                              func.__name__+'__'+key)
-            elif x == "location":
-                # fully specialize: create one version per call position
-                func = self.specialize_by_key(func, self.position_key)
-            else:
-                raise Exception, "unsupported specialization type '%s'"%(x,)
-
-        elif func.func_code.co_flags & CO_VARARGS:
-            # calls to *arg functions: create one version per number of args
-            assert not args.has_keywords(), (
-                "keyword forbidden in calls to *arg functions")
-            nbargs = len(args.arguments_w)
-            if args.w_stararg is not None:
-                s_len = args.w_stararg.len()
-                assert s_len.is_constant(), "calls require known number of args"
-                nbargs += s_len.const
-            func = self.specialize_by_key(func, nbargs,
-                                          name='%s__%d' % (func.func_name,
-                                                           nbargs))
-
-        # parse the arguments according to the function we are calling
-        signature = cpython_code_signature(func.func_code)
-        defs_s = []
-        if func.func_defaults:
-            for x in func.func_defaults:
-                defs_s.append(self.immutablevalue(x))
-        try:
-            inputcells = args.match_signature(signature, defs_s)
-        except ArgErr, e:
-            assert False, 'ABOUT TO IGNORE %r' % e     # we should take care that we don't end up here anymore
-            return SomeImpossibleValue()
-
-        return self.annotator.recursivecall(func, self.position_key, inputcells)
-
-    def whereami(self):
-        return self.annotator.whereami(self.position_key)
-
-    def warning(self, msg):
-        try:
-            pos = self.whereami()
-        except AttributeError:
-            pos = '?'
-        ansi_print("*** WARNING: [%s] %s" % (pos, msg), esc="31") # RED
-
-    def specialize_by_key(self, thing, key, name=None):
-        key = thing, key
-        try:
-            thing = self.cachespecializations[key]
-        except KeyError:
-            if isinstance(thing, FunctionType):
-                # XXX XXX XXX HAAAAAAAAAAAACK
-                # xxx we need a way to let know subsequent phases (the generator) about the specialized function
-                # the caller flowgraph as it is doesn't.
-                # This line just avoids that the flowgraph of the original function, which is what will be considered
-                # and compiled for now will be computed during generation itself
-                self.annotator.translator.getflowgraph(thing)
-                #
-                thing = func_with_new_name(thing, name or thing.func_name)
-            elif isinstance(thing, (type, ClassType)):
-                superclasses = iter(inspect.getmro(thing))
-                superclasses.next() # skip thing itself
-                for cls in superclasses:
-                    assert not hasattr(cls, "_specialize_"), "for now specialization only for leaf classes"
-                
-                newdict = {}
-                for attrname,val in thing.__dict__.iteritems():
-                    if attrname == '_specialize_': # don't copy the marker
-                        continue
-                    if isinstance(val, FunctionType):
-                        fname = val.func_name
-                        if name:
-                            fname = "%s_for_%s" % (fname, name)
-                        newval = func_with_new_name(val, fname)
-                    # xxx more special cases
-                    else: 
-                        newval  = val
-                    newdict[attrname] = newval
-
-                thing = type(thing)(name or thing.__name__, (thing,), newdict)
-            else:
-                raise Exception, "specializing %r?? why??"%thing
-            self.cachespecializations[key] = thing
-        return thing
-        
-
-def getbookkeeper():
-    """Get the current Bookkeeper.
-    Only works during the analysis of an operation."""
-    return getthreadlocals().bookkeeper
-
-def ishashable(x):
-    try:
-        hash(x)
-    except TypeError:
-        return False
-    else:
-        return True
-
-def short_type_name(args):
-    l = []
-    shape, args_w = args.flatten()
-    for x in args_w:
-        if isinstance(x, SomeInstance) and hasattr(x, 'knowntype'):
-            name = "SI_" + x.knowntype.__name__
-        else:
-            name = x.__class__.__name__
-        l.append(name)
-    return "__".join(l)

Deleted: /pypy/dist/pypy/annotation/builtin.py
==============================================================================
--- /pypy/dist/pypy/annotation/builtin.py	Thu Apr  7 02:01:08 2005
+++ (empty file)
@@ -1,227 +0,0 @@
-"""
-Built-in functions.
-"""
-
-import types
-import sys, math
-from pypy.tool.ansi_print import ansi_print
-from pypy.annotation.model import SomeInteger, SomeObject, SomeChar, SomeBool
-from pypy.annotation.model import SomeList, SomeString, SomeTuple, SomeSlice
-from pypy.annotation.bookkeeper import getbookkeeper
-from pypy.annotation.factory import ListFactory
-from pypy.objspace.flow.model import Constant
-import pypy.objspace.std.restricted_int
-
-# convenience only!
-def immutablevalue(x):
-    return getbookkeeper().immutablevalue(x)
-
-def builtin_len(s_obj):
-    return s_obj.len()
-
-def builtin_range(*args):
-    factory = getbookkeeper().getfactory(ListFactory)
-    factory.generalize(SomeInteger())  # XXX nonneg=...
-    return factory.create()
-
-def builtin_pow(s_base, s_exponent, *args):
-    if s_base.knowntype is s_exponent.knowntype is int:
-        return SomeInteger()
-    else:
-        return SomeObject()
-
-def builtin_int(s_obj):     # we can consider 'int' as a function
-    return SomeInteger()
-
-def restricted_uint(s_obj):    # for r_uint
-    return SomeInteger(nonneg=True, unsigned=True)
-
-def builtin_chr(s_int):
-    return SomeChar()
-
-def builtin_ord(s_chr):
-    return SomeInteger(nonneg=True)
-
-def builtin_id(o):
-    return SomeInteger()
-
-def builtin_hex(o):
-    return SomeString()
-
-def builtin_oct(o):
-    return SomeString()
-
-def builtin_abs(o):
-    return o.__class__()
-
-def builtin_divmod(o1, o2):
-    return SomeTuple([SomeObject(), SomeObject()])    # XXX
-
-def builtin_unicode(s_obj): 
-    return SomeString() 
-
-def builtin_float(s_obj): 
-    return SomeObject() 
-
-def builtin_long(s_str): 
-    return SomeObject() 
-
-def our_issubclass(cls1, cls2):
-    """ we're going to try to be less silly in the face of old-style classes"""
-    return cls2 is object or issubclass(cls1, cls2)
-
-def builtin_isinstance(s_obj, s_type):
-    s = SomeBool() 
-    if s_type.is_constant():
-        typ = s_type.const
-        # XXX bit of a hack:
-        if issubclass(typ, (int, long)):
-            typ = int
-        if s_obj.is_constant():
-            s.const = isinstance(s_obj.const, typ)
-        elif our_issubclass(s_obj.knowntype, typ):
-            s.const = True 
-        elif not our_issubclass(typ, s_obj.knowntype): 
-            s.const = False 
-        # XXX HACK HACK HACK
-        # XXX HACK HACK HACK
-        # XXX HACK HACK HACK
-        bk = getbookkeeper()
-        fn, block, i = bk.position_key
-        annotator = bk.annotator
-        op = block.operations[i]
-        assert op.opname == "simple_call" 
-        assert len(op.args) == 3
-        assert op.args[0] == Constant(isinstance)
-        assert annotator.binding(op.args[1]) == s_obj
-        s.knowntypedata = ([op.args[1]], bk.valueoftype(typ))
-    return s 
-
-def builtin_issubclass(s_cls1, s_cls2):
-    if s_cls1.is_constant() and s_cls2.is_constant():
-        return immutablevalue(issubclass(s_cls1.const, s_cls2.const))
-    else:
-        return SomeBool()
-
-def builtin_getattr(s_obj, s_attr, s_default=None):
-    if not s_attr.is_constant() or not isinstance(s_attr.const, str):
-        ansi_print("UN-RPYTHONIC-WARNING " +
-                   '[%s] getattr(%r, %r) is not RPythonic enough' % (getbookkeeper().whereami(),
-                                                                     s_obj, s_attr),
-                   esc="31") # RED
-        return SomeObject()
-    return s_obj.getattr(s_attr)
-
-def builtin_hasattr(s_obj, s_attr):
-    if not s_attr.is_constant() or not isinstance(s_attr.const, str):
-        ansi_print("UN-RPYTHONIC-WARNING " +
-                   '[%s] hasattr(%r, %r) is not RPythonic enough' % (getbookkeeper().whereami(),
-                                                                     s_obj, s_attr),
-                   esc="31") # RED
-    return SomeBool()
-
-def builtin_hash(s_obj):
-    return SomeInteger()
-
-def builtin_callable(s_obj):
-    return SomeBool()
-
-def builtin_tuple(s_iterable):
-    if isinstance(s_iterable, SomeTuple):
-        return s_iterable
-    return SomeObject()
-
-def builtin_iter(s_obj):
-    return s_obj.iter()
-
-def builtin_type(s_obj, *moreargs):
-    if moreargs:
-        raise Exception, 'type() called with more than one argument'
-    if s_obj.is_constant():
-        return immutablevalue(type(s_obj.const))
-    r = SomeObject()
-    # hack info
-    bk = getbookkeeper()
-    fn, block, i = bk.position_key
-    annotator = bk.annotator
-    op = block.operations[i]
-    assert op.opname == "simple_call" 
-    assert len(op.args) == 2
-    assert op.args[0] == Constant(type)
-    assert annotator.binding(op.args[1]) == s_obj   
-    r.is_type_of = [op.args[1]]
-    return r
-
-def builtin_str(s_obj):
-    return SomeString()
-
-def builtin_repr(s_obj):
-    return SomeString()
-
-def builtin_list(s_iterable):
-    factory = getbookkeeper().getfactory(ListFactory)
-    s_iter = s_iterable.iter()
-    factory.generalize(s_iter.next())
-    return factory.create()
-
-def builtin_zip(s_iterable1, s_iterable2):
-    factory = getbookkeeper().getfactory(ListFactory)
-    s_iter1 = s_iterable1.iter()
-    s_iter2 = s_iterable2.iter()
-    s_tup = SomeTuple((s_iter1.next(),s_iter2.next()))
-    factory.generalize(s_tup)
-    return factory.create()
-
-def builtin_apply(*stuff):
-    print "XXX ignoring apply%r" % (stuff,)
-    return SomeObject()
-
-def builtin_compile(*stuff):
-    s = SomeObject()
-    s.knowntype = types.CodeType
-    return s
-
-def builtin_slice(*args):
-    bk = getbookkeeper()
-    if len(args) == 1:
-        return SomeSlice(
-            bk.immutablevalue(None), args[0], bk.immutablevalue(None))
-    elif len(args) == 2:
-        return SomeSlice(
-            args[0], args[1], bk.immutablevalue(None))
-    elif len(args) == 3:
-        return SomeSlice(
-            args[0], args[1], args[2])
-    else:
-        raise Exception, "bogus call to slice()"
-        
-
-def exception_init(s_self, *args):
-    s_self.setattr(immutablevalue('args'), SomeTuple(args))
-
-def builtin_bool(s_obj):
-    return SomeBool()
-
-def count(s_obj):
-    return SomeInteger()
-
-def math_fmod(x, y):
-    return SomeObject()
-
-def math_floor(x):
-    return SomeObject()
-
-# collect all functions
-import __builtin__
-BUILTIN_ANALYZERS = {}
-for name, value in globals().items():
-    if name.startswith('builtin_'):
-        original = getattr(__builtin__, name[8:])
-        BUILTIN_ANALYZERS[original] = value
-
-BUILTIN_ANALYZERS[pypy.objspace.std.restricted_int.r_int] = builtin_int
-BUILTIN_ANALYZERS[pypy.objspace.std.restricted_int.r_uint] = restricted_uint
-BUILTIN_ANALYZERS[Exception.__init__.im_func] = exception_init
-BUILTIN_ANALYZERS[sys.getrefcount] = count
-BUILTIN_ANALYZERS[math.fmod] = math_fmod
-BUILTIN_ANALYZERS[math.floor] = math_floor

Deleted: /pypy/dist/pypy/annotation/model.py
==============================================================================
--- /pypy/dist/pypy/annotation/model.py	Thu Apr  7 02:01:08 2005
+++ (empty file)
@@ -1,295 +0,0 @@
-"""
-This file defines the 'subset' SomeValue classes.
-
-An instance of a SomeValue class stands for a Python object that has some
-known properties, for example that is known to be a list of non-negative
-integers.  Each instance can be considered as an object that is only
-'partially defined'.  Another point of view is that each instance is a
-generic element in some specific subset of the set of all objects.
-
-"""
-
-# Old terminology still in use here and there:
-#    SomeValue means one of the SomeXxx classes in this file.
-#    Cell is an instance of one of these classes.
-#
-# Think about cells as potato-shaped circles in a diagram:
-#    ______________________________________________________
-#   / SomeObject()                                         \
-#  /   ___________________________          ______________  \
-#  |  / SomeInteger(nonneg=False) \____    / SomeString() \  \
-#  | /     __________________________  \   |              |  |
-#  | |    / SomeInteger(nonneg=True) \ |   |      "hello" |  |
-#  | |    |   0    42       _________/ |   \______________/  |
-#  | \ -3 \________________/           /                     |
-#  \  \                     -5   _____/                      /
-#   \  \________________________/              3.1416       /
-#    \_____________________________________________________/
-#
-
-
-from types import BuiltinFunctionType, MethodType
-import pypy
-from pypy.annotation.pairtype import pair, extendabletype
-from pypy.objspace.flow.model import Constant
-import inspect
-
-
-DEBUG = True    # set to False to disable recording of debugging information
-
-
-class SomeObject:
-    """The set of all objects.  Each instance stands
-    for an arbitrary object about which nothing is known."""
-    __metaclass__ = extendabletype
-    knowntype = object
-    def __eq__(self, other):
-        return (self.__class__ is other.__class__ and
-                self.__dict__  == other.__dict__)
-    def __ne__(self, other):
-        return not (self == other)
-    def __repr__(self):
-        items = self.__dict__.items()
-        items.sort()
-        args = []
-        for k, v in items:
-            m = getattr(self, 'fmt_' + k, repr)
-            r = m(v)
-            if r is not None:
-                args.append('%s=%s'%(k, r))
-        kwds = ', '.join(args)
-        return '%s(%s)' % (self.__class__.__name__, kwds)
-
-    def fmt_knowntype(self, t):
-        return t.__name__
-    
-    def contains(self, other):
-        return self == other or pair(self, other).union() == self
-
-    def is_constant(self):
-        return hasattr(self, 'const')
-
-    # for debugging, record where each instance comes from
-    # this is disabled if DEBUG is set to False
-    _coming_from = {}
-    def __new__(cls, *args, **kw):
-        self = super(SomeObject, cls).__new__(cls, *args, **kw)
-        if DEBUG:
-            try:
-                bookkeeper = pypy.annotation.bookkeeper.getbookkeeper()
-                position_key = bookkeeper.position_key
-            except AttributeError:
-                pass
-            else:
-                SomeObject._coming_from[id(self)] = position_key, None
-        return self
-    def origin(self):
-        return SomeObject._coming_from.get(id(self), (None, None))[0]
-    origin = property(origin)
-    def caused_by_merge(self):
-        return SomeObject._coming_from.get(id(self), (None, None))[1]
-    def set_caused_by_merge(self, nvalue):
-        SomeObject._coming_from[id(self)] = self.origin, nvalue
-    caused_by_merge = property(caused_by_merge, set_caused_by_merge)
-    del set_caused_by_merge
-
-
-class SomeInteger(SomeObject):
-    "Stands for an object which is known to be an integer."
-    knowntype = int
-    def __init__(self, nonneg=False, unsigned=False):
-        self.nonneg = nonneg
-        self.unsigned = unsigned  # pypy.objspace.std.restricted_int.r_uint
-
-
-class SomeBool(SomeInteger):
-    "Stands for true or false."
-    knowntype = bool
-    nonneg = True
-    unsigned = False
-    def __init__(self):
-        pass
-
-
-class SomeString(SomeObject):
-    "Stands for an object which is known to be a string."
-    knowntype = str
-
-
-class SomeChar(SomeString):
-    "Stands for an object known to be a string of length 1."
-
-
-class SomeList(SomeObject):
-    "Stands for a homogenous list of any length."
-    knowntype = list
-    def __init__(self, factories, s_item=SomeObject()):
-        self.factories = factories
-        self.s_item = s_item     # general enough for any element
-
-
-class SomeSlice(SomeObject):
-    knowntype = slice
-    def __init__(self, start, stop, step):
-        self.start = start
-        self.stop = stop
-        self.step = step
-
-
-class SomeTuple(SomeObject):
-    "Stands for a tuple of known length."
-    knowntype = tuple
-    def __init__(self, items):
-        self.items = tuple(items)   # tuple of s_xxx elements
-        for i in items:
-            if not i.is_constant():
-                break
-        else:
-            self.const = tuple([i.const for i in items])
-
-
-class SomeDict(SomeObject):
-    "Stands for a dict."
-    knowntype = dict
-    def __init__(self, factories, s_key, s_value):
-        self.factories = factories
-        self.s_key = s_key
-        self.s_value = s_value
-
-
-class SomeIterator(SomeObject):
-    "Stands for an iterator returning objects of a known type."
-    knowntype = type(iter([]))  # arbitrarily chose seqiter as the type
-    def __init__(self, s_item=SomeObject()):
-        self.s_item = s_item
-
-
-class SomeInstance(SomeObject):
-    "Stands for an instance of a (user-defined) class."
-    def __init__(self, classdef):
-        self.classdef = classdef
-        self.knowntype = classdef.cls
-    def fmt_knowntype(self, kt):
-        return None
-    def fmt_classdef(self, cd):
-        return cd.cls.__name__
-
-def new_or_old_class(c):
-    if hasattr(c, '__class__'):
-        return c.__class__
-    else:
-        return type(c)
-
-
-class SomePBC(SomeObject):
-    """Stands for a global user instance, built prior to the analysis,
-    or a set of such instances."""
-    def __init__(self, prebuiltinstances):
-        # prebuiltinstances is a dictionary containing concrete python
-        # objects as keys.
-        # if the key is a function, the value can be a classdef to
-        # indicate that it is really a method.
-        prebuiltinstances = prebuiltinstances.copy()
-        self.prebuiltinstances = prebuiltinstances
-        self.simplify()
-        if self.isNone():
-            self.knowntype = type(None)
-        else:
-            self.knowntype = reduce(commonbase,
-                                    [new_or_old_class(x)
-                                     for x in prebuiltinstances
-                                     if x is not None])
-        if prebuiltinstances.values() == [True]:
-            # hack for the convenience of direct callers to SomePBC():
-            # only if there is a single object in prebuiltinstances and
-            # it doesn't have an associated ClassDef
-            self.const, = prebuiltinstances
-    def simplify(self):
-        # We check that the dictionary does not contain at the same time
-        # a function bound to a classdef, and constant bound method objects
-        # on that class.
-        for x, ignored in self.prebuiltinstances.items():
-            if isinstance(x, MethodType) and x.im_func in self.prebuiltinstances:
-                classdef = self.prebuiltinstances[x.im_func]
-                if isinstance(x.im_self, classdef.cls):
-                    del self.prebuiltinstances[x]
-
-    def isNone(self):
-        return self.prebuiltinstances == {None:True}
-
-    def fmt_prebuiltinstances(self, pbis):
-        if hasattr(self, 'const'):
-            return None
-        else:
-            return '{...%s...}'%(len(pbis),)
-
-    def fmt_knowntype(self, kt):
-        if self.is_constant():
-            return None
-        else:
-            return kt.__name__
-
-
-class SomeBuiltin(SomeObject):
-    "Stands for a built-in function or method with special-cased analysis."
-    knowntype = BuiltinFunctionType  # == BuiltinMethodType
-    def __init__(self, analyser, s_self=None):
-        self.analyser = analyser
-        self.s_self = s_self
-
-
-class SomeImpossibleValue(SomeObject):
-    """The empty set.  Instances are placeholders for objects that
-    will never show up at run-time, e.g. elements of an empty list."""
-    def __init__(self, benign=False):
-        self.benign = benign
-
-
-def unionof(*somevalues):
-    "The most precise SomeValue instance that contains all the values."
-    s1 = SomeImpossibleValue(benign=len(somevalues)>0)
-    for s2 in somevalues:
-        if s1 != s2:
-            s1 = pair(s1, s2).union()
-    if DEBUG and s1.caused_by_merge is None and len(somevalues) > 1:
-        s1.caused_by_merge = somevalues
-    return s1
-
-# ____________________________________________________________
-# internal
-
-def setunion(d1, d2):
-    "Union of two sets represented as dictionaries."
-    d = d1.copy()
-    d.update(d2)
-    return d
-
-def set(it):
-    "Turn an iterable into a set."
-    d = {}
-    for x in it:
-        d[x] = True
-    return d
-
-def commonbase(cls1, cls2):   # XXX single inheritance only  XXX hum
-    l1 = inspect.getmro(cls1)
-    l2 = inspect.getmro(cls2) 
-    if l1[-1] != object: 
-        l1 = l1 + (object,) 
-    if l2[-1] != object: 
-        l2 = l2 + (object,) 
-    for x in l1: 
-        if x in l2: 
-            return x 
-    assert 0, "couldn't get to commonbase of %r and %r" % (cls1, cls2)
-
-def missing_operation(cls, name):
-    def default_op(*args):
-        #print '* warning, no type available for %s(%s)' % (
-        #    name, ', '.join([repr(a) for a in args]))
-        return SomeObject()
-    setattr(cls, name, default_op)
-
-# this has the side-effect of registering the unary and binary operations
-from pypy.annotation.unaryop  import UNARY_OPERATIONS
-from pypy.annotation.binaryop import BINARY_OPERATIONS

Deleted: /pypy/dist/pypy/annotation/test/test_model.py
==============================================================================
--- /pypy/dist/pypy/annotation/test/test_model.py	Thu Apr  7 02:01:08 2005
+++ (empty file)
@@ -1,63 +0,0 @@
-
-import autopath
-from pypy.annotation.model import *
-
-
-s1 = SomeObject()
-s2 = SomeInteger(nonneg=True)
-s3 = SomeInteger(nonneg=False)
-s4 = SomeList({}, SomeTuple([SomeInteger(nonneg=True), SomeString()]))
-s5 = SomeList({}, SomeTuple([SomeInteger(nonneg=False), SomeString()]))
-s6 = SomeImpossibleValue()
-slist = [s1,s2,s3,s4,s5,s6]
-
-def test_equality():
-    assert s1 != s2 != s3 != s4 != s5 != s6
-    assert s1 == SomeObject()
-    assert s2 == SomeInteger(nonneg=True)
-    assert s3 == SomeInteger(nonneg=False)
-    assert s4 == SomeList({}, SomeTuple([SomeInteger(nonneg=True), SomeString()]))
-    assert s5 == SomeList({}, SomeTuple([SomeInteger(nonneg=False), SomeString()]))
-    assert s6 == SomeImpossibleValue()
-
-def test_contains():
-    assert ([(s,t) for s in slist for t in slist if s.contains(t)] ==
-            [(s1,s1), (s1,s2), (s1,s3), (s1,s4), (s1,s5), (s1,s6),
-                      (s2,s2),                            (s2,s6),
-                      (s3,s2), (s3,s3),                   (s3,s6),
-                                        (s4,s4),          (s4,s6),
-                                        (s5,s4), (s5,s5), (s5,s6),
-                                                          (s6,s6)])
-
-def test_union():
-    assert ([unionof(s,t) for s in slist for t in slist] ==
-            [s1, s1, s1, s1, s1, s1,
-             s1, s2, s3, s1, s1, s2,
-             s1, s3, s3, s1, s1, s3,
-             s1, s1, s1, s4, s5, s4,
-             s1, s1, s1, s5, s5, s5,
-             s1, s2, s3, s4, s5, s6])
-
-def test_commonbase_simple():
-    class A0: 
-        pass
-    class A1(A0): 
-        pass
-    class A2(A0): 
-        pass
-    class B1(object):
-        pass
-    class B2(object):
-        pass
-    class B3(object, A0):
-        pass
-    assert commonbase(A1,A2) is A0 
-    assert commonbase(A1,A0) is A0
-    assert commonbase(A1,A1) is A1
-    assert commonbase(A2,B2) is object 
-    assert commonbase(A2,B3) is A0 
-
-if __name__ == '__main__':
-    for name, value in globals().items():
-        if name.startswith('test_'):
-            value()

Deleted: /pypy/dist/pypy/annotation/unaryop.py
==============================================================================
--- /pypy/dist/pypy/annotation/unaryop.py	Thu Apr  7 02:01:08 2005
+++ (empty file)
@@ -1,312 +0,0 @@
-"""
-Unary operations on SomeValues.
-"""
-
-from types import FunctionType
-from pypy.interpreter.argument import Arguments
-from pypy.annotation.pairtype import pair
-from pypy.annotation.model import SomeObject, SomeInteger, SomeBool
-from pypy.annotation.model import SomeString, SomeChar, SomeList, SomeDict
-from pypy.annotation.model import SomeTuple, SomeImpossibleValue
-from pypy.annotation.model import SomeInstance, SomeBuiltin 
-from pypy.annotation.model import SomeIterator, SomePBC, new_or_old_class
-from pypy.annotation.model import unionof, set, setunion, missing_operation
-from pypy.annotation.factory import BlockedInference, generalize, ListFactory
-from pypy.annotation.bookkeeper import getbookkeeper
-from pypy.annotation.classdef import isclassdef
-
-# convenience only!
-def immutablevalue(x):
-    return getbookkeeper().immutablevalue(x)
-
-UNARY_OPERATIONS = set(['len', 'is_true', 'getattr', 'setattr',
-                        'simple_call', 'call_args',
-                        'iter', 'next', 'invert', 'type'])
-
-for opname in UNARY_OPERATIONS:
-    missing_operation(SomeObject, opname)
-
-
-class __extend__(SomeObject):
-
-    def type(obj):
-        if obj.is_constant():
-            r = immutablevalue(obj.knowntype)
-        else:
-            r = SomeObject()
-        bk = getbookkeeper()
-        fn, block, i = bk.position_key
-        annotator = bk.annotator
-        op = block.operations[i]
-        assert op.opname == "type" 
-        assert len(op.args) == 1
-        assert annotator.binding(op.args[0]) == obj
-        r.is_type_of = [op.args[0]]
-        return r
-    
-    def len(obj):
-        return SomeInteger(nonneg=True)
-
-    def is_true(obj):
-        if obj.is_constant():
-            return immutablevalue(bool(obj.const))
-        else:
-            s_len = obj.len()
-            if s_len.is_constant():
-                return immutablevalue(s_len.const > 0)
-            else:
-                return SomeBool()
-
-    def find_method(obj, name):
-        "Look for a special-case implementation for the named method."
-        analyser = getattr(obj.__class__, 'method_' + name)
-        return SomeBuiltin(analyser, obj)
-
-    def getattr(obj, s_attr):
-        # get a SomeBuiltin if the SomeObject has
-        # a corresponding method to handle it
-        if s_attr.is_constant() and isinstance(s_attr.const, str):
-            attr = s_attr.const
-            try:
-                return obj.find_method(attr)
-            except AttributeError:
-                pass
-            # if the SomeObject is itself a constant, allow reading its attrs
-            if obj.is_constant() and hasattr(obj.const, attr):
-                return immutablevalue(getattr(obj.const, attr))
-        return SomeObject()
-
-    def bindcallables(obj, classdef):
-        return obj   # default unbound __get__ implementation
-
-    def simple_call(obj, *args_s):
-        space = RPythonCallsSpace()
-        return obj.call(Arguments(space, args_s))
-
-    def call_args(obj, s_shape, *args_s):
-        space = RPythonCallsSpace()
-        return obj.call(Arguments.fromshape(space, s_shape.const, args_s))
-
-    def call(obj, args):
-        #raise Exception, "cannot follow call_args%r" % ((obj, args),)
-        getbookkeeper().warning("cannot follow call(%r, %r)" % (obj, args))
-        return SomeObject()
-
-class __extend__(SomeInteger):
-
-    def invert(self):
-        if self.unsigned:
-            return SomeInteger(unsigned=True)
-        return SomeInteger()
-
-
-class __extend__(SomeBool):
-    def is_true(self):
-        return self
-
-class __extend__(SomeTuple):
-
-    def len(tup):
-        return immutablevalue(len(tup.items))
-
-    def iter(tup):
-        return SomeIterator(unionof(*tup.items))
-
-
-class __extend__(SomeList):
-
-    def method_append(lst, s_value):
-        pair(lst, SomeInteger()).setitem(s_value)
-
-    def method_extend(lst, s_iterable):
-        s_iter = s_iterable.iter()
-        pair(lst, SomeInteger()).setitem(s_iter.next())
-
-    def method_reverse(lst):
-        pass
-
-    def method_insert(lst, s_index, s_value):
-        pair(lst, SomeInteger()).setitem(s_value)
-        
-    def method_pop(lst, s_index=None):
-        return lst.s_item
-
-    def iter(lst):
-        return SomeIterator(lst.s_item)
-
-class __extend__(SomeDict):
-    def iter(dct):
-        return SomeIterator(dct.s_key)
-
-    def method_copy(dct):
-        return SomeDict(dct.factories, dct.s_key, dct.s_value)
-
-    def method_update(dct1, dct2):
-        generalize(dct1.factories, dct2.s_key, dct2.s_value)
-
-    def method_keys(dct):
-        factory = getbookkeeper().getfactory(ListFactory)
-        factory.generalize(dct.s_key)
-        return factory.create()
-
-    def method_values(dct):
-        factory = getbookkeeper().getfactory(ListFactory)
-        factory.generalize(dct.s_value)
-        return factory.create()
-
-    def method_items(dct):
-        factory = getbookkeeper().getfactory(ListFactory)
-        factory.generalize(SomeTuple((dct.s_key, dct.s_value)))
-        return factory.create()
-        
-
-        
-class __extend__(SomeString):
-
-    def method_join(str, s_list):
-        return SomeString()
-
-    def iter(str):
-        return SomeIterator(SomeChar())
-
-
-class __extend__(SomeChar):
-
-    def len(chr):
-        return immutablevalue(1)
-
-
-class __extend__(SomeIterator):
-
-    def next(itr):
-        return itr.s_item
-
-
-class __extend__(SomeInstance):
-
-    def getattr(ins, s_attr):
-        if s_attr.is_constant() and isinstance(s_attr.const, str):
-            attr = s_attr.const
-            attrdef = ins.classdef.find_attribute(attr)
-            position = getbookkeeper().position_key
-            attrdef.read_locations[position] = True
-            s_result = attrdef.getvalue()
-            # hack: if s_result is a set of methods, discard the ones
-            #       that can't possibly apply to an instance of ins.classdef.
-            # XXX do it more nicely
-            if isinstance(s_result, SomePBC):
-                s_result = ins.classdef.matching(s_result, attr)
-            return s_result
-        return SomeObject()
-
-    def setattr(ins, s_attr, s_value):
-        if s_attr.is_constant() and isinstance(s_attr.const, str):
-            attr = s_attr.const
-            # find the (possibly parent) class where this attr is defined
-            clsdef = ins.classdef.locate_attribute(attr)
-            attrdef = clsdef.attrs[attr]
-            attrdef.readonly = False
-
-            # if the attrdef is new, this must fail
-            if attrdef.getvalue().contains(s_value):
-                return
-            # create or update the attribute in clsdef
-            clsdef.generalize_attr(attr, s_value)
-
-
-class __extend__(SomeBuiltin):
-    def simple_call(bltn, *args):
-        if bltn.s_self is not None:
-            return bltn.analyser(bltn.s_self, *args)
-        else:
-            return bltn.analyser(*args)
-
-    def call(bltn, args):
-        args, kw = args.unpack()
-        assert not kw, "don't call builtins with keywords arguments"
-        if bltn.s_self is not None:
-            return bltn.analyser(bltn.s_self, *args)
-        else:
-            return bltn.analyser(*args)
-        
-
-class __extend__(SomePBC):
-
-    def getattr(pbc, s_attr):
-        bookkeeper = getbookkeeper()
-        assert s_attr.is_constant()
-        attr = s_attr.const
-        actuals = []
-        for c in pbc.prebuiltinstances:
-            if hasattr(c, attr):
-                # force the attribute to be considered on the class
-                ##classdef = bookkeeper.getclassdef(new_or_old_class(c))
-                ##classdef.find_attribute(attr).getvalue()
-                # but only return the more precise result getattr(c, attr)
-                actuals.append(immutablevalue(getattr(c, attr)))
-        return unionof(*actuals)
-
-    def setattr(pbc, s_attr, s_value):
-        getbookkeeper().warning("setattr not wanted on %r" % (pbc,))
-
-    def call(pbc, args):
-        bookkeeper = getbookkeeper()
-        results = []
-        for func, classdef in pbc.prebuiltinstances.items():
-            if isclassdef(classdef): 
-                s_self = SomeInstance(classdef)
-                args1 = args.prepend(s_self)
-            else:
-                args1 = args
-            results.append(bookkeeper.pycall(func, args1))
-        return unionof(*results) 
-
-    def bindcallables(pbc, classdef):   
-        """ turn the callables in the given SomeCallable 'cal' 
-            into bound versions.
-        """
-        d = {}
-        for func, value in pbc.prebuiltinstances.items():
-            if isinstance(func, FunctionType): 
-                if isclassdef(value):
-                    getbookkeeper().warning("rebinding an already bound "
-                                            "method %r with %r" % (func, value))
-                d[func] = classdef
-            elif isinstance(func, staticmethod):
-                d[func.__get__(43)] = value
-            else:
-                d[func] = value 
-        return SomePBC(d)
-
-    def is_true(pbc):
-        outcome = None
-        for c in pbc.prebuiltinstances:
-            if outcome is None:
-                outcome = bool(c)
-            else:
-                if outcome != bool(c):
-                    return SomeBool()
-        return immutablevalue(outcome)
-            
-            
-class RPythonCallsSpace:
-    """Pseudo Object Space providing almost no real operation.
-    For the Arguments class: if it really needs other operations, it means
-    that the call pattern is too complex for R-Python.
-    """
-    def newtuple(self, items_s):
-        return SomeTuple(items_s)
-
-    def newdict(self, stuff):
-        raise CallPatternTooComplex, "'**' argument"
-
-    def unpackiterable(self, s_obj, expected_length=None):
-        if isinstance(s_obj, SomeTuple):
-            if (expected_length is not None and
-                expected_length != len(s_obj.items)):
-                raise ValueError
-            return s_obj.items
-        raise CallPatternTooComplex, "'*' argument must be SomeTuple"
-
-class CallPatternTooComplex(Exception):
-    pass

Deleted: /pypy/dist/pypy/documentation/controlflow.txt
==============================================================================
--- /pypy/dist/pypy/documentation/controlflow.txt	Thu Apr  7 02:01:08 2005
+++ (empty file)
@@ -1,102 +0,0 @@
-FlowObjSpace
-============
-
-Introduction
-------------
-
-The FlowObjSpace generates a control-flow graph from a function. This graph also contains a trace of the individual operations, so that it is actually just an alternate representation for the function.
-
-The FlowObjSpace is an object space, which means that it exports the standard object space interface and it is driven by the interpreter.
-
-The basic idea is that if the interpreter is given a function, e.g.::
-
-  def f(n):
-    return 3*n+2
-
-it will do whatever bytecode dispatching and stack-shuffling needed, during which it issues a sequence of calls to the object space.  The FlowObjSpace merely records these calls (corresponding to "operations") in a structure called a basic block.  To track which value goes where, the FlowObjSpace invents placeholder "wrapped objects" and give them to the interpreter, so that they appear in some next operation.
-
-For example, if the placeholder ``v1`` is given as the argument to the above function, the interpreter will call ``v2 = space.mul(space.wrap(3), v1)`` and then ``v3 = space.add(v2, space.wrap(2))`` and return ``v3`` as the result.  During these calls the FlowObjSpace will record a basic block::
-
-  Block(v1):     # input argument
-    v2 = mul(Constant(3), v1)
-    v3 = add(v2, Constant(2))
-
-
-The Flow model
---------------
-
-``pypy.objspace.flow.model`` defines the data model used by the flow graphs, as created by the FlowObjSpace, manipulated by ``pypy.translator.simplify`` and ``pypy.translator.transform``, and in general read by almost all the modules in ``pypy.translator``.
-
-It is recommended to play with ``python translator.py`` on a few examples to get an idea of the structure of flow graphs.  Here is a short summary of the non-obvious parts.
-
-
-FunctionGraph
-    A container for one graph (corresponding to one function).
-
-    :startblock:   the first block.  It is where the control goes when the function is called.  The input arguments of the startblock are the function's arguments.  If the function takes a ``*args`` argument, the ``args`` tuple is given as the last input argument of the startblock.
-    :returnblock:  the (unique) block that performs a function return.  It is empty, not actually containing any ``return`` operation; the return is implicit.  The returned value is the unique input variable of the returnblock.
-    :exceptblock:  the (unique) block that raises an exception out of the function.  The two input variables are the exception class and the exception value, respectively.  (No other block will actually link to the exceptblock if the function does not explicitely raise exceptions.)
-
-
-Block
-    A basic block, containing a list of operations and ending in jumps to other basic blocks.  All the values that are "live" during the execution of the block are stored in Variables.  Each basic block uses its own distinct Variables.
-
-    :inputargs:   list of fresh, distinct Variables that represent all the values that can enter this block from any of the previous blocks.
-    :operations:  list of SpaceOperations.
-    :exitswitch:  see below
-    :exits:       list of Links representing possible jumps from the end of this basic block to the beginning of other basic blocks.
-
-    Each Block ends in one of the following ways:
-
-    * unconditional jump: exitswitch is None, exits contains a single Link.
-    * conditional jump: exitswitch is one of the Variables that appear in the Block, and exits contains one or more Links (usually 2).  Each Link's exitcase gives a concrete value.  This is the equivalent of a "switch": the control follows the Link whose exitcase matches the run-time value of the exitswitch Variable.  It is a run-time error if the Variable doesn't match any exitcase.  (Currently only used with 2 Links whose exitcase are False and True, respectively.)
-    * exception catching: exitswitch is ``Constant(last_exception)``.  The first Link has exitcase set to None and represents the non-exceptional path.  The next Links have exitcase set to a subclass of Exception, and are taken when the *last* operation of the basic block raises a matching exception.  (Thus the basic block must not be empty, and only the last operation is protected by the handler.)
-    * return or except: the returnblock and the exceptblock have operations set to an empty tuple, exitswitch to None, and exits empty.
-
-
-Link
-    A link from one basic block to another.
-
-    :prevblock:  the Block that this Link is an exit of.
-    :target:     the target Block to which this Link points to.
-    :args:       a list of Variables and Constants, of the same size as the target Block's inputargs, which gives all the values passed into the next block.  (Note that each Variable used in the prevblock may appear zero, one or more times in the ``args`` list.)
-    :exitcase:   see above.
-
-    Note that ``args`` uses Variables from the prevblock, which are matched to the target block's ``inputargs`` by position, as in a tuple assignment or function call would do.
-
-
-SpaceOperation
-    A recorded (or otherwise generated) basic operation.
-
-    :opname:  the name of the operation.  Generally one from the list in ``pypy.interpreter.baseobjspace``.
-    :args:    list of arguments.  Each one is a Constant or a Variable seen previously in the basic block.
-    :result:  a *new* Variable into which the result is to be stored.
-
-    Note that operations usually cannot implicitely raise exceptions at run-time; so for example, code generators can assume that a ``getitem`` operation on a list is safe and can be performed without bound checking.  The exceptions to this rule are: (1) if the operation is the last in the block, which ends with ``exitswitch == Constant(last_exception)``, then the implicit exceptions must be checked for, generated, and caught appropriately; (2) calls to other functions, as per ``simple_call`` or ``call_args``, can always raise whatever the called function can raise --- and such exceptions must be passed through to the parent unless they are caught as above.
-
-
-Variable
-    A placeholder for a run-time value.  There is mostly debugging stuff here.
-
-    :name:  it is good style to use the Variable object itself instead of its ``name`` attribute to reference a value, although the ``name`` is guaranteed unique.
-
-
-Constant
-    A constant value used as argument to a SpaceOperation, or as value to pass across a Link to initialize an input Variable in the target Block.
-
-    :value:  the concrete value represented by this Constant.
-    :key:    a hashable object representing the value.
-
-    A Constant can occasionally store a mutable Python object.  It represents a static, pre-initialized, read-only version of that object.  The flow graph should not attempt to actually mutate such Constants.
-
-
-How the FlowObjSpace works
---------------------------
-
-The FlowObjSpace works by recording all operations issued by the interpreter into basic blocks.  A basic block ends in one of two cases: when the interpreters calls ``is_true()``, or when a joinpoint is reached.
-
-* A joinpoint occurs when the next operation is about to be recorded into the current block, but there is already another block that records an operation for the same bytecode position.  This means that the interpreter has closed a loop and is interpreting already-seen code again.  In this situation, we interrupt the interpreter and we make a link from the end of the current block back to the previous block, thus closing the loop in the flow graph as well.  (Note that this occurs only when an operation is about to be recorded, which allows some amount of constant-folding.)
-
-* If the interpreter calls ``is_true()``, the FlowObjSpace doesn't generally know if the answer should be True or False, so it puts a conditional jump and generates two successor blocks for the current basic block.  There is some trickery involved so that the interpreter is fooled into thinking that ``is_true()`` first returns False (and the subsequent operations are recorded in the first successor block), and later the *same* call to ``is_true()`` also returns True (and the subsequent operations go this time to the other successor block).
-
-(This section to be extended...)

Deleted: /pypy/dist/pypy/interpreter/baseobjspace.py
==============================================================================
--- /pypy/dist/pypy/interpreter/baseobjspace.py	Thu Apr  7 02:01:08 2005
+++ (empty file)
@@ -1,477 +0,0 @@
-from pypy.interpreter.executioncontext import ExecutionContext
-from pypy.interpreter.error import OperationError
-from pypy.interpreter.miscutils import getthreadlocals
-from pypy.interpreter.argument import Arguments
-from pypy.tool.cache import Cache 
-
-__all__ = ['ObjSpace', 'OperationError', 'Wrappable', 'BaseWrappable',
-           'W_Root']
-
-
-class W_Root:
-    """This is the abstract root class of all wrapped objects that live
-    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)
-
-class BaseWrappable(W_Root):
-    """A subclass of BaseWrappable is an internal, interpreter-level class
-    that can nevertheless be exposed at application-level by space.wrap()."""
-    def __spacebind__(self, space):
-        return self
-
-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"""
-    
-    full_exceptions = True  # full support for exceptions (normalization & more)
-
-    def __init__(self):
-        "NOT_RPYTHON: Basic initialization of objects."
-        self._gatewaycache = Cache()
-        self._codecache = Cache()
-        # set recursion limit
-        # sets all the internal descriptors
-        self.initialize()
-        
-    def __repr__(self):
-        return self.__class__.__name__
-
-    def setbuiltinmodule(self, name, importname=None): 
-        """NOT_RPYTHON. load a lazy pypy/module and put it into sys.modules"""
-        if importname is None: 
-            importname = name 
-        Module = __import__("pypy.module.%s" % importname, 
-                            None, None, ["Module"]).Module
-        w_name = self.wrap(name) 
-        w_mod = self.wrap(Module(self, w_name)) 
-        w_modules = self.sys.get('modules')
-        self.setitem(w_modules, w_name, w_mod) 
-
-    def make_builtins(self):
-        "NOT_RPYTHON: only for initializing the space."
-
-        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) 
-
-        # XXX we need to resolve unwrapping issues to 
-        #     make this the default _sre module
-        #self.setbuiltinmodule("_sre", "_sre_pypy") 
-
-        self.setbuiltinmodule('parser')
-
-        # initialize with "bootstrap types" from objspace  (e.g. w_None)
-        for name, value in self.__dict__.items():
-            if name.startswith('w_') and not name.endswith('Type'): 
-                name = name[2:]
-                #print "setitem: space instance %-20s into builtins" % name
-                self.setitem(self.builtin.w_dict, self.wrap(name), value)
-
-    def initialize(self):
-        """NOT_RPYTHON: Abstract method that should put some minimal
-        content into the w_builtins."""
-
-    def loadfromcache(self, key, builder, cache):
-        return cache.getorbuild(key, builder, self) 
-    loadfromcache._specialize_ = "location" 
-
-
-    def get_ec_state_dict(self):
-        "Return the 'state dict' from the active execution context."
-        return self.getexecutioncontext().get_state_dict()
-    
-    def getexecutioncontext(self):
-        "Return what we consider to be the active execution context."
-        ec = getthreadlocals().executioncontext
-        if ec is None:
-            ec = self.createexecutioncontext()
-        return ec
-
-    def createexecutioncontext(self):
-        "Factory function for execution contexts."
-        return ExecutionContext(self)
-
-    # Following is a friendly interface to common object space operations
-    # that can be defined in term of more primitive ones.  Subclasses
-    # may also override specific functions for performance.
-
-    #def is_(self, w_x, w_y):   -- not really useful.  Must be subclassed
-    #    "'x is y'."
-    #    w_id_x = self.id(w_x)
-    #    w_id_y = self.id(w_y)
-    #    return self.eq(w_id_x, w_id_y)
-
-    def not_(self, w_obj):
-        return self.wrap(not self.is_true(w_obj))
-
-    def eq_w(self, w_obj1, w_obj2):
-        """shortcut for space.is_true(space.eq(w_obj1, w_obj2))"""
-        return self.is_true(self.eq(w_obj1, w_obj2))
-
-    def is_w(self, w_obj1, w_obj2):
-        """shortcut for space.is_true(space.is_(w_obj1, w_obj2))"""
-        return self.is_true(self.is_(w_obj1, w_obj2))
-
-    def newbool(self, b):
-        if b:
-            return self.w_True
-        else:
-            return self.w_False
-
-    def interpclass_w(space, w_obj):
-        """
-         If w_obj is a wrapped internal interpreter class instance unwrap to it,
-         otherwise return None
-        """
-        if isinstance(w_obj, BaseWrappable):
-            return w_obj
-        return None
-
-    def unpackiterable(self, w_iterable, expected_length=-1):
-        """Unpack an iterable object into a real (interpreter-level) list.
-        Raise a real ValueError if the length is wrong."""
-        w_iterator = self.iter(w_iterable)
-        items = []
-        while True:
-            try:
-                w_item = self.next(w_iterator)
-            except OperationError, e:
-                if not e.match(self, self.w_StopIteration):
-                    raise
-                break  # done
-            if expected_length != -1 and len(items) == expected_length:
-                raise ValueError, "too many values to unpack"
-            items.append(w_item)
-        if expected_length != -1 and len(items) < expected_length:
-            i = len(items)
-            if i == 1:
-                plural = ""
-            else:
-                plural = "s"
-            raise ValueError, "need more than %d value%s to unpack" % (i, plural)
-        return items
-
-    def unpacktuple(self, w_tuple, expected_length=None):
-        """Same as unpackiterable(), but only for tuples.
-        Only use for bootstrapping or performance reasons."""
-        tuple_length = self.int_w(self.len(w_tuple))
-        if expected_length is not None and tuple_length != expected_length:
-            raise ValueError, "got a tuple of length %d instead of %d" % (
-                tuple_length, expected_length)
-        items = [
-            self.getitem(w_tuple, self.wrap(i)) for i in range(tuple_length)]
-        return items
-
-    def exception_match(self, w_exc_type, w_check_class):
-        """Checks if the given exception type matches 'w_check_class'."""
-        check_list = [w_check_class]
-        while check_list:
-            w_item = check_list.pop()
-            # Match identical items.
-            if self.is_true(self.is_(w_exc_type, w_item)):
-                return True
-            try:
-                # Match subclasses.
-                if self.is_true(self.abstract_issubclass(w_exc_type, w_item, failhard=True)):
-                    return True
-            except OperationError:
-                # Assume that this is a TypeError: w_item not a type,
-                # and assume that w_item is then actually a tuple.
-                try:
-                    exclst = self.unpackiterable(w_item)
-                except OperationError:
-                    # hum, maybe it is not a tuple after all, and w_exc_type
-                    # was not a type at all (string exceptions).  Give up.
-                    continue
-                check_list.extend(exclst)
-        return False
-
-    def normalize_exception(self, w_type, w_value, w_tb):
-        from pypy.interpreter import pyframe
-        return pyframe.normalize_exception(self, w_type,w_value, w_tb)
-
-    def call(self, w_callable, w_args, w_kwds=None):
-        args = Arguments.frompacked(self, w_args, w_kwds)
-        return self.call_args(w_callable, args)
-
-    def call_function(self, w_func, *args_w):
-        args = Arguments(self, list(args_w))
-        return self.call_args(w_func, args)
-
-    def call_method(self, w_obj, methname, *arg_w):
-        w_meth = self.getattr(w_obj, self.wrap(methname))
-        return self.call_function(w_meth, *arg_w)
-
-    def isinstance(self, w_obj, w_type):
-        w_objtype = self.type(w_obj)
-        return self.issubtype(w_objtype, w_type)
-
-    def abstract_issubclass(self, w_obj, w_cls, failhard=False):
-        try:
-            return self.issubtype(w_obj, w_cls)
-        except OperationError:
-            try:
-                self.getattr(w_cls, self.wrap('__bases__')) # type sanity check
-                return self.recursive_issubclass(w_obj, w_cls)
-            except OperationError:
-                if failhard:
-                    raise
-                else:
-                    return self.w_False
-
-    def recursive_issubclass(self, w_obj, w_cls):
-        if self.is_w(w_obj, w_cls):
-            return self.w_True
-        for w_base in self.unpackiterable(self.getattr(w_obj, 
-                                                       self.wrap('__bases__'))):
-            if self.is_true(self.recursive_issubclass(w_base, w_cls)):
-                return self.w_True
-        return self.w_False
-
-    def abstract_isinstance(self, w_obj, w_cls):
-        try:
-            return self.isinstance(w_obj, w_cls)
-        except OperationError:
-            try:
-                w_objcls = self.getattr(w_obj, self.wrap('__class__'))
-                return self.abstract_issubclass(w_objcls, w_cls)
-            except OperationError:
-                return self.w_False
-
-
-    def eval(self, expression, w_globals, w_locals):
-        "NOT_RPYTHON: For internal debugging."
-        import types
-        from pypy.interpreter.pycode import PyCode
-        if isinstance(expression, str):
-            expression = compile(expression, '?', 'eval')
-        if isinstance(expression, types.CodeType):
-            expression = PyCode(self)._from_code(expression)
-        if not isinstance(expression, PyCode):
-            raise TypeError, 'space.eval(): expected a string, code or PyCode object'
-        return expression.exec_code(self, w_globals, w_locals)
-
-    def exec_(self, statement, w_globals, w_locals):
-        "NOT_RPYTHON: For internal debugging."
-        import types
-        from pypy.interpreter.pycode import PyCode
-        if isinstance(statement, str):
-            statement = compile(statement, '?', 'exec')
-        if isinstance(statement, types.CodeType):
-            statement = PyCode(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_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)
-
-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
-    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
-## (if any).  XXX Maybe we should say that these methods must be accessed
-## as 'space.op.xxx()' instead of directly 'space.xxx()'.
-
-ObjSpace.MethodTable = [
-# method name # symbol # number of arguments # special method name(s)
-    ('is_',             'is',        2, []),
-    ('id',              'id',        1, []),
-    ('type',            'type',      1, []),
-    ('issubtype',       'issubtype', 2, []),  # not for old-style classes
-    ('repr',            'repr',      1, ['__repr__']),
-    ('str',             'str',       1, ['__str__']),
-    ('len',             'len',       1, ['__len__']),
-    ('hash',            'hash',      1, ['__hash__']),
-    ('getattr',         'getattr',   2, ['__getattribute__']),
-    ('setattr',         'setattr',   3, ['__setattr__']),
-    ('delattr',         'delattr',   2, ['__delattr__']),
-    ('getitem',         'getitem',   2, ['__getitem__']),
-    ('setitem',         'setitem',   3, ['__setitem__']),
-    ('delitem',         'delitem',   2, ['__delitem__']),
-    ('pos',             'pos',       1, ['__pos__']),
-    ('neg',             'neg',       1, ['__neg__']),
-    ('nonzero',         'truth',     1, ['__nonzero__']),
-    ('abs' ,            'abs',       1, ['__abs__']),
-    ('hex',             'hex',       1, ['__hex__']),
-    ('oct',             'oct',       1, ['__oct__']),
-    ('round',           'round',     2, []),
-    ('ord',             'ord',       1, []),
-    ('invert',          '~',         1, ['__invert__']),
-    ('add',             '+',         2, ['__add__', '__radd__']),
-    ('sub',             '-',         2, ['__sub__', '__rsub__']),
-    ('mul',             '*',         2, ['__mul__', '__rmul__']),
-    ('truediv',         '/',         2, ['__truediv__', '__rtruediv__']),
-    ('floordiv',        '//',        2, ['__floordiv__', '__rfloordiv__']),
-    ('div',             'div',       2, ['__div__', '__rdiv__']),
-    ('mod',             '%',         2, ['__mod__', '__rmod__']),
-    ('divmod',          'divmod',    2, ['__divmod__', '__rdivmod__']),
-    ('pow',             '**',        3, ['__pow__', '__rpow__']),
-    ('lshift',          '<<',        2, ['__lshift__', '__rlshift__']),
-    ('rshift',          '>>',        2, ['__rshift__', '__rrshift__']),
-    ('and_',            '&',         2, ['__and__', '__rand__']),
-    ('or_',             '|',         2, ['__or__', '__ror__']),
-    ('xor',             '^',         2, ['__xor__', '__rxor__']),
-    ('int',             'int',       1, ['__int__']),
-    ('float',           'float',     1, ['__float__']),
-    ('long',            'long',      1, ['__long__']),
-    ('inplace_add',     '+=',        2, ['__iadd__']),
-    ('inplace_sub',     '-=',        2, ['__isub__']),
-    ('inplace_mul',     '*=',        2, ['__imul__']),
-    ('inplace_truediv', '/=',        2, ['__itruediv__']),
-    ('inplace_floordiv','//=',       2, ['__ifloordiv__']),
-    ('inplace_div',     'div=',      2, ['__idiv__']),
-    ('inplace_mod',     '%=',        2, ['__imod__']),
-    ('inplace_pow',     '**=',       2, ['__ipow__']),
-    ('inplace_lshift',  '<<=',       2, ['__ilshift__']),
-    ('inplace_rshift',  '>>=',       2, ['__irshift__']),
-    ('inplace_and',     '&=',        2, ['__iand__']),
-    ('inplace_or',      '|=',        2, ['__ior__']),
-    ('inplace_xor',     '^=',        2, ['__ixor__']),
-    ('lt',              '<',         2, ['__lt__', '__gt__']),
-    ('le',              '<=',        2, ['__le__', '__ge__']),
-    ('eq',              '==',        2, ['__eq__', '__eq__']),
-    ('ne',              '!=',        2, ['__ne__', '__ne__']),
-    ('gt',              '>',         2, ['__gt__', '__lt__']),
-    ('ge',              '>=',        2, ['__ge__', '__le__']),
-    ('cmp',             'cmp',       2, ['__cmp__']),   # rich cmps preferred
-    ('coerce',          'coerce',    2, ['__coerce__', '__coerce__']),
-    ('contains',        'contains',  2, ['__contains__']),
-    ('iter',            'iter',      1, ['__iter__']),
-    ('next',            'next',      1, ['next']),
-#    ('call',            'call',      3, ['__call__']),
-    ('get',             'get',       3, ['__get__']),
-    ('set',             'set',       3, ['__set__']),
-    ('delete',          'delete',    2, ['__delete__']),
-    ('userdel',         'del',       2, ['__del__']),
-    ]
-
-ObjSpace.BuiltinModuleTable = [
-    '__builtin__',
-    'sys',
-    ]
-
-ObjSpace.ConstantTable = [
-    'None',
-    'False',
-    'True',
-    'Ellipsis',
-    'NotImplemented',
-    ]
-
-ObjSpace.ExceptionTable = [
-    'ArithmeticError',
-    'AssertionError',
-    'AttributeError',
-    'EOFError',
-    'EnvironmentError',
-    'Exception',
-    'FloatingPointError',
-    'IOError',
-    'ImportError',
-    'IndentationError',
-    'IndexError',
-    'KeyError',
-    'KeyboardInterrupt',
-    'LookupError',
-    'MemoryError',
-    'NameError',
-    'NotImplementedError',
-    'OSError',
-    'OverflowError',
-    'ReferenceError',
-    'RuntimeError',
-    'StandardError',
-    'StopIteration',
-    'SyntaxError',
-    'SystemError',
-    'SystemExit',
-    'TabError',
-    'TypeError',
-    'UnboundLocalError',
-    'UnicodeError',
-    'ValueError',
-    'ZeroDivisionError',
-    ]
-
-## Irregular part of the interface:
-#
-#                                   wrap(x) -> w_x
-#                              str_w(w_str) -> str
-#              int_w(w_ival or w_long_ival) -> ival
-#                       float_w(w_floatval) -> floatval
-#interpclass_w(w_interpclass_inst or w_obj) -> interpclass_inst|w_obj
-#                               unwrap(w_x) -> x
-#                              is_true(w_x) -> True or False
-#                  newtuple([w_1, w_2,...]) -> w_tuple
-#                   newlist([w_1, w_2,...]) -> w_list
-#                 newstring([w_1, w_2,...]) -> w_string from ascii numbers (bytes)
-#            newdict([(w_key,w_value),...]) -> w_dict
-#           newslice(w_start,w_stop,w_step) -> w_slice (any argument may be a real None)
-#              call_args(w_obj,Arguments()) -> w_result
-
-ObjSpace.IrregularOpTable = [
-    'wrap',
-    'str_w',
-    'int_w',
-    'float_w',
-    'interpclass_w',
-    'unwrap',
-    'is_true',
-    'newtuple',
-    'newlist',
-    'newdict',
-    'newslice',
-    'call_args'
-    ]
-

Deleted: /pypy/dist/pypy/interpreter/error.py
==============================================================================
--- /pypy/dist/pypy/interpreter/error.py	Thu Apr  7 02:01:08 2005
+++ (empty file)
@@ -1,143 +0,0 @@
-import autopath
-import os, sys
-
-AUTO_DEBUG = os.getenv('PYPY_DEBUG')
-
-
-class OperationError(Exception):
-    """Interpreter-level exception that signals an exception that should be
-    sent to the application level.
-
-    OperationError instances have three public attributes (and no .args),
-    w_type, w_value and application_traceback, which contain the wrapped
-    type and value describing the exception, and the unwrapped list of
-    (frame, instruction_position) making the application-level traceback.
-    """
-
-    def __init__(self, w_type, w_value, tb=None):
-        assert w_type is not None, w_value
-        self.w_type = w_type
-        self.w_value = w_value
-        self.application_traceback = tb
-        self.debug_excs = []
-
-    def clear(self, space):
-        # for sys.exc_clear()
-        self.w_type = space.w_None
-        self.w_value = space.w_None
-        self.application_traceback = None
-
-    def match(self, space, w_check_class):
-        "Check if this application-level exception matches 'w_check_class'."
-        return space.exception_match(self.w_type, w_check_class)
-
-    def __str__(self):
-        "NOT_RPYTHON: Convenience for tracebacks."
-        return '[%s: %s]' % (self.w_type, self.w_value)
-
-    def errorstr(self, space):
-        "NOT_RPYTHON: The exception class and value, as a string."
-        if space is None:
-            exc_typename = str(self.w_type)
-            exc_value    = self.w_value
-        else:
-            w = space.wrap
-            if space.is_true(space.is_(space.type(self.w_type), space.w_str)):
-                exc_typename = space.str_w(self.w_type)
-            else:
-                exc_typename = space.str_w(
-                    space.getattr(self.w_type, w('__name__')))
-            if self.w_value == space.w_None:
-                exc_value = None
-            else:
-                exc_value = space.str_w(space.str(self.w_value))
-        if not exc_value:
-            return exc_typename
-        else:
-            return '%s: %s' % (exc_typename, exc_value)
-
-    def getframe(self):
-        "The frame this exception was raised in, or None."
-        if self.application_traceback:
-            return self.application_traceback.frame
-        else:
-            return None
-
-    def record_interpreter_traceback(self):
-        """NOT_RPYTHON: Records the current traceback inside the interpreter.
-        This traceback is only useful to debug the interpreter, not the
-        application."""
-        self.debug_excs.append(sys.exc_info())
-
-    def print_application_traceback(self, space, file=None):
-        "NOT_RPYTHON: Dump a standard application-level traceback."
-        if file is None: file = sys.stderr
-        self.print_app_tb_only(file)
-        print >> file, self.errorstr(space)
-
-    def print_app_tb_only(self, file):
-        "NOT_RPYTHON"
-        tb = self.application_traceback
-        if tb:
-            import linecache
-            print >> file, "Traceback (application-level):"
-            while tb is not None:
-                co = tb.frame.code
-                lineno = tb.lineno
-                fname = co.co_filename
-                if fname.startswith('<inline>\n'):
-                    lines = fname.split('\n')
-                    fname = lines[0].strip()
-                    try:
-                        l = lines[lineno]
-                    except IndexError:
-                        l = ''
-                else:
-                    l = linecache.getline(fname, lineno)
-                print >> file, "  File \"%s\"," % fname,
-                print >> file, "line", lineno, "in", co.co_name
-                if l:
-                    if l.endswith('\n'):
-                        l = l[:-1]
-                    print >> file, l
-                tb = tb.next
-
-    def print_detailed_traceback(self, space=None, file=None):
-        """NOT_RPYTHON: Dump a nice detailed interpreter- and
-        application-level traceback, useful to debug the interpreter."""
-        import traceback, cStringIO
-        if file is None: file = sys.stderr
-        f = cStringIO.StringIO()
-        for i in range(len(self.debug_excs)-1, -1, -1):
-            print >> f, "Traceback (interpreter-level):"
-            traceback.print_tb(self.debug_excs[i][2], file=f)
-        f.seek(0)
-        debug_print(''.join(['|| ' + line for line in f.readlines()]), file)
-        if self.debug_excs:
-            from pypy.tool import tb_server
-            tb_server.publish_exc(self.debug_excs[-1])
-        self.print_app_tb_only(file)
-        print >> file, '(application-level)', self.errorstr(space)
-        if AUTO_DEBUG:
-            import debug
-            debug.fire(self)
-
-
-# Utilities
-from pypy.tool.ansi_print import ansi_print
-
-def debug_print(text, file=None):
-    ansi_print(text, esc="31", file=file) # ANSI color code "red"
-
-### installing the excepthook for OperationErrors
-##def operr_excepthook(exctype, value, traceback):
-##    if issubclass(exctype, OperationError):
-##        value.debug_excs.append((exctype, value, traceback))
-##        value.print_detailed_traceback()
-##    else:
-##        old_excepthook(exctype, value, traceback)
-##        from pypy.tool import tb_server
-##        tb_server.publish_exc((exctype, value, traceback))
-
-##old_excepthook = sys.excepthook
-##sys.excepthook = operr_excepthook

Deleted: /pypy/dist/pypy/interpreter/pyframe.py
==============================================================================
--- /pypy/dist/pypy/interpreter/pyframe.py	Thu Apr  7 02:01:08 2005
+++ (empty file)
@@ -1,591 +0,0 @@
-""" PyFrame class implementation with the interpreter main loop.
-"""
-
-from pypy.interpreter import eval, baseobjspace, gateway
-from pypy.interpreter.miscutils import Stack
-from pypy.interpreter.error import OperationError
-from pypy.interpreter import pytraceback
-import opcode
-
-# Define some opcodes used
-g = globals()
-for op in '''DUP_TOP POP_TOP SETUP_LOOP SETUP_EXCEPT SETUP_FINALLY
-POP_BLOCK END_FINALLY'''.split():
-    g[op] = opcode.opmap[op]
-HAVE_ARGUMENT = opcode.HAVE_ARGUMENT
-
-import __future__
-compiler_flags = 0
-for fname in __future__.all_feature_names:
-    compiler_flags |= getattr(__future__, fname).compiler_flag
-
-
-def cpython_tb():
-   """NOT_RPYTHON"""
-   import sys
-   return sys.exc_info()[2]   
-
-class PyFrame(eval.Frame):
-    """Represents a frame for a regular Python function
-    that needs to be interpreted.
-
-    See also pyopcode.PyStandardFrame and pynestedscope.PyNestedScopeFrame.
-
-    Public fields:
-     * 'space' is the object space this frame is running in
-     * 'code' is the PyCode object this frame runs
-     * 'w_locals' is the locals dictionary to use
-     * 'w_globals' is the attached globals dictionary
-     * 'builtin' is the attached built-in module
-     * 'valuestack', 'blockstack', 'next_instr' control the interpretation
-    """
-
-    def __init__(self, space, code, w_globals, closure):
-        eval.Frame.__init__(self, space, code, w_globals, code.co_nlocals)
-        self.valuestack = Stack()
-        self.blockstack = Stack()
-        self.last_exception = None
-        self.next_instr = 0
-        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():
-            self.w_locals = space.newdict([])  # set to None by Frame.__init__
-
-        self.fastlocals_w = [None]*self.numlocals
-        self.w_f_trace = None
-        self.last_instr = -1
-        self.f_back = None
-        self.f_lineno = self.code.co_firstlineno
-        
-        # For tracing
-        self.instr_lb = 0
-        self.instr_ub = -1
-        
-    def getfastscope(self):
-        "Get the fast locals as a list."
-        return self.fastlocals_w
-
-    def setfastscope(self, scope_w):
-        """Initialize the fast locals from a list of values,
-        where the order is according to self.code.signature()."""
-        if len(scope_w) > len(self.fastlocals_w):
-            raise ValueError, "new fastscope is longer than the allocated area"
-        self.fastlocals_w[:len(scope_w)] = scope_w
-        
-    def getclosure(self):
-        return None
-
-    def get_compile_flags(self):
-        return self.code.co_flags & compiler_flags
-
-    def eval(self, executioncontext):
-        "Interpreter main loop!"
-        try:
-            executioncontext.call_trace(self)
-            self.last_instr = -1
-            while True:
-                try:
-                    try:
-                        try:
-                            while True:
-                                # fetch and dispatch the next opcode
-                                # dispatch() is abstract, see pyopcode.
-                                self.last_instr = self.next_instr
-                                executioncontext.bytecode_trace(self)
-                                self.next_instr = self.last_instr
-                                self.dispatch()
-                        # catch asynchronous exceptions and turn them
-                        # into OperationErrors
-                        except KeyboardInterrupt:
-                            tb = cpython_tb()
-                            raise OperationError, OperationError(self.space.w_KeyboardInterrupt,
-                                                   self.space.w_None), tb
-                        except MemoryError:
-                            tb = cpython_tb()
-                            raise OperationError, OperationError(self.space.w_MemoryError,
-                                                   self.space.w_None), tb
-                        except RuntimeError, e:
-                            tb = cpython_tb()
-                            raise OperationError, OperationError(self.space.w_RuntimeError,
-                                self.space.wrap("internal error: " + str(e))), tb
-
-                    except OperationError, e:
-                        pytraceback.record_application_traceback(
-                            self.space, e, self, self.last_instr)
-                        executioncontext.exception_trace(self, e)
-                        # convert an OperationError into a control flow
-                        # exception
-                        raise SApplicationException(e)
-
-                except ControlFlowException, ctlflowexc:
-                    # we have a reason to change the control flow
-                    # (typically unroll the stack)
-                    ctlflowexc.action(self, self.last_instr, executioncontext)
-            
-        except ExitFrame, e:
-            # leave that frame
-            w_exitvalue = e.args[0]
-            executioncontext.return_trace(self, w_exitvalue)
-            return w_exitvalue
-        
-    ### line numbers ###
-
-    def fget_f_lineno(space, w_self):
-        "Returns the line number of the instruction currently being executed."
-        self = space.interpclass_w(w_self)
-        if self.w_f_trace is None:
-            return space.wrap(self.get_last_lineno())
-        else:
-            return space.wrap(self.f_lineno)
-
-    def fset_f_lineno(space, w_self, w_new_lineno):
-        "Returns the line number of the instruction currently being executed."
-        try:
-            new_lineno = space.int_w(w_new_lineno)
-        except OperationError, e:
-            raise OperationError(space.w_ValueError,
-                                 space.wrap("lineno must be an integer"))
-            
-        self = space.interpclass_w(w_self)
-        if self.w_f_trace is None:
-            raise OperationError(space.w_ValueError,
-                  space.wrap("f_lineo can only be set by a trace function."))
-
-        if new_lineno < self.code.co_firstlineno:
-            raise OperationError(space.w_ValueError,
-                  space.wrap("line %d comes before the current code." % new_lineno))
-        code = self.code.co_code
-        addr = 0
-        line = self.code.co_firstlineno
-        new_lasti = -1
-        offset = 0
-        lnotab = self.code.co_lnotab
-        for offset in xrange(0, len(lnotab), 2):
-            addr += ord(lnotab[offset])
-            line += ord(lnotab[offset + 1])
-            if line >= new_lineno:
-                new_lasti = addr
-                new_lineno = line
-                break
-
-        if new_lasti == -1:
-            raise OperationError(space.w_ValueError,
-                  space.wrap("line %d comes after the current code." % new_lineno))
-
-        # Don't jump to a line with an except in it.
-        if ord(code[new_lasti]) in (DUP_TOP, POP_TOP):
-            raise OperationError(space.w_ValueError,
-                  space.wrap("can't jump to 'except' line as there's no exception"))
-            
-        # Don't jump into or out of a finally block.
-        f_lasti_setup_addr = -1
-        new_lasti_setup_addr = -1
-        blockstack = Stack()
-        addr = 0
-        while addr < len(code):
-            op = ord(code[addr])
-            if op in (SETUP_LOOP, SETUP_EXCEPT, SETUP_FINALLY):
-                blockstack.push([addr, False])
-            elif op == POP_BLOCK:
-                setup_op = ord(code[blockstack.top()[0]])
-                if setup_op == SETUP_FINALLY:
-                    blockstack.top()[1] = True
-                else:
-                    blockstack.pop()
-            elif op == END_FINALLY:
-                if not blockstack.empty():
-                    setup_op = ord(code[blockstack.top()[0]])
-                    if setup_op == SETUP_FINALLY:
-                        blockstack.pop()
-
-            if addr == new_lasti or addr == self.last_instr:
-                for ii in range(blockstack.depth()):
-                    setup_addr, in_finally = blockstack.top(ii)
-                    if in_finally:
-                        if addr == new_lasti:
-                            new_lasti_setup_addr = setup_addr
-                        if addr == self.last_instr:
-                            f_lasti_setup_addr = setup_addr
-                        break
-                    
-            if op >= HAVE_ARGUMENT:
-                addr += 3
-            else:
-                addr += 1
-                
-        assert blockstack.empty()
-
-        if new_lasti_setup_addr != f_lasti_setup_addr:
-            raise OperationError(space.w_ValueError,
-                  space.wrap("can't jump into or out of a 'finally' block %d -> %d" %
-                             (f_lasti_setup_addr, new_lasti_setup_addr)))
-
-        if new_lasti < self.last_instr:
-            min_addr = new_lasti
-            max_addr = self.last_instr
-        else:
-            min_addr = self.last_instr
-            max_addr = new_lasti
-
-        delta_iblock = min_delta_iblock = 0
-        addr = min_addr
-        while addr < max_addr:
-            op = ord(code[addr])
-
-            if op in (SETUP_LOOP, SETUP_EXCEPT, SETUP_FINALLY):
-                delta_iblock += 1;
-            elif op == POP_BLOCK:
-                delta_iblock -= 1
-                if delta_iblock < min_delta_iblock:
-                    min_delta_iblock = delta_iblock
-
-            if op >= opcode.HAVE_ARGUMENT:
-                addr += 3
-            else:
-                addr += 1
-
-        f_iblock = self.blockstack.depth()
-        min_iblock = f_iblock + min_delta_iblock
-        if new_lasti > self.last_instr:
-            new_iblock = f_iblock + delta_iblock
-        else:
-            new_iblock = f_iblock - delta_iblock
-
-        if new_iblock > min_iblock:
-            raise OperationError(space.w_ValueError,
-                                 space.wrap("can't jump into the middle of a block"))
-
-        while f_iblock > new_iblock:
-            block = self.blockstack.pop()
-            block.cleanup(self)
-            f_iblock -= 1
-            
-        self.f_lineno = new_lineno
-        self.last_instr = new_lasti
-            
-    def get_last_lineno(self):
-        "Returns the line number of the instruction currently being executed."
-        return pytraceback.offset2lineno(self.code, self.next_instr-1)
-
-    def get_next_lineno(self):
-        "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()
-
-    def fget_f_back(space, w_self):
-        self = space.interpclass_w(w_self)
-        return self.space.wrap(self.f_back)
-
-    def fget_f_lasti(space, w_self):
-        self = space.interpclass_w(w_self)
-        return self.space.wrap(self.last_instr)
-
-    def fget_f_trace(space, w_self):
-        self = space.interpclass_w(w_self)
-        return self.w_f_trace
-
-    def fset_f_trace(space, w_self, w_trace):
-        self = space.interpclass_w(w_self)
-        if space.is_true(space.is_(w_trace, space.w_None)):
-            self.w_f_trace = None
-        else:
-            self.w_f_trace = w_trace
-            self.f_lineno = self.get_last_lineno()
-
-    def fget_f_exc_type(space, w_self):
-        self = space.interpclass_w(w_self)
-        if self.last_exception is not None:
-            f = self.f_back
-            while f is not None and f.last_exception is None:
-                f = f.f_back
-            if f is not None:
-                return f.last_exception.w_type
-        return space.w_None
-         
-    def fget_f_exc_value(space, w_self):
-        self = space.interpclass_w(w_self)
-        if self.last_exception is not None:
-            f = self.f_back
-            while f is not None and f.last_exception is None:
-                f = f.f_back
-            if f is not None:
-                return f.last_exception.w_value
-        return space.w_None
-
-    def fget_f_exc_traceback(space, w_self):
-        self = space.interpclass_w(w_self)
-        if self.last_exception is not None:
-            f = self.f_back
-            while f is not None and f.last_exception is None:
-                f = f.f_back
-            if f is not None:
-                return space.wrap(f.last_exception.application_traceback)
-        return space.w_None
-         
-    def fget_f_restricted(space, w_self):
-        self = space.interpclass_w(w_self)
-        return space.wrap(self.builtin is not space.builtin)
-
-### Frame Blocks ###
-
-class FrameBlock:
-
-    """Abstract base class for frame blocks from the blockstack,
-    used by the SETUP_XXX and POP_BLOCK opcodes."""
-
-    def __init__(self, frame, handlerposition):
-        self.handlerposition = handlerposition
-        self.valuestackdepth = frame.valuestack.depth()
-
-    def __eq__(self, other):
-        return (self.__class__ is other.__class__ and
-                self.handlerposition == other.handlerposition and
-                self.valuestackdepth == other.valuestackdepth)
-
-    def __ne__(self, other):
-        return not (self == other)
-
-    def __hash__(self):
-        return hash((self.handlerposition, self.valuestackdepth))
-
-    def cleanupstack(self, frame):
-        for i in range(self.valuestackdepth, frame.valuestack.depth()):
-            frame.valuestack.pop()
-
-    def cleanup(self, frame):
-        "Clean up a frame when we normally exit the block."
-        self.cleanupstack(frame)
-
-    def unroll(self, frame, unroller):
-        "Clean up a frame when we abnormally exit the block."
-        self.cleanupstack(frame)
-        return False  # continue to unroll
-
-
-class LoopBlock(FrameBlock):
-    """A loop block.  Stores the end-of-loop pointer in case of 'break'."""
-
-    def unroll(self, frame, unroller):
-        if isinstance(unroller, SContinueLoop):
-            # re-push the loop block without cleaning up the value stack,
-            # and jump to the beginning of the loop, stored in the
-            # exception's argument
-            frame.blockstack.push(self)
-            jump_to = unroller.args[0]
-            frame.next_instr = jump_to
-            return True  # stop unrolling
-        self.cleanupstack(frame)
-        if isinstance(unroller, SBreakLoop):
-            # jump to the end of the loop
-            frame.next_instr = self.handlerposition
-            return True  # stop unrolling
-        return False
-
-
-class ExceptBlock(FrameBlock):
-    """An try:except: block.  Stores the position of the exception handler."""
-
-    def unroll(self, frame, unroller):
-        self.cleanupstack(frame)
-        if isinstance(unroller, SApplicationException):
-            # push the exception to the value stack for inspection by the
-            # exception handler (the code after the except:)
-            operationerr = unroller.args[0]
-            w_type  = operationerr.w_type
-            w_value = operationerr.w_value
-            w_normalized = frame.space.normalize_exception(w_type, w_value,
-                                               frame.space.w_None)
-            w_type, w_value, w_tb = frame.space.unpacktuple(w_normalized, 3)
-            # save the normalized exception back into the OperationError
-            # -- in particular it makes sure that sys.exc_info() etc see
-            #    normalized exception.
-            operationerr.w_type = w_type
-            operationerr.w_value = w_value
-            # the stack setup is slightly different than in CPython:
-            # instead of the traceback, we store the unroller object,
-            # wrapped.
-            frame.valuestack.push(frame.space.wrap(unroller))
-            frame.valuestack.push(w_value)
-            frame.valuestack.push(w_type)
-            frame.next_instr = self.handlerposition   # jump to the handler
-            return True  # stop unrolling
-        return False
-
-# make the following flowable: need _classobj
-import types, __builtin__
-__builtin__._classobj = types.ClassType
-
-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)):
-        ## isinstance with tuple argument doesn't map to space.isinstance, yet
-        if isinstance(etype, type) or isinstance(etype, _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):
-    """A try:finally: block.  Stores the position of the exception handler."""
-
-    def cleanup(self, frame):
-        # upon normal entry into the finally: part, the standard Python
-        # bytecode pushes a single None for END_FINALLY.  In our case we
-        # always push three values into the stack: the wrapped ctlflowexc,
-        # the exception value and the exception type (which are all None
-        # here).
-        self.cleanupstack(frame)
-        # one None already pushed by the bytecode
-        frame.valuestack.push(frame.space.w_None)
-        frame.valuestack.push(frame.space.w_None)
-
-    def unroll(self, frame, unroller):
-        # any abnormal reason for unrolling a finally: triggers the end of
-        # the block unrolling and the entering the finally: handler.
-        # see comments in cleanup().
-        self.cleanupstack(frame)
-        frame.valuestack.push(frame.space.wrap(unroller))
-        frame.valuestack.push(frame.space.w_None)
-        frame.valuestack.push(frame.space.w_None)
-        frame.next_instr = self.handlerposition   # jump to the handler
-        return True  # stop unrolling
-
-
-### Internal exceptions that change the control flow ###
-### and (typically) unroll the block stack           ###
-
-class ControlFlowException(Exception, baseobjspace.BaseWrappable):
-    """Abstract base class for interpreter-level exceptions that
-    instruct the interpreter to change the control flow and the
-    block stack.
-
-    The concrete subclasses correspond to the various values WHY_XXX
-    values of the why_code enumeration in ceval.c:
-
-                WHY_NOT,        OK, not this one :-)
-                WHY_EXCEPTION,  SApplicationException
-                WHY_RERAISE,    we don't think this is needed
-                WHY_RETURN,     SReturnValue
-                WHY_BREAK,      SBreakLoop
-                WHY_CONTINUE,   SContinueLoop
-                WHY_YIELD       SYieldValue
-
-    """
-    def action(self, frame, last_instr, executioncontext):
-        "Default unroller implementation."
-        while not frame.blockstack.empty():
-            block = frame.blockstack.pop()
-            if block.unroll(frame, self):
-                break
-        else:
-            self.emptystack(frame)
-
-    def emptystack(self, frame):
-        "Default behavior when the block stack is exhausted."
-        # could occur e.g. when a BREAK_LOOP is not actually within a loop
-        raise BytecodeCorruption, "block stack exhausted"
-
-    # for the flow object space, a way to "pickle" and "unpickle" the
-    # ControlFlowException by enumerating the Variables it contains.
-    def state_unpack_variables(self, space):
-        return []     # by default, overridden below
-    def state_pack_variables(self, space, *values_w):
-        assert len(values_w) == 0
-
-class SApplicationException(ControlFlowException):
-    """Unroll the stack because of an application-level exception
-    (i.e. an OperationException)."""
-
-    def action(self, frame, last_instr, executioncontext):
-        e = self.args[0]
-        frame.last_exception = e
-
-        ControlFlowException.action(self, frame,
-                                    last_instr, executioncontext)
-
-    def emptystack(self, frame):
-        # propagate the exception to the caller
-        if len(self.args) == 2:
-            operationerr, tb = self.args
-            raise operationerr.__class__, operationerr, tb
-        else:
-            operationerr = self.args[0]
-            raise operationerr
-
-    def state_unpack_variables(self, space):
-        e = self.args[0]
-        assert isinstance(e, OperationError)
-        return [e.w_type, e.w_value]
-    def state_pack_variables(self, space, w_type, w_value):
-        self.args = (OperationError(w_type, w_value),)
-
-class SBreakLoop(ControlFlowException):
-    """Signals a 'break' statement."""
-
-class SContinueLoop(ControlFlowException):
-    """Signals a 'continue' statement.
-    Argument is the bytecode position of the beginning of the loop."""
-
-    def state_unpack_variables(self, space):
-        jump_to = self.args[0]
-        return [space.wrap(jump_to)]
-    def state_pack_variables(self, space, w_jump_to):
-        self.args = (space.int_w(w_jump_to),)
-
-class SReturnValue(ControlFlowException):
-    """Signals a 'return' statement.
-    Argument is the wrapped object to return."""
-    def emptystack(self, frame):
-        w_returnvalue = self.args[0]
-        raise ExitFrame(w_returnvalue)
-
-    def state_unpack_variables(self, space):
-        w_returnvalue = self.args[0]
-        return [w_returnvalue]
-    def state_pack_variables(self, space, w_returnvalue):
-        self.args = (w_returnvalue,)
-
-class ExitFrame(Exception):
-    """Signals the end of the frame execution.
-    The argument is the returned or yielded value, already wrapped."""
-
-class BytecodeCorruption(ValueError):
-    """Detected bytecode corruption.  Never caught; it's an error."""

Deleted: /pypy/dist/pypy/interpreter/pyopcode.py
==============================================================================
--- /pypy/dist/pypy/interpreter/pyopcode.py	Thu Apr  7 02:01:08 2005
+++ (empty file)
@@ -1,869 +0,0 @@
-"""
-Implementation of a part of the standard Python opcodes.
-The rest, dealing with variables in optimized ways, is in
-pyfastscope.py and pynestedscope.py.
-"""
-
-from pypy.interpreter.baseobjspace import OperationError, BaseWrappable
-from pypy.interpreter import gateway, function
-from pypy.interpreter import pyframe, pytraceback
-from pypy.interpreter.miscutils import InitializedClass
-from pypy.interpreter.argument import Arguments
-from pypy.interpreter.pycode import PyCode
-from pypy.tool import hack
-
-def unaryoperation(operationname):
-    """NOT_RPYTHON"""
-    def opimpl(f):
-        operation = getattr(f.space, operationname)
-        w_1 = f.valuestack.pop()
-        w_result = operation(w_1)
-        f.valuestack.push(w_result)
-
-    return hack.func_with_new_name(opimpl, "opcode_impl_for_%s" % operationname)
-
-def binaryoperation(operationname):
-    """NOT_RPYTHON"""    
-    def opimpl(f):
-        operation = getattr(f.space, operationname)
-        w_2 = f.valuestack.pop()
-        w_1 = f.valuestack.pop()
-        w_result = operation(w_1, w_2)
-        f.valuestack.push(w_result)
-
-    return hack.func_with_new_name(opimpl, "opcode_impl_for_%s" % operationname)        
-
-
-class PyInterpFrame(pyframe.PyFrame):
-    """A PyFrame that knows about interpretation of standard Python opcodes
-    minus the ones related to nested scopes."""
-    
-    ### opcode dispatch ###
- 
-    # 'opcode_has_arg' is a class attribute: list of True/False whether opcode takes arg
-    # 'dispatch_table_no_arg: list of functions/None
-    # 'dispatch_table_w_arg: list of functions/None 
-    # Currently, they are always setup in pyopcode.py
-    # but it could be a custom table.
-
-    def dispatch(self):
-        opcode = self.nextop()
-        if self.opcode_has_arg[opcode]:
-            fn = self.dispatch_table_w_arg[opcode]
-            oparg = self.nextarg()
-            fn(self, oparg)
-        else:
-            fn = self.dispatch_table_no_arg[opcode]            
-            fn(self)
-
-    def nextop(self):
-        c = self.code.co_code[self.next_instr]
-        self.next_instr += 1
-        return ord(c)
-
-    def nextarg(self):
-        lo = self.nextop()
-        hi = self.nextop()
-        return (hi<<8) + lo
-
-    ### accessor functions ###
-
-    def getlocalvarname(self, index):
-        return self.code.co_varnames[index]
-
-    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):
-        return self.space.wrap(self.code.co_names[index])
-
-
-    ################################################################
-    ##  Implementation of the "operational" opcodes
-    ##  See also pyfastscope.py and pynestedscope.py for the rest.
-    ##
-    
-    #  the 'self' argument of opcode implementations is called 'f'
-    #  for historical reasons
-
-    def NOP(f):
-        pass
-
-    def LOAD_FAST(f, varindex):
-        # access a local variable directly
-        w_value = f.fastlocals_w[varindex]
-        if w_value is None:
-            varname = f.getlocalvarname(varindex)
-            message = "local variable '%s' referenced before assignment" % varname
-            raise OperationError(f.space.w_UnboundLocalError, f.space.wrap(message))
-        f.valuestack.push(w_value)
-
-    def LOAD_CONST(f, constindex):
-        w_const = f.getconstant_w(constindex)
-        f.valuestack.push(w_const)
-
-    def STORE_FAST(f, varindex):
-        w_newvalue = f.valuestack.pop()
-        f.fastlocals_w[varindex] = w_newvalue
-        #except:
-        #    print "exception: got index error"
-        #    print " varindex:", varindex
-        #    print " len(locals_w)", len(f.locals_w)
-        #    import dis
-        #    print dis.dis(f.code)
-        #    print "co_varnames", f.code.co_varnames
-        #    print "co_nlocals", f.code.co_nlocals
-        #    raise
-
-    def POP_TOP(f):
-        f.valuestack.pop()
-
-    def ROT_TWO(f):
-        w_1 = f.valuestack.pop()
-        w_2 = f.valuestack.pop()
-        f.valuestack.push(w_1)
-        f.valuestack.push(w_2)
-
-    def ROT_THREE(f):
-        w_1 = f.valuestack.pop()
-        w_2 = f.valuestack.pop()
-        w_3 = f.valuestack.pop()
-        f.valuestack.push(w_1)
-        f.valuestack.push(w_3)
-        f.valuestack.push(w_2)
-
-    def ROT_FOUR(f):
-        w_1 = f.valuestack.pop()
-        w_2 = f.valuestack.pop()
-        w_3 = f.valuestack.pop()
-        w_4 = f.valuestack.pop()
-        f.valuestack.push(w_1)
-        f.valuestack.push(w_4)
-        f.valuestack.push(w_3)
-        f.valuestack.push(w_2)
-
-    def DUP_TOP(f):
-        w_1 = f.valuestack.top()
-        f.valuestack.push(w_1)
-
-    def DUP_TOPX(f, itemcount):
-        assert 1 <= itemcount <= 5, "limitation of the current interpreter"
-        for i in range(itemcount):
-            w_1 = f.valuestack.top(itemcount-1)
-            f.valuestack.push(w_1)
-
-    UNARY_POSITIVE = unaryoperation("pos")
-    UNARY_NEGATIVE = unaryoperation("neg")
-    UNARY_NOT      = unaryoperation("not_")
-    UNARY_CONVERT  = unaryoperation("repr")
-    UNARY_INVERT   = unaryoperation("invert")
-
-    def BINARY_POWER(f):
-        w_2 = f.valuestack.pop()
-        w_1 = f.valuestack.pop()
-        w_result = f.space.pow(w_1, w_2, f.space.w_None)
-        f.valuestack.push(w_result)
-
-    BINARY_MULTIPLY = binaryoperation("mul")
-    BINARY_TRUE_DIVIDE  = binaryoperation("truediv")
-    BINARY_FLOOR_DIVIDE = binaryoperation("floordiv")
-    BINARY_DIVIDE       = binaryoperation("div")
-    BINARY_MODULO       = binaryoperation("mod")
-    BINARY_ADD      = binaryoperation("add")
-    BINARY_SUBTRACT = binaryoperation("sub")
-    BINARY_SUBSCR   = binaryoperation("getitem")
-    BINARY_LSHIFT   = binaryoperation("lshift")
-    BINARY_RSHIFT   = binaryoperation("rshift")
-    BINARY_AND = binaryoperation("and_")
-    BINARY_XOR = binaryoperation("xor")
-    BINARY_OR  = binaryoperation("or_")
-
-    def INPLACE_POWER(f):
-        w_2 = f.valuestack.pop()
-        w_1 = f.valuestack.pop()
-        w_result = f.space.inplace_pow(w_1, w_2)
-        f.valuestack.push(w_result)
-
-    INPLACE_MULTIPLY = binaryoperation("inplace_mul")
-    INPLACE_TRUE_DIVIDE  = binaryoperation("inplace_truediv")
-    INPLACE_FLOOR_DIVIDE = binaryoperation("inplace_floordiv")
-    INPLACE_DIVIDE       = binaryoperation("inplace_div")
-    INPLACE_MODULO       = binaryoperation("inplace_mod")
-    INPLACE_ADD      = binaryoperation("inplace_add")
-    INPLACE_SUBTRACT = binaryoperation("inplace_sub")
-    INPLACE_LSHIFT   = binaryoperation("inplace_lshift")
-    INPLACE_RSHIFT   = binaryoperation("inplace_rshift")
-    INPLACE_AND = binaryoperation("inplace_and")
-    INPLACE_XOR = binaryoperation("inplace_xor")
-    INPLACE_OR  = binaryoperation("inplace_or")
-
-    def slice(f, w_start, w_end):
-        w_slice = f.space.newslice(w_start, w_end, None)
-        w_obj = f.valuestack.pop()
-        w_result = f.space.getitem(w_obj, w_slice)
-        f.valuestack.push(w_result)
-
-    def SLICE_0(f):
-        f.slice(None, None)
-
-    def SLICE_1(f):
-        w_start = f.valuestack.pop()
-        f.slice(w_start, None)
-
-    def SLICE_2(f):
-        w_end = f.valuestack.pop()
-        f.slice(None, w_end)
-
-    def SLICE_3(f):
-        w_end = f.valuestack.pop()
-        w_start = f.valuestack.pop()
-        f.slice(w_start, w_end)
-
-    def storeslice(f, w_start, w_end):
-        w_slice = f.space.newslice(w_start, w_end, None)
-        w_obj = f.valuestack.pop()
-        w_newvalue = f.valuestack.pop()
-        f.space.setitem(w_obj, w_slice, w_newvalue)
-
-    def STORE_SLICE_0(f):
-        f.storeslice(None, None)
-
-    def STORE_SLICE_1(f):
-        w_start = f.valuestack.pop()
-        f.storeslice(w_start, None)
-
-    def STORE_SLICE_2(f):
-        w_end = f.valuestack.pop()
-        f.storeslice(None, w_end)
-
-    def STORE_SLICE_3(f):
-        w_end = f.valuestack.pop()
-        w_start = f.valuestack.pop()
-        f.storeslice(w_start, w_end)
-
-    def deleteslice(f, w_start, w_end):
-        w_slice = f.space.newslice(w_start, w_end, None)
-        w_obj = f.valuestack.pop()
-        f.space.delitem(w_obj, w_slice)
-
-    def DELETE_SLICE_0(f):
-        f.deleteslice(None, None)
-
-    def DELETE_SLICE_1(f):
-        w_start = f.valuestack.pop()
-        f.deleteslice(w_start, None)
-
-    def DELETE_SLICE_2(f):
-        w_end = f.valuestack.pop()
-        f.deleteslice(None, w_end)
-
-    def DELETE_SLICE_3(f):
-        w_end = f.valuestack.pop()
-        w_start = f.valuestack.pop()
-        f.deleteslice(w_start, w_end)
-
-    def STORE_SUBSCR(f):
-        "obj[subscr] = newvalue"
-        w_subscr = f.valuestack.pop()
-        w_obj = f.valuestack.pop()
-        w_newvalue = f.valuestack.pop()
-        f.space.setitem(w_obj, w_subscr, w_newvalue)
-
-    def DELETE_SUBSCR(f):
-        "del obj[subscr]"
-        w_subscr = f.valuestack.pop()
-        w_obj = f.valuestack.pop()
-        f.space.delitem(w_obj, w_subscr)
-
-    def PRINT_EXPR(f):
-        w_expr = f.valuestack.pop()
-        print_expr(f.space, w_expr)
-
-    def PRINT_ITEM_TO(f):
-        w_stream = f.valuestack.pop()
-        w_item = f.valuestack.pop()
-        if w_stream == f.space.w_None:
-            w_stream = sys_stdout(f.space)   # grumble grumble special cases
-        print_item_to(f.space, w_item, w_stream)
-
-    def PRINT_ITEM(f):
-        w_item = f.valuestack.pop()
-        print_item_to(f.space, w_item, sys_stdout(f.space))
-
-    def PRINT_NEWLINE_TO(f):
-        w_stream = f.valuestack.pop()
-        if w_stream == f.space.w_None:
-            w_stream = sys_stdout(f.space)   # grumble grumble special cases
-        print_newline_to(f.space, w_stream)
-
-    def PRINT_NEWLINE(f):
-        print_newline_to(f.space, sys_stdout(f.space))
-
-    def BREAK_LOOP(f):
-        raise pyframe.SBreakLoop
-
-    def CONTINUE_LOOP(f, startofloop):
-        raise pyframe.SContinueLoop(startofloop)
-
-    def RAISE_VARARGS(f, nbargs):
-        # we use the .app.py file to prepare the exception/value/traceback
-        # but not to actually raise it, because we cannot use the 'raise'
-        # statement to implement RAISE_VARARGS
-        if nbargs == 0:
-            operror = f.space.getexecutioncontext().sys_exc_info()
-            if operror is None:
-                raise OperationError(f.space.w_TypeError,
-                    f.space.wrap("raise: no active exception to re-raise"))
-            # re-raise, no new traceback obj will be attached
-            raise pyframe.SApplicationException(operror)
-        w_value = w_traceback = f.space.w_None
-        if nbargs >= 3: w_traceback = f.valuestack.pop()
-        if nbargs >= 2: w_value     = f.valuestack.pop()
-        if 1:           w_type      = f.valuestack.pop()
-        w_resulttuple = f.space.normalize_exception(w_type, w_value,
-                                                    w_traceback)
-        w_type, w_value, w_traceback = f.space.unpacktuple(w_resulttuple, 3)
-        if w_traceback is not f.space.w_None:
-            tb = f.space.interpclass_w(w_traceback)
-            if not isinstance(tb,pytraceback.PyTraceback):
-                raise OperationError(f.space.w_TypeError,
-                      f.space.wrap("raise: arg 3 must be a traceback or None"))
-            operror = OperationError(w_type,w_value,tb)
-            # re-raise, no new traceback obj will be attached
-            raise pyframe.SApplicationException(operror) 
-        else:
-            # common-case
-            raise OperationError(w_type, w_value)
-
-    def LOAD_LOCALS(f):
-        f.valuestack.push(f.w_locals)
-
-    def RETURN_VALUE(f):
-        w_returnvalue = f.valuestack.pop()
-        raise pyframe.SReturnValue(w_returnvalue)
-
-    def EXEC_STMT(f):
-        w_locals  = f.valuestack.pop()
-        w_globals = f.valuestack.pop()
-        w_prog    = f.valuestack.pop()
-        w_compile_flags = f.space.wrap(f.get_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))
-        if plain:
-            w_locals = f.getdictscope()
-        pycode = f.space.interpclass_w(w_prog)
-        assert isinstance(pycode, PyCode)
-        pycode.exec_code(f.space, w_globals, w_locals)
-        if plain:
-            f.setdictscope(w_locals)
-
-    def POP_BLOCK(f):
-        block = f.blockstack.pop()
-        block.cleanup(f)  # the block knows how to clean up the value stack
-
-    def END_FINALLY(f):
-        # unlike CPython, when we reach this opcode the value stack has
-        # always been set up as follows (topmost first):
-        #   [exception type  or None]
-        #   [exception value or None]
-        #   [wrapped stack unroller ]
-        f.valuestack.pop()   # ignore the exception type
-        f.valuestack.pop()   # ignore the exception value
-        w_unroller = f.valuestack.pop()
-        if w_unroller is not f.space.w_None:
-            # re-raise the unroller, if any
-            raise f.space.interpclass_w(w_unroller)
-
-    def BUILD_CLASS(f):
-        w_methodsdict = f.valuestack.pop()
-        w_bases       = f.valuestack.pop()
-        w_name        = f.valuestack.pop()
-        w_metaclass = find_metaclass(f.space, w_bases,
-                                     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)
-
-    def STORE_NAME(f, varindex):
-        w_varname = f.getname_w(varindex)
-        w_newvalue = f.valuestack.pop()
-        f.space.setitem(f.w_locals, w_varname, w_newvalue)
-
-    def DELETE_NAME(f, varindex):
-        w_varname = f.getname_w(varindex)
-        try:
-            f.space.delitem(f.w_locals, w_varname)
-        except OperationError, e:
-            # catch KeyErrors and turn them into NameErrors
-            if not e.match(f.space, f.space.w_KeyError):
-                raise
-            message = "name '%s' is not defined" % f.space.str_w(w_varname)
-            raise OperationError(f.space.w_NameError, f.space.wrap(message))
-
-    def UNPACK_SEQUENCE(f, itemcount):
-        w_iterable = f.valuestack.pop()
-        try:
-            items = f.space.unpackiterable(w_iterable, itemcount)
-        except ValueError, e:
-            raise OperationError(f.space.w_ValueError, f.space.wrap(str(e)))
-        items.reverse()
-        for item in items:
-            f.valuestack.push(item)
-
-    def STORE_ATTR(f, nameindex):
-        "obj.attributename = newvalue"
-        w_attributename = f.getname_w(nameindex)
-        w_obj = f.valuestack.pop()
-        w_newvalue = f.valuestack.pop()
-        f.space.setattr(w_obj, w_attributename, w_newvalue)
-
-    def DELETE_ATTR(f, nameindex):
-        "del obj.attributename"
-        w_attributename = f.getname_w(nameindex)
-        w_obj = f.valuestack.pop()
-        f.space.delattr(w_obj, w_attributename)
-
-    def STORE_GLOBAL(f, nameindex):
-        w_varname = f.getname_w(nameindex)
-        w_newvalue = f.valuestack.pop()
-        f.space.setitem(f.w_globals, w_varname, w_newvalue)
-
-    def DELETE_GLOBAL(f, nameindex):
-        w_varname = f.getname_w(nameindex)
-        f.space.delitem(f.w_globals, w_varname)
-
-    def LOAD_NAME(f, nameindex):
-        if f.w_locals is not f.w_globals:
-            w_varname = f.getname_w(nameindex)
-            try:
-                w_value = f.space.getitem(f.w_locals, w_varname)
-            except OperationError, e:
-                if not e.match(f.space, f.space.w_KeyError):
-                    raise
-            else:
-                f.valuestack.push(w_value)
-                return
-        f.LOAD_GLOBAL(nameindex)    # fall-back
-
-    def LOAD_GLOBAL(f, nameindex):
-        w_varname = f.getname_w(nameindex)
-        try:
-            w_value = f.space.getitem(f.w_globals, w_varname)
-        except OperationError, e:
-            # catch KeyErrors
-            if not e.match(f.space, f.space.w_KeyError):
-                raise
-            # we got a KeyError, now look in the built-ins
-            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):
-        if f.fastlocals_w[varindex] is None:
-            varname = f.getlocalvarname(varindex)
-            message = "local variable '%s' referenced before assignment" % varname
-            raise OperationError(f.space.w_UnboundLocalError, f.space.wrap(message))
-        f.fastlocals_w[varindex] = None
-        
-
-    def BUILD_TUPLE(f, itemcount):
-        items = [f.valuestack.pop() for i in range(itemcount)]
-        items.reverse()
-        w_tuple = f.space.newtuple(items)
-        f.valuestack.push(w_tuple)
-
-    def BUILD_LIST(f, itemcount):
-        items = [f.valuestack.pop() for i in range(itemcount)]
-        items.reverse()
-        w_list = f.space.newlist(items)
-        f.valuestack.push(w_list)
-
-    def BUILD_MAP(f, zero):
-        if zero != 0:
-            raise pyframe.BytecodeCorruption
-        w_dict = f.space.newdict([])
-        f.valuestack.push(w_dict)
-
-    def LOAD_ATTR(f, nameindex):
-        "obj.attributename"
-        w_attributename = f.getname_w(nameindex)
-        w_obj = f.valuestack.pop()
-        w_value = f.space.getattr(w_obj, w_attributename)
-        f.valuestack.push(w_value)
-
-    def cmp_lt(f, w_1, w_2):  return f.space.lt(w_1, w_2)
-    def cmp_le(f, w_1, w_2):  return f.space.le(w_1, w_2)
-    def cmp_eq(f, w_1, w_2):  return f.space.eq(w_1, w_2)
-    def cmp_ne(f, w_1, w_2):  return f.space.ne(w_1, w_2)
-    def cmp_gt(f, w_1, w_2):  return f.space.gt(w_1, w_2)
-    def cmp_ge(f, w_1, w_2):  return f.space.ge(w_1, w_2)
-
-    def cmp_in(f, w_1, w_2):
-        return f.space.contains(w_2, w_1)
-    def cmp_not_in(f, w_1, w_2):
-        return f.space.not_(f.space.contains(w_2, w_1))
-    def cmp_is(f, w_1, w_2):
-        return f.space.is_(w_1, w_2)
-    def cmp_is_not(f, w_1, w_2):
-        return f.space.not_(f.space.is_(w_1, w_2))
-    def cmp_exc_match(f, w_1, w_2):
-        return f.space.newbool(f.space.exception_match(w_1, w_2))
-
-    compare_dispatch_table = {
-        0: cmp_lt,   # "<"
-        1: cmp_le,   # "<="
-        2: cmp_eq,   # "=="
-        3: cmp_ne,   # "!="
-        4: cmp_gt,   # ">"
-        5: cmp_ge,   # ">="
-        6: cmp_in,
-        7: cmp_not_in,
-        8: cmp_is,
-        9: cmp_is_not,
-        10: cmp_exc_match,
-        }
-    def COMPARE_OP(f, testnum):
-        w_2 = f.valuestack.pop()
-        w_1 = f.valuestack.pop()
-        try:
-            testfn = f.compare_dispatch_table[testnum]
-        except KeyError:
-            raise pyframe.BytecodeCorruption, "bad COMPARE_OP oparg"
-        w_result = testfn(f, w_1, w_2)
-        f.valuestack.push(w_result)
-
-    def IMPORT_NAME(f, nameindex):
-        space = f.space
-        w_modulename = f.getname_w(nameindex)
-        modulename = f.space.str_w(w_modulename)
-        w_fromlist = f.valuestack.pop()
-        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
-        if w_locals is None:            # CPython does this
-            w_locals = space.w_None
-        w_obj = space.call_function(w_import, space.wrap(modulename),
-                                    f.w_globals, w_locals, w_fromlist)
-        f.valuestack.push(w_obj)
-
-    def IMPORT_STAR(f):
-        w_module = f.valuestack.pop()
-        w_locals = f.getdictscope()
-        import_all_from(f.space, w_module, w_locals)
-        f.setdictscope(w_locals)
-
-    def IMPORT_FROM(f, nameindex):
-        w_name = f.getname_w(nameindex)
-        w_module = f.valuestack.top()
-        try:
-            w_obj = f.space.getattr(w_module, w_name)
-        except OperationError, e:
-            if not e.match(f.space, f.space.w_AttributeError):
-                raise
-            raise OperationError(f.space.w_ImportError,
-                             f.space.wrap("cannot import name '%s'" % f.space.str_w(w_name) ))
-        f.valuestack.push(w_obj)
-
-    def JUMP_FORWARD(f, stepby):
-        f.next_instr += stepby
-
-    def JUMP_IF_FALSE(f, stepby):
-        w_cond = f.valuestack.top()
-        if not f.space.is_true(w_cond):
-            f.next_instr += stepby
-
-    def JUMP_IF_TRUE(f, stepby):
-        w_cond = f.valuestack.top()
-        if f.space.is_true(w_cond):
-            f.next_instr += stepby
-
-    def JUMP_ABSOLUTE(f, jumpto):
-        f.next_instr = jumpto
-
-    def GET_ITER(f):
-        w_iterable = f.valuestack.pop()
-        w_iterator = f.space.iter(w_iterable)
-        f.valuestack.push(w_iterator)
-
-    def FOR_ITER(f, jumpby):
-        w_iterator = f.valuestack.top()
-        try:
-            w_nextitem = f.space.next(w_iterator)
-        except OperationError, e:
-            if not e.match(f.space, f.space.w_StopIteration):
-                raise 
-            # iterator exhausted
-            f.valuestack.pop()
-            f.next_instr += jumpby
-        else:
-            f.valuestack.push(w_nextitem)
-
-    def FOR_LOOP(f, oparg):
-        raise pyframe.BytecodeCorruption, "old opcode, no longer in use"
-
-    def SETUP_LOOP(f, offsettoend):
-        block = pyframe.LoopBlock(f, f.next_instr + offsettoend)
-        f.blockstack.push(block)
-
-    def SETUP_EXCEPT(f, offsettoend):
-        block = pyframe.ExceptBlock(f, f.next_instr + offsettoend)
-        f.blockstack.push(block)
-
-    def SETUP_FINALLY(f, offsettoend):
-        block = pyframe.FinallyBlock(f, f.next_instr + offsettoend)
-        f.blockstack.push(block)
-
-    def CALL_FUNCTION(f, oparg, w_star=None, w_starstar=None):
-        n_arguments = oparg & 0xff
-        n_keywords = (oparg>>8) & 0xff
-        keywords = {}
-        for i in range(n_keywords):
-            w_value = f.valuestack.pop()
-            w_key   = f.valuestack.pop()
-            key = f.space.str_w(w_key)
-            keywords[key] = w_value
-        arguments = [f.valuestack.pop() for i in range(n_arguments)]
-        arguments.reverse()
-        args = Arguments(f.space, arguments, keywords, w_star, w_starstar)
-        w_function  = f.valuestack.pop()
-        w_result = f.space.call_args(w_function, args)
-        f.valuestack.push(w_result)
-
-    def CALL_FUNCTION_VAR(f, oparg):
-        w_varargs = f.valuestack.pop()
-        f.CALL_FUNCTION(oparg, w_varargs)
-
-    def CALL_FUNCTION_KW(f, oparg):
-        w_varkw = f.valuestack.pop()
-        f.CALL_FUNCTION(oparg, None, w_varkw)
-
-    def CALL_FUNCTION_VAR_KW(f, oparg):
-        w_varkw = f.valuestack.pop()
-        w_varargs = f.valuestack.pop()
-        f.CALL_FUNCTION(oparg, w_varargs, w_varkw)
-
-    def MAKE_FUNCTION(f, numdefaults):
-        w_codeobj = f.valuestack.pop()
-        codeobj = f.space.interpclass_w(w_codeobj)
-        assert isinstance(codeobj, PyCode)        
-        defaultarguments = [f.valuestack.pop() for i in range(numdefaults)]
-        defaultarguments.reverse()
-        fn = function.Function(f.space, codeobj, f.w_globals, defaultarguments)
-        f.valuestack.push(f.space.wrap(fn))
-
-    def BUILD_SLICE(f, numargs):
-        if numargs == 3:
-            w_step = f.valuestack.pop()
-        elif numargs == 2:
-            w_step = None
-        else:
-            raise pyframe.BytecodeCorruption
-        w_end   = f.valuestack.pop()
-        w_start = f.valuestack.pop()
-        w_slice = f.space.newslice(w_start, w_end, w_step)
-        f.valuestack.push(w_slice)
-
-    def LIST_APPEND(f):
-        w = f.valuestack.pop()
-        v = f.valuestack.pop()
-        f.space.call_method(v, 'append', w)
-
-    def SET_LINENO(f, lineno):
-        pass
-
-    def EXTENDED_ARG(f, oparg):
-        opcode = f.nextop()
-        oparg = oparg<<16 | f.nextarg()
-        fn = f.dispatch_table_w_arg[opcode]        
-        if fn is None:
-            raise pyframe.BytecodeCorruption            
-        fn(f, oparg)
-
-    def MISSING_OPCODE(f, oparg=None):
-        raise pyframe.BytecodeCorruption, "unknown opcode"
-
-    ### dispatch_table ###
-
-    # 'opcode_has_arg' is a class attribute: list of True/False whether opcode takes arg
-    # 'dispatch_table_no_arg: list of functions/None
-    # 'dispatch_table_w_arg: list of functions/None
-
-    __metaclass__ = InitializedClass
-    def __initclass__(cls):
-        "NOT_RPYTHON"
-        # create the 'cls.dispatch_table' attribute
-        import dis
-        opcode_has_arg = []
-        dispatch_table_no_arg = []
-        dispatch_table_w_arg = []
-        missing_opcode = cls.MISSING_OPCODE
-        for i in range(256):
-            opname = dis.opname[i].replace('+', '_')
-            fn = getattr(cls, opname, missing_opcode)
-            fn = getattr(fn, 'im_func',fn)
-            has_arg = i >= dis.HAVE_ARGUMENT
-            #if fn is missing_opcode and not opname.startswith('<') and i>0:
-            #    import warnings
-            #    warnings.warn("* Warning, missing opcode %s" % opname)
-            opcode_has_arg.append(has_arg)
-            if has_arg:
-                dispatch_table_w_arg.append(fn)
-                dispatch_table_no_arg.append(None)
-            else:
-                dispatch_table_no_arg.append(fn)
-                dispatch_table_w_arg.append(None)
-
-        cls.opcode_has_arg = opcode_has_arg
-        cls.dispatch_table_no_arg = dispatch_table_no_arg
-        cls.dispatch_table_w_arg = dispatch_table_w_arg
-
-
-### 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,
-# like finding out which metaclass a new class should have.
-# This is why they are not methods of PyInterpFrame.
-# There are also a couple of helpers that are methods, defined in the
-# class above.
-
-app = gateway.applevel(r'''
-    # NOT_RPYTHON   (but should be, soon)
-
-    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:
-            file.softspace = newflag
-        except AttributeError:
-            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)
-''')
-
-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/objspace/dummy.py
==============================================================================
--- /pypy/dist/pypy/objspace/dummy.py	Thu Apr  7 02:01:08 2005
+++ (empty file)
@@ -1,143 +0,0 @@
-from pypy.interpreter.baseobjspace import ObjSpace, W_Root, BaseWrappable
-from pypy.interpreter.module import Module
-from pypy.interpreter.error import OperationError
-
-from pypy.tool.cache import Cache
-
-class W_Obj(W_Root):
-    
-    def is_true(self):
-        return True
-
-    def str_w(self, space):
-        raise OperationError(space.w_TypeError,space.wrap("!")) 
-
-    def int_w(self, space):
-        raise OperationError(space.w_TypeError,space.wrap("!")) 
-
-    def float_w(self, space):
-        raise OperationError(space.w_TypeError,space.wrap("!")) 
-
-    def unwrap(self, space):
-        raise OperationError(space.w_TypeError,space.wrap("!")) 
-
-class W_Str(W_Obj):
-    def __init__(self, s):
-        self.s = s
-
-    def is_true(self):
-        return self.s != ""
-
-    def str_w(self, space):
-        return self.s
-
-    def unwrap(self, space):
-        return self.s
-
-class W_Int(W_Obj):
-    def __init__(self, i):
-        self.i = i
-
-    def is_true(self):
-        return self.i != 0
-
-    def int_w(self, space):
-        return self.i
-
-    def unwrap(self, space):
-        return self.i
-
-class W_None(W_Obj):
-    
-    def unwrap(self, space):
-        return None
-
-class W_Special(W_Obj):
-    def __init__(self, spec):
-        self.spec = spec
-
-class BuiltinModule(Module):
-    def __init__(self, space):
-        Module.__init__(self, space, space.wrap('__builtin__'), space.wrap({}))
-
-    def pick_builtin(self, w_globals):
-        return self
-    
-class DummyObjSpace(ObjSpace):
-
-    def __init__(self):
-        """NOT_RPYTHON"""
-        self.builtin    = BuiltinModule(self)
-
-        self.sys    = Module(self, self.wrap('sys'), self.wrap({}))
-        self.sys.recursionlimit = 1000
-
-        self.w_None = W_None()
-        self.w_NotImplemented = W_Special(NotImplemented)
-        self.w_Ellpisis = W_Special(Ellipsis)
-        self.w_False = self.wrap(0)
-        self.w_True = self.wrap(1)
-
-        for en in ObjSpace.ExceptionTable:
-            setattr(self, 'w_'+en, self.wrap(en))
-
-        self._gatewaycache = Cache()
-
-    for n, symbol, arity, ign in ObjSpace.MethodTable+[('newdict',"",1,[]), ('newlist',"",1,[]),
-                                                       ('newtuple',"",1,[]), ('newslice',"",3,[]), ]:
-        source = ("""if 1:
-        def %s(self, %s):
-            return W_Root()
-""" % (n, ', '.join(["w_a%d" % i for i in range(arity)])))
-        #print source
-        exec source
-
-    del n, symbol, arity, ign, i
-        
-    def wrap(self, obj):
-        if obj is None:
-            return self.w_None
-        if isinstance(obj, str):
-            return W_Str(obj)
-        if isinstance(obj, int):
-            return W_Int(obj)
-        return W_Root()
-    wrap._specialize_ = "argtypes"
-
-    def call_args(self, w_obj, args):
-        return W_Root()
-    
-    def is_true(self, w_obj):
-        if isinstance(w_obj, W_Obj):
-            return w_obj.is_true()
-        return True
-
-    def str_w(self, w_obj):
-        if not isinstance(w_obj, W_Obj):
-            w_obj = self.w_None
-        
-        return w_obj.str_w(self)
-
-    def int_w(self, w_obj):
-        if not isinstance(w_obj, W_Obj):
-            w_obj = self.w_None
-        
-        return w_obj.int_w(self)
-
-    def float_w(self, w_obj):
-        if not isinstance(w_obj, W_Obj):
-            w_obj = self.w_None
-               
-        return w_obj.float_w(self)
-
-    def unwrap(self, w_obj):
-        if isinstance(w_obj, BaseWrappable):
-            return w_obj
-        return w_obj.unwrap()
-
-    def _freeze_(self):
-        return True
-
-if __name__ == '__main__':
-  dummy_space = DummyObjSpace()
-  print dummy_space.eval("a+b",dummy_space.wrap({'a': 1,'b': 2}),dummy_space.wrap({}))

Deleted: /pypy/dist/pypy/objspace/flow/objspace.py
==============================================================================
--- /pypy/dist/pypy/objspace/flow/objspace.py	Thu Apr  7 02:01:08 2005
+++ (empty file)
@@ -1,535 +0,0 @@
-# ______________________________________________________________________
-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
-
-debug = 0
-
-class UnwrapException(Exception):
-    "Attempted to unwrap a Variable."
-
-class WrapException(Exception):
-    """Attempted wrapping of a type that cannot sanely appear in flow graph or during its construction"""
-
-# method-wrappers
-method_wrapper = type(complex.real.__get__)
-
-
-# ______________________________________________________________________
-class FlowObjSpace(ObjSpace):
-    """NOT_RPYTHON.
-    The flow objspace space is used to produce a flow graph by recording
-    the space operations that the interpreter generates when it interprets
-    (the bytecode of) some function.
-    """
-    
-    full_exceptions = False
-
-    builtins_can_raise_exceptions = False
-
-    do_imports_immediately = True  # overridden in geninterplevel
-
-    def initialize(self):
-        import __builtin__
-        self.concrete_mode = 0
-        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)
-        for exc in [KeyError, ValueError, IndexError, StopIteration,
-                    AssertionError]:
-            clsname = exc.__name__
-            setattr(self, 'w_'+clsname, Constant(exc))
-        # the following exceptions are the ones that should not show up
-        # during flow graph construction; they are triggered by
-        # non-R-Pythonic constructs or real bugs like typos.
-        for exc in [NameError, UnboundLocalError]:
-            clsname = exc.__name__
-            setattr(self, 'w_'+clsname, None)
-        self.specialcases = {}
-        #self.make_builtins()
-        #self.make_sys()
-
-    def loadfromcache(self, key, builder, cache):
-        # when populating the caches, the flow space switches to
-        # "concrete mode".  In this mode, only Constants are allowed
-        # and no SpaceOperation is recorded.
-        def my_builder(key, stuff):
-            previous_recorder = self.executioncontext.recorder
-            self.executioncontext.recorder = flowcontext.ConcreteNoOp()
-            self.concrete_mode += 1
-            try:
-                return builder(key, stuff)
-            finally:
-                self.executioncontext.recorder = previous_recorder
-                self.concrete_mode -= 1
-        return super(FlowObjSpace, self).loadfromcache(key, my_builder, cache)
-
-    def newdict(self, items_w):
-        if self.concrete_mode:
-            content = [(self.unwrap(w_key), self.unwrap(w_value))
-                       for w_key, w_value in items_w]
-            return Constant(dict(content))
-        flatlist_w = []
-        for w_key, w_value in items_w:
-            flatlist_w.append(w_key)
-            flatlist_w.append(w_value)
-        return self.do_operation('newdict', *flatlist_w)
-
-    def newtuple(self, args_w):
-        try:
-            content = [self.unwrap(w_arg) for w_arg in args_w]
-        except UnwrapException:
-            return self.do_operation('newtuple', *args_w)
-        else:
-            return Constant(tuple(content))
-
-    def newlist(self, args_w):
-        if self.concrete_mode:
-            content = [self.unwrap(w_arg) for w_arg in args_w]
-            return Constant(content)
-        return self.do_operation('newlist', *args_w)
-
-    def newslice(self, w_start=None, w_stop=None, w_step=None):
-        if w_start is None: w_start = self.w_None
-        if w_stop  is None: w_stop  = self.w_None
-        if w_step  is None: w_step  = self.w_None
-        if self.concrete_mode:
-            return Constant(slice(self.unwrap(w_start),
-                                  self.unwrap(w_stop),
-                                  self.unwrap(w_step)))
-        return self.do_operation('newslice', w_start, w_stop, w_step)
-
-    def wrap(self, obj):
-        if isinstance(obj, (Variable, Constant)):
-            raise TypeError("already wrapped: " + repr(obj))
-        # method-wrapper have ill-defined comparison and introspection
-        # to appear in a flow graph
-        if type(obj) is method_wrapper:
-            raise WrapException
-        return Constant(obj)
-
-    def int_w(self, w_obj):
-        if isinstance(w_obj, Constant):
-            val = w_obj.value
-            if type(val) not in (int,long):
-                raise TypeError("expected integer: " + repr(w_obj))
-            return val
-        return self.unwrap(w_obj)
-
-    def str_w(self, w_obj):
-        if isinstance(w_obj, Constant):
-            val = w_obj.value
-            if type(val) is not str:
-                raise TypeError("expected string: " + repr(w_obj))
-            return val
-        return self.unwrap(w_obj)                                
-
-    def float_w(self, w_obj):
-        if isinstance(w_obj, Constant):
-            val = w_obj.value
-            if type(val) is not float:
-                raise TypeError("expected float: " + repr(w_obj))
-            return val
-        return self.unwrap(w_obj)
-
-    def unwrap(self, w_obj):
-        if isinstance(w_obj, Variable):
-            raise UnwrapException
-        elif isinstance(w_obj, Constant):
-            return w_obj.value
-        else:
-            raise TypeError("not wrapped: " + repr(w_obj))
-
-    def unwrap_for_computation(self, w_obj):
-        obj = self.unwrap(w_obj)
-        to_check = obj
-        if hasattr(to_check, 'im_self'):
-            to_check = to_check.im_self
-        if (not isinstance(to_check, (type, types.ClassType)) and # classes/types are assumed immutable
-            hasattr(to_check, '__class__') and to_check.__class__.__module__ != '__builtin__'):
-            frozen = hasattr(to_check, '_freeze_') and to_check._freeze_()
-            if not frozen:
-                if self.concrete_mode:
-                    # xxx do we want some warning? notice that some stuff is harmless
-                    # like setitem(dict, 'n', mutable)
-                    pass
-                else: # cannot count on it not mutating at runtime!
-                    raise UnwrapException
-        return obj
-
-    def interpclass_w(self, w_obj):
-        obj = self.unwrap(w_obj)
-        if isinstance(obj, BaseWrappable):
-            return obj
-        return None
-
-    def getexecutioncontext(self):
-        return self.executioncontext
-
-    def setup_executioncontext(self, ec):
-        self.executioncontext = ec
-        from pypy.objspace.flow import specialcase
-        specialcase.setup(self)
-
-    def exception_match(self, w_exc_type, w_check_class):
-        self.executioncontext.recorder.crnt_block.exc_handler = True
-        try:
-            check_class = self.unwrap(w_check_class)
-        except UnwrapException:
-            raise Exception, "non-constant except guard"
-        if not isinstance(check_class, tuple):
-            # the simple case
-            return ObjSpace.exception_match(self, w_exc_type, w_check_class)
-        # checking a tuple of classes
-        for w_klass in self.unpacktuple(w_check_class):
-            if ObjSpace.exception_match(self, w_exc_type, w_klass):
-                return True
-        return False
-
-    def getconstclass(space, w_cls):
-        try:
-            ecls = space.unwrap(w_cls)
-        except UnwrapException:
-            pass
-        else:
-            if isinstance(ecls, (type, types.ClassType)):
-                return ecls
-        return None
-
-    def normalize_exception(space, w_arg1, w_arg2, w_tb):
-        """Special-case for 'raise' statements.  Case-by-case analysis:
-
-        * raise Class
-           - with a constant Class, it is easy to recognize.
-             But we don't normalize: the associated value is None.
-
-        * raise Class(...)
-           - when the class is instantiated in-place, we can figure that out
-
-        * raise Instance
-           - assumes that it's not a class, and raises an exception whose class
-             is variable and whose value is Instance.
-
-        * raise Class, Arg
-           - assumes that Arg is the value you want for the exception, and
-             that Class is exactly the exception class.  No check or normalization.
-        """
-
-        # w_arg3 (the traceback) is ignored and replaced with None
-        # if it is a Variable, because pyopcode.py tries to unwrap it.
-        # It means that we ignore the 'tb' argument of 'raise' in most cases.
-        if not isinstance(w_tb, Constant):
-            w_tb = space.w_None
-
-        if w_arg2 != space.w_None:
-            # raise Class, Arg: no normalization
-            return (w_arg1, w_arg2, w_tb)
-
-        etype = space.getconstclass(w_arg1)
-        if etype is not None:
-            # raise Class
-            return (w_arg1, space.w_None, w_tb)
-
-        # raise Class(..)?  We need a hack to figure out of which class it is.
-        # Normally, Instance should have been created by the previous operation
-        # which should be a simple_call(<Class>, ...).
-        # Fetch the <Class> out of there.  (This doesn't work while replaying)
-        # XXX this case is likely not triggered anymore, because the instance creation op
-        # is walled off in a different block by the surrounding it with exception
-        # handling logic that is always put in place for calls.
-        # We may want to make this more clever!
-        operations = space.executioncontext.recorder.crnt_block.operations
-        if operations:
-            spaceop = operations[-1]
-            if (spaceop.opname == 'simple_call' and
-                spaceop.result is w_arg1):
-                w_type = spaceop.args[0]
-                return (w_type, w_arg1, w_tb)
-
-        # raise Instance.  Fall-back.
-        w_type = space.do_operation('type', w_arg1)
-        return (w_type, w_arg1, w_tb)
-        # this function returns a real tuple that can be handled
-        # by FlowObjSpace.unpacktuple()
-
-
-    def build_flow(self, func, constargs={}):
-        """
-        """
-        if func.func_doc and func.func_doc.lstrip().startswith('NOT_RPYTHON'):
-            raise Exception, "%r is tagged as NOT_RPYTHON" % (func,)
-        code = func.func_code
-        code = PyCode(self)._from_code(code)
-        if func.func_closure is None:
-            closure = None
-        else:
-            closure = [extract_cell_content(c) for c in func.func_closure]
-        # CallableFactory.pycall may add class_ to functions that are methods
-        name = func.func_name
-        class_ = getattr(func, 'class_', None)
-        if class_ is not None:
-            name = '%s.%s' % (class_.__name__, name)
-        for c in "<>&!":
-            name = name.replace(c, '_')
-        ec = flowcontext.FlowExecutionContext(self, code, func.func_globals,
-                                              constargs, closure, name)
-        self.setup_executioncontext(ec)
-        ec.build_flow()
-        checkgraph(ec.graph)
-        return ec.graph
-
-    def unpacktuple(self, w_tuple, expected_length=None):
-        # special case to accept either Constant tuples
-        # or real tuples of Variables/Constants
-        if isinstance(w_tuple, tuple):
-            result = w_tuple
-        else:
-            unwrapped = self.unwrap(w_tuple)
-            result = tuple([Constant(x) for x in unwrapped])
-        if expected_length is not None and len(result) != expected_length:
-            raise ValueError, "got a tuple of length %d instead of %d" % (
-                len(result), expected_length)
-        return result
-
-    def unpackiterable(self, w_iterable, expected_length=None):
-        if isinstance(w_iterable, Variable) and expected_length is None:
-            raise UnwrapException, ("cannot unpack a Variable iterable"
-                                    "without knowing its length")
-##            # XXX TEMPORARY HACK XXX TEMPORARY HACK XXX TEMPORARY HACK
-##            print ("*** cannot unpack a Variable iterable "
-##                   "without knowing its length,")
-##            print "    assuming a list or tuple with up to 7 items"
-##            items = []
-##            w_len = self.len(w_iterable)
-##            i = 0
-##            while True:
-##                w_i = self.wrap(i)
-##                w_cond = self.eq(w_len, w_i)
-##                if self.is_true(w_cond):
-##                    break  # done
-##                if i == 7:
-##                    # too many values
-##                    raise OperationError(self.w_AssertionError, self.w_None)
-##                w_item = self.do_operation('getitem', w_iterable, w_i)
-##                items.append(w_item)
-##                i += 1
-##            return items
-##            # XXX TEMPORARY HACK XXX TEMPORARY HACK XXX TEMPORARY HACK
-        elif expected_length is not None:
-            w_len = self.len(w_iterable)
-            w_correct = self.eq(w_len, self.wrap(expected_length))
-            if not self.is_true(w_correct):
-                raise OperationError(self.w_ValueError, self.w_None)
-            return [self.do_operation('getitem', w_iterable, self.wrap(i)) 
-                        for i in range(expected_length)]
-        return ObjSpace.unpackiterable(self, w_iterable, expected_length)
-
-    # ____________________________________________________________
-    def do_operation(self, name, *args_w):
-        spaceop = SpaceOperation(name, args_w, Variable())
-        if hasattr(self, 'executioncontext'):  # not here during bootstrapping
-            spaceop.offset = self.executioncontext.crnt_offset
-            self.executioncontext.recorder.append(spaceop)
-        return spaceop.result
-    
-    def is_true(self, w_obj):
-        try:
-            obj = self.unwrap_for_computation(w_obj)
-        except UnwrapException:
-            pass
-        else:
-            return bool(obj)
-        w_truthvalue = self.do_operation('is_true', w_obj)
-        context = self.getexecutioncontext()
-        return context.guessbool(w_truthvalue)
-
-    def next(self, w_iter):
-        w_item = self.do_operation("next", w_iter)
-        context = self.getexecutioncontext()
-        outcome, w_exc_cls, w_exc_value = context.guessexception(StopIteration)
-        if outcome is StopIteration:
-            raise OperationError(self.w_StopIteration, self.w_None)
-        else:
-            return w_item
-
-    def call_args(self, w_callable, args):
-        try:
-            fn = self.unwrap(w_callable)
-            sc = self.specialcases[fn]   # TypeError if 'fn' not hashable
-        except (UnwrapException, KeyError, TypeError):
-            pass
-        else:
-            return sc(self, fn, args)
-
-        try:
-            args_w, kwds_w = args.unpack()
-        except UnwrapException:
-            args_w, kwds_w = '?', '?'
-        if not kwds_w:
-            # simple case
-            w_res = self.do_operation('simple_call', w_callable, *args_w)
-        else:
-            # general case
-            shape, args_w = args.flatten()
-            w_res = self.do_operation('call_args', w_callable, Constant(shape),
-                                      *args_w)
-
-        # maybe the call has generated an exception (any one)
-        # but, let's say, not if we are calling a built-in class or function
-        # because this gets in the way of the special-casing of
-        #
-        #    raise SomeError(x)
-        #
-        # as shown by test_objspace.test_raise3.
-        
-        exceptions = [Exception]   # *any* exception by default
-        if isinstance(w_callable, Constant):
-            c = w_callable.value
-            if isinstance(c, (types.BuiltinFunctionType,
-                              types.BuiltinMethodType)):
-                if not self.builtins_can_raise_exceptions:
-                    exceptions = None
-            elif (isinstance(c, (type, types.ClassType)) and
-                  c.__module__ in ['__builtin__', 'exceptions']):
-                exceptions = None
-        self.handle_implicit_exceptions(exceptions)
-        return w_res
-
-    def handle_implicit_exceptions(self, exceptions):
-        if exceptions:
-            # catch possible exceptions implicitly.  If the OperationError
-            # below is not caught in the same function, it will produce an
-            # exception-raising return block in the flow graph.  The special
-            # value 'wrap(last_exception)' is used as a marker for this kind
-            # of implicit exceptions, and simplify.py will remove it as per
-            # the RPython definition: implicit exceptions not explicitly
-            # caught in the same function are assumed not to occur.
-            context = self.getexecutioncontext()
-            outcome, w_exc_cls, w_exc_value = context.guessexception(*exceptions)
-            if outcome is not None:
-                # we assume that the caught exc_cls will be exactly the
-                # one specified by 'outcome', and not a subclass of it,
-                # unless 'outcome' is Exception.
-                if outcome is not Exception:
-                    w_exc_cls = Constant(outcome, last_exception=True)
-                raise OperationError(w_exc_cls, w_exc_value)
-
-# ______________________________________________________________________
-
-implicit_exceptions = {
-    'getitem': [IndexError, KeyError],
-    'delitem': [IndexError, KeyError],
-    'getattr': [AttributeError],
-    'delattr': [AttributeError],
-    'iter'   : [TypeError],
-    'coerce' : [TypeError],
-    }
-# continuing like above, but in a more programmatic style.
-def _add_exceptions(names, exc):
-    for name in names.split():
-        lis = implicit_exceptions.setdefault(name, [])
-        if exc in lis:
-            raise ValueError, "your list is causing duplication!"
-        lis.append(exc)
-
-_add_exceptions("""div mod divmod truediv floordiv pow
-                   inplace_div inplace_mod inplace_divmod inplace_truediv
-                   inplace_floordiv inplace_pow""", ZeroDivisionError)
-_add_exceptions("""pos neg abs invert add sub mul truediv
-                   floordiv div mod divmod pow lshift
-                   inplace_add inplace_sub inplace_mul inplace_truediv
-                   inplace_floordiv inplace_div inplace_mod inplace_pow
-                   inplace_lshift""", OverflowError)
-_add_exceptions("""pow inplace_pow""", ValueError)
-_add_exceptions("""add sub mul truediv floordiv div mod divmod pow
-                   inplace_add inplace_sub inplace_mul inplace_truediv
-                   inplace_floordiv inplace_div inplace_mod inplace_divmod
-                   inplace_pow""", FloatingPointError)
-del _add_exceptions
-
-def extract_cell_content(c):
-    """Get the value contained in a CPython 'cell', as read through
-    the func_closure of a function object."""
-    # yuk! this is all I could come up with that works in Python 2.2 too
-    class X(object):
-        def __eq__(self, other):
-            self.other = other
-    x = X()
-    x_cell, = (lambda: x).func_closure
-    x_cell == c
-    return x.other
-
-def make_op(name, symbol, arity, specialnames):
-    if hasattr(FlowObjSpace, name):
-        return # Shouldn't do it
-
-    if name == 'pow':
-        op = pow
-    else:
-        op = getattr(operator, name, None)
-    if not op:
-        #if name == 'call':
-        #    op = apply
-        if name == 'issubtype':
-            op = issubclass
-        elif name == 'is_':
-            op = lambda x, y: x is y
-        elif name == 'getattr':
-            op = getattr
-        else:
-            if debug: print >> sys.stderr, "XXX missing operator:", name
-
-    exceptions = implicit_exceptions.get(name)
-
-    def generic_operator(self, *args_w):
-        assert len(args_w) == arity, name+" got the wrong number of arguments"
-        if op:
-            args = []
-            for w_arg in args_w:
-                try:
-                    arg = self.unwrap_for_computation(w_arg)
-                except UnwrapException:
-                    break
-                else:
-                    args.append(arg)
-            else:
-                # All arguments are constants: call the operator now
-                #print >> sys.stderr, 'Constant operation', op
-                try:
-                    result = op(*args)
-                except:
-                    etype, evalue, etb = sys.exc_info()
-                    msg = "generated by a constant operation:  %s%r" % (
-                        name, tuple(args))
-                    raise flowcontext.OperationThatShouldNotBePropagatedError(
-                        self.wrap(etype), self.wrap(msg))
-                else:
-                    try:
-                        return self.wrap(result)
-                    except WrapException:
-                        # type cannot sanely appear in flow graph,
-                        # store operation with variable result instead
-                        pass
-
-        #print >> sys.stderr, 'Variable operation', name, args_w
-        w_result = self.do_operation(name, *args_w)
-        self.handle_implicit_exceptions(exceptions)
-        return w_result
-
-    setattr(FlowObjSpace, name, generic_operator)
-
-for line in ObjSpace.MethodTable:
-    make_op(*line)
-
-# ______________________________________________________________________
-# End of objspace.py

Deleted: /pypy/dist/pypy/objspace/flow/test/test_objspace.py
==============================================================================
--- /pypy/dist/pypy/objspace/flow/test/test_objspace.py	Thu Apr  7 02:01:08 2005
+++ (empty file)
@@ -1,467 +0,0 @@
-import autopath
-from pypy.objspace.flow.model import Constant, Block, Link, Variable, traverse
-from pypy.interpreter.argument import Arguments
-from pypy.translator.simplify import simplify_graph
-
-objspacename = 'flow'
-
-import operator
-is_operator = getattr(operator, 'is_', operator.eq) # it's not there 2.2
-
-class TestFlowObjSpace:
-    def codetest(self, func):
-        import inspect
-        try:
-            func = func.im_func
-        except AttributeError:
-            pass
-        #name = func.func_name
-        graph = self.space.build_flow(func)
-        graph.source = inspect.getsource(func)
-        return graph
-
-    def reallyshow(self, x):
-        x.show()
-        #import os
-        #from pypy.translator.tool.make_dot import make_dot
-        #dest = make_dot(x.name, x)
-        #os.system('gv %s' % str(dest))
-
-    def show(self, x):
-        pass   # or   self.reallyshow(x)
-
-    #__________________________________________________________
-    def nothing():
-        pass
-
-    def test_nothing(self):
-        x = self.codetest(self.nothing)
-        assert len(x.startblock.exits) == 1
-        link, = x.startblock.exits
-        assert link.target == x.returnblock
-        self.show(x)
-
-    #__________________________________________________________
-    def simplebranch(i, j):
-        if i < 0:
-            return i
-        return j
-
-    def test_simplebranch(self):
-        x = self.codetest(self.simplebranch)
-        self.show(x)
-
-    #__________________________________________________________
-    def ifthenelse(i, j):
-        if i < 0:
-            i = j
-        return g(i) + 1
-    
-    def test_ifthenelse(self):
-        x = self.codetest(self.simplebranch)
-        self.show(x)
-
-    #__________________________________________________________
-    def print_(i):
-        print i
-    
-    def test_print(self):
-        x = self.codetest(self.print_)
-        self.show(x)
-
-    #__________________________________________________________
-    def while_(i):
-        while i > 0:
-            i = i - 1
-
-    def test_while(self):
-        x = self.codetest(self.while_)
-        self.show(x)
-
-    #__________________________________________________________
-    def union_easy(i):
-        if i:
-            pass
-        else:
-            i = 5
-        return i
-
-    def test_union_easy(self):
-        x = self.codetest(self.union_easy)
-        self.show(x)
-
-    #__________________________________________________________
-    def union_hard(i):
-        if i:
-            i = 5
-        return i
-    
-    def test_union_hard(self):
-        x = self.codetest(self.union_hard)
-        self.show(x)
-
-    #__________________________________________________________
-    def while_union(i):
-        total = 0
-        while i > 0:
-            total += i
-            i = i - 1
-        return total
-    
-    def test_while_union(self):
-        x = self.codetest(self.while_union)
-        self.show(x)
-
-    #__________________________________________________________
-    def simple_for(lst):
-        total = 0
-        for i in lst:
-            total += i
-        return total
-    
-    def test_simple_for(self):
-        x = self.codetest(self.simple_for)
-        self.show(x)
-
-    #__________________________________________________________
-    def nested_whiles(i, j):
-        s = ''
-        z = 5
-        while z > 0:
-            z = z - 1
-            u = i
-            while u < j:
-                u = u + 1
-                s = s + '.'
-            s = s + '!'
-        return s
-
-    def test_nested_whiles(self):
-        x = self.codetest(self.nested_whiles)
-        self.show(x)
-
-    #__________________________________________________________
-    def break_continue(x):
-        result = []
-        i = 0
-        while 1:
-            i = i + 1
-            try:
-                if i&1:
-                    continue
-                if i >= x:
-                    break
-            finally:
-                result.append(i)
-            i = i + 1
-        return result
-
-    def test_break_continue(self):
-        x = self.codetest(self.break_continue)
-        self.show(x)
-
-    #__________________________________________________________
-    def unpack_tuple(lst):
-        a, b, c = lst
-
-    def test_unpack_tuple(self):
-        x = self.codetest(self.unpack_tuple)
-        self.show(x)
-
-    #__________________________________________________________
-    def reverse_3(lst):
-        try:
-            a, b, c = lst
-        except:
-            return 0, 0, 0
-        else:
-            return c, b, a
-
-    def test_reverse_3(self):
-        x = self.codetest(self.reverse_3)
-        self.show(x)
-
-    #__________________________________________________________
-    def finallys(lst):
-        x = 1
-        try:
-            x = 2
-            try:
-                x = 3
-                a, = lst
-                x = 4
-            except KeyError:
-                return 5
-            except ValueError:
-                return 6
-            b, = lst
-            x = 7
-        finally:
-            x = 8
-        return x
-
-    def test_finallys(self):
-        x = self.codetest(self.finallys)
-        self.show(x)
-
-    #__________________________________________________________
-    def const_pow():
-        return 2 ** 5
-
-    def test_const_pow(self):
-        x = self.codetest(self.const_pow)
-        self.show(x)
-
-    #__________________________________________________________
-    def implicitIndexError(lst):
-        try:
-            x = lst[5]
-        except IndexError:
-            return 'catch'
-        return lst[3]   # not caught
-
-    def test_implicitIndexError(self):
-        x = self.codetest(self.implicitIndexError)
-        self.show(x)
-
-    #__________________________________________________________
-    def freevar(self, x):
-        def adder(y):
-            return x+y
-        return adder
-
-    def test_freevar(self):
-        x = self.codetest(self.freevar(3))
-        self.show(x)
-
-    #__________________________________________________________
-    def raise1(msg):
-        raise IndexError
-    
-    def test_raise1(self):
-        x = self.codetest(self.raise1)
-        self.show(x)
-        assert len(x.startblock.operations) == 0
-        assert x.startblock.exits[0].args == [
-            Constant(IndexError),
-            Constant(None)]         # no normalization
-        assert x.startblock.exits[0].target is x.exceptblock
-
-    #__________________________________________________________
-    def raise2(msg):
-        raise IndexError, msg
-    
-    def test_raise2(self):
-        x = self.codetest(self.raise2)
-        self.show(x)
-        assert len(x.startblock.operations) == 0
-        assert x.startblock.exits[0].args == [
-            Constant(IndexError),
-            x.startblock.inputargs[0]]
-        assert x.startblock.exits[0].target is x.exceptblock
-
-    #__________________________________________________________
-    def raise3(msg):
-        raise IndexError(msg)
-    
-    def test_raise3(self):
-        x = self.codetest(self.raise3)
-        self.show(x)
-        simplify_graph(x)
-        assert len(x.startblock.operations) == 1
-        assert x.startblock.operations[0].opname == 'simple_call'
-        assert list(x.startblock.operations[0].args) == [
-            Constant(IndexError),
-            x.startblock.inputargs[0]]
-        assert x.startblock.exits[0].args == [
-            Constant(IndexError),
-            x.startblock.operations[0].result]
-        assert x.startblock.exits[0].target is x.exceptblock
-
-    #__________________________________________________________
-    def raise4(stuff):
-        raise stuff
-    
-    def test_raise4(self):
-        x = self.codetest(self.raise4)
-        self.show(x)
-
-    #__________________________________________________________
-    def raise_and_catch_1(exception_instance):
-        try:
-            raise exception_instance
-        except IndexError:
-            return -1
-        return 0
-    
-    def test_raise_and_catch_1(self):
-        x = self.codetest(self.raise_and_catch_1)
-        self.show(x)
-
-    #__________________________________________________________
-    def catch_simple_call():
-        try:
-            user_defined_function()
-        except IndexError:
-            return -1
-        return 0
-    
-    def test_catch_simple_call(self):
-        x = self.codetest(self.catch_simple_call)
-        self.show(x)
-
-    #__________________________________________________________
-    def dellocal():
-        x = 1
-        del x
-        for i in range(10):
-            pass
-    
-    def test_dellocal(self):
-        x = self.codetest(self.dellocal)
-        self.show(x)
-
-    #__________________________________________________________
-    def globalconstdict(name):
-        x = DATA['x']
-        z = DATA[name]
-        return x, z
-    
-    def test_globalconstdict(self):
-        x = self.codetest(self.globalconstdict)
-        self.show(x)
-
-    #__________________________________________________________
-    
-    def specialcases():
-        import operator
-        operator.lt(2,3)
-        operator.le(2,3)
-        operator.eq(2,3)
-        operator.ne(2,3)
-        operator.gt(2,3)
-        operator.ge(2,3)
-        is_operator(2,3)
-        operator.__lt__(2,3)
-        operator.__le__(2,3)
-        operator.__eq__(2,3)
-        operator.__ne__(2,3)
-        operator.__gt__(2,3)
-        operator.__ge__(2,3)
-    
-    def test_specialcases(self):
-        x = self.codetest(self.specialcases)
-        from pypy.translator.simplify import join_blocks
-        join_blocks(x)
-        assert len(x.startblock.operations) == 13
-        for op in x.startblock.operations:
-            assert op.opname in ['lt', 'le', 'eq', 'ne',
-                                       'gt', 'ge', 'is_']
-            assert len(op.args) == 2
-            assert op.args[0].value == 2
-            assert op.args[1].value == 3
-
-    #__________________________________________________________
-    def jump_target_specialization(x):
-        if x:
-            n = 5
-        else:
-            n = 6
-        return n*2
-
-    def test_jump_target_specialization(self):
-        x = self.codetest(self.jump_target_specialization)
-        self.show(x)
-        def visitor(node):
-            if isinstance(node, Block):
-                for op in node.operations:
-                    assert op.opname != 'mul', "mul should have disappeared"
-        traverse(visitor, x)
-
-    #__________________________________________________________
-    def test_unfrozen_user_class1(self):
-        class C:
-            def __nonzero__(self):
-                return True
-        c = C()
-        def f():
-            if c:
-                return 1
-            else:
-                return 2
-        graph = self.codetest(f)
-
-        results = []
-        def visit(link):
-            if isinstance(link, Link):
-                if link.target == graph.returnblock:
-                    results.extend(link.args)
-        traverse(visit, graph)
-        assert len(results) == 2
-
-    def test_unfrozen_user_class2(self):
-        class C:
-            def __add__(self, other):
-                return 4
-        c = C()
-        d = C()
-        def f():
-            return c+d
-        graph = self.codetest(f)
-
-        results = []
-        def visit(link):
-            if isinstance(link, Link):
-                if link.target == graph.returnblock:
-                    results.extend(link.args)
-        traverse(visit, graph)
-        assert not isinstance(results[0], Constant)
-
-    def test_frozen_user_class1(self):
-        class C:
-            def __nonzero__(self):
-                return True
-            def _freeze_(self):
-                return True
-        c = C()
-        def f():
-            if c:
-                return 1
-            else:
-                return 2
-
-        graph = self.codetest(f)
-
-        results = []
-        def visit(link):
-            if isinstance(link, Link):
-                if link.target == graph.returnblock:
-                    results.extend(link.args)
-        traverse(visit, graph)
-        assert len(results) == 1
-
-    def test_frozen_user_class2(self):
-        class C:
-            def __add__(self, other):
-                return 4
-            def _freeze_(self):
-                return True
-        c = C()
-        d = C()
-        def f():
-            return c+d
-        graph = self.codetest(f)
-
-        results = []
-        def visit(link):
-            if isinstance(link, Link):
-                if link.target == graph.returnblock:
-                    results.extend(link.args)
-        traverse(visit, graph)
-        assert results == [Constant(4)]
-
-DATA = {'x': 5,
-        'y': 6}
-
-def user_defined_function():
-    pass

Deleted: /pypy/dist/pypy/objspace/std/objspace.py
==============================================================================
--- /pypy/dist/pypy/objspace/std/objspace.py	Thu Apr  7 02:01:08 2005
+++ (empty file)
@@ -1,311 +0,0 @@
-from pypy.objspace.std.register_all import register_all
-from pypy.interpreter.baseobjspace import ObjSpace, BaseWrappable
-from pypy.interpreter.error import OperationError
-from pypy.interpreter.typedef import get_unique_interplevel_subclass
-from pypy.interpreter.typedef import instantiate
-from pypy.tool.cache import Cache 
-from pypy.objspace.std.model import W_Object, UnwrapError
-from pypy.objspace.std.model import W_ANY, MultiMethod, StdTypeModel
-from pypy.objspace.std.multimethod import FailedToImplement
-from pypy.objspace.descroperation import DescrOperation
-from pypy.objspace.std import stdtypedef
-import types
-
-
-def registerimplementation(implcls):
-    # this function should ultimately register the implementation class somewhere
-    # it may be modified to take 'typedef' instead of requiring it to be
-    # stored in 'implcls' itself
-    assert issubclass(implcls, W_Object)
-
-
-##################################################################
-
-class StdObjSpace(ObjSpace, DescrOperation):
-    """The standard object space, implementing a general-purpose object
-    library in Restricted Python."""
-
-    PACKAGE_PATH = 'objspace.std'
-
-    def _freeze_(self): 
-        return True 
-
-    def initialize(self):
-        "NOT_RPYTHON: only for initializing the space."
-        self._typecache = Cache()
-
-        # Import all the object types and implementations
-        self.model = StdTypeModel()
-
-        # install all the MultiMethods into the space instance
-        for name, mm in self.MM.__dict__.items():
-            if isinstance(mm, MultiMethod) and not hasattr(self, name):
-                if name.endswith('_w'): # int_w, str_w...: these do not return a wrapped object
-                    func = mm.install_not_sliced(self.model.typeorder, baked_perform_call=True)
-                else:               
-                    exprargs, expr, miniglobals, fallback = (
-                        mm.install_not_sliced(self.model.typeorder, baked_perform_call=False))
-
-                    func = stdtypedef.make_perform_trampoline('__mm_'+name,
-                                                              exprargs, expr, miniglobals,
-                                                              mm)
-                
-                                                  # e.g. add(space, w_x, w_y)
-                boundmethod = func.__get__(self)  # bind the 'space' argument
-                setattr(self, name, boundmethod)  # store into 'space' instance
-
-        # hack to avoid imports in the time-critical functions below
-        for cls in self.model.typeorder:
-            globals()[cls.__name__] = cls
-
-        # singletons
-        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
-        self.w_NotImplemented = self.wrap(NotImplemented(self))  
-        self.w_Ellipsis = self.wrap(Ellipsis(self))  
-
-        # types
-        self.types_w = {}
-        for typedef in self.model.pythontypes:
-            w_type = self.gettypeobject(typedef)
-            setattr(self, 'w_' + 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], {})
-
-        # 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()
-
-    def enable_old_style_classes_as_default_metaclass(self):
-        self.setitem(self.builtin.w_dict, self.wrap('__metaclass__'), self.w_classobj)
-
-    def setup_old_style_classes(self):
-        """NOT_RPYTHON"""
-        from pypy.module import classobjinterp
-        # sanity check that this approach is working and is not too late
-        assert not self.is_true(self.contains(self.builtin.w_dict,self.wrap('_classobj'))),"app-level code has seen dummy old style classes"
-        w_setup = classobjinterp.initclassobj(self)
-        w_classobj, w_instance, w_purify = self.unpackiterable(w_setup)
-        self.call_function(w_purify)
-        self.w_classobj = w_classobj
-        self.w_instance = w_instance
-
-    def setup_exceptions(self):
-        """NOT_RPYTHON"""
-        ## hacking things in
-        from pypy.module import exceptionsinterp as ex
-        def call(w_type, w_args):
-            space = self
-            # too early for unpackiterable as well :-(
-            name  = space.unwrap(space.getitem(w_args, space.wrap(0)))
-            bases = space.unpacktuple(space.getitem(w_args, space.wrap(1)))
-            dic   = space.unwrap(space.getitem(w_args, space.wrap(2)))
-            dic = dict([(key,space.wrap(value)) for (key, value) in dic.items()])
-            bases = list(bases)
-            if not bases:
-                bases = [space.w_object]
-            res = W_TypeObject(space, name, bases, dic)
-            return res
-        try:
-            # note that we hide the real call method by an instance variable!
-            self.call = call
-            w_dic = ex.initexceptions(self)
-
-            self.w_IndexError = self.getitem(w_dic, self.wrap("IndexError"))
-            self.w_StopIteration = self.getitem(w_dic, self.wrap("StopIteration"))
-        finally:
-            del self.call # revert
-
-        names_w = self.unpackiterable(self.call_function(self.getattr(w_dic, self.wrap("keys"))))
-
-        for w_name in names_w:
-            name = self.str_w(w_name)
-            if not name.startswith('__'):
-                excname = name
-                w_exc = self.getitem(w_dic, w_name)
-                setattr(self, "w_"+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
-        return Module(self, self.wrap("exceptions"), w_dic)
-
-    def gettypeobject(self, typedef):
-        # types_w maps each StdTypeDef instance to its
-        # unique-for-this-space W_TypeObject instance
-        return self.loadfromcache(typedef, 
-                                  stdtypedef.buildtypeobject,
-                                  self._typecache)
-
-    def wrap(self, x):
-        "Wraps the Python value 'x' into one of the wrapper classes."
-        if x is None:
-            return self.w_None
-        if isinstance(x, W_Object):
-            raise TypeError, "attempt to wrap already wrapped object: %s"%(x,)
-        if isinstance(x, OperationError):
-            raise TypeError, ("attempt to wrap already wrapped exception: %s"%
-                              (x,))
-        if isinstance(x, int):
-            if isinstance(bool, type) and isinstance(x, bool):
-                return self.newbool(x)
-            return W_IntObject(self, x)
-        if isinstance(x, str):
-            return W_StringObject(self, x)
-        if isinstance(x, dict):
-            items_w = [(self.wrap(k), self.wrap(v)) for (k, v) in x.iteritems()]
-            return W_DictObject(self, items_w)
-        if isinstance(x, float):
-            return W_FloatObject(self, x)
-        if isinstance(x, tuple):
-            wrappeditems = [self.wrap(item) for item in x]
-            return W_TupleObject(self, wrappeditems)
-        if isinstance(x, list):
-            wrappeditems = [self.wrap(item) for item in x]
-            return W_ListObject(self, wrappeditems)
-        if isinstance(x, long):
-            return W_LongObject(self, x)
-        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.builtin.get('complex') 
-            return self.call_function(c,
-                                      self.wrap(x.real), 
-                                      self.wrap(x.imag))
-        if isinstance(x, BaseWrappable):
-            w_result = x.__spacebind__(self)
-            #print 'wrapping', x, '->', w_result
-            return w_result
-        # anything below this line is implicitly XXX'ed
-        if isinstance(x, type(Exception)) and issubclass(x, Exception):
-            if hasattr(self, 'w_' + x.__name__):
-                w_result = getattr(self, 'w_' + x.__name__)
-                assert isinstance(w_result, W_TypeObject)
-                return w_result
-        from fake import fake_type
-        if isinstance(x, type):
-            ft = fake_type(x)
-            return self.gettypeobject(ft.typedef)
-        ft = fake_type(type(x))
-        return ft(self, x)
-    wrap._specialize_ = "argtypes"
-
-    def unwrap(self, w_obj):
-        if isinstance(w_obj, BaseWrappable):
-            return w_obj
-        if isinstance(w_obj, W_Object):
-            return w_obj.unwrap()
-        raise UnwrapError, "cannot unwrap: %r" % w_obj
-        
-
-    def newint(self, intval):
-        return W_IntObject(self, intval)
-
-    def newfloat(self, floatval):
-        return W_FloatObject(self, floatval)
-
-    def newtuple(self, list_w):
-        assert isinstance(list_w, list)
-        return W_TupleObject(self, list_w)
-
-    def newlist(self, list_w):
-        return W_ListObject(self, list_w)
-
-    def newdict(self, list_pairs_w):
-        return W_DictObject(self, list_pairs_w)
-
-    def newslice(self, w_start, w_end, w_step):
-        # w_step may be a real None
-        if w_step is None:
-            w_step = self.w_None
-        return W_SliceObject(self, w_start, w_end, w_step)
-
-    def newstring(self, chars_w):
-        try:
-            chars = [chr(self.int_w(w_c)) for w_c in chars_w]
-        except ValueError:  # chr(out-of-range)
-            raise OperationError(self.w_ValueError,
-                                 self.wrap("character code not in range(256)"))
-        return W_StringObject(self, ''.join(chars))
-
-    def newseqiter(self, w_obj):
-        return W_SeqIterObject(self, w_obj)
-
-    def type(self, w_obj):
-        return w_obj.getclass(self)
-
-    def lookup(self, w_obj, name):
-        w_type = w_obj.getclass(self)
-        return w_type.lookup(name)
-
-    def allocate_instance(self, cls, w_subtype):
-        """Allocate the memory needed for an instance of an internal or
-        user-defined type, without actually __init__ializing the instance."""
-        w_type = self.gettypeobject(cls.typedef)
-        if self.is_true(self.is_(w_type, w_subtype)):
-            return instantiate(cls)
-        else:
-            w_type.check_user_subclass(w_subtype)
-            subcls = get_unique_interplevel_subclass(cls, w_subtype.hasdict, w_subtype.nslots != 0)
-            instance = instantiate(subcls)
-            instance.user_setup(self, w_subtype, w_subtype.nslots)
-            return instance
-
-    def unpacktuple(self, w_tuple, expected_length=None):
-        assert isinstance(w_tuple, W_TupleObject)
-        t = w_tuple.wrappeditems
-        if expected_length is not None and expected_length != len(t):
-            raise ValueError, "got a tuple of length %d instead of %d" % (
-                len(t), expected_length)
-        return t
-
-    def is_(self, w_one, w_two):
-        # XXX a bit of hacking to gain more speed 
-        if w_one is w_two:
-            return self.w_True
-        return self.w_False
-
-    def is_true(self, w_obj):
-        # XXX don't look!
-        if isinstance(w_obj, W_DictObject):
-            return not not w_obj.used
-        else:
-            return DescrOperation.is_true(self, w_obj)
-
-
-    class MM:
-        "Container for multimethods."
-        call    = MultiMethod('call', 1, ['__call__'], general__args__=True)
-        init    = MultiMethod('__init__', 1, general__args__=True)
-        # special visible multimethods
-        int_w   = MultiMethod('int_w', 1, [])     # returns an unwrapped int
-        str_w   = MultiMethod('str_w', 1, [])     # returns an unwrapped string
-        float_w = MultiMethod('float_w', 1, [])   # returns an unwrapped float
-
-        # add all regular multimethods here
-        for _name, _symbol, _arity, _specialnames in ObjSpace.MethodTable:
-            if _name not in locals():
-                mm = MultiMethod(_symbol, _arity, _specialnames)
-                locals()[_name] = mm
-                del mm
-
-        pow.extras['defaults'] = (None,)

Deleted: /pypy/dist/pypy/tool/pytestsupport.py
==============================================================================
--- /pypy/dist/pypy/tool/pytestsupport.py	Thu Apr  7 02:01:08 2005
+++ (empty file)
@@ -1,186 +0,0 @@
-from __future__ import generators 
-import autopath
-import py
-from py.__impl__.magic import exprinfo
-from pypy.interpreter import gateway
-from pypy.interpreter.error import OperationError
-
-# ____________________________________________________________
-
-class AppFrame(py.code.Frame):
-
-    def __init__(self, pyframe):
-        self.code = py.code.Code(pyframe.code)
-        self.lineno = pyframe.get_last_lineno() - 1
-        self.space = pyframe.space
-        self.w_globals = pyframe.w_globals
-        self.w_locals = pyframe.getdictscope()
-        self.f_locals = self.w_locals   # for py.test's recursion detection
-
-    def eval(self, code, **vars):
-        space = self.space
-        for key, w_value in vars.items():
-            space.setitem(self.w_locals, space.wrap(key), w_value)
-        return space.eval(code, self.w_globals, self.w_locals)
-
-    def exec_(self, code, **vars):
-        space = self.space
-        for key, w_value in vars.items():
-            space.setitem(self.w_locals, space.wrap(key), w_value)
-        space.exec_(code, self.w_globals, self.w_locals)
-
-    def repr(self, w_value):
-        return self.space.unwrap(self.space.repr(w_value))
-
-    def is_true(self, w_value):
-        return self.space.is_true(w_value)
-
-class AppExceptionInfo(py.code.ExceptionInfo):
-    """An ExceptionInfo object representing an app-level exception."""
-
-    def __init__(self, space, operr):
-        self.space = space
-        self.operr = operr
-        self.traceback = AppTraceback(self.operr.application_traceback)
-
-    def __str__(self):
-        return '(application-level) ' + self.operr.errorstr(self.space)
-
-class AppTracebackEntry(py.code.Traceback.Entry):
-    exprinfo = None
-
-    def __init__(self, tb):
-        self.frame = AppFrame(tb.frame)
-        self.lineno = tb.lineno - 1
-
-    def reinterpret(self):
-        # XXX we need to solve a general problem: how to prevent
-        #     reinterpretation from generating a different exception?
-        #     This problem includes the fact that exprinfo will generate
-        #     its own long message that looks like
-        #        OperationError:   << [<W_TypeObject(NameError)>: W_StringObj...
-        #     which is much less nice than the one produced by str(self).
-        # XXX this reinterpret() is only here to prevent reinterpretation.
-        return self.exprinfo
-
-class AppTraceback(py.code.Traceback): 
-    Entry = AppTracebackEntry 
-
-    def __init__(self, apptb):
-        l = []
-        while apptb is not None: 
-            l.append(self.Entry(apptb))
-            apptb = apptb.next 
-        list.__init__(self, l) 
-
-# ____________________________________________________________
-
-def build_pytest_assertion(space):
-    def my_init(space, w_self, __args__):
-        "Our new AssertionError.__init__()."
-        w_parent_init = space.getattr(w_BuiltinAssertionError,
-                                      space.wrap('__init__'))
-        space.call_args(w_parent_init, __args__.prepend(w_self))
-        framestack = space.getexecutioncontext().framestack
-        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 == 'normalize_exception': 
-            frame = framestack.top(1)
-        
-        # if the assertion provided a message, don't do magic
-        args_w, kwargs_w = __args__.unpack()
-        if args_w: 
-            w_msg = args_w[0]
-        else:
-            runner = AppFrame(frame)
-            try:
-                source = runner.statement
-                source = str(source).strip()
-            except py.error.ENOENT: 
-                source = None
-            if source and not py.test.config.option.nomagic:
-                msg = exprinfo.interpret(source, runner, should_fail=True)
-                space.setattr(w_self, space.wrap('args'),
-                            space.newtuple([space.wrap(msg)]))
-                w_msg = space.wrap(msg)
-            else:
-                w_msg = space.w_None
-        space.setattr(w_self, space.wrap('msg'), w_msg)
-
-    # build a new AssertionError class to replace the original one.
-    w_BuiltinAssertionError = space.getitem(space.builtin.w_dict, 
-                                            space.wrap('AssertionError'))
-    w_metaclass = space.type(w_BuiltinAssertionError)
-    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,
-                               space.wrap('AssertionError'),
-                               space.newtuple([w_BuiltinAssertionError]),
-                               w_dict)
-
-def pypyraises(space, w_ExpectedException, w_expr, __args__):
-    """A built-in function providing the equivalent of py.test.raises()."""
-    args_w, kwds_w = __args__.unpack()
-    if space.is_true(space.isinstance(w_expr, space.w_str)):
-        if args_w:
-            raise OperationError(space.w_TypeError,
-                                 space.wrap("raises() takes no argument "
-                                            "after a string expression"))
-        expr = space.unwrap(w_expr)
-        source = py.code.Source(expr)
-        frame = space.getexecutioncontext().framestack.top()
-        w_locals = frame.getdictscope()
-        w_locals = space.call_method(w_locals, 'copy')
-        for key, w_value in kwds_w.items():
-            space.setitem(w_locals, space.wrap(key), w_value)
-        try:
-            space.call_method(space.w_builtin, 'eval',
-                              space.wrap(str(source)),
-                              frame.w_globals,
-                              w_locals)
-        except OperationError, e:
-            if e.match(space, w_ExpectedException):
-                return space.sys.call('exc_info')
-            raise
-    else:
-        try:
-            space.call_args(w_expr, __args__)
-        except OperationError, e:
-            if e.match(space, w_ExpectedException):
-                return space.sys.call('exc_info')
-            raise
-    raise OperationError(space.w_AssertionError,
-                         space.wrap("DID NOT RAISE"))
-
-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 = gateway.interp2app_temp(pypyskip)
-
-def raises_w(space, w_ExpectedException, *args, **kwds):
-    try:
-        excinfo = py.test.raises(OperationError, *args, **kwds)
-        type, value, tb = excinfo._excinfo
-        if not value.match(space, w_ExpectedException):
-            raise type, value, tb
-        return excinfo
-    except py.test.Item.ExceptionFailure, e:
-        e.tbindex = getattr(e, 'tbindex', -1) - 1
-        raise
-
-def eq_w(space, w_obj1, w_obj2): 
-    """ return interp-level boolean of eq(w_obj1, w_obj2). """ 
-    return space.is_true(space.eq(w_obj1, w_obj2))

Deleted: /pypy/dist/pypy/translator/annrpython.py
==============================================================================
--- /pypy/dist/pypy/translator/annrpython.py	Thu Apr  7 02:01:08 2005
+++ (empty file)
@@ -1,489 +0,0 @@
-from __future__ import generators
-
-from types import FunctionType, ClassType
-from pypy.tool.ansi_print import ansi_print
-from pypy.annotation import model as annmodel
-from pypy.annotation.model import pair
-from pypy.annotation.factory import ListFactory, DictFactory, BlockedInference
-from pypy.annotation.bookkeeper import Bookkeeper
-from pypy.objspace.flow.model import Variable, Constant, undefined_value
-from pypy.objspace.flow.model import SpaceOperation, FunctionGraph
-from pypy.objspace.flow.model import last_exception, last_exc_value
-
-class AnnotatorError(Exception):
-    pass
-
-
-class RPythonAnnotator:
-    """Block annotator for RPython.
-    See description in doc/translation/annotation.txt."""
-
-    def __init__(self, translator=None, overrides={}):
-        self.translator = translator
-        self.pendingblocks = {}  # map {block: function}
-        self.bindings = {}       # map Variables to SomeValues
-        self.annotated = {}      # set of blocks already seen
-        self.links_followed = {} # set of links that have ever been followed
-        self.notify = {}        # {block: {positions-to-reflow-from-when-done}}
-        # --- the following information is recorded for debugging only ---
-        # --- and only if annotation.model.DEBUG is kept to True
-        self.why_not_annotated = {} # {block: (exc_type, exc_value, traceback)}
-                                    # records the location of BlockedInference
-                                    # exceptions that blocked some blocks.
-        self.blocked_functions = {} # set of functions that have blocked blocks
-        self.bindingshistory = {}# map Variables to lists of SomeValues
-        self.binding_caused_by = {}     # map Variables to position_keys
-               # records the caller position that caused bindings of inputargs
-               # to be updated
-        self.binding_cause_history = {} # map Variables to lists of positions
-                # history of binding_caused_by, kept in sync with
-                # bindingshistory
-        self.return_bindings = {} # map return Variables to functions
-        # user-supplied annotation logic for functions we don't want to flow into
-        self.overrides = overrides
-        # --- end of debugging information ---
-        self.bookkeeper = Bookkeeper(self)
-
-
-    def _register_returnvar(self, flowgraph, func):
-        if annmodel.DEBUG:
-            self.return_bindings[flowgraph.getreturnvar()] = func
-
-    #___ convenience high-level interface __________________
-
-    def getflowgraph(self, func, called_by=None, call_tag=None):        
-        flowgraph = self.translator.getflowgraph(func, called_by=called_by, call_tag=call_tag)
-        self._register_returnvar(flowgraph, func)
-        return flowgraph
-        
-
-    def build_types(self, func_or_flowgraph, input_arg_types, func=None):
-        """Recursively build annotations about the specific entry point."""
-        if isinstance(func_or_flowgraph, FunctionGraph):
-            flowgraph = func_or_flowgraph
-            self._register_returnvar(flowgraph, func)
-        else:
-            func = func_or_flowgraph
-            if self.translator is None:
-                from pypy.translator.translator import Translator
-                self.translator = Translator(func, simplifying=True)
-                self.translator.annotator = self
-            flowgraph = self.getflowgraph(func)
-        # make input arguments and set their type
-        input_arg_types = list(input_arg_types)
-        nbarg = len(flowgraph.getargs())
-        while len(input_arg_types) < nbarg:
-            input_arg_types.append(object)
-        inputcells = []
-        for t in input_arg_types:
-            if not isinstance(t, annmodel.SomeObject):
-                t = self.bookkeeper.valueoftype(t)
-            inputcells.append(t)
-        
-        # register the entry point
-        self.addpendingblock(func, flowgraph.startblock, inputcells)
-        # recursively proceed until no more pending block is left
-        self.complete()
-        return self.binding(flowgraph.getreturnvar(), extquery=True)
-
-    def gettype(self, variable):
-        """Return the known type of a control flow graph variable,
-        defaulting to 'object'."""
-        if isinstance(variable, Constant):
-            return type(variable.value)
-        elif isinstance(variable, Variable):
-            cell = self.bindings.get(variable)
-            if cell:
-                return cell.knowntype
-            else:
-                return object
-        else:
-            raise TypeError, ("Variable or Constant instance expected, "
-                              "got %r" % (variable,))
-
-    def getuserclasses(self):
-        """Return a set of known user classes."""
-        return self.bookkeeper.userclasses
-
-    def getuserclassdefinitions(self):
-        """Return a list of ClassDefs."""
-        return self.bookkeeper.userclasseslist
-
-    def getuserattributes(self, cls):
-        """Enumerate the attributes of the given user class, as Variable()s."""
-        clsdef = self.bookkeeper.userclasses[cls]
-        for attr, s_value in clsdef.attrs.items():
-            v = Variable(name=attr)
-            self.bindings[v] = s_value
-            yield v
-
-    #___ medium-level interface ____________________________
-
-    def addpendingblock(self, fn, block, cells, called_from=None):
-        """Register an entry point into block with the given input cells."""
-        assert self.translator is None or fn in self.translator.flowgraphs
-        for a in cells:
-            assert isinstance(a, annmodel.SomeObject)
-        if block not in self.annotated:
-            self.bindinputargs(block, cells, called_from)
-        else:
-            self.mergeinputargs(block, cells, called_from)
-        if not self.annotated[block]:
-            self.pendingblocks[block] = fn
-
-    def complete(self):
-        """Process pending blocks until none is left."""
-        while self.pendingblocks:
-            block, fn = self.pendingblocks.popitem()
-            self.processblock(fn, block)
-        if False in self.annotated.values():
-            if annmodel.DEBUG:
-                for block in self.annotated:
-                    if self.annotated[block] is False:
-                        fn = self.why_not_annotated[block][1].break_at[0]
-                        self.blocked_functions[fn] = True
-                        import traceback
-                        print '-+' * 30
-                        print 'BLOCKED block at:',
-                        print self.whereami(self.why_not_annotated[block][1].break_at)
-                        print 'because of:'
-                        traceback.print_exception(*self.why_not_annotated[block])
-                        print '-+' * 30
-                        print
-            print "++-" * 20
-            print ('%d blocks are still blocked' %
-                                 self.annotated.values().count(False))
-            print "continuing anyway ...."
-            print "++-" * 20
-            
-
-    def binding(self, arg, extquery=False):
-        "Gives the SomeValue corresponding to the given Variable or Constant."
-        if isinstance(arg, Variable):
-            try:
-                return self.bindings[arg]
-            except KeyError:
-                if extquery:
-                    return None
-                else:
-                    raise
-        elif isinstance(arg, Constant):
-            if arg.value is undefined_value:   # undefined local variables
-                return annmodel.SomeImpossibleValue()
-            assert not arg.value is last_exception and not arg.value is last_exc_value
-            return self.bookkeeper.immutablevalue(arg.value)
-        else:
-            raise TypeError, 'Variable or Constant expected, got %r' % (arg,)
-
-    def setbinding(self, arg, s_value, called_from=None):
-        if arg in self.bindings:
-            assert s_value.contains(self.bindings[arg])
-            # for debugging purposes, record the history of bindings that
-            # have been given to this variable
-            if annmodel.DEBUG:
-                history = self.bindingshistory.setdefault(arg, [])
-                history.append(self.bindings[arg])
-                cause_history = self.binding_cause_history.setdefault(arg, [])
-                cause_history.append(self.binding_caused_by[arg])
-        self.bindings[arg] = s_value
-        if annmodel.DEBUG:
-            if arg in self.return_bindings:
-                ansi_print("%s -> %s" % (self.whereami((self.return_bindings[arg],
-                                                         None, None)),
-                                         s_value),
-                           esc="1") # bold
-
-            if arg in self.return_bindings and s_value == annmodel.SomeObject():
-                ansi_print("*** WARNING: %s result degenerated to SomeObject" %
-                           self.whereami((self.return_bindings[arg],None, None)),
-                           esc="31") # RED
-                
-            self.binding_caused_by[arg] = called_from
-
-
-    #___ interface for annotator.factory _______
-
-    def recursivecall(self, func, position_key, inputcells):
-        override = self.overrides.get(func, None)
-        if override is not None:
-            return override(*inputcells)
-        parent_fn, parent_block, parent_index = position_key
-        graph = self.getflowgraph(func, parent_fn, position_key)
-        # self.notify[graph.returnblock] is a dictionary of call
-        # points to this func which triggers a reflow whenever the
-        # return block of this graph has been analysed.
-        callpositions = self.notify.setdefault(graph.returnblock, {})
-        callpositions[position_key] = True
-
-        # generalize the function's input arguments
-        self.addpendingblock(func, graph.startblock, inputcells, position_key)
-
-        # get the (current) return value
-        v = graph.getreturnvar()
-        try:
-            return self.bindings[v]
-        except KeyError: 
-            # let's see if the graph only has exception returns 
-            if graph.hasonlyexceptionreturns(): 
-                # XXX for functions with exceptions what to 
-                #     do anyway? 
-                #return self.bookkeeper.immutablevalue(None)
-                return annmodel.SomeImpossibleValue(benign=True)
-            return annmodel.SomeImpossibleValue()
-
-    def reflowfromposition(self, position_key):
-        fn, block, index = position_key
-        self.reflowpendingblock(fn, block)
-
-
-    #___ simplification (should be moved elsewhere?) _______
-
-    # it should be!
-    # now simplify_calls is moved to transform.py.
-    # i kept reverse_binding here for future(?) purposes though. --sanxiyn
-
-    def reverse_binding(self, known_variables, cell):
-        """This is a hack."""
-        # In simplify_calls, when we are trying to create the new
-        # SpaceOperation, all we have are SomeValues.  But SpaceOperations take
-        # Variables, not SomeValues.  Trouble is, we don't always have a
-        # Variable that just happens to be bound to the given SomeValue.
-        # A typical example would be if the tuple of arguments was created
-        # from another basic block or even another function.  Well I guess
-        # there is no clean solution, short of making the transformations
-        # more syntactic (e.g. replacing a specific sequence of SpaceOperations
-        # with another one).  This is a real hack because we have to use
-        # the identity of 'cell'.
-        if cell.is_constant():
-            return Constant(cell.const)
-        else:
-            for v in known_variables:
-                if self.bindings[v] is cell:
-                    return v
-            else:
-                raise CannotSimplify
-
-    def simplify(self):
-        # Generic simplifications
-        from pypy.translator import transform
-        transform.transform_graph(self)
-        from pypy.translator import simplify 
-        for graph in self.translator.flowgraphs.values(): 
-            simplify.eliminate_empty_blocks(graph) 
-
-
-    #___ flowing annotations in blocks _____________________
-
-    def processblock(self, fn, block):
-        # Important: this is not called recursively.
-        # self.flowin() can only issue calls to self.addpendingblock().
-        # The analysis of a block can be in three states:
-        #  * block not in self.annotated:
-        #      never seen the block.
-        #  * self.annotated[block] == False:
-        #      the input variables of the block are in self.bindings but we
-        #      still have to consider all the operations in the block.
-        #  * self.annotated[block] == True or <original function object>:
-        #      analysis done (at least until we find we must generalize the
-        #      input variables).
-
-        #print '* processblock', block, cells
-        self.annotated[block] = fn or True
-        try:
-            self.flowin(fn, block)
-        except BlockedInference, e:
-            #print '_'*60
-            #print 'Blocked at %r:' % (e.break_at,)
-            #import traceback, sys
-            #traceback.print_tb(sys.exc_info()[2])
-            self.annotated[block] = False   # failed, hopefully temporarily
-            if annmodel.DEBUG:
-                import sys
-                self.why_not_annotated[block] = sys.exc_info()
-        except Exception, e:
-            # hack for debug tools only
-            if not hasattr(e, '__annotator_block'):
-                setattr(e, '__annotator_block', block)
-            raise
-
-    def reflowpendingblock(self, fn, block):
-        self.pendingblocks[block] = fn
-        assert block in self.annotated
-        self.annotated[block] = False  # must re-flow
-
-    def bindinputargs(self, block, inputcells, called_from=None):
-        # Create the initial bindings for the input args of a block.
-        assert len(block.inputargs) == len(inputcells)
-        for a, cell in zip(block.inputargs, inputcells):
-            self.setbinding(a, cell, called_from)
-        self.annotated[block] = False  # must flowin.
-
-    def mergeinputargs(self, block, inputcells, called_from=None):
-        # Merge the new 'cells' with each of the block's existing input
-        # variables.
-        oldcells = [self.binding(a) for a in block.inputargs]
-        unions = [annmodel.unionof(c1,c2) for c1, c2 in zip(oldcells,inputcells)]
-        # if the merged cells changed, we must redo the analysis
-        if unions != oldcells:
-            self.bindinputargs(block, unions, called_from)
-
-    def whereami(self, position_key):
-        fn, block, i = position_key
-        mod = getattr(fn, '__module__', None)
-        if mod is None:
-            mod = '?'
-        name = getattr(fn, '__name__', None)
-        if name is not None:
-            firstlineno = fn.func_code.co_firstlineno
-        else:
-            name = 'UNKNOWN'
-            firstlineno = -1
-        blk = ""
-        if block:
-            at = block.at()
-            if at:
-                blk = " block"+at
-        opid=""
-        if i is not None:
-            opid = " op=%d" % i
-        return "(%s:%d) %s%s%s" % (mod, firstlineno, name, blk, opid)
-
-    def flowin(self, fn, block):
-        #print 'Flowing', block, [self.binding(a) for a in block.inputargs]
-        for i in range(len(block.operations)):
-            try:
-                self.bookkeeper.enter((fn, block, i))
-                self.consider_op(block.operations[i])
-            finally:
-                self.bookkeeper.leave()
-        # dead code removal: don't follow all exits if the exitswitch is known
-        exits = block.exits
-        if isinstance(block.exitswitch, Variable):
-            s_exitswitch = self.bindings[block.exitswitch]
-            if s_exitswitch.is_constant():
-                exits = [link for link in exits
-                              if link.exitcase == s_exitswitch.const]
-        knownvars, knownvarvalue = getattr(self.bindings.get(block.exitswitch),
-                                          "knowntypedata", (None, None))
-        for link in exits:
-            self.links_followed[link] = True
-            import types
-            in_except_block = False
-            if isinstance(link.exitcase, (types.ClassType, type)) \
-                   and issubclass(link.exitcase, Exception):
-                last_exception_object = annmodel.SomeObject()
-                if link.exitcase is Exception:
-                    last_exc_value_object = annmodel.SomeObject()
-                else:
-                    last_exc_value_object = self.bookkeeper.valueoftype(link.exitcase)
-                last_exc_value_vars = []
-                in_except_block = True
-                last_exception_unknown = True
-                last_exception_unused = True
-                
-            cells = []
-            renaming = dict(zip(link.args,link.target.inputargs))
-            for a,v in zip(link.args,link.target.inputargs):
-                if a == Constant(last_exception):
-                    assert in_except_block
-                    assert last_exception_unknown
-                    cells.append(last_exception_object)
-                    last_exception_unused = False
-                elif a == Constant(last_exc_value):
-                    assert in_except_block
-                    cells.append(last_exc_value_object)
-                    last_exc_value_vars.append(v)
-                elif isinstance(a, Constant) and a.has_flag('last_exception'):
-                    assert in_except_block
-                    assert last_exception_unused
-                    if last_exception_unknown:
-                        # this modeling should be good enough
-                        # the exc type is not seen by user code
-                        last_exception_object.const = a.value 
-                    cell = last_exception_object
-                    cells.append(cell)
-                    last_exception_unknown = False
-                else:
-                    cell = self.binding(a)
-                    if link.exitcase is True and knownvars is not None and a in knownvars \
-                            and not knownvarvalue.contains(cell):
-                        cell = knownvarvalue
-                    if hasattr(cell,'is_type_of'):
-                        renamed_is_type_of = []
-                        for v in cell.is_type_of:
-                            new_v = renaming.get(v,None)
-                            if new_v is not None:
-                                renamed_is_type_of.append(new_v)
-                        cell = annmodel.SomeObject()
-                        cell.is_type_of = renamed_is_type_of
-                    cells.append(cell)
-
-            if in_except_block:
-                last_exception_object.is_type_of = last_exc_value_vars
-
-            self.addpendingblock(fn, link.target, cells)
-        if block in self.notify:
-            # reflow from certain positions when this block is done
-            for position_key in self.notify[block]:
-                self.reflowfromposition(position_key)
-
-
-    #___ creating the annotations based on operations ______
-
-    def consider_op(self,op):
-        argcells = [self.binding(a) for a in op.args]
-        consider_meth = getattr(self,'consider_op_'+op.opname,
-                                self.default_consider_op)
-        resultcell = consider_meth(*argcells)
-        if resultcell is None:
-            resultcell = annmodel.SomeImpossibleValue()  # no return value
-        elif resultcell == annmodel.SomeImpossibleValue():
-            raise BlockedInference(info=op)  # the operation cannot succeed
-        assert isinstance(resultcell, annmodel.SomeObject)
-        assert isinstance(op.result, Variable)
-        self.setbinding(op.result, resultcell)  # bind resultcell to op.result
-
-    def default_consider_op(self, *args):
-        return annmodel.SomeObject()
-
-    def _registeroperations(loc):
-        # All unary operations
-        for opname in annmodel.UNARY_OPERATIONS:
-            exec """
-def consider_op_%s(self, arg, *args):
-    return arg.%s(*args)
-""" % (opname, opname) in globals(), loc
-        # All binary operations
-        for opname in annmodel.BINARY_OPERATIONS:
-            exec """
-def consider_op_%s(self, arg1, arg2, *args):
-    return pair(arg1,arg2).%s(*args)
-""" % (opname, opname) in globals(), loc
-
-    _registeroperations(locals())
-    del _registeroperations
-
-    # XXX "contains" clash with SomeObject method
-    def consider_op_contains(self, seq, elem):
-        return annmodel.SomeBool()
-
-    def consider_op_newtuple(self, *args):
-        return annmodel.SomeTuple(items = args)
-
-    def consider_op_newlist(self, *args):
-        factory = self.bookkeeper.getfactory(ListFactory)
-        for a in args:
-            factory.generalize(a)
-        return factory.create()
-
-    def consider_op_newdict(self, *args):
-        assert not args, "XXX only supports newdict([])"
-        factory = self.bookkeeper.getfactory(DictFactory)
-        return factory.create()
-
-    def consider_op_newslice(self, start, stop, step):
-        return annmodel.SomeSlice(start, stop, step)
-
-
-class CannotSimplify(Exception):
-    pass

Deleted: /pypy/dist/pypy/translator/geninterplevel.py
==============================================================================
--- /pypy/dist/pypy/translator/geninterplevel.py	Thu Apr  7 02:01:08 2005
+++ (empty file)
@@ -1,1545 +0,0 @@
-"""
-Implementation of a translator from application Python to interpreter level RPython.
-
-The idea is that we can automatically transform app-space implementations
-of methods into some equivalent representation at interpreter level.
-Then, the RPython to C translation might hopefully spit out some
-more efficient code than always interpreting these methods.
-
-Note that the appspace functions are treated as rpythonic, in a sense
-that globals are constants, for instance. This definition is not
-exact and might change.
-
-Integration of this module will be done half-automatically
-using a simple caching mechanism. The generated files are
-not meant to be checked into svn, although this currently
-still happens.
-"""
-
-from __future__ import generators
-import autopath, os, sys, exceptions, inspect, types
-import cPickle as pickle, __builtin__
-from pypy.objspace.flow.model import Variable, Constant, SpaceOperation
-from pypy.objspace.flow.model import FunctionGraph, Block, Link
-from pypy.objspace.flow.model import last_exception, last_exc_value
-from pypy.objspace.flow.model import traverse, uniqueitems, checkgraph
-from pypy.interpreter.pycode import CO_VARARGS, CO_VARKEYWORDS
-from pypy.annotation import model as annmodel
-from types import FunctionType, CodeType, ModuleType
-from pypy.interpreter.error import OperationError
-from pypy.interpreter.argument import Arguments
-from pypy.objspace.std.restricted_int import r_int, r_uint
-
-from pypy.translator.translator import Translator
-from pypy.objspace.flow import FlowObjSpace
-
-from pypy.interpreter.gateway import app2interp, interp2app
-
-from pypy.tool.sourcetools import render_docstr
-
-from pypy.translator.gensupp import ordered_blocks, UniqueList, builtin_base, \
-     c_string, uniquemodulename, C_IDENTIFIER, NameManager
-
-import pypy # __path__
-import py.path
-# ____________________________________________________________
-
-def eval_helper(self, typename, expr):
-    name = self.uniquename("gtype_%s" % typename)
-    unique = self.uniquenameofprebuilt("eval_helper", eval_helper)
-    self.initcode.append1(
-        'def %s(expr):\n'
-        '    dic = space.newdict([])\n'
-        '    if "types." in expr:\n'
-        '        space.exec_("import types", dic, dic)\n'
-        '    else:\n'
-        '        space.exec_("", dic, dic)\n'
-        '    return space.eval(expr, dic, dic)' % (unique, ))
-    self.initcode.append1('%s = %s(%r)' % (name, unique, expr))
-    return name
-
-def unpickle_helper(self, name, value):
-    unique = self.uniquenameofprebuilt("unpickle_helper", unpickle_helper)
-    self.initcode.append1(
-        'def %s(value):\n'
-        '    dic = space.newdict([])\n'
-        '    space.exec_("import cPickle as pickle", dic, dic)\n'
-        '    return space.eval("pickle.loads(%%r)" %% value, dic, dic)' % unique)
-    self.initcode.append1('%s = %s(%r)' % (
-        name, unique, pickle.dumps(value, 2)) )
-
-# hey, for longs we can do even easier:
-def long_helper(self, name, value):
-    unique = self.uniquenameofprebuilt("long_helper", long_helper)
-    self.initcode.append1(
-        'def %s(value):\n'
-        '    dic = space.newdict([])\n'
-        '    space.exec_("", dic, dic) # init __builtins__\n'
-        '    return space.eval("long(%%r, 16)" %% value, dic, dic)' % unique)
-    self.initcode.append1('%s = %s(%r)' % (
-        name, unique, hex(value)[2:-1] ) )
-
-class GenRpy:
-    def __init__(self, translator, entrypoint=None, modname=None, moddict=None):
-        self.translator = translator
-        if entrypoint is None:
-            entrypoint = translator.entrypoint
-        self.entrypoint = entrypoint
-        self.modname = self.trans_funcname(modname or
-                        uniquemodulename(entrypoint))
-        self.moddict = moddict # the dict if we translate a module
-        
-        def late_OperationError():
-            self.initcode.append1(
-                'from pypy.interpreter.error import OperationError as gOperationError')
-            return 'gOperationError'
-        def late_Arguments():
-            self.initcode.append1('from pypy.interpreter import gateway')
-            return 'gateway.Arguments'
-
-        self.rpynames = {Constant(None).key:  'space.w_None',
-                         Constant(False).key: 'space.w_False',
-                         Constant(True).key:  'space.w_True',
-                         Constant(OperationError).key: late_OperationError,
-                         Constant(Arguments).key: late_Arguments,
-                       }
-        u = UniqueList
-        self.initcode = u()    # list of lines for the module's initxxx()
-        self.latercode = u()   # list of generators generating extra lines
-                               #   for later in initxxx() -- for recursive
-                               #   objects
-        self.namespace = NameManager()
-        self.namespace.make_reserved_names('__doc__ __args__ space goto')
-        self.globaldecl = []
-        self.globalobjects = []
-        self.pendingfunctions = []
-        self.currentfunc = None
-        self.debugstack = ()  # linked list of nested nameof()
-
-        # special constructors:
-        self.has_listarg = {}
-        for name in "newtuple newlist newdict newstring".split():
-            self.has_listarg[name] = name
-
-        # catching all builtins in advance, to avoid problems
-        # with modified builtins
-
-        # add a dummy _issubtype() to builtins
-        def _issubtype(cls1, cls2):
-            raise TypeError, "this dummy should *not* be reached"
-        __builtin__._issubtype = _issubtype
-        
-        class bltinstub:
-            def __init__(self, name):
-                self.__name__ = name
-            def __repr__(self):
-                return '<%s>' % self.__name__
-            
-        self.builtin_ids = dict( [
-            (id(value), bltinstub(key))
-            for key, value in __builtin__.__dict__.items()
-            if callable(value) and type(value) not in [type(Exception), type] ] )
-        
-        self.space = FlowObjSpace() # for introspection
-
-        self.use_fast_call = True
-        self.specialize_goto = False
-        self._labeltable = {} # unique label names, reused per func
-
-        self._space_arities = None
-        
-    def expr(self, v, localscope, wrapped = True):
-        if isinstance(v, Variable):
-            return localscope.localname(v.name, wrapped)
-        elif isinstance(v, Constant):
-            return self.nameof(v.value,
-                               debug=('Constant in the graph of', self.currentfunc))
-        else:
-            raise TypeError, "expr(%r)" % (v,)
-
-    def arglist(self, args, localscope):
-        res = [self.expr(arg, localscope) for arg in args]
-        return ", ".join(res)
-
-    def oper(self, op, localscope):
-        if op.opname == "simple_call":
-            v = op.args[0]
-            space_shortcut = self.try_space_shortcut_for_builtin(v, len(op.args)-1)
-            if space_shortcut is not None:
-                # space method call
-                exv = space_shortcut
-                fmt = "%(res)s = %(func)s(%(args)s)"
-            else:
-                exv = self.expr(v, localscope)                
-                # default for a spacecall:
-                fmt = "%(res)s = space.call_function(%(func)s, %(args)s)"
-                # see if we can optimize for a fast call.
-                # we just do the very simple ones.
-                if self.use_fast_call and (isinstance(v, Constant)
-                                           and exv.startswith('gfunc_')):
-                    func = v.value
-                    if (not func.func_code.co_flags & CO_VARARGS) and (
-                        func.func_defaults is None):
-                        fmt = "%(res)s = fastf_%(func)s(space, %(args)s)"
-                        exv = exv[6:]
-            return fmt % {"res" : self.expr(op.result, localscope),
-                          "func": exv,
-                          "args": self.arglist(op.args[1:], localscope) }
-        if op.opname == "call_args":
-            v = op.args[0]
-            exv = self.expr(v, localscope)
-            fmt = (
-                "_args = %(Arg)s.fromshape(space, %(shape)s, [%(data_w)s])\n"
-                "%(res)s = space.call_args(%(func)s, _args)")
-            assert isinstance(op.args[1], Constant)
-            shape = op.args[1].value
-            return fmt % {"res": self.expr(op.result, localscope),
-                          "func": exv,
-                          "shape": repr(shape),
-                          "data_w": self.arglist(op.args[2:], localscope),
-                          'Arg': self.nameof(Arguments) }
-        if op.opname in self.has_listarg:
-            fmt = "%s = %s([%s])"
-        else:
-            fmt = "%s = %s(%s)"
-        # special case is_true
-        wrapped = op.opname != "is_true"
-        oper = "space.%s" % op.opname
-        return fmt % (self.expr(op.result, localscope, wrapped), oper,
-                      self.arglist(op.args, localscope))
-
-    def large_assignment(self, left, right, margin=65):
-        expr = "(%s) = (%s)" % (", ".join(left), ", ".join(right))
-        pieces = expr.split(",")
-        res = [pieces.pop(0)]
-        for piece in pieces:
-            if len(res[-1])+len(piece)+1 > margin:
-                res[-1] += ","
-                res.append(piece)
-            else:
-                res[-1] += (","+piece)
-        return res
-
-    def large_initialize(self, vars, margin=65):
-        res = []
-        nonestr = "None"
-        margin -= len(nonestr)
-        for var in vars:
-            ass = var+"="
-            if not res or len(res[-1]) >= margin:
-                res.append(ass)
-            else:
-                res[-1] += ass
-        res = [line + nonestr for line in res]
-        return res
-
-    def mklabel(self, blocknum):
-        if self.specialize_goto:
-            lbname = self._labeltable.get(blocknum)
-            if not lbname:
-                self.initcode.append1(
-                    'from pypy.objspace.flow.framestate import SpecTag')
-                lbname = self.uniquename("glabel_%d" % blocknum)
-                self._labeltable[blocknum] = lbname
-                self.initcode.append1('%s = SpecTag()' % lbname)
-            return lbname
-        else:
-            return repr(blocknum)
-
-    def gen_link(self, link, localscope, blocknum, block, linklocalvars=None):
-        "Generate the code to jump across the given Link."
-        linklocalvars = linklocalvars or {}
-        left, right = [], []
-        for a1, a2 in zip(link.args, link.target.inputargs):
-            if a1 in linklocalvars:
-                src = linklocalvars[a1]
-            else:
-                src = self.expr(a1, localscope)
-            left.append(self.expr(a2, localscope))
-            right.append(src)
-        if left: # anything at all?
-            txt = "%s = %s" % (", ".join(left), ", ".join(right))
-            if len(txt) <= 65: # arbitrary
-                yield txt
-            else:
-                for line in self.large_assignment(left, right):
-                    yield line
-        goto = blocknum[link.target]
-        yield 'goto = %s' % self.mklabel(goto)
-        if goto <= blocknum[block]:
-            yield 'continue'
-
-    def register_early(self, obj, name):
-        # this was needed for recursive lists.
-        # note that self.latercode led to too late initialization.
-        key = Constant(obj).key
-        self.rpynames[key] = name
-
-    def nameof(self, obj, debug=None, namehint=None):
-        key = Constant(obj).key
-        try:
-            txt = self.rpynames[key]
-            if type(txt) is not str:
-                # this is a predefined constant, initialized on first use
-                func = txt
-                txt = func()
-                self.rpynames[key] = txt
-            return txt
-            
-        except KeyError:
-            if debug:
-                stackentry = debug, obj
-            else:
-                stackentry = obj
-            self.debugstack = (self.debugstack, stackentry)
-            obj_builtin_base = builtin_base(obj)
-            if obj_builtin_base in (object, int, long) and type(obj) is not obj_builtin_base:
-                # assume it's a user defined thingy
-                name = self.nameof_instance(obj)
-            else:
-                # shortcutting references to __builtin__
-                if id(obj) in self.builtin_ids:
-                    func = self.builtin_ids[id(obj)]
-                    name = "(space.builtin.get(space.str_w(%s)))" % self.nameof(func.__name__)
-                else:
-                    for cls in type(obj).__mro__:
-                        meth = getattr(self,
-                                       'nameof_' + cls.__name__.replace(' ', ''),
-                                       None)
-                        if meth:
-                            break
-                    else:
-                        raise Exception, "nameof(%r)" % (obj,)
-
-                    code = meth.im_func.func_code
-                    if namehint and 'namehint' in code.co_varnames[:code.co_argcount]:
-                        name = meth(obj, namehint=namehint)
-                    else:
-                        name = meth(obj)
-            self.debugstack, x = self.debugstack
-            assert x is stackentry
-            self.rpynames[key] = name
-            return name
-
-    def uniquename(self, basename):
-        name = self.namespace.uniquename(basename)
-        self.globalobjects.append(name)
-        self.globaldecl.append('# global object %s' % (name,))
-        return name
-
-    def uniquenameofprebuilt(self, basename, obj):
-        # identifying an object and giving it a name,
-        # without the attempt to render it.
-        key = Constant(obj).key
-        try:
-            txt = self.rpynames[key]
-        except KeyError:
-            self.rpynames[key] = txt = self.uniquename(basename)
-        return txt
-            
-
-    def nameof_NotImplementedType(self, value):
-        return "space.w_NotImplemented"
-
-    def nameof_object(self, value):
-        if type(value) is not object:
-            # try to just wrap it?
-            name = self.uniquename('g_%sinst_%r' % (type(value).__name__, value))
-            self.initcode.append1('%s = space.wrap(%r)' % (name, value))
-            return name
-        name = self.uniquename('g_object')
-        self.initcode.append('_tup = space.newtuple([])\n'
-                                '%s = space.call(space.w_object, _tup)'
-                                % name)
-        return name
-
-    def nameof_module(self, value):
-        #assert value is os or not hasattr(value, "__file__") or \
-        #       not (value.__file__.endswith('.pyc') or
-        #            value.__file__.endswith('.py') or
-        #            value.__file__.endswith('.pyo')), \
-        #       "%r is not a builtin module (probably :)"%value
-        # assume that we get a faked module
-        name = self.uniquename('mod_%s' % value.__name__)
-        self.initcode.append1('import %s as _tmp' % value.__name__)
-        self.initcode.append1('%s = space.wrap(_tmp)' % (name))
-        return name
-        
-
-    def nameof_int(self, value):
-        if value >= 0:
-            name = 'gi_%d' % value
-        else:
-            # make sure that the type ident is completely described by
-            # the prefixbefore the initial '_' for easy postprocessing
-            name = 'gi_minus_%d' % abs(value)
-        name = self.uniquename(name)
-        self.initcode.append1('%s = space.newint(%d)' % (name, value))
-        return name
-
-    def nameof_long(self, value):
-        # assume we want them in hex most of the time
-        if value < 256L:
-            s = "%dL" % value
-        else:
-            s = "0x%08xL" % value
-        if value >= 0:
-            name = 'glong_%s' % s
-        else:
-            # mae sure that the type ident is completely described by
-            # the prefix  before the initial '_'
-            name = 'glong_minus_%d' % abs(value)
-        name = self.uniquename(name)
-        # allow literally short longs only, meaning they
-        # must fit into a machine word.
-        if (sys.maxint*2+1)&value == value:
-            self.initcode.append1('%s = space.wrap(%s) # XXX implement long!' % (name, s))
-        else:
-            long_helper(self, name, value)
-        return name
-
-    def nameof_float(self, value):
-        name = 'gfloat_%s' % value
-        name = (name.replace('-', 'minus')
-                    .replace('.', 'dot'))
-        name = self.uniquename(name)
-        self.initcode.append1('%s = space.newfloat(%r)' % (name, value))
-        return name
-    
-    def nameof_str(self, value):
-        if [c for c in value if c<' ' or c>'~' or c=='"' or c=='\\']:
-            # non-printable string
-            namestr = repr(value)[1:-1]
-        else:
-            # printable string
-            namestr = value
-        if not namestr:
-            namestr = "_emptystr_"
-        name = self.uniquename('gs_' + namestr[:32])
-        # self.initcode.append1('%s = space.newstring(%r)' % (name, value))
-        # ick! very unhandy
-        self.initcode.append1('%s = space.wrap(%r)' % (name, value))
-        return name
-
-    def skipped_function(self, func):
-        # debugging only!  Generates a placeholder for missing functions
-        # that raises an exception when called.
-        name = self.uniquename('gskippedfunc_' + func.__name__)
-        self.globaldecl.append('# global decl %s' % (name, ))
-        self.initcode.append1('# build func %s' % name)
-        return name
-
-    def skipped_class(self, cls):
-        # debugging only!  Generates a placeholder for missing classes
-        # that raises an exception when called.
-        name = self.uniquename('gskippedclass_' + cls.__name__)
-        self.globaldecl.append('# global decl %s' % (name, ))
-        self.initcode.append1('# build class %s' % name)
-        return name
-
-    def trans_funcname(self, s):
-        return s.translate(C_IDENTIFIER)
-
-    def nameof_function(self, func, namehint=''):
-        if hasattr(func, 'geninterplevel_name'):
-            return func.geninterplevel_name(self)
-
-        printable_name = '(%s:%d) %s' % (
-            self.trans_funcname(func.func_globals.get('__name__', '?')),
-            func.func_code.co_firstlineno,
-            func.__name__)
-        if self.translator.frozen:
-            if func not in self.translator.flowgraphs:
-                print "NOT GENERATING", printable_name
-                return self.skipped_function(func)
-        else:
-            if (func.func_doc and
-                func.func_doc.lstrip().startswith('NOT_RPYTHON')):
-                print "skipped", printable_name
-                return self.skipped_function(func)
-        name = self.uniquename('gfunc_' + self.trans_funcname(
-            namehint + func.__name__))
-        f_name = 'f_' + name[6:]
-        self.initcode.append1('from pypy.interpreter import gateway')
-        self.initcode.append1('%s = space.wrap(gateway.interp2app(%s, unwrap_spec=[gateway.ObjSpace, gateway.Arguments]))' % (name, f_name))
-        self.pendingfunctions.append(func)
-        return name
-
-    def nameof_staticmethod(self, sm):
-        # XXX XXX XXXX
-        func = sm.__get__(42.5)
-        name = self.uniquename('gsm_' + func.__name__)
-        functionname = self.nameof(func)
-        self.initcode.append1('%s = space.wrap(%s)' % (name, functionname))
-        return name
-
-    def nameof_instancemethod(self, meth):
-        if meth.im_self is None:
-            # no error checking here
-            return self.nameof(meth.im_func, namehint="%s_" % meth.im_class.__name__)
-        else:
-            ob = self.nameof(meth.im_self)
-            func = self.nameof(meth.im_func)
-            typ = self.nameof(meth.im_class)
-            name = self.uniquename('gmeth_' + meth.im_func.__name__)
-            funcname = self.nameof(meth.im_func.__name__)
-            self.initcode.append1(
-                '%s = space.getattr(%s, %s)' % (name, ob, funcname))
-            return name
-
-    def should_translate_attr(self, pbc, attr):
-        ann = self.translator.annotator
-        if ann is None:
-            ignore = getattr(pbc.__class__, 'NOT_RPYTHON_ATTRIBUTES', [])
-            if attr in ignore:
-                return False
-            else:
-                return "probably"   # True
-        classdef = ann.getuserclasses().get(pbc.__class__)
-        if classdef and classdef.about_attribute(attr) is not None:
-            return True
-        return False
-
-    def later(self, gen):
-        self.latercode.append1((gen, self.debugstack))
-
-    def nameof_instance(self, instance):
-        klass = instance.__class__
-        name = self.uniquename('ginst_' + klass.__name__)
-        cls = self.nameof(klass)
-        if hasattr(klass, '__base__'):
-            base_class = builtin_base(instance)
-            base = self.nameof(base_class)
-        else:
-            base_class = None
-            base = cls
-        def initinstance():
-            content = instance.__dict__.items()
-            content.sort()
-            for key, value in content:
-                if self.should_translate_attr(instance, key):
-                    try:
-                            yield 'space.setattr(%s, %s, %s)' % (
-                                name, self.nameof(key), self.nameof(value))
-                    except:
-                        print >> sys.stderr, "Problem while generating %s of %r" % (
-                                name, instance)
-                        raise
-        self.initcode.append1("%s = space.call_method(%s, '__new__', %s)" % (
-                             name, cls, cls))
-        self.later(initinstance())
-        return name
-
-    def space_arities(self):
-        if self._space_arities is None:
-            arities = self._space_arities = {}
-            for name, sym, arity, specnames in self.space.MethodTable:
-                arities[name] = arity
-            arities['isinstance'] = 2
-        return self._space_arities
-        
-    def try_space_shortcut_for_builtin(self, v, nargs):
-        if isinstance(v, Constant) and id(v.value) in self.builtin_ids:
-            name = self.builtin_ids[id(v.value)].__name__
-            if hasattr(self.space, name):
-                if self.space_arities().get(name, -1) == nargs:
-                    return "space.%s" % name
-        return None
-        
-    def nameof_builtin_function_or_method(self, func):
-        if func.__self__ is None:
-            # builtin function
-            if id(func) in self.builtin_ids:
-                func = self.builtin_ids[id(func)]
-                return "(space.builtin.get(space.str_w(%s)))" % self.nameof(func.__name__)
-            # where does it come from? Python2.2 doesn't have func.__module__
-            for modname, module in sys.modules.items():
-                if hasattr(module, '__file__'):
-                    if (module.__file__.endswith('.py') or
-                        module.__file__.endswith('.pyc') or
-                        module.__file__.endswith('.pyo')):
-                        continue    # skip non-builtin modules
-                if func is getattr(module, func.__name__, None):
-                    break
-            else:
-                raise Exception, '%r not found in any built-in module' % (func,)
-            if modname == '__builtin__':
-                # be lazy
-                return "(space.builtin.get(space.str_w(%s)))" % self.nameof(func.__name__)
-            elif modname == 'sys':
-                # be lazy
-                return "(space.sys.get(space.str_w(%s)))" % self.nameof(func.__name__)                
-            else:
-                name = self.uniquename('gbltin_' + func.__name__)
-                self.initcode.append1('%s = space.getattr(%s, %s)' % (
-                    name, self.nameof(module), self.nameof(func.__name__)))
-        else:
-            # builtin (bound) method
-            name = self.uniquename('gbltinmethod_' + func.__name__)
-            self.initcode.append1('%s = space.getattr(%s, %s)' % (
-                name, self.nameof(func.__self__), self.nameof(func.__name__)))
-        return name
-
-    def nameof_classobj(self, cls):
-        printable_name = cls.__name__
-        if cls.__doc__ and cls.__doc__.lstrip().startswith('NOT_RPYTHON'):
-            #raise Exception, "%r should never be reached" % (cls,)
-            print "skipped class", printable_name
-            return self.skipped_class(cls)
-
-        metaclass = "space.w_type"
-        name = self.uniquename('gcls_' + cls.__name__)
-
-        if issubclass(cls, Exception):
-            # if cls.__module__ == 'exceptions':
-            # don't rely on this, py.magic redefines AssertionError
-            if getattr(__builtin__,cls.__name__,None) is cls:
-                # exception are defined on the space
-                return 'space.w_%s' % cls.__name__
-
-        if not isinstance(cls, type):
-            assert type(cls) is type(Exception)
-            # do *not* change metaclass, but leave the
-            # decision to what PyPy thinks is correct.
-            # metaclass = 'space.w_classobj'
-
-        basenames = [self.nameof(base) for base in cls.__bases__]
-
-        def initclassobj():
-            content = cls.__dict__.items()
-            content.sort()
-            for key, value in content:
-                if key.startswith('__'):
-                    if key in ['__module__', '__doc__', '__dict__',
-                               '__weakref__', '__metaclass__', '__slots__','__new__']:
-                        continue
-
-                # redirect value through class interface, in order to
-                # get methods instead of functions.
-                value = getattr(cls, key)
-
-                if isinstance(value, staticmethod) and value.__get__(1) not in self.translator.flowgraphs and self.translator.frozen:
-                    print "skipped staticmethod:", value
-                    continue
-                if isinstance(value, FunctionType) and value not in self.translator.flowgraphs and self.translator.frozen:
-                    print "skipped function:", value
-                    continue
-                    
-                yield 'space.setattr(%s, %s, %s)' % (
-                    name, self.nameof(key), self.nameof(value))
-
-        baseargs = ", ".join(basenames)
-        self.initcode.append('_dic = space.newdict([])')
-        for key, value in cls.__dict__.items():
-            if key.startswith('__'):
-                if key in ['__module__', '__metaclass__', '__slots__','__new__']:
-                    keyname = self.nameof(key)
-                    valname = self.nameof(value)
-                    self.initcode.append("space.setitem(_dic, %s, %s)" % (
-                        keyname, valname))
-
-        if cls.__doc__ is not None:
-            sdoc = self.nameof("__doc__")
-            docstr = render_docstr(cls, "_doc = space.wrap(", ")")
-            self.initcode.append1((docstr,)) # not splitted
-            self.initcode.append("space.setitem(_dic, %s, _doc)" % (
-                self.nameof("__doc__"),))
-        self.initcode.append1('_bases = space.newtuple([%(bases)s])\n'
-                             '_args = space.newtuple([%(name)s, _bases, _dic])\n'
-                             '%(klass)s = space.call(%(meta)s, _args)'
-                             % {"bases": baseargs,
-                                "klass": name,
-                                "name" : self.nameof(cls.__name__),
-                                "meta" : metaclass} )
-        
-        self.later(initclassobj())
-        return name
-
-    nameof_class = nameof_classobj   # for Python 2.2
-
-    typename_mapping = {
-        object: 'space.w_object',
-        int:    'space.w_int',
-        long:   'space.w_long',
-        bool:   'space.w_bool',
-        list:   'space.w_list',
-        tuple:  'space.w_tuple',
-        dict:   'space.w_dict',
-        str:    'space.w_str',
-        float:  'space.w_float',
-        slice:  'space.w_slice',
-        type(Exception()): 'space.wrap(types.InstanceType)',
-        type:   'space.w_type',
-        complex:'space.wrap(types.ComplexType)',
-        unicode:'space.w_unicode',
-        file:   (eval_helper, 'file', 'file'),
-        type(None): (eval_helper, 'NoneType', 'type(None)'),
-        CodeType: (eval_helper, 'code', 'type((lambda:42).func_code)'),
-        ModuleType: (eval_helper, 'ModuleType', 'types.ModuleType'),
-        xrange: (eval_helper, 'xrange', 'xrange'),
-
-        ##r_int:  'space.w_int',
-        ##r_uint: 'space.w_int',
-
-        type(len): (eval_helper, 'FunctionType', 'type(lambda:42)'),
-        # type 'method_descriptor':
-        # XXX small problem here:
-        # XXX with space.eval, we get <W_TypeObject(method)>
-        # XXX but with wrap, we get <W_TypeObject(instancemethod)>
-        type(list.append): (eval_helper, "method_descriptor", "type(list.append)"),
-        # type 'wrapper_descriptor':
-        type(type(None).__repr__): (eval_helper, "wrapper_descriptor",
-                                    "type(type(None).__repr__)"),
-        # type 'getset_descriptor':
-        # XXX here we get <W_TypeObject(FakeDescriptor)>,
-        # while eval gives us <W_TypeObject(GetSetProperty)>
-        type(type.__dict__['__dict__']): (eval_helper, "getset_descriptor",
-            "type(type.__dict__[\'__dict__\'])"),
-        # type 'member_descriptor':
-        # XXX this does not work in eval!
-        # type(type.__dict__['__basicsize__']): "cannot eval type(type.__dict__['__basicsize__'])",
-        # XXX there seems to be no working support for member descriptors ???
-        type(types.GeneratorType.gi_frame):
-            (eval_helper, "member_descriptor", 'type(property.fdel)'),
-        types.ClassType: 'space.w_classobj',
-        types.MethodType: (eval_helper, "instancemethod",
-            "type((lambda:42).__get__(42))"),
-        property: (eval_helper, "property", 'property'),
-    }
-
-    def nameof_type(self, cls):
-        if cls in self.typename_mapping:
-            ret = self.typename_mapping[cls]
-            if type(ret) is tuple:
-                ret = ret[0](self, ret[1], ret[2])
-            return ret
-        assert cls.__module__ != '__builtin__', (
-            "built-in class %r not found in typename_mapping "
-            "while compiling %s" % (cls, self.currentfunc and
-                                    self.currentfunc.__name__ or "*no function at all*"))
-        return self.nameof_classobj(cls)
-
-    def nameof_tuple(self, tup):
-        name = self.uniquename('g%dtuple' % len(tup))
-        args = [self.nameof(x) for x in tup]
-        args = ', '.join(args)
-        self.initcode.append1('%s = space.newtuple([%s])' % (name, args))
-        return name
-
-    def nameof_list(self, lis):
-        name = self.uniquename('g%dlist' % len(lis))
-        # note that self.latercode led to too late initialization.
-        self.register_early(lis, name)
-        self.initcode.append('%s = space.newlist([space.w_None])' % (name,))
-        self.initcode.append('%s = space.mul(%s, %s)' % (name, name, self.nameof(len(lis))))
-        for i in range(len(lis)):
-            item = self.nameof(lis[i])
-            self.initcode.append('space.setitem(%s, %s, %s);' % (
-                name, self.nameof(i), item))
-        return name
-
-    def nameof_dict(self, dic):
-        assert dic is not __builtins__
-        assert '__builtins__' not in dic, 'Seems to be the globals of %s' % (
-            dic.get('__name__', '?'),)
-        name = self.uniquename('g%ddict' % len(dic))
-        self.register_early(dic, name)
-        self.initcode.append('%s = space.newdict([])' % (name,))
-        for k in dic:
-            self.initcode.append('space.setitem(%s, %s, %s)'%(
-                name, self.nameof(k), self.nameof(dic[k])))
-        return name
-
-    # strange prebuilt instances below, don't look too closely
-    # XXX oh well.
-    def nameof_member_descriptor(self, md):
-        name = self.uniquename('gdescriptor_%s_%s' % (
-            md.__objclass__.__name__, md.__name__))
-        cls = self.nameof(md.__objclass__)
-        # do I need to take the dict and then getitem???
-        self.initcode.append1('%s = space.getattr(%s, %s)' %
-                                (name, cls, self.nameof(md.__name__)))
-        return name
-    nameof_getset_descriptor  = nameof_member_descriptor
-    nameof_method_descriptor  = nameof_member_descriptor
-    nameof_wrapper_descriptor = nameof_member_descriptor
-
-    def nameof_file(self, fil):
-        if fil is sys.stdin:
-            return 'PySys_GetObject("stdin")'
-        if fil is sys.stdout:
-            return 'PySys_GetObject("stdout")'
-        if fil is sys.stderr:
-            return 'PySys_GetObject("stderr")'
-        raise Exception, 'Cannot translate an already-open file: %r' % (fil,)
-
-    def gen_source(self, fname, ftmpname=None, file=file):
-        self.fname = fname
-        self.ftmpname = ftmpname
-
-        # generate unordered source file, first.
-        # I prefer this over ordering everything in memory.
-        fname = self.fname
-        if self.ftmpname:
-            fname = self.ftmpname
-        f = file(fname, "w")
-        # generate ordered source file
-        try:
-            self.f = f
-            self.gen_source_temp()
-        finally:
-            f.close()
-
-        def copyfile(source, target):
-            file(target, "w").write(file(source).read())
-
-        def order_sections(fname):
-            sep = "\n##SECTION##\n"
-            txt = file(fname).read()
-            pieces = txt.split(sep)
-            prelude = pieces.pop(0)
-            postlude = pieces.pop()
-            dic = {}
-            while pieces:
-                func = pieces.pop()
-                head = pieces.pop()
-                key = makekey(head, len(pieces))
-                dic[key] = head + sep + func
-            lis = dic.items()
-            lis.sort()
-            lis = [prelude] + [func for head, func in lis] + [postlude]
-            txt = sep.join(lis)
-            file(fname, "w").write(txt)
-
-        def makekey(txt, uniqueno):
-            dic = {}
-            for line in txt.split("\n"):
-                ign, name, value = line.split(None, 2)
-                dic[name] = eval(value, {})
-            key = (dic["filename"], dic["firstlineno"],
-                   dic["function"], uniqueno)
-            return key
-
-        order_sections(fname)
-        if self.ftmpname:
-            copyfile(self.ftmpname, self.fname)
-        
-    def gen_source_temp(self):
-        f = self.f
-        info = {
-            'modname': self.modname,
-             # the side-effects of this is kick-start the process
-            'entrypoint': self.nameof(self.entrypoint),
-            }
-        # header
-        print >> f, self.RPY_HEADER
-        print >> f
-
-        # doc
-        if self.moddict and self.moddict.get("__doc__"):
-            doc = self.moddict["__doc__"]
-            print >> f, render_docstr(doc)
-            print >> f
-            # make sure it is not rendered again
-            key = Constant(doc).key
-            self.rpynames[key] = "__doc__"
-            self.initcode.append("__doc__ = space.wrap('__doc__')")
-
-        # header """def initmodule(space):"""
-        print >> f, self.RPY_INIT_HEADER % info
-
-        # function implementations
-        while self.pendingfunctions or self.latercode:
-            if self.pendingfunctions:
-                func = self.pendingfunctions.pop()
-                self.currentfunc = func
-                self.gen_rpyfunction(func)
-            # collect more of the latercode after each function
-            while self.latercode:
-                gen, self.debugstack = self.latercode.pop()
-                #self.initcode.extend(gen) -- eats TypeError! bad CPython!
-                for line in gen:
-                    self.initcode.append1(line)
-                self.debugstack = ()
-            self.gen_global_declarations()
-
-        # set the final splitter
-        print >> f, "##SECTION##"
-        # footer, init code
-        for codelines in self.initcode:
-            # keep docstrings unindented
-            indent = "  "
-            if type(codelines) is tuple:
-                codelines = codelines[0].split("\n", 1)
-                codelines[0] = indent + codelines[0]
-                indent = ""
-            else:
-                codelines = codelines.split("\n")
-            for codeline in codelines:
-                print >> f, indent + codeline
-
-        self.gen_trailer(info, "  ")
-        # do not close the file here!
-
-    def gen_trailer(self, info, indent):
-        if self.moddict:
-            # we are generating a module, no __main__ etc.
-            print >> self.f, indent + "return %s" % self.nameof(self.entrypoint)
-            print >> self.f
-        else:
-            # we should have an entrypoint function
-            info['entrypointname'] = self.trans_funcname(self.entrypoint.__name__)
-            print >> self.f, self.RPY_INIT_FOOTER % info
-       
-    def gen_global_declarations(self):
-        g = self.globaldecl
-        if g:
-            f = self.f
-            print >> f, '# global declaration%s' % ('s'*(len(g)>1))
-            for line in g:
-                print >> f, line
-            print >> f
-            del g[:]
-        g = self.globalobjects
-        for name in g:
-            pass # self.initcode.append1('# REGISTER_GLOBAL(%s)' % (name,))
-        del g[:]
-
-    def rel_filename(self, name):
-        # try to find a name relative to pypy and unify.
-        # if not possible, stick with the original.
-        ref = py.path.local(pypy.__path__[0])
-        rel = py.path.local(name).relto(ref)
-        if rel:
-            # make it os independent
-            return rel.replace('\\', '/')
-        return name # no success
-
-    def gen_rpyfunction(self, func):
-
-        f = self.f
-        print >> f, "##SECTION##" # simple to split, afterwards
-        print >> f, ("## filename    %r\n"
-                     "## function    %r\n"
-                     "## firstlineno %d") % (
-            self.rel_filename(func.func_code.co_filename),
-            func.func_code.co_name,
-            func.func_code.co_firstlineno)
-        print >> f, "##SECTION##"
-        localscope = self.namespace.localScope()
-        body = list(self.rpyfunction_body(func, localscope))
-        name_of_defaults = [self.nameof(x, debug=('Default argument of', func))
-                            for x in (func.func_defaults or ())]
-        self.gen_global_declarations()
-
-        # print header
-        docstr = render_docstr(func, "    ")
-        cname = self.nameof(func)
-        assert cname.startswith('gfunc_')
-        f_name = 'f_' + cname[6:]
-
-        # collect all the local variables
-        graph = self.translator.getflowgraph(func)
-        localslst = []
-        def visit(node):
-            if isinstance(node, Block):
-                localslst.extend(node.getvariables())
-        traverse(visit, graph)
-        localnames = [self.expr(a, localscope) for a in uniqueitems(localslst)]
-
-        # collect all the arguments
-        vararg = varkw = None
-        varargname = varkwname = None
-        all_args = graph.getargs()
-        p = len(all_args)
-        if func.func_code.co_flags & CO_VARKEYWORDS:
-            p -= 1
-            varkw = graph.getargs()[p]
-            varkwname = func.func_code.co_varnames[p]
-        if func.func_code.co_flags & CO_VARARGS:
-            p -= 1
-            vararg = graph.getargs()[p]
-            varargname = func.func_code.co_varnames[p]
-        positional_args = all_args[:p]
-
-        fast_args = [self.expr(a, localscope) for a in positional_args]
-        if vararg is not None:
-            vararg = self.expr(vararg, localscope)
-            fast_args.append(vararg)
-        if varkw is not None:
-            varkw = self.expr(varkw, localscope)
-            fast_args.append(varkw)
-        fast_name = 'fast' + f_name
-
-        fast_set = dict(zip(fast_args, fast_args))
-
-        # create function declaration
-        name = self.trans_funcname(func.__name__) # for <lambda>
-        argstr = ", ".join(['space'] + fast_args)
-        fast_function_header = ('  def %s(%s):'
-                                % (name, argstr))
-
-        def install_func(f_name, name):
-            yield ''
-            yield '  %s = %s' % (f_name, name)
-            #import __builtin__
-            #dic = __builtin__.__dict__
-            #if dic.get(name):
-            #    yield 'del %s # hiding a builtin!' % name
-            #else:
-            #    self.initcode.append1('del m.%s' % (name,))
-
-        print >> f, '  def %s(space, __args__):' % (name,)
-        if docstr is not None:
-            print >> f, docstr
-            print >> f
-        def tupstr(seq):
-            if len(seq) == 1:
-                fmt = '%s,'
-            else:
-                fmt = '%s'
-            return fmt % ', '.join(seq)
-        def tupassstr(seq):
-            if not seq:
-                return ""
-            else:
-                return tupstr(seq) + " = "
-
-        print >> f, '    funcname = "%s"' % func.__name__
-
-        kwlist = list(func.func_code.co_varnames[:func.func_code.co_argcount])
-        signature = '    signature = %r' % kwlist
-        signature = ", ".join([signature, repr(varargname), repr(varkwname)])
-        print >> f, signature
-
-        print >> f, '    defaults_w = [%s]' % ", ".join(name_of_defaults)
-
-        print >> f, '    %s__args__.parse(funcname, signature, defaults_w)' % (
-            tupassstr(fast_args),)
-        print >> f, '    return %s(%s)' % (fast_name, ', '.join(["space"]+fast_args))
-
-        for line in install_func(f_name, name):
-            print >> f, line
-
-        print >> f
-        print >> f, fast_function_header
-        if docstr is not None:
-            print >> f, docstr
-
-        fast_locals = [arg for arg in localnames if arg not in fast_set]
-##        # if goto is specialized, the false detection of
-##        # uninitialized variables goes away.
-##        if fast_locals and not self.specialize_goto:
-##            print >> f
-##            for line in self.large_initialize(fast_locals):
-##                print >> f, "    %s" % line
-##            print >> f
-
-        # print the body
-        for line in body:
-            print >> f, line
-        for line in install_func("fast"+f_name, name):
-            print >> f, line
-        print >> f
-
-        # print the PyMethodDef
-        # skipped
-
-        if not self.translator.frozen:
-            # this is only to keep the RAM consumption under control
-            del self.translator.flowgraphs[func]
-            Variable.instances.clear()
-
-    def rpyfunction_body(self, func, localscope):
-        try:
-            graph = self.translator.getflowgraph(func)
-        except Exception, e:
-            print 20*"*", e
-            print func
-            raise
-        # not needed, we use tuple assignment!
-        # remove_direct_loops(graph)
-        checkgraph(graph)
-
-        allblocks = []
-        
-        f = self.f
-        t = self.translator
-        #t.simplify(func)
-        graph = t.getflowgraph(func)
-
-
-        start = graph.startblock
-        allblocks = ordered_blocks(graph)
-        nblocks = len(allblocks)
-
-        blocknum = {}
-        for block in allblocks:
-            blocknum[block] = len(blocknum)+1
-
-        yield "    goto = %s # startblock" % self.mklabel(blocknum[start])
-        yield "    while True:"
-                
-        def render_block(block):
-            catch_exception = block.exitswitch == Constant(last_exception)
-            regular_op = len(block.operations) - catch_exception
-            # render all but maybe the last op
-            for op in block.operations[:regular_op]:
-                for line in self.oper(op, localscope).split("\n"):
-                    yield "%s" % line
-            # render the last op if it is exception handled
-            for op in block.operations[regular_op:]:
-                yield "try:"
-                for line in self.oper(op, localscope).split("\n"):
-                    yield "    %s" % line
-
-            if len(block.exits) == 0:
-                if len(block.inputargs) == 2:   # exc_cls, exc_value
-                    # exceptional return block
-                    exc_cls = self.expr(block.inputargs[0], localscope)
-                    exc_val = self.expr(block.inputargs[1], localscope)
-                    yield "raise %s(%s, %s)" % (self.nameof(OperationError),
-                                                exc_cls, exc_val)
-                else:
-                    # regular return block
-                    retval = self.expr(block.inputargs[0], localscope)
-                    yield "return %s" % retval
-                return
-            elif block.exitswitch is None:
-                # single-exit block
-                assert len(block.exits) == 1
-                for op in self.gen_link(block.exits[0], localscope, blocknum, block):
-                    yield "%s" % op
-            elif catch_exception:
-                # block catching the exceptions raised by its last operation
-                # we handle the non-exceptional case first
-                link = block.exits[0]
-                assert link.exitcase is None
-                for op in self.gen_link(link, localscope, blocknum, block):
-                    yield "    %s" % op
-                # we must catch the exception raised by the last operation,
-                # which goes to the last err%d_%d label written above.
-                # Since we only have OperationError, we need to select:
-                yield "except %s, e:" % (self.nameof(OperationError),)
-                yield "    e.w_type, e.w_value, _ign = space.unpacktuple("
-                yield "        space.normalize_exception(e.w_type, e.w_value, space.w_None), 3)"
-                q = "if"
-                for link in block.exits[1:]:
-                    assert issubclass(link.exitcase, Exception)
-                    # Exeption classes come unwrapped in link.exitcase
-                    yield "    %s space.is_true(space.issubtype(e.w_type, %s)):" % (q,
-                                            self.nameof(link.exitcase))
-                    q = "elif"
-                    for op in self.gen_link(link, localscope, blocknum, block, {
-                                Constant(last_exception): 'e.w_type',
-                                Constant(last_exc_value): 'e.w_value'}):
-                        yield "        %s" % op
-                yield "    else:raise # unhandled case, should not happen"
-            else:
-                # block ending in a switch on a value
-                exits = list(block.exits)
-                if len(exits) == 2 and (
-                    exits[0].exitcase is False and exits[1].exitcase is True):
-                    # order these guys like Python does
-                    exits.reverse()
-                q = "if"
-                for link in exits[:-1]:
-                    yield "%s %s == %s:" % (q, self.expr(block.exitswitch,
-                                                     localscope),
-                                                     link.exitcase)
-                    for op in self.gen_link(link, localscope, blocknum, block):
-                        yield "    %s" % op
-                    q = "elif"
-                link = exits[-1]
-                yield "else:"
-                yield "    assert %s == %s" % (self.expr(block.exitswitch,
-                                                    localscope),
-                                                    link.exitcase)
-                for op in self.gen_link(exits[-1], localscope, blocknum, block):
-                    yield "    %s" % op
-
-        cmpop = ('==', 'is') [self.specialize_goto]
-        for block in allblocks:
-            blockno = blocknum[block]
-            yield ""
-            yield "        if goto %s %s:" % (cmpop, self.mklabel(blockno))
-            for line in render_block(block):
-                yield "            %s" % line
-
-# ____________________________________________________________
-
-    RPY_HEADER = '''#!/bin/env python
-# -*- coding: LATIN-1 -*-'''
-
-    RPY_SEP = "#*************************************************************"
-
-    RPY_INIT_HEADER = RPY_SEP + '''
-
-def init%(modname)s(space):
-  """NOT_RPYTHON"""
-'''
-
-    RPY_INIT_FOOTER = '''
-# entry point: %(entrypointname)s, %(entrypoint)s
-if __name__ == "__main__":
-    from pypy.objspace.std import StdObjSpace
-    from pypy.objspace.std.model import UnwrapError
-    space = StdObjSpace()
-    init%(modname)s(space)
-    ret = space.call(%(entrypoint)s, space.newtuple([]))
-    try:
-        print space.unwrap(ret)
-    except UnwrapError:
-        print "cannot unwrap, here the wrapped result:"
-        print ret
-'''
-
-# _____________________________________________________________________
-
-## this should go into some test file
-
-def somefunc(arg):
-    pass
-
-# XXX problem with local functions:
-def randint(low, high, seed = 1234567): # really not a real random
-    return (seed % (high-low)) + low
-
-def small_loop():
-    ''' this is a test for small loops.
-    How would we generate small blocks which call
-    each other? Hey, and """ is a doc string test """
-    '''
-    #from random import randint
-    # does not work. flowspace really complains on random.
-    # XXX we also seem to have problems with local functions
-    #def randint(low, high, seed = 1234567): # really not a real random
-    #    return (seed % (high-low)) + low
-                
-    for i in range(10000):
-        r = randint(0, 10000)
-        if r > 9000:
-            return r
-
-def f(a,b):
-##    print "start"
-    a = []
-    a.append(3)
-    for i in range(3):
-        pass#print i
-    if a > b:
-        try:
-            if b == 123:
-                raise ValueError
-            elif b == 321:
-                raise IndexError
-            return 123
-        except ValueError:
-            raise TypeError
-    else:
-        dummy = somefunc(23)
-        return 42
-
-class TestClass:pass
-
-def ff(a, b, c=3,*rest):
-    """ this is
-    some
-    docstring
-"""
-    try:
-        try:
-            if rest:
-                raise SystemError, 42
-            return a+b
-        finally:
-            a = 7
-            if rest:
-                return len(rest),c
-    except TypeError:
-        print "eek"
-
-glob = 100
-def fff():
-    global glob
-    return 42+glob
-
-def app_mod__String_ANY(format, values):
-    import _formatting
-    if isinstance(values, tuple):
-        return _formatting.format(format, values, None)
-    else:
-        if hasattr(values, 'keys'):
-            return _formatting.format(format, (values,), values)
-        else:
-            return _formatting.format(format, (values,), None)
-
-def app_str_decode__String_ANY_ANY(str, encoding=None, errors=None):
-    if encoding is None and errors is None:
-        return unicode(str)
-    elif errors is None:
-        return unicode(str, encoding)
-    else:
-        return unicode(str, encoding, errors)
-        
-
-def test_md5():
-    #import md5
-    # how do I avoid the builtin module?
-    from pypy.appspace import md5
-    digest = md5.new("hello").hexdigest()
-    return digest
-
-def test_mod():
-    return app_mod__String_ANY("-%s-", ["hallo"])
-
-def test_join():
-    return " ".join(["hi", "there"])
-
-# cannot nest local classes, yet
-# this appears to be a problem in flow space.
-class AnIterClass(object):
-    def __init__(self):
-        self.lis = [c for c in "test"]
-    def next(self):
-        if self.lis:
-            return self.lis.pop()
-        raise StopIteration
-    def __iter__(self):
-        return self
-    
-def test_iter():
-    res = []
-    for i in "hallo":
-        res.append(i)
-    for i in AnIterClass():
-        res.append(i)
-    return res
-
-def test_loop():
-    res = []
-    i = 0
-    while 1:
-        i += 1
-        res.append(i)
-        if i == 42:
-            break
-        res.append(-i)
-    return res
-
-def test_exc(a=5):
-    try:
-        b = 0
-        return a / b
-    except ZeroDivisionError:
-        return 42
-
-def test_strutil():
-    from pypy.objspace.std import strutil
-    return (strutil.string_to_int("42"),
-            strutil.string_to_long("12345678901234567890"))
-
-def test_struct():
-    from pypy.appspace import struct
-    import struct as stru
-    res1 = stru.pack('f',1.23), struct.pack('f',1.23)
-    res2 = struct.unpack('f', struct.pack('f',1.23))
-    return res1, res2
-
-def exceptions_helper():
-    import pypy
-    prefix = os.path.dirname(pypy.__file__)
-    libdir = os.path.join(prefix, "lib")
-    fname = "_exceptions.py"
-    fpath = os.path.join(libdir, fname)
-    dic = {"__name__": "exceptions"}
-    execfile(fpath, dic)
-    del dic["__builtins__"]
-    def test_exceptions():
-        """ enumerate all exceptions """
-        return dic.keys()
-        #return [thing for thing in _exceptions.__dict__.values()]
-    return dic, test_exceptions
-
-def make_class_instance_helper():
-    import pypy
-    prefix = os.path.dirname(pypy.__file__)
-    libdir = os.path.join(prefix, "lib")
-    hold = sys.path
-    sys.path.insert(0, libdir)
-    import _classobj
-    sys.path = hold
-    def make_class_instance():
-        return _classobj.classobj, _classobj.instance
-    return None, make_class_instance
-
-def test_complex():
-    return 1j
-
-def test_NoneType():
-    return types.NoneType
-    
-def all_entries():
-    res = [func() for func in entrypoints[:-1]]
-    return res
-
-entrypoints = (small_loop,
-                lambda: f(2, 3),
-                lambda: ff(2, 3, 5),
-                fff,
-                lambda: app_str_decode__String_ANY_ANY("hugo"),
-                test_mod,
-                test_md5,
-                test_join,
-                test_iter,
-                test_loop,
-                test_exc,
-                test_strutil,
-                test_struct,
-                exceptions_helper,
-                make_class_instance_helper,
-                test_complex,
-                test_NoneType,
-                all_entries)
-entrypoint = entrypoints[5]
-
-if False and __name__ == "__main__":
-    # XXX TODO:
-    # extract certain stuff like a general module maker
-    # and put this into tools/compile_exceptions, maybe???
-    dic, entrypoint = exceptions_helper()
-    t = Translator(None, verbose=False, simplifying=True,
-                   builtins_can_raise_exceptions=True,
-                   do_imports_immediately=False)
-    gen = GenRpy(t, entrypoint)
-    gen.moddict = dic
-    gen.gen_source('/tmp/look.py')
-    
-    _oldcodetogointotestcases = '''
-    import os, sys
-    from pypy.interpreter import autopath
-    srcdir = os.path.dirname(autopath.pypydir)
-    appdir = os.path.join(autopath.pypydir, 'appspace')
-
-    if appdir not in sys.path:
-        sys.path.insert(0, appdir)
-
-    dic = None
-    if entrypoint.__name__.endswith("_helper"):
-        dic, entrypoint = entrypoint()
-    t = Translator(entrypoint, verbose=False, simplifying=True, builtins_can_raise_exceptions=True)
-    gen = GenRpy(t)
-    gen.use_fast_call = True
-    if dic: gen.moddict = dic
-    import pypy.appspace.generated as tmp
-    pth = os.path.dirname(tmp.__file__)
-    ftmpname = "/tmp/look.py"
-    fname = os.path.join(pth, gen.modname+".py")
-    gen.gen_source(fname, ftmpname)
-    '''
-
-def crazy_test():
-    """ this thingy is generating the whole interpreter in itself"""
-    dic = {"__builtins__": __builtins__, "__name__": "__main__"}
-    execfile("/tmp/look.py", dic)
-
-    entrypoint = dic[gen.entrypoint]
-    def test():
-        entrypoint()
-        
-    t = Translator(test, verbose=False, simplifying=True,
-                   builtins_can_raise_exceptions=True,
-                   do_imports_immediately=False)
-    gen2 = GenRpy(t)
-    gen2.gen_source("/tmp/look2.py")
-
-
-import py.code
-import cStringIO as StringIO
-
-class memfile(object):
-    _storage = {}
-    def __init__(self, name, mode="r"):
-        if mode == "w":
-            self._storage[name] = StringIO.StringIO()
-        elif mode == "r":
-            try:
-                data = self._storage[name].getvalue()
-            except IndexError:
-                data = file(name).read()
-            self._storage[name] = StringIO.StringIO(data)
-        else:
-            raise ValueError, "mode %s not supported" % mode
-        self._file = self._storage[name]
-    def __getattr__(self, name):
-        return getattr(self._file, name)
-    def close(self):
-        pass
-
-def translate_as_module(sourcetext, filename=None, modname="app2interpexec",
-                        do_imports=False, tmpname=None):
-    """ compile sourcetext as a module, translating to interp level.
-    The result is the init function that creates the wrapped module dict.
-    This init function needs a space as argument.
-    tmpname can be passed for debugging purposes.
-
-    Example:
-
-    initfunc = translate_as_module(text)
-    from pypy.objspace.std import Space
-    space = Space()
-    dic = ini(space)
-    # and now use the members of the dict
-    """
-    # create something like a module
-    # the following code will be removed when app_descriptor works
-    ##print 80*"T", sourcetext
-    if "class property" in sourcetext:
-        # debugging app_descriptor.py
-        tmpname = "/tmp/look.py"
-    if filename is None: 
-        code = py.code.Source(sourcetext).compile()
-    else: 
-        code = compile(sourcetext, filename, 'exec')
-    dic = {'__name__': modname}
-    exec code in dic
-    del dic['__builtins__']
-    entrypoint = dic
-    t = Translator(None, verbose=False, simplifying=True,
-                   builtins_can_raise_exceptions=True,
-                   do_imports_immediately=do_imports)
-    hold = sys.path
-    sys.path.insert(0, os.path.join(pypy.__path__[0], "lib"))
-    gen = GenRpy(t, entrypoint, modname, dic)
-    sys.path = hold
-    if tmpname:
-        _file = file
-    else:
-        _file = memfile
-        tmpname = "nada"
-    out = _file(tmpname, 'w')
-    gen.f = out
-    gen.gen_source(tmpname, file=_file)
-    out.close()
-    newsrc = _file(tmpname).read()
-    code = py.code.Source(newsrc).compile()
-    dic = {'__name__': modname}
-    exec code in dic
-    # now we just need to return the init function,
-    # which then needs to be called with the space to return the dict.
-    return dic['init%s' % modname]
-
-#___________________________________________________________________
-
-# some testing code
-
-testcode = """
-def f(a, b):
-    return a + b
-
-def g():
-    return f(f(1, 2), f(4, 8))
-"""
-
-if __name__ == '__main__':
-    res = translate_as_module(testcode, tmpname='/tmp/look.py')

Deleted: /pypy/dist/pypy/translator/test/test_annrpython.py
==============================================================================
--- /pypy/dist/pypy/translator/test/test_annrpython.py	Thu Apr  7 02:01:08 2005
+++ (empty file)
@@ -1,691 +0,0 @@
-
-import autopath
-import py.test
-from pypy.tool.udir import udir
-
-from pypy.translator.annrpython import RPythonAnnotator, annmodel
-from pypy.translator.translator import Translator
-from pypy.objspace.flow.model import *
-
-from pypy.translator.test import snippet
-
-class TestAnnonateTestCase:
-    objspacename = 'flow'
-
-    def make_fun(self, func):
-        import inspect
-        try:
-            func = func.im_func
-        except AttributeError:
-            pass
-        name = func.func_name
-        funcgraph = self.space.build_flow(func)
-        funcgraph.source = inspect.getsource(func)
-        return funcgraph
-
-    def reallyshow(self, graph):
-        import os
-        from pypy.translator.tool.make_dot import make_dot
-        dest = make_dot('b', graph)
-        os.system('gv %s' % str(dest))
-
-    def test_simple_func(self):
-        """
-        one test source:
-        def f(x):
-            return x+1
-        """
-        x = Variable("x")
-        result = Variable("result")
-        op = SpaceOperation("add", [x, Constant(1)], result)
-        block = Block([x])
-        fun = FunctionGraph("f", block)
-        block.operations.append(op)
-        block.closeblock(Link([result], fun.returnblock))
-        a = RPythonAnnotator()
-        a.build_types(fun, [int])
-        assert a.gettype(fun.getreturnvar()) == int
-
-    def test_while(self):
-        """
-        one test source:
-        def f(i):
-            while i > 0:
-                i = i - 1
-            return i
-        """
-        i = Variable("i")
-        conditionres = Variable("conditionres")
-        conditionop = SpaceOperation("gt", [i, Constant(0)], conditionres)
-        decop = SpaceOperation("add", [i, Constant(-1)], i)
-        headerblock = Block([i])
-        whileblock = Block([i])
-
-        fun = FunctionGraph("f", headerblock)
-        headerblock.operations.append(conditionop)
-        headerblock.exitswitch = conditionres
-        headerblock.closeblock(Link([i], fun.returnblock, False),
-                               Link([i], whileblock, True))
-        whileblock.operations.append(decop)
-        whileblock.closeblock(Link([i], headerblock))
-
-        a = RPythonAnnotator()
-        a.build_types(fun, [int])
-        assert a.gettype(fun.getreturnvar()) == int
-
-    def test_while_sum(self):
-        """
-        one test source:
-        def f(i):
-            sum = 0
-            while i > 0:
-                sum = sum + i
-                i = i - 1
-            return sum
-        """
-        i = Variable("i")
-        sum = Variable("sum")
-
-        conditionres = Variable("conditionres")
-        conditionop = SpaceOperation("gt", [i, Constant(0)], conditionres)
-        decop = SpaceOperation("add", [i, Constant(-1)], i)
-        addop = SpaceOperation("add", [i, sum], sum)
-        startblock = Block([i])
-        headerblock = Block([i, sum])
-        whileblock = Block([i, sum])
-
-        fun = FunctionGraph("f", startblock)
-        startblock.closeblock(Link([i, Constant(0)], headerblock))
-        headerblock.operations.append(conditionop)
-        headerblock.exitswitch = conditionres
-        headerblock.closeblock(Link([sum], fun.returnblock, False),
-                               Link([i, sum], whileblock, True))
-        whileblock.operations.append(addop)
-        whileblock.operations.append(decop)
-        whileblock.closeblock(Link([i, sum], headerblock))
-
-        a = RPythonAnnotator()
-        a.build_types(fun, [int])
-        assert a.gettype(fun.getreturnvar()) == int
-
-    def test_f_calls_g(self):
-        a = RPythonAnnotator()
-        s = a.build_types(f_calls_g, [int])
-        # result should be an integer
-        assert s.knowntype == int
-
-    def test_lists(self):
-        a = RPythonAnnotator()
-        end_cell = a.build_types(snippet.poor_man_rev_range, [int])
-        # result should be a list of integers
-        assert end_cell.knowntype == list
-        assert end_cell.s_item.knowntype == int
-
-    def test_factorial(self):
-        a = RPythonAnnotator()
-        s = a.build_types(snippet.factorial, [int])
-        # result should be an integer
-        assert s.knowntype == int
-
-    def test_factorial2(self):
-        a = RPythonAnnotator()
-        s = a.build_types(snippet.factorial2, [int])
-        # result should be an integer
-        assert s.knowntype == int
-
-    def test_build_instance(self):
-        a = RPythonAnnotator()
-        s = a.build_types(snippet.build_instance, [])
-        # result should be a snippet.C instance
-        assert s.knowntype == snippet.C
-
-    def test_set_attr(self):
-        a = RPythonAnnotator()
-        s = a.build_types(snippet.set_attr, [])
-        # result should be an integer
-        assert s.knowntype == int
-
-    def test_merge_setattr(self):
-        a = RPythonAnnotator()
-        s = a.build_types(snippet.merge_setattr, [int])
-        # result should be an integer
-        assert s.knowntype == int
-
-    def test_inheritance1(self):
-        a = RPythonAnnotator()
-        s = a.build_types(snippet.inheritance1, [])
-        # result should be exactly:
-        assert s == annmodel.SomeTuple([
-                                a.bookkeeper.immutablevalue(()),
-                                annmodel.SomeInteger()
-                                ])
-
-    def test_inheritance2(self):
-        a = RPythonAnnotator()
-        s = a.build_types(snippet._inheritance_nonrunnable, [])
-        # result should be exactly:
-        assert s == annmodel.SomeTuple([
-                                annmodel.SomeInteger(),
-                                annmodel.SomeObject()
-                                ])
-
-    def test_poor_man_range(self):
-        a = RPythonAnnotator()
-        s = a.build_types(snippet.poor_man_range, [int])
-        # result should be a list of integers
-        assert s.knowntype == list
-        assert s.s_item.knowntype == int
-
-    def test_methodcall1(self):
-        a = RPythonAnnotator()
-        s = a.build_types(snippet._methodcall1, [int])
-        # result should be a tuple of (C, positive_int)
-        assert s.knowntype == tuple
-        assert len(s.items) == 2
-        assert s.items[0].knowntype == snippet.C
-        assert s.items[1].knowntype == int
-        assert s.items[1].nonneg == True
-
-    def test_classes_methodcall1(self):
-        a = RPythonAnnotator()
-        a.build_types(snippet._methodcall1, [int])
-        # the user classes should have the following attributes:
-        classes = a.bookkeeper.userclasses
-        assert classes[snippet.F].attrs.keys() == ['m']
-        assert classes[snippet.G].attrs.keys() == ['m2']
-        assert classes[snippet.H].attrs.keys() == ['attr'] 
-        assert classes[snippet.H].about_attribute('attr') == (
-                          a.bookkeeper.immutablevalue(1))
-
-    def DISABLED_test_knownkeysdict(self):
-        # disabled, SomeDict() is now a general {s_key: s_value} dict
-        a = RPythonAnnotator()
-        s = a.build_types(snippet.knownkeysdict, [int])
-        # result should be an integer
-        assert s.knowntype == int
-
-    def test_generaldict(self):
-        a = RPythonAnnotator()
-        s = a.build_types(snippet.generaldict, [str, int, str, int])
-        # result should be an integer
-        assert s.knowntype == int
-
-    def test_somebug1(self):
-        a = RPythonAnnotator()
-        s = a.build_types(snippet._somebug1, [int])
-        # result should be a built-in method
-        assert isinstance(s, annmodel.SomeBuiltin)
-
-    def test_with_init(self):
-        a = RPythonAnnotator()
-        s = a.build_types(snippet.with_init, [int])
-        # result should be an integer
-        assert s.knowntype == int
-
-    def test_with_more_init(self):
-        a = RPythonAnnotator()
-        s = a.build_types(snippet.with_more_init, [int, bool])
-        # the user classes should have the following attributes:
-        classes = a.bookkeeper.userclasses
-        # XXX on which class should the attribute 'a' appear?  We only
-        #     ever flow WithInit.__init__ with a self which is an instance
-        #     of WithMoreInit, so currently it appears on WithMoreInit.
-        assert classes[snippet.WithMoreInit].about_attribute('a') == (
-                          annmodel.SomeInteger())
-        assert classes[snippet.WithMoreInit].about_attribute('b') == (
-                          annmodel.SomeBool())
-
-    def test_global_instance(self):
-        a = RPythonAnnotator()
-        s = a.build_types(snippet.global_instance, [])
-        # currently this returns the constant 42.
-        # XXX not sure this is the best behavior...
-        assert s == a.bookkeeper.immutablevalue(42)
-
-    def test_call_five(self):
-        a = RPythonAnnotator()
-        s = a.build_types(snippet.call_five, [])
-        # returns should be a list of constants (= 5)
-        assert isinstance(s, annmodel.SomeList)
-        assert s.s_item == a.bookkeeper.immutablevalue(5)
-
-    def test_call_five_six(self):
-        a = RPythonAnnotator()
-        s = a.build_types(snippet.call_five_six, [])
-        # returns should be a list of positive integers
-        assert isinstance(s, annmodel.SomeList)
-        assert s.s_item == annmodel.SomeInteger(nonneg=True)
-
-    def test_constant_result(self):
-        a = RPythonAnnotator()
-        s = a.build_types(snippet.constant_result, [])
-        #a.translator.simplify()
-        # must return "yadda"
-        assert s == a.bookkeeper.immutablevalue("yadda")
-        keys = a.translator.flowgraphs.keys()
-        keys.sort()
-        expected = [snippet.constant_result,
-                    snippet.forty_two,
-                    # and not snippet.never_called
-                    ]
-        expected.sort()
-        assert keys == expected
-        a.simplify()
-        #a.translator.view()
-
-    def test_call_pbc(self):
-        a = RPythonAnnotator()
-        s = a.build_types(snippet.call_cpbc, [])
-        assert s == a.bookkeeper.immutablevalue(42)
-
-    def test_flow_type_info(self):
-        a = RPythonAnnotator()
-        s = a.build_types(snippet.flow_type_info, [object])
-        a.translator.simplify()
-        a.simplify()
-        #a.translator.view()
-        assert s.knowntype == int
-
-    def test_flow_type_info_2(self):
-        a = RPythonAnnotator()
-        s = a.build_types(snippet.flow_type_info,
-                          [annmodel.SomeInteger(nonneg=True)])
-        # this checks that isinstance(i, int) didn't loose the
-        # actually more precise information that i is non-negative
-        assert s == annmodel.SomeInteger(nonneg=True)
-
-    def test_flow_usertype_info(self):
-        a = RPythonAnnotator()
-        s = a.build_types(snippet.flow_usertype_info, [object])
-        #a.translator.view()
-        assert s.knowntype == snippet.WithInit
-
-    def test_flow_usertype_info2(self):
-        a = RPythonAnnotator()
-        s = a.build_types(snippet.flow_usertype_info, [snippet.WithMoreInit])
-        #a.translator.view()
-        assert s.knowntype == snippet.WithMoreInit
-
-    def test_flow_identity_info(self):
-        a = RPythonAnnotator()
-        s = a.build_types(snippet.flow_identity_info, [object, object])
-        a.translator.simplify()
-        a.simplify()
-        #a.translator.view()
-        assert s == a.bookkeeper.immutablevalue((None, None))
-
-    def test_mergefunctions(self):
-        a = RPythonAnnotator()
-        s = a.build_types(snippet.mergefunctions, [int])
-        # the test is mostly that the above line hasn't blown up
-        # but let's at least check *something*
-        assert isinstance(s, annmodel.SomePBC)
-
-    def test_func_calls_func_which_just_raises(self):
-        a = RPythonAnnotator()
-        s = a.build_types(snippet.funccallsex, [])
-        # the test is mostly that the above line hasn't blown up
-        # but let's at least check *something*
-        #self.assert_(isinstance(s, SomeCallable))
-
-    def test_tuple_unpack_from_const_tuple_with_different_types(self):
-        a = RPythonAnnotator()
-        s = a.build_types(snippet.func_arg_unpack, [])
-        assert isinstance(s, annmodel.SomeInteger) 
-        assert s.const == 3 
-
-    def test_pbc_attr_preserved_on_instance(self):
-        a = RPythonAnnotator()
-        s = a.build_types(snippet.preserve_pbc_attr_on_instance, [bool])
-        #a.simplify()
-        #a.translator.view()
-        assert s == annmodel.SomeInteger(nonneg=True) 
-        #self.assertEquals(s.__class__, annmodel.SomeInteger) 
-
-    def test_is_and_knowntype_data(self): 
-        a = RPythonAnnotator()
-        s = a.build_types(snippet.is_and_knowntype, [bool])
-        #a.simplify()
-        #a.translator.view()
-        assert s == a.bookkeeper.immutablevalue(None)
-
-    def test_isinstance_and_knowntype_data(self): 
-        a = RPythonAnnotator()
-        x = annmodel.SomePBC({snippet.apbc: True}) 
-        s = a.build_types(snippet.isinstance_and_knowntype, [x]) 
-        #a.simplify()
-        #a.translator.view()
-        assert s == x
-
-    def test_somepbc_simplify(self):
-        a = RPythonAnnotator()
-        # this example used to trigger an AssertionError
-        a.build_types(snippet.somepbc_simplify, [])
-
-    def test_builtin_methods(self):
-        a = RPythonAnnotator()
-        iv = a.bookkeeper.immutablevalue
-        # this checks that some built-in methods are really supported by
-        # the annotator (it doesn't check that they operate property, though)
-        for example, methname, s_example in [
-            ('', 'join',    annmodel.SomeString()),
-            ([], 'append',  annmodel.SomeList({})), 
-            ([], 'extend',  annmodel.SomeList({})),           
-            ([], 'reverse', annmodel.SomeList({})),
-            ([], 'insert',  annmodel.SomeList({})),
-            ([], 'pop',     annmodel.SomeList({})),
-            ]:
-            constmeth = getattr(example, methname)
-            s_constmeth = iv(constmeth)
-            assert isinstance(s_constmeth, annmodel.SomeBuiltin)
-            s_meth = s_example.getattr(iv(methname))
-            assert isinstance(s_constmeth, annmodel.SomeBuiltin)
-
-    def test_simple_slicing0(self):
-        a = RPythonAnnotator()
-        s = a.build_types(snippet.simple_slice, [list])
-        g = a.translator.getflowgraph(snippet.simple_slice)
-        for thing in flatten(g):
-            if isinstance(thing, Block):
-                for op in thing.operations:
-                    if op.opname == "newslice":
-                        assert isinstance(a.binding(op.result),
-                                          annmodel.SomeSlice)
-
-    def test_simple_slicing(self):
-        a = RPythonAnnotator()
-        s = a.build_types(snippet.simple_slice, [list])
-        assert isinstance(s, annmodel.SomeList)
-
-    def test_simple_iter_list(self):
-        a = RPythonAnnotator()
-        s = a.build_types(snippet.simple_iter, [list])
-        assert isinstance(s, annmodel.SomeIterator)
-        
-    def test_simple_iter_dict(self):
-        a = RPythonAnnotator()
-        t = annmodel.SomeDict({}, annmodel.SomeInteger(), annmodel.SomeInteger())
-        s = a.build_types(snippet.simple_iter, [t])
-        assert isinstance(s, annmodel.SomeIterator)
-
-    def test_simple_zip(self):
-        a = RPythonAnnotator()
-        x = annmodel.SomeList({}, annmodel.SomeInteger())
-        y = annmodel.SomeList({}, annmodel.SomeString())
-        s = a.build_types(snippet.simple_zip, [x,y])
-        assert s.knowntype == list
-        assert s.s_item.knowntype == tuple
-        assert s.s_item.items[0].knowntype == int
-        assert s.s_item.items[1].knowntype == str
-        
-    def test_dict_copy(self):
-        a = RPythonAnnotator()
-        t = annmodel.SomeDict({}, annmodel.SomeInteger(), annmodel.SomeInteger())
-        s = a.build_types(snippet.dict_copy, [t])
-        assert isinstance(s, annmodel.SomeDict)
-        assert isinstance(s.s_key, annmodel.SomeInteger)
-        assert isinstance(s.s_value, annmodel.SomeInteger)
-
-    def test_dict_update(self):
-        a = RPythonAnnotator()
-        s = a.build_types(snippet.dict_update, [int])
-        assert isinstance(s, annmodel.SomeDict)
-        assert isinstance(s.s_key, annmodel.SomeInteger)
-        assert isinstance(s.s_value, annmodel.SomeInteger)
-
-        a = RPythonAnnotator()
-        s = a.build_types(snippet.dict_update, [str])
-        assert isinstance(s, annmodel.SomeDict)
-        assert not isinstance(s.s_key, annmodel.SomeString)
-        assert not isinstance(s.s_value, annmodel.SomeString)
-
-    def test_dict_keys(self):
-        a = RPythonAnnotator()
-        s = a.build_types(snippet.dict_keys, [])
-        assert isinstance(s, annmodel.SomeList)
-        assert isinstance(s.s_item, annmodel.SomeString)
-
-    def test_dict_keys2(self):
-        a = RPythonAnnotator()
-        s = a.build_types(snippet.dict_keys2, [])
-        assert isinstance(s, annmodel.SomeList)
-        assert not isinstance(s.s_item, annmodel.SomeString)
-
-    def test_dict_values(self):
-        a = RPythonAnnotator()
-        s = a.build_types(snippet.dict_values, [])
-        assert isinstance(s, annmodel.SomeList)
-        assert isinstance(s.s_item, annmodel.SomeString)
-    
-    def test_dict_values2(self):
-        a = RPythonAnnotator()
-        s = a.build_types(snippet.dict_values2, [])
-        assert isinstance(s, annmodel.SomeList)
-        assert not isinstance(s.s_item, annmodel.SomeString)
-
-    def test_dict_items(self):
-        a = RPythonAnnotator()
-        s = a.build_types(snippet.dict_items, [])
-        assert isinstance(s, annmodel.SomeList)
-        assert isinstance(s.s_item, annmodel.SomeTuple)
-        s_key, s_value = s.s_item.items
-        assert isinstance(s_key, annmodel.SomeString)
-        assert isinstance(s_value, annmodel.SomeInteger)
-
-    def test_exception_deduction(self):
-        a = RPythonAnnotator()
-        s = a.build_types(snippet.exception_deduction, [])
-        assert isinstance(s, annmodel.SomeInstance)
-        assert s.knowntype is snippet.Exc
-        
-    def test_exception_deduction_we_are_dumb(self):
-        a = RPythonAnnotator()
-        s = a.build_types(snippet.exception_deduction_we_are_dumb, [])
-        assert isinstance(s, annmodel.SomeInstance)
-        assert s.knowntype is snippet.Exc
-        
-    def test_nested_exception_deduction(self):
-        a = RPythonAnnotator()
-        s = a.build_types(snippet.nested_exception_deduction, [])
-        assert isinstance(s, annmodel.SomeTuple)
-        assert isinstance(s.items[0], annmodel.SomeInstance)
-        assert isinstance(s.items[1], annmodel.SomeInstance)
-        assert s.items[0].knowntype is snippet.Exc
-        assert s.items[1].knowntype is snippet.Exc2
-
-    def test_exc_deduction_our_exc_plus_others(self):
-        a = RPythonAnnotator()
-        s = a.build_types(snippet.exc_deduction_our_exc_plus_others, [])
-        assert isinstance(s, annmodel.SomeInteger)
-
-    def test_exc_deduction_our_excs_plus_others(self):
-        a = RPythonAnnotator()
-        s = a.build_types(snippet.exc_deduction_our_excs_plus_others, [])
-        assert isinstance(s, annmodel.SomeInteger)
-
-    def test_slice_union(self):
-        a = RPythonAnnotator()
-        s = a.build_types(snippet.slice_union, [int])
-        assert isinstance(s, annmodel.SomeSlice)
-
-    def test_bltin_code_frame_confusion(self):
-        a = RPythonAnnotator()
-        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)
-        # 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)
-        assert isinstance(a.binding(g_flowgraph.getreturnvar()),
-                          annmodel.SomeString)
-
-    def test_propagation_of_fresh_instances_through_attrs(self):
-        a = RPythonAnnotator()
-        s = a.build_types(snippet.propagation_of_fresh_instances_through_attrs, [int])
-        assert s is not None
-
-    def test_propagation_of_fresh_instances_through_attrs_rec_0(self):
-        a = RPythonAnnotator()
-        s = a.build_types(snippet.make_r, [int])
-        assert s.knowntype == snippet.R
-        Rdef = a.getuserclasses()[snippet.R]
-        assert Rdef.attrs['r'].s_value.knowntype == snippet.R
-        assert Rdef.attrs['n'].s_value.knowntype == int
-        assert Rdef.attrs['m'].s_value.knowntype == int
-    
-        
-    def test_propagation_of_fresh_instances_through_attrs_rec_eo(self):
-        a = RPythonAnnotator()
-        s = a.build_types(snippet.make_eo, [int])
-        assert s.knowntype == snippet.B
-        Even_def = a.getuserclasses()[snippet.Even]
-        Odd_def = a.getuserclasses()[snippet.Odd]
-        assert Even_def.attrs['x'].s_value.s_item.knowntype == snippet.Odd
-        assert Even_def.attrs['y'].s_value.s_item.knowntype == snippet.Even
-        assert Odd_def.attrs['x'].s_value.s_item.knowntype == snippet.Even
-        assert Odd_def.attrs['y'].s_value.s_item.knowntype == snippet.Odd        
-
-    def test_flow_rev_numbers(self):
-        a = RPythonAnnotator()
-        s = a.build_types(snippet.flow_rev_numbers, [])
-        assert s.knowntype == int
-        assert not s.is_constant() # !
-
-    def test_methodcall_is_precise(self):
-        a = RPythonAnnotator()
-        s = a.build_types(snippet.methodcall_is_precise, [])
-        classes = a.bookkeeper.userclasses
-        assert 'x' not in classes[snippet.CBase].attrs
-        assert (classes[snippet.CSub1].attrs['x'].s_value ==
-                a.bookkeeper.immutablevalue(42))
-        assert (classes[snippet.CSub2].attrs['x'].s_value ==
-                a.bookkeeper.immutablevalue('world'))
-        assert s == a.bookkeeper.immutablevalue(42)
-
-    def test_class_spec(self):
-        a = RPythonAnnotator()
-        s = a.build_types(snippet.class_spec, [])
-        assert s.items[0].knowntype == int
-        assert s.items[1].knowntype == str
-
-    def test_exception_deduction_with_raise1(self):
-        a = RPythonAnnotator()
-        s = a.build_types(snippet.exception_deduction_with_raise1, [bool])
-        assert isinstance(s, annmodel.SomeInstance)
-        assert s.knowntype is snippet.Exc
-
-
-    def test_exception_deduction_with_raise2(self):
-        a = RPythonAnnotator()
-        s = a.build_types(snippet.exception_deduction_with_raise2, [bool])
-        assert isinstance(s, annmodel.SomeInstance)
-        assert s.knowntype is snippet.Exc
-
-    def test_exception_deduction_with_raise3(self):
-        a = RPythonAnnotator()
-        s = a.build_types(snippet.exception_deduction_with_raise3, [bool])
-        assert isinstance(s, annmodel.SomeInstance)
-        assert s.knowntype is snippet.Exc
-
-    def test_type_is(self):
-        class C(object):
-            pass
-        def f(x):
-            if type(x) is C:
-                return x
-            raise Exception
-        a = RPythonAnnotator()
-        s = a.build_types(f, [object])
-        assert s.knowntype is C
-
-    def test_implicit_exc(self):
-        def f(l):
-            try:
-                l[0]
-            except (KeyError, IndexError),e:
-                return e
-            return None
-
-        a = RPythonAnnotator()
-        s = a.build_types(f, [list])
-        assert s.knowntype is LookupError
-
-    def test_overrides(self):
-        import sys
-        excs = []
-        def record_exc(e):
-            """NOT_RPYTHON"""
-            excs.append(sys.exc_info)
-        def g():
-            pass
-        def f():
-            try:
-                g()
-            except Exception, e:
-                record_exc(e)
-        def ann_record_exc(s_e):
-            return a.bookkeeper.immutablevalue(None)
-        a = RPythonAnnotator(overrides={record_exc: ann_record_exc})
-        s = a.build_types(f, [])
-        assert s.const is None
-
-    def test_freeze_protocol(self):
-        class Stuff:
-            def __init__(self, flag):
-                self.called = False
-                self.flag = flag
-            def _freeze_(self):
-                self.called = True
-                return self.flag
-        myobj = Stuff(True)
-        a = RPythonAnnotator()
-        s = a.build_types(lambda: myobj, [])
-        assert myobj.called
-        assert s == annmodel.SomePBC({myobj: True})
-        myobj = Stuff(False)
-        a = RPythonAnnotator()
-        s = a.build_types(lambda: myobj, [])
-        assert myobj.called
-        assert s == annmodel.SomeInstance(a.bookkeeper.getclassdef(Stuff))
-
-    def test_circular_mutable_getattr(self):
-        class C:
-            pass
-        c = C()
-        c.x = c
-        def f():
-            return c.x
-        a = RPythonAnnotator()
-        s = a.build_types(f, [])
-        assert s.knowntype == C
-
-    def DONT_YET_test_circular_list_type(self):
-        def f(n):
-            lst = []
-            for i in range(n):
-                lst = [lst]
-            return lst
-        a = RPythonAnnotator()
-        s = a.build_types(f, [int])
-        assert isinstance(s, annmodel.SomeList)
-        assert s.s_item == s
-
-def g(n):
-    return [0,1,2,n]
-
-def f_calls_g(n):
-    total = 0
-    lst = g(n)
-    i = 0
-    while i < len(lst):
-        total += i
-        i += 1
-    return total



More information about the Pypy-commit mailing list