Commits

Alexander Hesse committed af5aee9

Moved pypy.tool.pairtype and pypy.tool.sourcetools to rpython. Fixed missing rename in bin/rpython

Comments (0)

Files changed (130)

 """
 
 import sys
-from pypy.translator.goal.translate import main
+from rpython.translator.goal.translate import main
 
 # no implicit targets
 if len(sys.argv) == 1:

pypy/config/config.py

 import py
 import optparse
-from pypy.tool.pairtype import extendabletype
+from rpython.tool.pairtype import extendabletype
 
 SUPPRESS_USAGE = optparse.SUPPRESS_USAGE
 

pypy/interpreter/astcompiler/ast.py

 from pypy.interpreter.gateway import interp2app
 from pypy.interpreter.error import OperationError, operationerrfmt
 from rpython.rlib.unroll import unrolling_iterable
-from pypy.tool.pairtype import extendabletype
-from pypy.tool.sourcetools import func_with_new_name
+from rpython.tool.pairtype import extendabletype
+from rpython.tool.sourcetools import func_with_new_name
 
 
 def check_string(space, w_obj):

pypy/interpreter/astcompiler/tools/asdl_py.py

 from pypy.interpreter.gateway import interp2app
 from pypy.interpreter.error import OperationError, operationerrfmt
 from rpython.rlib.unroll import unrolling_iterable
-from pypy.tool.pairtype import extendabletype
-from pypy.tool.sourcetools import func_with_new_name
+from rpython.tool.pairtype import extendabletype
+from rpython.tool.sourcetools import func_with_new_name
 
 
 def check_string(space, w_obj):

pypy/interpreter/gateway.py

 from rpython.rlib import rstackovf
 from rpython.rlib.objectmodel import we_are_translated
 from rpython.rlib.rarithmetic import r_longlong, r_int, r_ulonglong, r_uint
-from pypy.tool.sourcetools import func_with_new_name, compile2
+from rpython.tool.sourcetools import func_with_new_name, compile2
 
 
 # internal non-translatable parts:

pypy/interpreter/pyframe.py

 """ PyFrame class implementation with the interpreter main loop.
 """
 
-from pypy.tool.pairtype import extendabletype
+from rpython.tool.pairtype import extendabletype
 from pypy.interpreter import eval, baseobjspace, pycode
 from pypy.interpreter.argument import Arguments
 from pypy.interpreter.error import OperationError, operationerrfmt

pypy/interpreter/pyopcode.py

 from pypy.interpreter.baseobjspace import Wrappable
 from pypy.interpreter import gateway, function, eval, pyframe, pytraceback
 from pypy.interpreter.pycode import PyCode, BytecodeCorruption
-from pypy.tool.sourcetools import func_with_new_name
+from rpython.tool.sourcetools import func_with_new_name
 from rpython.rlib.objectmodel import we_are_translated
 from rpython.rlib import jit, rstackovf
 from rpython.rlib.rarithmetic import r_uint, intmask

pypy/interpreter/typedef.py

 from pypy.interpreter.argument import Arguments
 from pypy.interpreter.baseobjspace import Wrappable, DescrMismatch
 from pypy.interpreter.error import OperationError, operationerrfmt
-from pypy.tool.sourcetools import compile2, func_with_new_name
+from rpython.tool.sourcetools import compile2, func_with_new_name
 from rpython.rlib.objectmodel import instantiate, compute_identity_hash, specialize
 from rpython.rlib.jit import promote
 

pypy/module/__pypy__/interp_builders.py

 from pypy.interpreter.gateway import interp2app, unwrap_spec
 from pypy.interpreter.typedef import TypeDef
 from rpython.rlib.rstring import UnicodeBuilder, StringBuilder
-from pypy.tool.sourcetools import func_with_new_name
+from rpython.tool.sourcetools import func_with_new_name
 
 
 def create_builder(name, strtype, builder_cls):

pypy/module/_cffi_backend/cdataobj.py

 from rpython.rtyper.lltypesystem import lltype, rffi
 from rpython.rlib.objectmodel import keepalive_until_here, specialize
 from rpython.rlib import objectmodel, rgc
-from pypy.tool.sourcetools import func_with_new_name
+from rpython.tool.sourcetools import func_with_new_name
 
 from pypy.module._cffi_backend import misc
 

pypy/module/_hashlib/interp_hashlib.py

 from pypy.interpreter.gateway import unwrap_spec, interp2app
 from pypy.interpreter.typedef import TypeDef, GetSetProperty
 from pypy.interpreter.error import OperationError
-from pypy.tool.sourcetools import func_renamer
+from rpython.tool.sourcetools import func_renamer
 from pypy.interpreter.baseobjspace import Wrappable
 from rpython.rtyper.lltypesystem import lltype, llmemory, rffi
 from rpython.rlib import rgc, ropenssl

pypy/module/_io/interp_bufferedio.py

 from rpython.rlib.rstring import StringBuilder
 from rpython.rlib.rarithmetic import r_longlong, intmask
 from rpython.rlib import rposix
-from pypy.tool.sourcetools import func_renamer
+from rpython.tool.sourcetools import func_renamer
 from pypy.module._io.interp_iobase import (
     W_IOBase, DEFAULT_BUFFER_SIZE, convert_size,
     check_readable_w, check_writable_w, check_seekable_w)

pypy/module/_rawffi/interp_rawffi.py

 if _MS_WINDOWS:
     from rpython.rlib import rwin32
 
-from pypy.tool.sourcetools import func_with_new_name
+from rpython.tool.sourcetools import func_with_new_name
 from rpython.rlib.rarithmetic import intmask, r_uint
 from pypy.module._rawffi.tracker import tracker
 

pypy/module/clr/boxing_rules.py

-from pypy.tool.pairtype import extendabletype
+from rpython.tool.pairtype import extendabletype
 from pypy.interpreter.baseobjspace import W_Root
 from pypy.objspace.std.intobject import W_IntObject
 from pypy.objspace.std.floatobject import W_FloatObject

pypy/module/cmath/interp_cmath.py

 import math
 from rpython.rlib.objectmodel import specialize
-from pypy.tool.sourcetools import func_with_new_name
+from rpython.tool.sourcetools import func_with_new_name
 from pypy.interpreter.error import OperationError
 from pypy.module.cmath import names_and_docstrings
 from rpython.rlib import rcomplex

pypy/module/cpyext/api.py

 from pypy.module.exceptions import interp_exceptions
 # CPython 2.4 compatibility
 from py.builtin import BaseException
-from pypy.tool.sourcetools import func_with_new_name
+from rpython.tool.sourcetools import func_with_new_name
 from rpython.rtyper.lltypesystem.lloperation import llop
 
 DEBUG_WRAPPER = True

pypy/module/cpyext/cdatetime.py

 from pypy.module.cpyext.import_ import PyImport_Import
 from pypy.module.cpyext.typeobject import PyTypeObjectPtr
 from pypy.interpreter.error import OperationError
-from pypy.tool.sourcetools import func_renamer
+from rpython.tool.sourcetools import func_renamer
 
 # API import function
 

pypy/module/cpyext/number.py

 from pypy.module.cpyext.api import cpython_api, CANNOT_FAIL, Py_ssize_t
 from pypy.module.cpyext.pyobject import PyObject
 from rpython.rtyper.lltypesystem import rffi, lltype
-from pypy.tool.sourcetools import func_with_new_name
+from rpython.tool.sourcetools import func_with_new_name
 
 @cpython_api([PyObject], rffi.INT_real, error=CANNOT_FAIL)
 def PyIndex_Check(space, w_obj):

pypy/module/cpyext/slotdefs.py

 from pypy.interpreter.argument import Arguments
 from rpython.rlib.unroll import unrolling_iterable
 from rpython.rlib.objectmodel import specialize
-from pypy.tool.sourcetools import func_renamer
+from rpython.tool.sourcetools import func_renamer
 from rpython.rtyper.annlowlevel import llhelper
 
 # XXX: Also defined in object.h

pypy/module/cpyext/unicodeobject.py

 from pypy.module._codecs.interp_codecs import CodecState
 from pypy.objspace.std import unicodeobject, unicodetype, stringtype
 from rpython.rlib import runicode
-from pypy.tool.sourcetools import func_renamer
+from rpython.tool.sourcetools import func_renamer
 import sys
 
 ## See comment in stringobject.py.

pypy/module/micronumpy/base.py

 
 from pypy.interpreter.baseobjspace import Wrappable
-from pypy.tool.pairtype import extendabletype
+from rpython.tool.pairtype import extendabletype
 from pypy.module.micronumpy.support import calc_strides
 
 def issequence_w(space, w_obj):

pypy/module/micronumpy/interp_boxes.py

 from pypy.objspace.std.complextype import complex_typedef
 from rpython.rlib.rarithmetic import LONG_BIT
 from rpython.rtyper.lltypesystem import rffi
-from pypy.tool.sourcetools import func_with_new_name
+from rpython.tool.sourcetools import func_with_new_name
 from pypy.module.micronumpy.arrayimpl.voidbox import VoidBoxStorage
 
 MIXIN_32 = (int_typedef,) if LONG_BIT == 32 else ()

pypy/module/micronumpy/interp_numarray.py

 from pypy.module.micronumpy import loop
 from pypy.module.micronumpy.dot import match_dot_shapes
 from pypy.module.micronumpy.interp_arrayops import repeat
-from pypy.tool.sourcetools import func_with_new_name
+from rpython.tool.sourcetools import func_with_new_name
 from rpython.rlib import jit
 from rpython.rlib.rstring import StringBuilder
 

pypy/module/micronumpy/interp_ufuncs.py

 from pypy.module.micronumpy import interp_boxes, interp_dtype, loop
 from rpython.rlib import jit
 from rpython.rlib.rarithmetic import LONG_BIT
-from pypy.tool.sourcetools import func_with_new_name
+from rpython.tool.sourcetools import func_with_new_name
 from pypy.module.micronumpy.interp_support import unwrap_axis_arg
 from pypy.module.micronumpy.strides import shape_agreement
 from pypy.module.micronumpy.base import convert_to_array, W_NDimArray

pypy/module/micronumpy/types.py

 from rpython.rlib.rstruct.nativefmttable import native_is_bigendian
 from rpython.rlib.rstruct.ieee import (float_pack, float_unpack, 
                                     unpack_float, unpack_float128)
-from pypy.tool.sourcetools import func_with_new_name
+from rpython.tool.sourcetools import func_with_new_name
 from rpython.rlib import jit
 from rpython.rlib.rstring import StringBuilder
 

pypy/module/pypyjit/interp_jit.py

 This is transformed to become a JIT by code elsewhere: pypy/jit/*
 """
 
-from pypy.tool.pairtype import extendabletype
+from rpython.tool.pairtype import extendabletype
 from rpython.rlib.rarithmetic import r_uint, intmask
 from rpython.rlib.jit import JitDriver, hint, we_are_jitted, dont_look_inside
 from rpython.rlib import jit

pypy/objspace/descroperation.py

 from pypy.interpreter.function import Function, Method, FunctionWithFixedCode
 from pypy.interpreter.argument import Arguments
 from pypy.interpreter.typedef import default_identity_hash
-from pypy.tool.sourcetools import compile2, func_with_new_name
+from rpython.tool.sourcetools import compile2, func_with_new_name
 from pypy.module.__builtin__.interp_classobj import W_InstanceObject
 from rpython.rlib.objectmodel import specialize
 

pypy/objspace/fake/objspace.py

 from rpython.rtyper.extregistry import ExtRegistryEntry
 from rpython.rtyper.lltypesystem import lltype
 from pypy.tool.option import make_config
-from pypy.tool.sourcetools import compile2, func_with_new_name
+from rpython.tool.sourcetools import compile2, func_with_new_name
 from rpython.translator.translator import TranslationContext
 
 

pypy/objspace/std/builtinshortcut.py

 from pypy.objspace.descroperation import DescrOperation
 from pypy.objspace.std.multimethod import FailedToImplement
 from pypy.objspace.std.boolobject import W_BoolObject
-from pypy.tool.sourcetools import func_with_new_name
+from rpython.tool.sourcetools import func_with_new_name
 
 # ____________________________________________________________
 #

pypy/objspace/std/bytearrayobject.py

     makebytearraydata_w, getbytevalue,
     new_bytearray
 )
-from pypy.tool.sourcetools import func_with_new_name
+from rpython.tool.sourcetools import func_with_new_name
 
 
 class W_BytearrayObject(W_Object):

pypy/objspace/std/dictmultiobject.py

 from rpython.rlib.objectmodel import r_dict, we_are_translated, specialize,\
      newlist_hint
 from rpython.rlib.debug import mark_dict_non_null
-from pypy.tool.sourcetools import func_with_new_name
+from rpython.tool.sourcetools import func_with_new_name
 
 from rpython.rlib import rerased
 from rpython.rlib import jit

pypy/objspace/std/floatobject.py

     DTSF_ADD_DOT_0, DTSF_STR_PRECISION)
 from rpython.rlib.rbigint import rbigint
 from rpython.rlib import rfloat
-from pypy.tool.sourcetools import func_with_new_name
+from rpython.tool.sourcetools import func_with_new_name
 
 
 import math

pypy/objspace/std/formatting.py

 from rpython.rlib.rfloat import formatd, DTSF_ALT, isnan, isinf
 from rpython.rlib.rstring import StringBuilder, UnicodeBuilder
 from rpython.rlib.unroll import unrolling_iterable
-from pypy.tool.sourcetools import func_with_new_name
+from rpython.tool.sourcetools import func_with_new_name
 
 
 class BaseStringFormatter(object):

pypy/objspace/std/intobject.py

 
 def declare_new_int_comparison(opname):
     import operator
-    from pypy.tool.sourcetools import func_with_new_name
+    from rpython.tool.sourcetools import func_with_new_name
     op = getattr(operator, opname)
     def f(space, w_int1, w_int2):
         i = w_int1.intval

pypy/objspace/std/listobject.py

 from rpython.rlib.listsort import make_timsort_class
 from rpython.rlib import rerased, jit, debug
 from pypy.interpreter.argument import Signature
-from pypy.tool.sourcetools import func_with_new_name
+from rpython.tool.sourcetools import func_with_new_name
 
 UNROLL_CUTOFF = 5
 

pypy/objspace/std/multimethod.py

 
-from pypy.tool.sourcetools import compile2
+from rpython.tool.sourcetools import compile2
 
 # This provide two compatible implementations of "multimethods".  A
 # multimethod is a callable object which chooses and calls a real

pypy/objspace/std/proxy_helpers.py

 from pypy.objspace.std.model import W_ANY, W_Object
 from pypy.interpreter import baseobjspace
 from pypy.interpreter.argument import Arguments
-from pypy.tool.sourcetools import func_with_new_name
+from rpython.tool.sourcetools import func_with_new_name
 
 def create_mm_names(classname, mm, is_local):
     s = ""

pypy/objspace/std/smallintobject.py

 from rpython.rlib.objectmodel import UnboxedValue
 from rpython.rlib.rbigint import rbigint
 from rpython.rlib.rarithmetic import r_uint
-from pypy.tool.sourcetools import func_with_new_name
+from rpython.tool.sourcetools import func_with_new_name
 from pypy.objspace.std.inttype import wrapint
 
 class W_SmallIntObject(W_AbstractIntObject, UnboxedValue):

pypy/objspace/std/smalltupleobject.py

 from pypy.interpreter import gateway
 from rpython.rlib.debug import make_sure_not_resized
 from rpython.rlib.unroll import unrolling_iterable
-from pypy.tool.sourcetools import func_with_new_name
+from rpython.tool.sourcetools import func_with_new_name
 from pypy.objspace.std.tupleobject import W_AbstractTupleObject, W_TupleObject
 
 class W_SmallTupleObject(W_AbstractTupleObject):

pypy/objspace/std/specialisedtupleobject.py

 from rpython.rlib.rarithmetic import intmask
 from rpython.rlib.objectmodel import compute_hash
 from rpython.rlib.unroll import unrolling_iterable
-from pypy.tool.sourcetools import func_with_new_name
+from rpython.tool.sourcetools import func_with_new_name
 
 class NotSpecialised(Exception):
     pass

pypy/objspace/std/stdtypedef.py

 from pypy.objspace.std.model import StdObjSpaceMultiMethod
 from pypy.objspace.std.multimethod import FailedToImplement
 from rpython.rlib import jit
-from pypy.tool.sourcetools import compile2
+from rpython.tool.sourcetools import compile2
 
 __all__ = ['StdTypeDef', 'SMM']
 

pypy/objspace/std/stringobject.py

     return space.newlist(res_w)
 
 def make_rsplit_with_delim(funcname, sliced):
-    from pypy.tool.sourcetools import func_with_new_name
+    from rpython.tool.sourcetools import func_with_new_name
 
     def fn(space, w_self, w_by, w_maxsplit=-1):
         maxsplit = space.int_w(w_maxsplit)

pypy/objspace/std/tupleobject.py

 from pypy.objspace.std import slicetype
 from rpython.rlib.debug import make_sure_not_resized
 from rpython.rlib import jit
-from pypy.tool.sourcetools import func_with_new_name
+from rpython.tool.sourcetools import func_with_new_name
 
 # Tuples of known length up to UNROLL_TUPLE_LIMIT have unrolled certain methods
 UNROLL_TUPLE_LIMIT = 10

pypy/objspace/std/unicodeobject.py

 from rpython.rlib.rstring import UnicodeBuilder
 from rpython.rlib.runicode import make_unicode_escape_function
 from pypy.module.unicodedata import unicodedb
-from pypy.tool.sourcetools import func_with_new_name
+from rpython.tool.sourcetools import func_with_new_name
 from rpython.rlib import jit
 
 from pypy.objspace.std.formatting import mod_format

pypy/tool/frozenlist.py

-from pypy.tool.sourcetools import func_with_new_name
+from rpython.tool.sourcetools import func_with_new_name
 
 def forbid(*args):
     raise TypeError, "cannot mutate a frozenlist"

pypy/tool/pairtype.py

-"""
-Two magic tricks for classes:
-
-    class X:
-        __metaclass__ = extendabletype
-        ...
-
-    # in some other file...
-    class __extend__(X):
-        ...      # and here you can add new methods and class attributes to X
-
-Mostly useful together with the second trick, which lets you build
-methods whose 'self' is a pair of objects instead of just one:
-
-    class __extend__(pairtype(X, Y)):
-        attribute = 42
-        def method((x, y), other, arguments):
-            ...
-
-    pair(x, y).attribute
-    pair(x, y).method(other, arguments)
-
-This finds methods and class attributes based on the actual
-class of both objects that go into the pair(), with the usual
-rules of method/attribute overriding in (pairs of) subclasses.
-
-For more information, see test_pairtype.
-"""
-
-class extendabletype(type):
-    """A type with a syntax trick: 'class __extend__(t)' actually extends
-    the definition of 't' instead of creating a new subclass."""
-    def __new__(cls, name, bases, dict):
-        if name == '__extend__':
-            for cls in bases:
-                for key, value in dict.items():
-                    if key == '__module__':
-                        continue
-                    # XXX do we need to provide something more for pickling?
-                    setattr(cls, key, value)
-            return None
-        else:
-            return super(extendabletype, cls).__new__(cls, name, bases, dict)
-
-
-def pair(a, b):
-    """Return a pair object."""
-    tp = pairtype(a.__class__, b.__class__)
-    return tp((a, b))   # tp is a subclass of tuple
-
-pairtypecache = {}
-
-def pairtype(cls1, cls2):
-    """type(pair(a,b)) is pairtype(a.__class__, b.__class__)."""
-    try:
-        pair = pairtypecache[cls1, cls2]
-    except KeyError:
-        name = 'pairtype(%s, %s)' % (cls1.__name__, cls2.__name__)
-        bases1 = [pairtype(base1, cls2) for base1 in cls1.__bases__]
-        bases2 = [pairtype(cls1, base2) for base2 in cls2.__bases__]
-        bases = tuple(bases1 + bases2) or (tuple,)  # 'tuple': ultimate base
-        pair = pairtypecache[cls1, cls2] = extendabletype(name, bases, {})
-    return pair

pypy/tool/sourcetools.py

-# a couple of support functions which
-# help with generating Python source.
-
-# XXX This module provides a similar, but subtly different, functionality
-# XXX several times over, which used to be scattered over four modules.
-# XXX We should try to generalize and single out one approach to dynamic
-# XXX code compilation.
-
-import sys, os, inspect, new
-import autopath, py
-
-def render_docstr(func, indent_str='', closing_str=''):
-    """ Render a docstring as a string of lines.
-        The argument is either a docstring or an object.
-        Note that we don't use a sequence, since we want
-        the docstring to line up left, regardless of
-        indentation. The shorter triple quotes are
-        choosen automatically.
-        The result is returned as a 1-tuple."""
-    if not isinstance(func, str):
-        doc = func.__doc__
-    else:
-        doc = func
-    if doc is None:
-        return None
-    doc = doc.replace('\\', r'\\')
-    compare = []
-    for q in '"""', "'''":
-        txt = indent_str + q + doc.replace(q[0], "\\"+q[0]) + q + closing_str
-        compare.append(txt)
-    doc, doc2 = compare
-    doc = (doc, doc2)[len(doc2) < len(doc)]
-    return doc
-
-
-class NiceCompile(object):
-    """ Compiling parameterized strings in a way that debuggers
-        are happy. We provide correct line numbers and a real
-        __file__ attribute.
-    """
-    def __init__(self, namespace_or_filename):
-        if type(namespace_or_filename) is str:
-            srcname = namespace_or_filename
-        else:
-            srcname = namespace_or_filename.get('__file__')
-        if not srcname:
-            # assume the module was executed from the
-            # command line.
-            srcname = os.path.abspath(sys.argv[-1])
-        self.srcname = srcname
-        if srcname.endswith('.pyc') or srcname.endswith('.pyo'):
-            srcname = srcname[:-1]
-        if os.path.exists(srcname):
-            self.srcname = srcname
-            self.srctext = file(srcname).read()
-        else:
-            # missing source, what to do?
-            self.srctext = None
-
-    def __call__(self, src, args=None):
-        """ instance NiceCompile (src, args) -- formats src with args
-            and returns a code object ready for exec. Instead of <string>,
-            the code object has correct co_filename and line numbers.
-            Indentation is automatically corrected.
-        """
-        if self.srctext:
-            try:
-                p = self.srctext.index(src)
-            except ValueError:
-                msg = "Source text not found in %s - use a raw string" % self.srcname
-                raise ValueError(msg)
-            prelines = self.srctext[:p].count("\n") + 1
-        else:
-            prelines = 0
-        # adjust indented def
-        for line in src.split('\n'):
-            content = line.strip()
-            if content and not content.startswith('#'):
-                break
-        # see if first line is indented
-        if line and line[0].isspace():
-            # fake a block
-            prelines -= 1
-            src = 'if 1:\n' + src
-        if args is not None:
-            src = '\n' * prelines + src % args
-        else:
-            src = '\n' * prelines + src
-        c = compile(src, self.srcname, "exec")
-        # preserve the arguments of the code in an attribute
-        # of the code's co_filename
-        if self.srcname:
-            srcname = MyStr(self.srcname)
-            if args is not None:
-                srcname.__sourceargs__ = args
-            c = newcode_withfilename(c, srcname)
-        return c
-
-def getsource(object):
-    """ similar to inspect.getsource, but trying to
-    find the parameters of formatting generated methods and
-    functions.
-    """
-    name = inspect.getfile(object)
-    if hasattr(name, '__source__'):
-        src = str(name.__source__)
-    else:
-        try:
-            src = inspect.getsource(object)
-        except Exception:   # catch IOError, IndentationError, and also rarely
-            return None     # some other exceptions like IndexError
-    if hasattr(name, "__sourceargs__"):
-        return src % name.__sourceargs__
-    return src
-
-## the following is stolen from py.code.source.py for now.
-## XXX discuss whether and how to put this functionality
-## into py.code.source.
-#
-# various helper functions
-#
-class MyStr(str):
-    """ custom string which allows adding attributes. """
-
-def newcode(fromcode, **kwargs):
-    names = [x for x in dir(fromcode) if x[:3] == 'co_']
-    for name in names:
-        if name not in kwargs:
-            kwargs[name] = getattr(fromcode, name)
-    return new.code(
-             kwargs['co_argcount'],
-             kwargs['co_nlocals'],
-             kwargs['co_stacksize'],
-             kwargs['co_flags'],
-             kwargs['co_code'],
-             kwargs['co_consts'],
-             kwargs['co_names'],
-             kwargs['co_varnames'],
-             kwargs['co_filename'],
-             kwargs['co_name'],
-             kwargs['co_firstlineno'],
-             kwargs['co_lnotab'],
-             kwargs['co_freevars'],
-             kwargs['co_cellvars'],
-    )
-
-def newcode_withfilename(co, co_filename):
-    newconstlist = []
-    cotype = type(co)
-    for c in co.co_consts:
-        if isinstance(c, cotype):
-            c = newcode_withfilename(c, co_filename)
-        newconstlist.append(c)
-    return newcode(co, co_consts = tuple(newconstlist),
-                       co_filename = co_filename)
-
-# ____________________________________________________________
-
-import __future__
-
-def compile2(source, filename='', mode='exec', flags=
-             __future__.generators.compiler_flag, dont_inherit=0):
-    """
-    A version of compile() that caches the code objects it returns.
-    It uses py.code.compile() to allow the source to be displayed in tracebacks.
-    """
-    key = (source, filename, mode, flags)
-    try:
-        co = compile2_cache[key]
-        #print "***** duplicate code ******* "
-        #print source 
-    except KeyError: 
-        #if DEBUG: 
-        co = py.code.compile(source, filename, mode, flags) 
-        #else: 
-        #    co = compile(source, filename, mode, flags) 
-        compile2_cache[key] = co 
-    return co 
-
-compile2_cache = {}
-
-# ____________________________________________________________
-
-def compile_template(source, resultname):
-    """Compiles the source code (a string or a list/generator of lines)
-    which should be a definition for a function named 'resultname'.
-    The caller's global dict and local variable bindings are captured.
-    """
-    if not isinstance(source, py.code.Source):
-        if isinstance(source, str):
-            lines = [source]
-        else:
-            lines = list(source)
-        lines.append('')
-        source = py.code.Source('\n'.join(lines))
-
-    caller = sys._getframe(1)
-    locals = caller.f_locals
-    if locals is caller.f_globals:
-        localnames = []
-    else:
-        localnames = locals.keys()
-        localnames.sort()
-    values = [locals[key] for key in localnames]
-    
-    source = source.putaround(
-        before = "def container(%s):" % (', '.join(localnames),),
-        after  = "# no unindent\n    return %s" % resultname)
-
-    d = {}
-    exec source.compile() in caller.f_globals, d
-    container = d['container']
-    return container(*values)
-
-# ____________________________________________________________
-
-def func_with_new_name(func, newname, globals=None):
-    """Make a renamed copy of a function."""
-    if globals is None:
-        globals = func.func_globals
-    f = new.function(func.func_code, globals,
-                        newname, func.func_defaults,
-                        func.func_closure)
-    if func.func_dict:
-        f.func_dict = {}
-        f.func_dict.update(func.func_dict)
-    f.func_doc = func.func_doc
-    return f
-
-def func_renamer(newname):
-    """A function decorator which changes the name of a function."""
-    def decorate(func):
-        return func_with_new_name(func, newname)
-    return decorate
-
-PY_IDENTIFIER = ''.join([(('0' <= chr(i) <= '9' or
-                           'a' <= chr(i) <= 'z' or
-                           'A' <= chr(i) <= 'Z') and chr(i) or '_')
-                         for i in range(256)])
-PY_IDENTIFIER_MAX = 120
-
-def valid_identifier(stuff):
-    stuff = str(stuff).translate(PY_IDENTIFIER)
-    if not stuff or ('0' <= stuff[0] <= '9'):
-        stuff = '_' + stuff
-    return stuff[:PY_IDENTIFIER_MAX]
-
-CO_VARARGS      = 0x0004
-CO_VARKEYWORDS  = 0x0008
-
-def has_varargs(func):
-    func = getattr(func, 'func_code', func)
-    return (func.co_flags & CO_VARARGS) != 0
-
-def has_varkeywords(func):
-    func = getattr(func, 'func_code', func)
-    return (func.co_flags & CO_VARKEYWORDS) != 0
-
-def nice_repr_for_func(fn, name=None):
-    mod = getattr(fn, '__module__', None)
-    if name is None:
-        name = getattr(fn, '__name__', None)
-        cls = getattr(fn, 'class_', None)
-        if name is not None and cls is not None:
-            name = "%s.%s" % (cls.__name__, name)
-    try:
-        firstlineno = fn.func_code.co_firstlineno
-    except AttributeError:
-        firstlineno = -1
-    return "(%s:%d)%s" % (mod or '?', firstlineno, name or 'UNKNOWN')
-
-
-def rpython_wrapper(f, template, templateargs=None, **globaldict):
-    """  
-    We cannot simply wrap the function using *args, **kwds, because it's not
-    RPython. Instead, we generate a function from ``template`` with exactly
-    the same argument list.
-    """
-    if templateargs is None:
-        templateargs = {}
-    srcargs, srcvarargs, srckeywords, defaults = inspect.getargspec(f)
-    assert not srcvarargs, '*args not supported by enforceargs'
-    assert not srckeywords, '**kwargs not supported by enforceargs'
-    #
-    arglist = ', '.join(srcargs)
-    templateargs.update(name=f.func_name,
-                        arglist=arglist,
-                        original=f.func_name+'_original')
-    src = template.format(**templateargs)
-    src = py.code.Source(src)
-    #
-    globaldict[f.func_name + '_original'] = f
-    exec src.compile() in globaldict
-    result = globaldict[f.func_name]
-    result.func_defaults = f.func_defaults
-    result.func_dict.update(f.func_dict)
-    return result

pypy/tool/test/test_pairtype.py

 
-from pypy.tool.pairtype import pairtype, pair, extendabletype
+from rpython.tool.pairtype import pairtype, pair, extendabletype
 
 def test_binop(): 
     ### Binary operation example

pypy/tool/test/test_sourcetools.py

-from pypy.tool.sourcetools import func_with_new_name, func_renamer, rpython_wrapper
+from rpython.tool.sourcetools import func_with_new_name, func_renamer, rpython_wrapper
 
 def test_rename():
     def f(x, y=5):

pypy/tool/test/test_template.py

 import autopath
-from pypy.tool.sourcetools import compile_template
+from rpython.tool.sourcetools import compile_template
 
 
 some_global = 5

rpython/annotator/annrpython.py

 
 import types
 from pypy.tool.ansi_print import ansi_log
-from pypy.tool.pairtype import pair
+from rpython.tool.pairtype import pair
 from pypy.tool.error import (format_blocked_annotation_error,
                              AnnotatorError, gather_error, ErrorWrapper)
 from rpython.flowspace.model import (Variable, Constant, FunctionGraph,

rpython/annotator/binaryop.py

 
 import py
 import operator
-from pypy.tool.pairtype import pair, pairtype
+from rpython.tool.pairtype import pair, pairtype
 from rpython.annotator.model import SomeObject, SomeInteger, SomeBool, s_Bool
 from rpython.annotator.model import SomeString, SomeChar, SomeList, SomeDict
 from rpython.annotator.model import SomeUnicodeCodePoint, SomeUnicodeString

rpython/annotator/description.py

 from rpython.flowspace.model import Constant, FunctionGraph
 from rpython.flowspace.bytecode import cpython_code_signature
 from rpython.flowspace.argument import rawshape, ArgErr
-from pypy.tool.sourcetools import valid_identifier
-from pypy.tool.pairtype import extendabletype
+from rpython.tool.sourcetools import valid_identifier
+from rpython.tool.pairtype import extendabletype
 
 class CallFamily(object):
     """A family of Desc objects that could be called from common call sites.

rpython/annotator/model.py

 from types import BuiltinFunctionType, MethodType, FunctionType
 import pypy
 from pypy.tool import descriptor
-from pypy.tool.pairtype import pair, extendabletype
+from rpython.tool.pairtype import pair, extendabletype
 from rpython.rlib.rarithmetic import r_uint, r_ulonglong, base_int
 from rpython.rlib.rarithmetic import r_singlefloat, r_longfloat
 import inspect, weakref

rpython/annotator/specialize.py

 # specialization support
 import py
 from pypy.tool.uid import uid
-from pypy.tool.sourcetools import func_with_new_name
+from rpython.tool.sourcetools import func_with_new_name
 from pypy.tool.algo.unionfind import UnionFind
 from rpython.flowspace.model import Block, Link, Variable, SpaceOperation
 from rpython.flowspace.model import Constant, checkgraph

rpython/flowspace/generator.py

 from rpython.translator.unsimplify import insert_empty_startblock
 from rpython.translator.unsimplify import split_block
 from rpython.translator.simplify import eliminate_empty_blocks, simplify_graph
-from pypy.tool.sourcetools import func_with_new_name
+from rpython.tool.sourcetools import func_with_new_name
 from rpython.flowspace.argument import Signature
 
 

rpython/flowspace/model.py

 # a discussion in Berlin, 4th of october 2003
 import py
 from pypy.tool.uid import uid, Hashable
-from pypy.tool.sourcetools import PY_IDENTIFIER, nice_repr_for_func
+from rpython.tool.sourcetools import PY_IDENTIFIER, nice_repr_for_func
 from rpython.rlib.rarithmetic import is_valid_int, r_longlong, r_ulonglong, r_uint
 
 
     def source(self):
         if hasattr(self, "_source"):
             return self._source
-        from pypy.tool.sourcetools import getsource
+        from rpython.tool.sourcetools import getsource
         self.func    # can raise AttributeError
         src = getsource(self.func)
         if src is None:

rpython/flowspace/operation.py

 import __builtin__
 import __future__
 import operator
-from pypy.tool.sourcetools import compile2
+from rpython.tool.sourcetools import compile2
 from rpython.rlib.rarithmetic import ovfcheck
 
 # this is a copy that should be shared with standard objspace

rpython/jit/backend/cli/method.py

 import py
 import os
 from rpython.rlib.debug import debug_start, debug_stop
-from pypy.tool.pairtype import extendabletype
+from rpython.tool.pairtype import extendabletype
 from rpython.rtyper.ootypesystem import ootype
 from rpython.translator.cli import dotnet
 from rpython.translator.cli.dotnet import CLR

rpython/jit/backend/cli/runner.py

-from pypy.tool.pairtype import extendabletype
+from rpython.tool.pairtype import extendabletype
 from rpython.rtyper.ootypesystem import ootype
 from rpython.rlib.objectmodel import we_are_translated
 from rpython.jit.metainterp import history

rpython/jit/backend/x86/jump.py

 import sys
-from pypy.tool.pairtype import extendabletype
+from rpython.tool.pairtype import extendabletype
 from rpython.jit.backend.x86.regloc import ImmediateAssemblerLocation, StackLoc
 
 def remap_frame_layout(assembler, src_locations, dst_locations, tmpreg):

rpython/jit/backend/x86/regloc.py

 from rpython.jit.backend.x86 import rx86
 from rpython.rlib.unroll import unrolling_iterable
 from rpython.jit.backend.x86.arch import WORD, IS_X86_32, IS_X86_64
-from pypy.tool.sourcetools import func_with_new_name
+from rpython.tool.sourcetools import func_with_new_name
 from rpython.rlib.objectmodel import specialize, instantiate
 from rpython.rlib.rarithmetic import intmask
 from rpython.jit.metainterp.history import FLOAT

rpython/jit/metainterp/compile.py

 from rpython.rlib import rstack
 from rpython.rlib.jit import JitDebugInfo, Counters
 from pypy.conftest import option
-from pypy.tool.sourcetools import func_with_new_name
+from rpython.tool.sourcetools import func_with_new_name
 
 from rpython.jit.metainterp.resoperation import ResOperation, rop, get_deep_immutable_oplist
 from rpython.jit.metainterp.history import TreeLoop, Box, History, JitCellToken, TargetToken

rpython/jit/metainterp/optimizeopt/optimizer.py

 from rpython.jit.metainterp.optimizeopt.util import make_dispatcher_method
 from rpython.jit.metainterp.resoperation import rop, ResOperation, AbstractResOp
 from rpython.jit.metainterp.typesystem import llhelper, oohelper
-from pypy.tool.pairtype import extendabletype
+from rpython.tool.pairtype import extendabletype
 from rpython.rlib.debug import debug_print
 from rpython.rlib.objectmodel import specialize
 

rpython/jit/metainterp/warmspot.py

 import sys, py
-from pypy.tool.sourcetools import func_with_new_name
+from rpython.tool.sourcetools import func_with_new_name
 from rpython.rtyper.lltypesystem import lltype, llmemory
 from rpython.rtyper.annlowlevel import llhelper, MixLevelHelperAnnotator,\
      cast_base_ptr_to_instance, hlstr

rpython/jit/metainterp/warmstate.py

 from rpython.rlib.debug import debug_start, debug_stop, debug_print
 from rpython.jit.metainterp import history
 from rpython.jit.codewriter import support, heaptracker, longlong
-from pypy.tool.sourcetools import func_with_new_name
+from rpython.tool.sourcetools import func_with_new_name
 
 # ____________________________________________________________
 

rpython/rlib/_jit_vref.py

 from rpython.annotator import model as annmodel
-from pypy.tool.pairtype import pairtype
+from rpython.tool.pairtype import pairtype
 from rpython.rtyper.extregistry import ExtRegistryEntry
 from rpython.rtyper.rclass import getinstancerepr
 from rpython.rtyper.rmodel import Repr

rpython/rlib/jit.py

 from rpython.rlib.objectmodel import CDefinedIntSymbolic, keepalive_until_here, specialize
 from rpython.rlib.unroll import unrolling_iterable
 from rpython.rtyper.extregistry import ExtRegistryEntry
-from pypy.tool.sourcetools import rpython_wrapper
+from rpython.tool.sourcetools import rpython_wrapper
 
 DEBUG_ELIDABLE_FUNCTIONS = False
 

rpython/rlib/objectmodel.py

 import types
 import math
 import inspect
-from pypy.tool.sourcetools import rpython_wrapper
+from rpython.tool.sourcetools import rpython_wrapper
 
 # specialize is a decorator factory for attaching _annspecialcase_
 # attributes to functions: for example

rpython/rlib/parsing/parsing.py

         self.made = {}
 
     def compile(self):
-        from pypy.tool.sourcetools import func_with_new_name
+        from rpython.tool.sourcetools import func_with_new_name
         self.allcode.append("class CompileableParser(baseclass):")
         self.make_matcher(self.parser.startsymbol)
         self.make_fixed()

rpython/rlib/rerased.py

 
 import sys
 from rpython.annotator import model as annmodel
-from pypy.tool.pairtype import pairtype
+from rpython.tool.pairtype import pairtype
 from rpython.rtyper.extregistry import ExtRegistryEntry
 from rpython.rtyper.rclass import getinstancerepr
 from rpython.rtyper.rmodel import Repr

rpython/rlib/rmarshal.py

 from rpython.annotator import model as annmodel
 from rpython.annotator.signature import annotation
 from rpython.annotator.listdef import ListDef, TooLateForChange
-from pypy.tool.pairtype import pair, pairtype
+from rpython.tool.pairtype import pair, pairtype
 from rpython.rlib.rarithmetic import r_longlong, intmask, LONG_BIT
 from rpython.rlib.rfloat import formatd, rstring_to_float
 from rpython.rlib.unroll import unrolling_iterable

rpython/rlib/rsre/rsre_core.py

 from rpython.rlib.debug import check_nonneg
 from rpython.rlib.unroll import unrolling_iterable
 from rpython.rlib.rsre import rsre_char
-from pypy.tool.sourcetools import func_with_new_name
+from rpython.tool.sourcetools import func_with_new_name
 from rpython.rlib.objectmodel import we_are_translated
 from rpython.rlib import jit
 from rpython.rlib.rsre.rsre_jit import install_jitdriver, install_jitdriver_spec

rpython/rlib/rstring.py

 from rpython.annotator.model import (SomeObject, SomeString, s_None, SomeChar,
     SomeInteger, SomeUnicodeCodePoint, SomeUnicodeString, SomePtr, SomePBC)
 from rpython.rlib.rarithmetic import ovfcheck
-from pypy.tool.pairtype import pair, pairtype
+from rpython.tool.pairtype import pair, pairtype
 from rpython.rtyper.extregistry import ExtRegistryEntry
 
 

rpython/rlib/rweakref.py

 from rpython.rtyper import extregistry
 from rpython.annotator import model as annmodel
 from rpython.annotator.bookkeeper import getbookkeeper
-from pypy.tool.pairtype import pairtype
+from rpython.tool.pairtype import pairtype
 
 class Entry(extregistry.ExtRegistryEntry):
     _about_ = has_weakref_support

rpython/rtyper/annlowlevel.py

 """
 
 import types
-from pypy.tool.sourcetools import valid_identifier
+from rpython.tool.sourcetools import valid_identifier
 from rpython.annotator import model as annmodel
 from rpython.annotator.policy import AnnotatorPolicy, Sig
 from rpython.annotator.specialize import flatten_star_args

rpython/rtyper/controllerentry.py

 from rpython.annotator import model as annmodel
-from pypy.tool.pairtype import pairtype
+from rpython.tool.pairtype import pairtype
 from rpython.annotator.binaryop import _make_none_union, SomePBC # SomePBC needed by _make_none_union
 from rpython.annotator.bookkeeper import getbookkeeper
 from rpython.rtyper.extregistry import ExtRegistryEntry

rpython/rtyper/extfunc.py

             if hasattr(self, fake_method_name):
                 # If we have both an {ll,oo}impl and a {ll,oo}fakeimpl,
                 # we need a wrapper that selects the proper one and calls it
-                from pypy.tool.sourcetools import func_with_new_name
+                from rpython.tool.sourcetools import func_with_new_name
                 # Using '*args' is delicate because this wrapper is also
                 # created for init-time functions like llarena.arena_malloc
                 # which are called before the GC is fully initialized

rpython/rtyper/extfuncregistry.py

 # ___________________________
 # os.path functions
 
-from pypy.tool.sourcetools import func_with_new_name
+from rpython.tool.sourcetools import func_with_new_name
 import os.path
 
 # os.path.join is RPython, but we don't want to compile it directly

rpython/rtyper/lltypesystem/module/ll_math.py

 import sys
 
 from rpython.rtyper.lltypesystem import lltype, rffi
-from pypy.tool.sourcetools import func_with_new_name
+from rpython.tool.sourcetools import func_with_new_name
 from pypy.tool.autopath import pypydir
 from rpython.rlib import jit, rposix
 from rpython.translator.tool.cbuild import ExternalCompilationInfo

rpython/rtyper/lltypesystem/opimpl.py

 from rpython.rlib import debug
 from rpython.rlib.rarithmetic import is_valid_int
 from rpython.rtyper.lltypesystem import lltype, llmemory
-from pypy.tool.sourcetools import func_with_new_name
+from rpython.tool.sourcetools import func_with_new_name
 
 # ____________________________________________________________
 # Implementation of the 'canfold' operations

rpython/rtyper/lltypesystem/rbuilder.py

 from rpython.rtyper.lltypesystem.rstr import (STR, UNICODE, char_repr,
     string_repr, unichar_repr, unicode_repr)
 from rpython.rtyper.rbuilder import AbstractStringBuilderRepr
-from pypy.tool.sourcetools import func_with_new_name
+from rpython.tool.sourcetools import func_with_new_name
 
 # Think about heuristics below, maybe we can come up with something
 # better or at least compare it with list heuristics

rpython/rtyper/lltypesystem/rclass.py

 import sys
 import types
-from pypy.tool.pairtype import pairtype, pair
+from rpython.tool.pairtype import pairtype, pair
 from rpython.flowspace.model import Constant
 from rpython.rtyper.error import TyperError
 from rpython.rtyper.rmodel import Repr, inputconst, warning, mangle

rpython/rtyper/lltypesystem/rdict.py

-from pypy.tool.pairtype import pairtype
+from rpython.tool.pairtype import pairtype
 from rpython.flowspace.model import Constant
 from rpython.rtyper.rdict import (AbstractDictRepr, AbstractDictIteratorRepr,
      rtype_newdict)

rpython/rtyper/lltypesystem/rffi.py

 from rpython.rtyper.lltypesystem.llmemory import cast_adr_to_ptr, cast_ptr_to_adr
 from rpython.rtyper.lltypesystem.llmemory import itemoffsetof, raw_memcopy
 from rpython.annotator.model import lltype_to_annotation
-from pypy.tool.sourcetools import func_with_new_name
+from rpython.tool.sourcetools import func_with_new_name
 from rpython.rlib.objectmodel import Symbolic, CDefinedIntSymbolic
 from rpython.rlib.objectmodel import keepalive_until_here
 from rpython.rlib import rarithmetic, rgc

rpython/rtyper/lltypesystem/rlist.py

     AbstractFixedSizeListRepr, AbstractListIteratorRepr, ll_setitem_nonneg,
     ADTIList, ADTIFixedList, dum_nocheck)
 from rpython.rtyper.rmodel import Repr, inputconst, externalvsinternal
-from pypy.tool.pairtype import pairtype, pair
+from rpython.tool.pairtype import pairtype, pair
 
 
 # ____________________________________________________________

rpython/rtyper/lltypesystem/rpbc.py

 import types
 import sys
-from pypy.tool.pairtype import pairtype, pair
+from rpython.tool.pairtype import pairtype, pair
 from rpython.annotator import model as annmodel
 from rpython.annotator import description
 from rpython.flowspace.model import Constant, Variable
      AbstractFunctionsPBCRepr, AbstractMultipleUnrelatedFrozenPBCRepr, \
      SingleFrozenPBCRepr, none_frozen_pbc_repr, get_concrete_calltable
 from rpython.rtyper.lltypesystem import rclass, llmemory
-from pypy.tool.sourcetools import has_varargs
+from rpython.tool.sourcetools import has_varargs
 from rpython.rlib.unroll import unrolling_iterable
 from rpython.rlib.debug import ll_assert
 

rpython/rtyper/lltypesystem/rstr.py

      staticAdtMethod, GcForwardReference, malloc
 from rpython.rtyper.rmodel import Repr
 from rpython.rtyper.lltypesystem import llmemory
-from pypy.tool.sourcetools import func_with_new_name
+from rpython.tool.sourcetools import func_with_new_name
 
 # ____________________________________________________________
 #

rpython/rtyper/lltypesystem/rtuple.py

-from pypy.tool.pairtype import pairtype
+from rpython.tool.pairtype import pairtype
 from rpython.rtyper.rmodel import inputconst
 from rpython.rtyper.rtuple import AbstractTupleRepr, AbstractTupleIteratorRepr
 from rpython.rtyper.lltypesystem.lltype import \

rpython/rtyper/memory/gc/minimark.py

 from rpython.rlib.rarithmetic import LONG_BIT_SHIFT
 from rpython.rlib.debug import ll_assert, debug_print, debug_start, debug_stop
 from rpython.rlib.objectmodel import we_are_translated
-from pypy.tool.sourcetools import func_with_new_name
+from rpython.tool.sourcetools import func_with_new_name
 
 #
 # Handles the objects in 2 generations:

rpython/rtyper/memory/gctransform/framework.py

 from rpython.rtyper.memory.gctransform.transform import GCTransformer
 from rpython.rtyper.memory.gctypelayout import ll_weakref_deref, WEAKREF, \
      WEAKREFPTR
-from pypy.tool.sourcetools import func_with_new_name
+from rpython.tool.sourcetools import func_with_new_name
 from rpython.translator.backendopt import graphanalyze
 from rpython.translator.backendopt.finalizer import FinalizerAnalyzer
 from rpython.translator.backendopt.support import var_needsgc

rpython/rtyper/module/ll_os.py

 import os, sys, errno
 import py
 from rpython.rtyper.module.support import OOSupport
-from pypy.tool.sourcetools import func_renamer
+from rpython.tool.sourcetools import func_renamer
 from rpython.rlib.rarithmetic import r_longlong
 from rpython.rtyper.extfunc import (
     BaseLazyRegistering, register_external)

rpython/rtyper/module/ll_os_stat.py

 """
 import os, sys
 from rpython.annotator import model as annmodel
-from pypy.tool.pairtype import pairtype
-from pypy.tool.sourcetools import func_with_new_name, func_renamer
+from rpython.tool.pairtype import pairtype
+from rpython.tool.sourcetools import func_with_new_name, func_renamer
 from rpython.rtyper import extregistry
 from rpython.rtyper.extfunc import register_external, extdef
 from rpython.rtyper.lltypesystem import rffi, lltype

rpython/rtyper/module/ll_win32file.py

 from rpython.rtyper.lltypesystem import lltype, rffi
 from rpython.translator.tool.cbuild import ExternalCompilationInfo
 from rpython.rtyper.tool import rffi_platform as platform
-from pypy.tool.sourcetools import func_renamer
+from rpython.tool.sourcetools import func_renamer
 from rpython.rlib.objectmodel import specialize
 
 def make_win32_traits(traits):

rpython/rtyper/module/r_os_stat.py

 """
 from rpython.annotator import model as annmodel
 from rpython.flowspace.model import Constant
-from pypy.tool.pairtype import pairtype
+from rpython.tool.pairtype import pairtype
 from rpython.rtyper.rmodel import Repr, IntegerRepr
 from rpython.rtyper.error import TyperError
 from rpython.rtyper.module import ll_os_stat

rpython/rtyper/normalizecalls.py

 from rpython.rlib.objectmodel import ComputedIntSymbolic
 from rpython.rtyper.error import TyperError
 from rpython.rtyper.rmodel import getgcflavor
-from pypy.tool.sourcetools import valid_identifier
+from rpython.tool.sourcetools import valid_identifier
 
 
 def normalize_call_familes(annotator):

rpython/rtyper/ootypesystem/rclass.py

                                 getinstancerepr, getclassrepr, get_type_repr
 from rpython.rtyper.ootypesystem import ootype
 from rpython.rtyper.exceptiondata import standardexceptions
-from pypy.tool.pairtype import pairtype
-from pypy.tool.sourcetools import func_with_new_name
+from rpython.tool.pairtype import pairtype
+from rpython.tool.sourcetools import func_with_new_name
 from pypy.tool.identity_dict import identity_dict
 
 OBJECT = ootype.ROOT

rpython/rtyper/ootypesystem/rdict.py

 from rpython.rtyper.error import TyperError
-from pypy.tool.pairtype import pairtype
+from rpython.tool.pairtype import pairtype
 from rpython.flowspace.model import Constant
 from rpython.rtyper.rdict import AbstractDictRepr, AbstractDictIteratorRepr
 from rpython.rtyper.rpbc import (MethodOfFrozenPBCRepr, AbstractFunctionsPBCRepr,

rpython/rtyper/ootypesystem/rlist.py

-from pypy.tool.pairtype import pairtype
+from rpython.tool.pairtype import pairtype
 from rpython.rtyper.rlist import AbstractBaseListRepr, AbstractListRepr, \
         AbstractListIteratorRepr, AbstractFixedSizeListRepr, rtype_newlist, rtype_alloc_and_set
 from rpython.rtyper.rmodel import Repr, IntegerRepr

rpython/rtyper/ootypesystem/rootype.py

 from rpython.rtyper.rmodel import Repr
 from rpython.rtyper.ootypesystem import ootype
 from rpython.rtyper.ootypesystem.ootype import Void, Class, Object
-from pypy.tool.pairtype import pairtype
+from rpython.tool.pairtype import pairtype
 
 class __extend__(annmodel.SomeOOObject):
     def rtyper_makerepr(self, rtyper):

rpython/rtyper/ootypesystem/rpbc.py

 from rpython.rtyper.ootypesystem.rclass import mangle, META
 from rpython.annotator import model as annmodel
 from rpython.annotator import description
-from pypy.tool.pairtype import pairtype
+from rpython.tool.pairtype import pairtype
 from rpython.flowspace.model import Constant, Variable
 import types
 

rpython/rtyper/ootypesystem/rstr.py

-from pypy.tool.pairtype import pairtype
+from rpython.tool.pairtype import pairtype
 from rpython.annotator import model as annmodel
 from rpython.rlib.objectmodel import specialize
 from rpython.rlib.rarithmetic import ovfcheck

rpython/rtyper/raddress.py

 # rtyping of memory address operations
-from pypy.tool.pairtype import pairtype
+from rpython.tool.pairtype import pairtype
 from rpython.annotator import model as annmodel
 from rpython.rtyper.lltypesystem.llmemory import NULL, Address, \
      cast_adr_to_int, fakeaddress, sizeof

rpython/rtyper/rbool.py

-from pypy.tool.pairtype import pairtype
+from rpython.tool.pairtype import pairtype
 from rpython.annotator import model as annmodel
 from rpython.rtyper.lltypesystem.lltype import Signed, Unsigned, Bool, Float
 from rpython.rtyper.error import TyperError

rpython/rtyper/rbuiltin.py

 from rpython.rtyper.error import TyperError
 from rpython.rtyper.lltypesystem import lltype, llmemory
 from rpython.rtyper.rmodel import Repr
-from pypy.tool.pairtype import pairtype
+from rpython.tool.pairtype import pairtype
 
 
 class __extend__(annmodel.SomeBuiltin):

rpython/rtyper/rbytearray.py

 
 from rpython.annotator import model as annmodel
-from pypy.tool.pairtype import pairtype
+from rpython.tool.pairtype import pairtype
 from rpython.rtyper.rstr import AbstractStringRepr
 from rpython.rtyper.rmodel import IntegerRepr
 from rpython.rtyper.lltypesystem import lltype

rpython/rtyper/rcontrollerentry.py

-from pypy.tool.pairtype import pairtype
+from rpython.tool.pairtype import pairtype
 from rpython.flowspace.model import Constant
 from rpython.rtyper.rmodel import Repr
 from rpython.rtyper.error import TyperError

rpython/rtyper/rexternalobj.py

 from rpython.flowspace.model import Constant, Variable
 from rpython.rtyper import extregistry
 from rpython.annotator.signature import annotation
-from pypy.tool.pairtype import pairtype
+from rpython.tool.pairtype import pairtype
 
 # ExternalObjects
 

rpython/rtyper/rfloat.py

-from pypy.tool.pairtype import pairtype
+from rpython.tool.pairtype import pairtype
 from rpython.annotator import model as annmodel
 from rpython.rtyper.lltypesystem.lltype import (Signed, Unsigned, SignedLongLong,
     UnsignedLongLong, Bool, Float)

rpython/rtyper/rgeneric.py

 from rpython.rtyper.rmodel import Repr
 from rpython.rtyper.rpbc import AbstractFunctionsPBCRepr,\
      AbstractMethodsPBCRepr
-from pypy.tool.pairtype import pairtype
+from rpython.tool.pairtype import pairtype
 from rpython.rtyper.lltypesystem import lltype
 
 class AbstractGenericCallableRepr(Repr):

rpython/rtyper/rint.py

 import sys
-from pypy.tool.pairtype import pairtype
+from rpython.tool.pairtype import pairtype
 from rpython.annotator import model as annmodel
 from rpython.flowspace.operation import op_appendices
 from rpython.rtyper.lltypesystem.lltype import Signed, Unsigned, Bool, Float, \

rpython/rtyper/rlist.py

-from pypy.tool.pairtype import pairtype, pair
+from rpython.tool.pairtype import pairtype, pair
 from rpython.flowspace.model import Constant
 from rpython.annotator import model as annmodel
 from rpython.rtyper.error import TyperError

rpython/rtyper/rmodel.py

-from pypy.tool.pairtype import pairtype, extendabletype, pair
+from rpython.tool.pairtype import pairtype, extendabletype, pair
 from rpython.annotator import model as annmodel, unaryop, binaryop
 from rpython.annotator import description
 from rpython.flowspace.model import Constant

rpython/rtyper/rpbc.py

 import types
 import sys
-from pypy.tool.pairtype import pair, pairtype
+from rpython.tool.pairtype import pair, pairtype
 from rpython.annotator import model as annmodel
 from rpython.annotator import description
 from rpython.flowspace.model import Constant

rpython/rtyper/rptr.py

-from pypy.tool.pairtype import pairtype
+from rpython.tool.pairtype import pairtype
 from rpython.annotator import model as annmodel
 from rpython.flowspace import model as flowmodel
 from rpython.rtyper.lltypesystem import lltype

rpython/rtyper/rrange.py

-from pypy.tool.pairtype import pairtype
+from rpython.tool.pairtype import pairtype
 from rpython.rtyper.error import TyperError
 from rpython.rtyper.lltypesystem.lltype import Signed, Void, Ptr
 from rpython.rtyper.rmodel import Repr, IntegerRepr, IteratorRepr

rpython/rtyper/rstr.py

 from pypy.tool.staticmethods import StaticMethods
-from pypy.tool.pairtype import pairtype, pair
-from pypy.tool.sourcetools import func_with_new_name
+from rpython.tool.pairtype import pairtype, pair
+from rpython.tool.sourcetools import func_with_new_name
 from rpython.annotator import model as annmodel
 from rpython.rlib import jit
 from rpython.rlib.nonconst import NonConstant

rpython/rtyper/rtuple.py

 import operator
-from pypy.tool.pairtype import pairtype
+from rpython.tool.pairtype import pairtype
 from rpython.annotator import model as annmodel
 from rpython.flowspace.model import Constant
 from rpython.rtyper.error import TyperError

rpython/rtyper/rtyper.py

 
 import os
 import py
-from pypy.tool.pairtype import pair
+from rpython.tool.pairtype import pair
 from rpython.annotator import model as annmodel, unaryop, binaryop
 from rpython.annotator.annrpython import FAIL
 from rpython.flowspace.model import Variable, Constant

rpython/rtyper/typesystem.py

 
 """typesystem.py -- Typesystem-specific operations for RTyper."""
 
-from pypy.tool.pairtype import extendabletype
+from rpython.tool.pairtype import extendabletype
 
 from rpython.rtyper.ootypesystem import ootype
 from rpython.rtyper.lltypesystem import lltype
 
 # Multiple dispatch on type system and high-level annotation
 
-from pypy.tool.pairtype import pairtype
+from rpython.tool.pairtype import pairtype
 from rpython.annotator.model import SomeObject
 
 class __extend__(pairtype(TypeSystem, SomeObject)):

rpython/tool/pairtype.py

+"""
+Two magic tricks for classes:
+
+    class X:
+        __metaclass__ = extendabletype
+        ...
+
+    # in some other file...
+    class __extend__(X):
+        ...      # and here you can add new methods and class attributes to X
+
+Mostly useful together with the second trick, which lets you build
+methods whose 'self' is a pair of objects instead of just one:
+
+    class __extend__(pairtype(X, Y)):
+        attribute = 42
+        def method((x, y), other, arguments):
+            ...
+
+    pair(x, y).attribute
+    pair(x, y).method(other, arguments)
+
+This finds methods and class attributes based on the actual
+class of both objects that go into the pair(), with the usual
+rules of method/attribute overriding in (pairs of) subclasses.
+
+For more information, see test_pairtype.
+"""
+
+class extendabletype(type):
+    """A type with a syntax trick: 'class __extend__(t)' actually extends
+    the definition of 't' instead of creating a new subclass."""
+    def __new__(cls, name, bases, dict):
+        if name == '__extend__':
+            for cls in bases:
+                for key, value in dict.items():
+                    if key == '__module__':
+                        continue
+                    # XXX do we need to provide something more for pickling?
+                    setattr(cls, key, value)
+            return None
+        else:
+            return super(extendabletype, cls).__new__(cls, name, bases, dict)