Commits

David Schneider committed 14906f1 Merge

merge

Comments (0)

Files changed (36)

pypy/interpreter/baseobjspace.py

 import sys
 
+from rpython.rlib.cache import Cache
+from rpython.tool.uid import HUGEVAL_BYTES
+from rpython.rlib import jit, types
+from rpython.rlib.debug import make_sure_not_resized
+from rpython.rlib.objectmodel import (we_are_translated, newlist_hint,
+     compute_unique_id)
+from rpython.rlib.signature import signature
+from rpython.rlib.rarithmetic import r_uint
+
 from pypy.interpreter.executioncontext import (ExecutionContext, ActionFlag,
     UserDelAction, FrameTraceAction)
 from pypy.interpreter.error import (OperationError, operationerrfmt,
     new_exception_class, typed_unwrap_error_msg)
 from pypy.interpreter.argument import Arguments
 from pypy.interpreter.miscutils import ThreadLocals
-from rpython.rlib.cache import Cache
-from rpython.tool.uid import HUGEVAL_BYTES
-from rpython.rlib import jit
-from rpython.rlib.debug import make_sure_not_resized
-from rpython.rlib.objectmodel import we_are_translated, newlist_hint,\
-     compute_unique_id
-from rpython.rlib.rarithmetic import r_uint
 
 
 __all__ = ['ObjSpace', 'OperationError', 'Wrappable', 'W_Root']
 
 UINT_MAX_32_BITS = r_uint(4294967295)
 
-unpackiterable_driver = jit.JitDriver(name = 'unpackiterable',
-                                      greens = ['tp'],
-                                      reds = ['items', 'w_iterator'])
+unpackiterable_driver = jit.JitDriver(name='unpackiterable',
+                                      greens=['tp'],
+                                      reds=['items', 'w_iterator'])
+
 
 class W_Root(object):
     """This is the abstract root class of all wrapped objects that live
                 raise
             return None
 
+    @signature(types.bool(), returns=types.instance(W_Root))
     def newbool(self, b):
         if b:
             return self.w_True

pypy/module/_socket/test/test_sock_app.py

     assert space.unwrap(host) == socket.gethostname()
 
 def test_gethostbyname():
-    host = "localhost"
-    ip = space.appexec([w_socket, space.wrap(host)],
-                       "(_socket, host): return _socket.gethostbyname(host)")
-    assert space.unwrap(ip) == socket.gethostbyname(host)
+    for host in ["localhost", "127.0.0.1"]:
+        ip = space.appexec([w_socket, space.wrap(host)],
+                           "(_socket, host): return _socket.gethostbyname(host)")
+        assert space.unwrap(ip) == socket.gethostbyname(host)
 
 def test_gethostbyname_ex():
-    host = "localhost"
-    ip = space.appexec([w_socket, space.wrap(host)],
-                       "(_socket, host): return _socket.gethostbyname_ex(host)")
-    assert isinstance(space.unwrap(ip), tuple)
-    assert space.unwrap(ip) == socket.gethostbyname_ex(host)
+    for host in ["localhost", "127.0.0.1"]:
+        ip = space.appexec([w_socket, space.wrap(host)],
+                           "(_socket, host): return _socket.gethostbyname_ex(host)")
+        assert space.unwrap(ip) == socket.gethostbyname_ex(host)
 
 def test_gethostbyaddr():
-    host = "localhost"
-    expected = socket.gethostbyaddr(host)
-    expecteds = (expected, expected[:2]+(['0.0.0.0'],))
-    ip = space.appexec([w_socket, space.wrap(host)],
-                       "(_socket, host): return _socket.gethostbyaddr(host)")
-    assert space.unwrap(ip) in expecteds
-    host = "127.0.0.1"
-    expected = socket.gethostbyaddr(host)
-    expecteds = (expected, expected[:2]+(['0.0.0.0'],))
-    ip = space.appexec([w_socket, space.wrap(host)],
-                       "(_socket, host): return _socket.gethostbyaddr(host)")
-    assert space.unwrap(ip) in expecteds
+    for host in ["localhost", "127.0.0.1", "::1"]:
+        ip = space.appexec([w_socket, space.wrap(host)],
+                           "(_socket, host): return _socket.gethostbyaddr(host)")
+        assert space.unwrap(ip) == socket.gethostbyaddr(host)
 
 def test_getservbyname():
     name = "smtp"

pypy/module/micronumpy/interp_boxes.py

 class W_BoolBox(W_GenericBox, PrimitiveBox):
     descr__new__, _get_dtype = new_dtype_getter("bool")
 
+    def descr_any(self, space):
+        return self
+
+    def descr_all(self, space):
+        return self
+
 class W_NumberBox(W_GenericBox):
     _attrs_ = ()
 
 W_BoolBox.typedef = TypeDef("bool_", W_GenericBox.typedef,
     __module__ = "numpypy",
     __new__ = interp2app(W_BoolBox.descr__new__.im_func),
-
     __index__ = interp2app(descr_index),
+    any = interp2app(W_BoolBox.descr_any),
+    all = interp2app(W_BoolBox.descr_all),
 )
 
 W_NumberBox.typedef = TypeDef("number", W_GenericBox.typedef,

pypy/module/micronumpy/test/test_dtypes.py

         assert X(True) is numpy.True_
         assert numpy.bool_("False") is numpy.True_
 
+    def test_bool_any_all(self):
+        import numpypy as numpy
+        x = numpy.bool_(True)
+        assert x.any()
+        assert x.all()
+        x = numpy.bool_(False)
+        assert not x.any()
+        assert not x.all()
+
     def test_int8(self):
         import numpypy as numpy
 

pypy/tool/ann_override.py

 # overrides for annotation specific to PyPy codebase
-from rpython.annotator.policy import AnnotatorPolicy, Sig
+from rpython.annotator.policy import AnnotatorPolicy
 # for some reason, model must be imported first,
 # or we create a cycle.
 from rpython.flowspace.model import Constant
-from rpython.annotator import model as annmodel
-from rpython.annotator.bookkeeper import getbookkeeper
 from rpython.annotator import specialize
-from pypy.interpreter import baseobjspace
+
 
 def isidentifier(s):
-    if not s: return False
+    if not s:
+        return False
     s = s.replace('_', 'x')
     return s[0].isalpha() and s.isalnum()
 
-# patch - mostly for debugging, to enforce some signatures
-baseobjspace.ObjSpace.newbool.im_func._annenforceargs_ = Sig(lambda s1,s2: s1,
-                                                             bool)
-
 
 class PyPyAnnotatorPolicy(AnnotatorPolicy):
     def __init__(pol, single_space=None):
         # for jit benefit
         if cached not in t._immutable_fields_: # accessed this way just
                                                # for convenience
-            t._immutable_fields_.append(cached)        
-    
+            t._immutable_fields_.append(cached)
+
     def attach_lookup(pol, t, attr):
         cached = "cached_%s" % attr
         if not t.is_heaptype() and not t.is_cpytype():

rpython/annotator/annrpython.py

             # a graph that has already been rtyped.  Safety-check the new
             # annotations that are passed in, and don't annotate the old
             # graph -- it's already low-level operations!
-            for a, s_newarg in zip(graph.getargs(), cells):
+            for a, s_newarg in zip(block.inputargs, cells):
                 s_oldarg = self.binding(a)
                 assert annmodel.unionof(s_oldarg, s_newarg) == s_oldarg
         else:
             assert not self.frozen
-            for a in cells:
-                assert isinstance(a, annmodel.SomeObject)
             if block not in self.annotated:
                 self.bindinputargs(graph, block, cells)
             else:

rpython/annotator/binaryop.py

 from rpython.annotator.model import SomeTuple, SomeImpossibleValue, s_ImpossibleValue
 from rpython.annotator.model import SomeInstance, SomeBuiltin, SomeIterator
 from rpython.annotator.model import SomePBC, SomeFloat, s_None, SomeByteArray
-from rpython.annotator.model import SomeExternalObject, SomeWeakRef
+from rpython.annotator.model import SomeWeakRef
 from rpython.annotator.model import SomeAddress, SomeTypedAddressAccess
 from rpython.annotator.model import SomeSingleFloat, SomeLongFloat, SomeType
 from rpython.annotator.model import unionof, UnionError, missing_operation
 from rpython.annotator.model import TLS
 from rpython.annotator.model import read_can_only_throw
 from rpython.annotator.model import add_knowntypedata, merge_knowntypedata
-from rpython.annotator.model import SomeGenericCallable
 from rpython.annotator.bookkeeper import getbookkeeper
 from rpython.flowspace.model import Variable, Constant
 from rpython.rlib import rarithmetic
     def is_((obj1, obj2)):
         r = SomeBool()
         if obj2.is_constant():
-            if obj1.is_constant(): 
+            if obj1.is_constant():
                 r.const = obj1.const is obj2.const
             if obj2.const is None and not obj1.can_be_none():
                 r.const = False
 
             def bind(src_obj, tgt_obj, tgt_arg):
                 if hasattr(tgt_obj, 'is_type_of') and src_obj.is_constant():
-                    add_knowntypedata(knowntypedata, True, tgt_obj.is_type_of, 
+                    add_knowntypedata(knowntypedata, True, tgt_obj.is_type_of,
                                       bk.valueoftype(src_obj.const))
 
                 assert annotator.binding(op.args[tgt_arg]) == tgt_obj
         getbookkeeper().count("coerce", obj1, obj2)
         return pair(obj1, obj2).union()   # reasonable enough
 
-    # approximation of an annotation intersection, the result should be the annotation obj or 
+    # approximation of an annotation intersection, the result should be the annotation obj or
     # the intersection of obj and improvement
     def improve((obj, improvement)):
         if not improvement.contains(obj) and obj.contains(improvement):
             return int0.knowntype
         if int1.nonneg and isinstance(op.args[1], Variable):
             case = opname in ('lt', 'le', 'eq')
-                
+
             add_knowntypedata(knowntypedata, case, [op.args[1]],
                               SomeInteger(nonneg=True, knowntype=tointtype(int2)))
         if int2.nonneg and isinstance(op.args[0], Variable):
         # a special case for 'x < 0' or 'x >= 0',
         # where 0 is a flow graph Constant
         # (in this case we are sure that it cannot become a r_uint later)
-        if (isinstance(op.args[1], Constant) and 
+        if (isinstance(op.args[1], Constant) and
             type(op.args[1].value) is int and    # filter out Symbolics
             op.args[1].value == 0):
             if int1.nonneg:
 class __extend__(pairtype(SomeBool, SomeBool)):
 
     def union((boo1, boo2)):
-        s = SomeBool() 
-        if getattr(boo1, 'const', -1) == getattr(boo2, 'const', -2): 
-            s.const = boo1.const 
+        s = SomeBool()
+        if getattr(boo1, 'const', -1) == getattr(boo2, 'const', -2):
+            s.const = boo1.const
         if hasattr(boo1, 'knowntypedata') and \
            hasattr(boo2, 'knowntypedata'):
             ktd = merge_knowntypedata(boo1.knowntypedata, boo2.knowntypedata)
             s.set_knowntypedata(ktd)
-        return s 
+        return s
 
     def and_((boo1, boo2)):
         s = SomeBool()
             if boo2.const:
                 s.const = True
         return s
-        
+
     def xor((boo1, boo2)):
         s = SomeBool()
         if boo1.is_constant() and boo2.is_constant():
             s.const = boo1.const ^ boo2.const
         return s
-        
+
 class __extend__(pairtype(SomeString, SomeString)):
 
     def union((str1, str2)):
         return s_string.__class__()
 
 class __extend__(pairtype(SomeFloat, SomeFloat)):
-    
+
     def union((flt1, flt2)):
         return SomeFloat()
 
 
 
 class __extend__(pairtype(SomeSingleFloat, SomeSingleFloat)):
-    
+
     def union((flt1, flt2)):
         return SomeSingleFloat()
 
 
 class __extend__(pairtype(SomeLongFloat, SomeLongFloat)):
-    
+
     def union((flt1, flt2)):
         return SomeLongFloat()
 
 
 
 class __extend__(pairtype(SomeTuple, SomeInteger)):
-    
+
     def getitem((tup1, int2)):
         if int2.is_immutable_constant():
             try:
 
 
 class __extend__(pairtype(SomeList, SomeInteger)):
-    
+
     def mul((lst1, int2)):
         return lst1.listdef.offspring()
 
     getitem_idx_key = getitem_idx
 
     def setitem((lst1, int2), s_value):
-        getbookkeeper().count("list_setitem", int2)        
+        getbookkeeper().count("list_setitem", int2)
         lst1.listdef.mutate()
         lst1.listdef.generalize(s_value)
     setitem.can_only_throw = [IndexError]
 
     def delitem((lst1, int2)):
-        getbookkeeper().count("list_delitem", int2)        
+        getbookkeeper().count("list_delitem", int2)
         lst1.listdef.resize()
     delitem.can_only_throw = [IndexError]
 
 class __extend__(pairtype(SomeString, SomeInteger)):
 
     def getitem((str1, int2)):
-        getbookkeeper().count("str_getitem", int2)        
+        getbookkeeper().count("str_getitem", int2)
         return SomeChar(no_nul=str1.no_nul)
     getitem.can_only_throw = []
 
     getitem_key = getitem
 
     def getitem_idx((str1, int2)):
-        getbookkeeper().count("str_getitem", int2)        
+        getbookkeeper().count("str_getitem", int2)
         return SomeChar(no_nul=str1.no_nul)
     getitem_idx.can_only_throw = [IndexError]
 
 
 class __extend__(pairtype(SomeUnicodeString, SomeInteger)):
     def getitem((str1, int2)):
-        getbookkeeper().count("str_getitem", int2)        
+        getbookkeeper().count("str_getitem", int2)
         return SomeUnicodeCodePoint()
     getitem.can_only_throw = []
 
     getitem_key = getitem
 
     def getitem_idx((str1, int2)):
-        getbookkeeper().count("str_getitem", int2)        
+        getbookkeeper().count("str_getitem", int2)
         return SomeUnicodeCodePoint()
     getitem_idx.can_only_throw = [IndexError]
 
 
 class __extend__(pairtype(SomeInteger, SomeString),
                  pairtype(SomeInteger, SomeUnicodeString)):
-    
+
     def mul((int1, str2)): # xxx do we want to support this
         getbookkeeper().count("str_mul", str2, int1)
         return str2.basestringclass()
         return result
 
 class __extend__(pairtype(SomeInteger, SomeList)):
-    
+
     def mul((int1, lst2)):
         return lst2.listdef.offspring()
 
 
 class __extend__(pairtype(SomePBC, SomePBC)):
 
-    def union((pbc1, pbc2)):       
+    def union((pbc1, pbc2)):
         d = pbc1.descriptions.copy()
         d.update(pbc2.descriptions)
         return SomePBC(d, can_be_None = pbc1.can_be_None or pbc2.can_be_None)
                     s.const = False    # no common desc in the two sets
         return s
 
-class __extend__(pairtype(SomeGenericCallable, SomePBC)):
-    def union((gencall, pbc)):
-        for desc in pbc.descriptions:
-            unique_key = desc
-            bk = desc.bookkeeper
-            s_result = bk.emulate_pbc_call(unique_key, pbc, gencall.args_s)
-            s_result = unionof(s_result, gencall.s_result)
-            assert gencall.s_result.contains(s_result)
-        return gencall
-
-class __extend__(pairtype(SomePBC, SomeGenericCallable)):
-    def union((pbc, gencall)):
-        return pair(gencall, pbc).union()
-
 class __extend__(pairtype(SomeImpossibleValue, SomeObject)):
     def union((imp1, obj2)):
         return obj2
 _make_none_union('SomeUnicodeString', 'can_be_None=True')
 _make_none_union('SomeList',         'obj.listdef')
 _make_none_union('SomeDict',          'obj.dictdef')
-_make_none_union('SomeExternalObject', 'obj.knowntype')
 _make_none_union('SomeWeakRef',         'obj.classdef')
 
 # getitem on SomePBCs, in particular None fails
             raise AnnotatorError('add on %r' % pbc)
         return s_ImpossibleValue
 
-class __extend__(pairtype(SomeExternalObject, SomeExternalObject)):
-    def union((ext1, ext2)):
-        if ext1.knowntype == ext2.knowntype:
-            return SomeExternalObject(ext1.knowntype)
-        return SomeObject()
-
 # ____________________________________________________________
 # annotation of low-level types
 from rpython.annotator.model import SomePtr, SomeOOInstance, SomeOOClass

rpython/annotator/bookkeeper.py

         elif ishashable(x) and x in BUILTIN_ANALYZERS:
             _module = getattr(x,"__module__","unknown")
             result = SomeBuiltin(BUILTIN_ANALYZERS[x], methodname="%s.%s" % (_module, x.__name__))
-        elif extregistry.is_registered(x, self.policy):
-            entry = extregistry.lookup(x, self.policy)
+        elif extregistry.is_registered(x):
+            entry = extregistry.lookup(x)
             result = entry.compute_annotation_bk(self)
         elif isinstance(x, lltype._ptr):
             result = SomePtr(lltype.typeOf(x))

rpython/annotator/model.py

 
 from __future__ import absolute_import
 
-from types import BuiltinFunctionType, MethodType, FunctionType
+import inspect
+import weakref
+from types import BuiltinFunctionType, MethodType
+
 import rpython
 from rpython.tool import descriptor
 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
+from rpython.rlib.rarithmetic import r_uint, base_int, r_singlefloat, r_longfloat
+
 
 class State(object):
     # A global attribute :-(  Patch it with 'True' to enable checking of
     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):
         try:
             reprdict = TLS.reprdict
                     m = getattr(self, 'fmt_' + k, repr)
                     r = m(v)
                     if r is not None:
-                        args.append('%s=%s'%(k, r))
+                        args.append('%s=%s' % (k, r))
                 kwds = ', '.join(args)
             finally:
                 del reprdict[self]
 
     def fmt_knowntype(self, t):
         return t.__name__
-    
+
     def contains(self, other):
         if self == other:
             return True
     def can_be_none(self):
         return False
 
+
 class SomeFloat(SomeObject):
     "Stands for a float or an integer."
     knowntype = float   # if we don't know if it's a float or an int,
     def can_be_none(self):
         return False
 
+
 class SomeSingleFloat(SomeObject):
     "Stands for an r_singlefloat."
     # No operation supported, not even union with a regular float
     def can_be_none(self):
         return False
 
+
 class SomeLongFloat(SomeObject):
     "Stands for an r_longfloat."
     # No operation supported, not even union with a regular float
     def can_be_none(self):
         return False
 
+
 class SomeInteger(SomeFloat):
     "Stands for an object which is known to be an integer."
     knowntype = int
+
     # size is in multiples of C's sizeof(long)!
     def __init__(self, nonneg=False, unsigned=None, knowntype=None):
         assert (knowntype is None or knowntype is int or
         self.nonneg = unsigned or nonneg
         self.unsigned = unsigned  # rpython.rlib.rarithmetic.r_uint
 
+
 class SomeBool(SomeInteger):
     "Stands for true or false."
     knowntype = bool
     nonneg = True
     unsigned = False
+
     def __init__(self):
         pass
+
     def set_knowntypedata(self, knowntypedata):
         assert not hasattr(self, 'knowntypedata')
         if knowntypedata:
             self.knowntypedata = knowntypedata
 
+
 class SomeStringOrUnicode(SomeObject):
     """Base class for shared implementation of SomeString and SomeUnicodeString.
 
     Cannot be an annotation."""
 
     immutable = True
-    can_be_None=False
+    can_be_None = False
     no_nul = False  # No NUL character in the string.
 
     def __init__(self, can_be_None=False, no_nul=False):
         d1 = self.__dict__
         d2 = other.__dict__
         if not TLS.check_str_without_nul:
-            d1 = d1.copy(); d1['no_nul'] = 0   # ignored
-            d2 = d2.copy(); d2['no_nul'] = 0   # ignored
+            d1 = d1.copy()
+            d1['no_nul'] = 0
+            d2 = d2.copy()
+            d2['no_nul'] = 0
         return d1 == d2
 
     def nonnoneify(self):
     def nonnulify(self):
         return self.__class__(can_be_None=self.can_be_None, no_nul=True)
 
+
 class SomeString(SomeStringOrUnicode):
     "Stands for an object which is known to be a string."
     knowntype = str
 
+
 class SomeUnicodeString(SomeStringOrUnicode):
     "Stands for an object which is known to be an unicode string"
     knowntype = unicode
 
+
 class SomeByteArray(SomeStringOrUnicode):
     knowntype = bytearray
 
+
 class SomeChar(SomeString):
     "Stands for an object known to be a string of length 1."
     can_be_None = False
+
     def __init__(self, no_nul=False):    # no 'can_be_None' argument here
         if no_nul:
             self.no_nul = True
 
+
 class SomeUnicodeCodePoint(SomeUnicodeString):
     "Stands for an object known to be a unicode codepoint."
     can_be_None = False
+
     def __init__(self, no_nul=False):    # no 'can_be_None' argument here
         if no_nul:
             self.no_nul = True
 SomeUnicodeString.basestringclass = SomeUnicodeString
 SomeUnicodeString.basecharclass = SomeUnicodeCodePoint
 
+
 class SomeList(SomeObject):
     "Stands for a homogenous list of any length."
     knowntype = list
+
     def __init__(self, listdef):
         self.listdef = listdef
+
     def __eq__(self, other):
         if self.__class__ is not other.__class__:
             return False
     def can_be_none(self):
         return True
 
+
 class SomeTuple(SomeObject):
     "Stands for a tuple of known length."
     knowntype = tuple
     immutable = True
+
     def __init__(self, items):
         self.items = tuple(items)   # tuple of s_xxx elements
         for i in items:
     def can_be_none(self):
         return False
 
+
 class SomeDict(SomeObject):
     "Stands for a dict."
     knowntype = dict
+
     def __init__(self, dictdef):
         self.dictdef = dictdef
+
     def __eq__(self, other):
         if self.__class__ is not other.__class__:
             return False
         if len(const) < 20:
             return repr(const)
         else:
-            return '{...%s...}'%(len(const),)
+            return '{...%s...}' % (len(const),)
 
 
 class SomeIterator(SomeObject):
     "Stands for an iterator returning objects from a given container."
     knowntype = type(iter([]))  # arbitrarily chose seqiter as the type
+
     def __init__(self, s_container, *variant):
         self.variant = variant
         self.s_container = s_container
     def can_be_none(self):
         return False
 
+
 class SomeInstance(SomeObject):
     "Stands for an instance of a (user-defined) class."
 
 
     def fmt_knowntype(self, kt):
         return None
+
     def fmt_classdef(self, cdef):
         if cdef is None:
             return 'object'
         else:
             return cdef.name
+
     def fmt_flags(self, flags):
         if flags:
             return repr(flags)
         if hasattr(self, 'const'):
             return None
         else:
-            return '{...%s...}'%(len(pbis),)
+            return '{...%s...}' % (len(pbis),)
 
     def fmt_knowntype(self, kt):
         if self.is_constant():
         else:
             return kt.__name__
 
-class SomeGenericCallable(SomeObject):
-    """ Stands for external callable with known signature
-    """
-    def __init__(self, args, result):
-        self.args_s = args
-        self.s_result = result
-
-    def can_be_None(self):
-        return True
 
 class SomeBuiltin(SomeObject):
     "Stands for a built-in function or method with special-cased analysis."
     def can_be_none(self):
         return False
 
+
 class SomeBuiltinMethod(SomeBuiltin):
     """ Stands for a built-in method which has got special meaning
     """
     knowntype = MethodType
 
-class SomeExternalObject(SomeObject):
-    """Stands for an object of 'external' type.  External types have a Repr
-    controlled by rpython.rtyper.extregistry."""
-
-    def __init__(self, knowntype):
-        self.knowntype = knowntype
-
-    def can_be_none(self):
-        return True
 
 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."""
     immutable = True
-    annotationcolor = (160,160,160)
+    annotationcolor = (160, 160, 160)
 
     def can_be_none(self):
         return False
 
 s_None = SomePBC([], can_be_None=True)
 s_Bool = SomeBool()
-s_Int  = SomeInteger()
+s_Int = SomeInteger()
 s_ImpossibleValue = SomeImpossibleValue()
 s_Str0 = SomeString(no_nul=True)
 
+
 # ____________________________________________________________
 # weakrefs
 
 class SomeWeakRef(SomeObject):
     knowntype = weakref.ReferenceType
     immutable = True
+
     def __init__(self, classdef):
         # 'classdef' is None for known-to-be-dead weakrefs.
         self.classdef = classdef
 
 from rpython.rtyper.lltypesystem import llmemory
 
+
 class SomeAddress(SomeObject):
     immutable = True
 
     def is_null_address(self):
         return self.is_immutable_constant() and not self.const
 
+
 # The following class is used to annotate the intermediate value that
 # appears in expressions of the form:
 # addr.signed[offset] and addr.signed[offset] = value
 # annotation of low-level types
 
 from rpython.rtyper.lltypesystem import lltype
-from rpython.rtyper.ootypesystem import ootype
+
 
 class SomePtr(SomeObject):
     knowntype = lltype._ptr
     immutable = True
+
     def __init__(self, ll_ptrtype):
         assert isinstance(ll_ptrtype, lltype.Ptr)
         self.ll_ptrtype = ll_ptrtype
     def can_be_none(self):
         return False
 
+
 class SomeInteriorPtr(SomePtr):
     def __init__(self, ll_ptrtype):
         assert isinstance(ll_ptrtype, lltype.InteriorPtr)
         self.ll_ptrtype = ll_ptrtype
 
+
 class SomeLLADTMeth(SomeObject):
     immutable = True
+
     def __init__(self, ll_ptrtype, func):
         self.ll_ptrtype = ll_ptrtype
-        self.func = func 
+        self.func = func
 
     def can_be_none(self):
         return False
 
+
 class SomeOOObject(SomeObject):
     def __init__(self):
+        from rpython.rtyper.ootypesystem import ootype
         self.ootype = ootype.Object
 
+
 class SomeOOClass(SomeObject):
     def __init__(self, ootype):
         self.ootype = ootype
 
+
 class SomeOOInstance(SomeObject):
     def __init__(self, ootype, can_be_None=False):
         self.ootype = ootype
         self.can_be_None = can_be_None
 
+
 class SomeOOBoundMeth(SomeObject):
     immutable = True
+
     def __init__(self, ootype, name):
         self.ootype = ootype
         self.name = name
 
+
 class SomeOOStaticMeth(SomeObject):
     immutable = True
+
     def __init__(self, method):
         self.method = method
 
     (SomeAddress(), llmemory.Address),
 ]
 
+
 def annotation_to_lltype(s_val, info=None):
+    from rpython.rtyper.ootypesystem import ootype
+
     if isinstance(s_val, SomeOOInstance):
         return s_val.ootype
     if isinstance(s_val, SomeOOStaticMeth):
 
 ll_to_annotation_map = dict([(ll, ann) for ann, ll in annotation_to_ll_map])
 
+
 def lltype_to_annotation(T):
+    from rpython.rtyper.ootypesystem import ootype
+
     try:
         s = ll_to_annotation_map.get(T)
     except TypeError:
     else:
         return s
 
+
 def ll_to_annotation(v):
     if v is None:
         # i think we can only get here in the case of void-returning
         T = lltype.InteriorPtr(lltype.typeOf(ob), v._T, v._offsets)
         return SomeInteriorPtr(T)
     return lltype_to_annotation(lltype.typeOf(v))
-    
+
+
 # ____________________________________________________________
 
 class UnionError(Exception):
     """Signals an suspicious attempt at taking the union of
     deeply incompatible SomeXxx instances."""
 
+
 def unionof(*somevalues):
     "The most precise SomeValue instance that contains all the values."
     try:
             s1 = pair(s1, s2).union()
     return s1
 
+
 # make knowntypedata dictionary
 
 def add_knowntypedata(ktd, truth, vars, s_obj):
     for v in vars:
         ktd[(truth, v)] = s_obj
 
+
 def merge_knowntypedata(ktd1, ktd2):
     r = {}
     for truth_v in ktd1:
             r[truth_v] = unionof(ktd1[truth_v], ktd2[truth_v])
     return r
 
+
 def not_const(s_obj):
     if s_obj.is_constant() and not isinstance(s_obj, SomePBC):
         new_s_obj = SomeObject.__new__(s_obj.__class__)
         s_obj = new_s_obj
     return s_obj
 
+
 # ____________________________________________________________
 # internal
 
 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 
+    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):
         if args and isinstance(args[0], tuple):
             flattened = args
         for arg in flattened:
             if arg.__class__ is SomeObject and arg.knowntype is not type:
-                return  SomeObject()
+                return SomeObject()
         bookkeeper = rpython.annotator.bookkeeper.getbookkeeper()
         bookkeeper.warning("no precise annotation supplied for %s%r" % (name, args))
         return s_ImpossibleValue
     setattr(cls, name, default_op)
 
+
 class HarmlesslyBlocked(Exception):
     """Raised by the unaryop/binaryop to signal a harmless kind of
     BlockedInference: the current block is blocked, but not in a way

rpython/annotator/signature.py

         return SomeUnicodeString()
     elif t is types.NoneType:
         return s_None
-    elif bookkeeper and extregistry.is_registered_type(t, bookkeeper.policy):
-        entry = extregistry.lookup_type(t, bookkeeper.policy)
+    elif bookkeeper and extregistry.is_registered_type(t):
+        entry = extregistry.lookup_type(t)
         return entry.compute_annotation_bk(bookkeeper)
     elif t is type:
         return SomeType()
 
     def __init__(self, *argtypes):
         self.argtypes = argtypes
-        
+
     def __call__(self, funcdesc, inputcells):
         from rpython.rtyper.lltypesystem import lltype
         args_s = []

rpython/annotator/test/test_annrpython.py

         s = a.build_types(fun, [])
         assert s.const == 0
 
-    def test_some_generic_function_call(self):
-        def h(x):
-            return int(x)
-
-        def c(x):
-            return int(x)
-
-        def g(a, x):
-            if x == -1:
-                a = None
-            if x < 0:
-                if x == -1:
-                    a = h
-                else:
-                    a = c
-                x = x + .01
-            return a(x)
-
-        #def fun(x):
-
-        a = self.RPythonAnnotator(policy=policy.AnnotatorPolicy())
-        s = a.build_types(g, [annmodel.SomeGenericCallable(
-            args=[annmodel.SomeFloat()], result=annmodel.SomeInteger()),
-                              annmodel.SomeFloat()])
-        assert isinstance(s, annmodel.SomeInteger)
-        assert not hasattr(s, 'const')
-
     def test_compare_int_bool(self):
         def fun(x):
             return 50 < x

rpython/annotator/test/test_signature.py

     assert _annotation_key({str:(str, [str])}) == ('dict', (str, (str, ('list', str))))
     for i in ([[str]], [str], (int, int, {str: [str]})):
         assert hash(_annotation_key(i))
-
-def test_genericcallable():
-    py.test.skip("this two annotations should be equal - fix!")
-    from rpython.rtyper.extfunc import genericcallable
-    s1 = annotation([genericcallable([str], int)])
-    s2 = annotation([genericcallable([str], int)])
-    assert s1 == s2

rpython/annotator/unaryop.py

      SomeObject, SomeInteger, SomeBool, SomeString, SomeChar, SomeList, \
      SomeDict, SomeTuple, SomeImpossibleValue, SomeUnicodeCodePoint, \
      SomeInstance, SomeBuiltin, SomeFloat, SomeIterator, SomePBC, \
-     SomeExternalObject, SomeTypedAddressAccess, SomeAddress, SomeType, \
+     SomeTypedAddressAccess, SomeAddress, SomeType, \
      s_ImpossibleValue, s_Bool, s_None, \
      unionof, missing_operation, add_knowntypedata, HarmlesslyBlocked, \
-     SomeGenericCallable, SomeWeakRef, SomeUnicodeString
+     SomeWeakRef, SomeUnicodeString
 from rpython.annotator.bookkeeper import getbookkeeper
 from rpython.annotator import builtin
 from rpython.annotator.binaryop import _clone ## XXX where to put this?
         s_value = dct.dictdef.read_value()
         return (isinstance(s_key, SomeImpossibleValue) or
                 isinstance(s_value, SomeImpossibleValue))
-        
+
     def len(dct):
         if dct._is_empty():
             return immutablevalue(0)
         else:
             return SomeObject()    # len() on a pbc? no chance
 
-class __extend__(SomeGenericCallable):
-    def call(self, args):
-        bookkeeper = getbookkeeper()
-        for arg, expected in zip(args.unpack()[0], self.args_s):
-            assert expected.contains(arg)
-        
-        return self.s_result
-
-class __extend__(SomeExternalObject):
-    def getattr(p, s_attr):
-        if s_attr.is_constant() and isinstance(s_attr.const, str):
-            attr = s_attr.const
-            entry = extregistry.lookup_type(p.knowntype)
-            s_value = entry.get_field_annotation(p.knowntype, attr)
-            return s_value
-        else:
-            return SomeObject()
-    getattr.can_only_throw = []
-    
-    def setattr(p, s_attr, s_value):
-        assert s_attr.is_constant()
-        attr = s_attr.const
-        entry = extregistry.lookup_type(p.knowntype)
-        entry.set_field_annotation(p.knowntype, attr, s_value)
-    
-    def is_true(p):
-        return s_Bool
-
 # annotation of low-level types
 from rpython.annotator.model import SomePtr, SomeLLADTMeth
 from rpython.annotator.model import SomeOOInstance, SomeOOBoundMeth, SomeOOStaticMeth
             return SomeOOBoundMeth(r.ootype, s_attr.const)
         return ll_to_annotation(v)
 
-    def setattr(r, s_attr, s_value): 
+    def setattr(r, s_attr, s_value):
         assert s_attr.is_constant(), "setattr on ref %r with non-constant field-name" % r.ootype
         v = annotation_to_lltype(s_value)
         example = r.ootype._example()

rpython/rlib/_rsocket_rffi.py

 CConfig.in_addr = platform.Struct('struct in_addr',
                                          [('s_addr', rffi.UINT)])
 CConfig.in6_addr = platform.Struct('struct in6_addr',
-                                          [])
+                                          [('s6_addr', rffi.CFixedArray(rffi.CHAR, 16))])
 CConfig.sockaddr_in = platform.Struct('struct sockaddr_in',
                                         [('sin_family', rffi.INT),
                                          ('sin_port',   rffi.USHORT),

rpython/rlib/jit.py

             return result
 
         return decorate
-        
+
 
     def clone(self):
         assert self.inline_jit_merge_point, 'JitDriver.clone works only after @inline'
         assert s_name.is_constant()
         if s_name.const == 'enable_opts':
             assert annmodel.SomeString(can_be_None=True).contains(s_value)
-        else: 
+        else:
             assert (s_value == annmodel.s_None or
                     annmodel.SomeInteger().contains(s_value))
         return annmodel.s_None
 
 class AsmInfo(object):
     """ An addition to JitDebugInfo concerning assembler. Attributes:
-    
+
     ops_offset - dict of offsets of operations or None
     asmaddr - (int) raw address of assembler block
     asmlen - assembler block length
 
     def specialize_call(self, hop):
         from rpython.rtyper.lltypesystem import rclass, lltype
-        
+
         classrepr = rclass.get_type_repr(hop.rtyper)
 
         hop.exception_cannot_occur()

rpython/rlib/rStringIO.py

         #  * the list of characters self.bigbuffer;
         #  * each of the strings in self.strings.
         #
+        self.closed = False
         self.strings = None
-        self.bigbuffer = []
+        self.bigbuffer = None
         self.pos = AT_END
 
     def close(self):
+        self.closed = True
         self.strings = None
         self.bigbuffer = None
 
     def is_closed(self):
-        return self.bigbuffer is None
+        return self.closed
 
     def getvalue(self):
         """If self.strings contains more than 1 string, join all the
         strings together.  Return the final single string."""
-        if len(self.bigbuffer):
+        if self.bigbuffer is not None:
             self.copy_into_bigbuffer()
             return ''.join(self.bigbuffer)
         if self.strings is not None:
         return ''
 
     def getsize(self):
-        result = len(self.bigbuffer)
+        result = 0
+        if self.bigbuffer is not None:
+            result += len(self.bigbuffer)
         if self.strings is not None:
             result += self.strings.getlength()
         return result
 
     def copy_into_bigbuffer(self):
         """Copy all the data into the list of characters self.bigbuffer."""
+        if self.bigbuffer is None:
+            self.bigbuffer = []
         if self.strings is not None:
             self.bigbuffer += self.strings.build()
             self.strings = None
         if p != AT_END:    # slow or semi-fast paths
             assert p >= 0
             endp = p + len(buffer)
-            if len(self.bigbuffer) >= endp:
+            if self.bigbuffer is not None and len(self.bigbuffer) >= endp:
                 # semi-fast path: the write is entirely inside self.bigbuffer
                 for i in range(len(buffer)):
                     self.bigbuffer[p + i] = buffer[i]
         if p == 0 and n < 0:
             self.pos = AT_END
             return self.getvalue()     # reading everything
-        if p == AT_END:
+        if p == AT_END or n == 0:
             return ''
         assert p >= 0
         self.copy_into_bigbuffer()
             return ''.join(self.bigbuffer[p:p+count])
 
     def readline(self, size=-1):
-        p = self.tell()
+        p = self.pos
+        if p == AT_END or size == 0:
+            return ''
+        assert p >= 0
         self.copy_into_bigbuffer()
         end = len(self.bigbuffer)
         if size >= 0 and size < end - p:
             end = p + size
-        assert p >= 0
         i = p
         while i < end:
             finished = self.bigbuffer[i] == '\n'
         # than CPython: it never grows the buffer, and it sets the current
         # position to the end.
         assert size >= 0
-        if size > len(self.bigbuffer):
+        if self.bigbuffer is None or size > len(self.bigbuffer):
             self.copy_into_bigbuffer()
         else:
             # we can drop all extra strings
                 self.strings = None
         if size < len(self.bigbuffer):
             del self.bigbuffer[size:]
+        if len(self.bigbuffer) == 0:
+            self.bigbuffer = None
         self.pos = AT_END

rpython/rlib/rsocket.py

         # to avoid leaks if an exception occurs inbetween
         sin = lltype.malloc(_c.sockaddr_in6, flavor='raw', zero=True)
         result.setdata(sin, sizeof(_c.sockaddr_in6))
-        rffi.setintfield(sin, 'c_sin6_family', AF_INET)
+        rffi.setintfield(sin, 'c_sin6_family', AF_INET6)
         rffi.structcopy(sin.c_sin6_addr, in6_addr)
         return result
     from_in6_addr = staticmethod(from_in6_addr)

rpython/rlib/signature.py

 from rpython.rlib import types
 
+
 def signature(*paramtypes, **kwargs):
     """Decorate a function to specify its type signature.
 
     """
     returntype = kwargs.pop('returns', None)
     if returntype is None:
-        raise TypeError, "signature: parameter 'returns' required"
+        raise TypeError("signature: parameter 'returns' required")
 
     def decorator(f):
         f._signature_ = (paramtypes, returntype)

rpython/rlib/test/test_rsocket.py

     a = NETLINKAddress(pid, group_mask)
     assert a.get_pid() == pid
     assert a.get_groups() == group_mask
-    
+
 def test_gethostname():
     s = gethostname()
     assert isinstance(s, str)
 
 def test_gethostbyname():
-    a = gethostbyname('localhost')
-    assert isinstance(a, INETAddress)
-    assert a.get_host() == "127.0.0.1"
+    for host in ["localhost", "127.0.0.1"]:
+        a = gethostbyname(host)
+        assert isinstance(a, INETAddress)
+        assert a.get_host() == "127.0.0.1"
 
 def test_gethostbyname_ex():
-    name, aliases, address_list = gethostbyname_ex('localhost')
-    allnames = [name] + aliases
-    for n in allnames:
-        assert isinstance(n, str)
-    if sys.platform != 'win32':
-        assert 'localhost' in allnames
-    for a in address_list:
-        if isinstance(a, INETAddress) and a.get_host() == "127.0.0.1":
-            break  # ok
-    else:
-        py.test.fail("could not find the 127.0.0.1 IPv4 address in %r"
-                     % (address_list,))
-
-def test_gethostbyaddr():
-    name, aliases, address_list = gethostbyaddr('127.0.0.1')
-    allnames = [name] + aliases
-    for n in allnames:
-        assert isinstance(n, str)
-    if sys.platform != 'win32':
-        assert 'localhost' in allnames
-    for a in address_list:
-        if isinstance(a, INETAddress) and a.get_host() == "127.0.0.1":
-            break  # ok
-    else:
-        py.test.fail("could not find the 127.0.0.1 IPv4 address in %r"
-                     % (address_list,))
-
-        name, aliases, address_list = gethostbyaddr('localhost')
+    for host in ["localhost", "127.0.0.1"]:
+        name, aliases, address_list = gethostbyname_ex(host)
         allnames = [name] + aliases
         for n in allnames:
             assert isinstance(n, str)
         if sys.platform != 'win32':
-            assert 'localhost' in allnames
+            assert host in allnames
         for a in address_list:
-            if isinstance(a, INET6Address) and a.get_host() == "::1":
+            if isinstance(a, INETAddress) and a.get_host() == "127.0.0.1":
                 break  # ok
+            # no IPV6, should always return IPV4
         else:
-            py.test.fail("could not find the ::1 IPv6 address in %r"
+            py.test.fail("could not find the localhost address in %r"
+                         % (address_list,))
+
+def test_gethostbyaddr():
+    for host in ["localhost", "127.0.0.1", "::1"]:
+        name, aliases, address_list = gethostbyaddr(host)
+        allnames = [name] + aliases
+        for n in allnames:
+            assert isinstance(n, str)
+        if sys.platform != 'win32':
+            assert 'localhost' in allnames or 'ip6-localhost' in allnames
+        for a in address_list:
+            if isinstance(a, INETAddress) and a.get_host() == "127.0.0.1":
+                break  # ok
+            if host != '127.0.0.1':  # name lookup might return IPV6
+                if isinstance(a, INET6Address) and a.get_host() == "::1":
+                    break  # ok
+        else:
+            py.test.fail("could not find the localhost address in %r"
                          % (address_list,))
 
 def test_getservbyname():
 
         def as_str(self):
             return self.x
-    
+
     if sys.platform == "win32":
         py.test.skip('No socketpair on Windows')
     s1, s2 = socketpair()

rpython/rlib/types.py

 def float():
     return model.SomeFloat()
 
+
 def singlefloat():
     return model.SomeSingleFloat()
 
+
 def longfloat():
     return model.SomeLongFloat()
 
     return model.SomeInteger()
 
 
+def bool():
+    return model.SomeBool()
+
+
 def unicode():
     return model.SomeUnicodeString()
 
+
 def unicode0():
     return model.SomeUnicodeString(no_nul=True)
 
+
 def str():
     return model.SomeString()
 
+
 def str0():
     return model.SomeString(no_nul=True)
 
+
 def char():
     return model.SomeChar()
 
     listdef = ListDef(None, element, mutated=True, resized=True)
     return model.SomeList(listdef)
 
+
 def array(element):
     listdef = ListDef(None, element, mutated=True, resized=False)
     return model.SomeList(listdef)
 
+
 def dict(keytype, valuetype):
     dictdef = DictDef(None, keytype, valuetype)
     return model.SomeDict(dictdef)
 
 
-def instance(class_):
-    return lambda bookkeeper: model.SomeInstance(bookkeeper.getuniqueclassdef(class_))
+def instance(cls):
+    return lambda bookkeeper: model.SomeInstance(bookkeeper.getuniqueclassdef(cls))
+
 
 class SelfTypeMarker(object):
     pass
 
+
 def self():
     return SelfTypeMarker()
 
 class AnyTypeMarker(object):
     pass
 
+
 def any():
     return AnyTypeMarker()

rpython/rtyper/extfunc.py

     def _freeze_(self):
         return True
 
-class genericcallable(object):
-    """ A way to specify the callable annotation, but deferred until
-    we have bookkeeper
-    """
-    def __init__(self, args, result=None):
-        self.args = args
-        self.result = result
-
-class _ext_callable(ExtRegistryEntry):
-    _type_ = genericcallable
-    # we defer a bit annotation here
-
-    def compute_result_annotation(self):
-        return annmodel.SomeGenericCallable([annotation(i, self.bookkeeper)
-                                             for i in self.instance.args],
-                           annotation(self.instance.result, self.bookkeeper))
-
 class ExtFuncEntry(ExtRegistryEntry):
     safe_not_sandboxed = False
 
     llfakeimpl, oofakeimpl: optional; if provided, they are called by the llinterpreter
     sandboxsafe: use True if the function performs no I/O (safe for --sandbox)
     """
-    
+
     if export_name is None:
         export_name = function.__name__
 

rpython/rtyper/extregistry.py

             for k in key:
                 selfcls._register(dict, k)
         else:
-            for basecls in selfcls.__mro__:
-                if '_condition_' in basecls.__dict__:
-                    cond = basecls.__dict__['_condition_']
-                    break
-            else:
-                cond = None
-            try:
-                family = dict[key]
-            except KeyError:
-                family = dict[key] = ClassFamily()
-            family.add(selfcls, cond)
+            if key in dict:
+                raise ValueError("duplicate extregistry entry %r" % (selfcls,))
+            dict[key] = selfcls
 
     def _register_value(selfcls, key):
         selfcls._register(EXT_REGISTRY_BY_VALUE, key)
     def _register_metatype(selfcls, key):
         selfcls._register(EXT_REGISTRY_BY_METATYPE, key)
 
-class ClassFamily(object):
-
-    def __init__(self):
-        self.default = None
-        self.conditionals = []
-
-    def add(self, cls, cond=None):
-        if cond is None:
-            assert self.default is None, (
-                "duplicate extregistry entry %r" % (cls,))
-            self.default = cls
-        else:
-            self.conditionals.append((cls, cond))
-
-    def match(self, config):
-        if config is not None:
-            matches = [cls for cls, cond in self.conditionals
-                           if cond(config)]
-            if matches:
-                assert len(matches) == 1, (
-                    "multiple extregistry matches: %r" % (matches,))
-                return matches[0]
-        if self.default:
-            return self.default
-        raise KeyError("no default extregistry entry")
-
 
 class ExtRegistryEntry(object):
     __metaclass__ = AutoRegisteringType
 # ____________________________________________________________
 # Public interface to access the registry
 
-def _lookup_type_cls(tp, config):
+def _lookup_type_cls(tp):
     try:
-        return EXT_REGISTRY_BY_TYPE[tp].match(config)
+        return EXT_REGISTRY_BY_TYPE[tp]
     except (KeyError, TypeError):
-        return EXT_REGISTRY_BY_METATYPE[type(tp)].match(config)
+        return EXT_REGISTRY_BY_METATYPE[type(tp)]
 
-def lookup_type(tp, config=None):
-    Entry = _lookup_type_cls(tp, config)
+def lookup_type(tp):
+    Entry = _lookup_type_cls(tp)
     return Entry(tp)
 
-def is_registered_type(tp, config=None):
+def is_registered_type(tp):
     try:
-        _lookup_type_cls(tp, config)
+        _lookup_type_cls(tp)
     except KeyError:
         return False
     return True
 
-def _lookup_cls(instance, config):
+def _lookup_cls(instance):
     try:
-        return EXT_REGISTRY_BY_VALUE[instance].match(config)
+        return EXT_REGISTRY_BY_VALUE[instance]
     except (KeyError, TypeError):
-        return _lookup_type_cls(type(instance), config)
+        return _lookup_type_cls(type(instance))
 
-def lookup(instance, config=None):
-    Entry = _lookup_cls(instance, config)
+def lookup(instance):
+    Entry = _lookup_cls(instance)
     return Entry(type(instance), instance)
 
-def is_registered(instance, config=None):
+def is_registered(instance):
     try:
-        _lookup_cls(instance, config)
+        _lookup_cls(instance)
     except KeyError:
         return False
     return True

rpython/rtyper/lltypesystem/rgeneric.py

-
-from rpython.rtyper.rgeneric import AbstractGenericCallableRepr
-from rpython.rtyper.lltypesystem.lltype import Ptr, FuncType
-
-class GenericCallableRepr(AbstractGenericCallableRepr):
-    def create_low_leveltype(self):
-        l_args = [r_arg.lowleveltype for r_arg in self.args_r]
-        l_retval = self.r_result.lowleveltype
-        return Ptr(FuncType(l_args, l_retval))

rpython/rtyper/lltypesystem/rlist.py

-from rpython.rlib import rgc, jit
+from rpython.rlib import rgc, jit, types
 from rpython.rlib.debug import ll_assert
-from rpython.rlib.objectmodel import enforceargs
+from rpython.rlib.signature import signature
 from rpython.rtyper.lltypesystem import rstr
 from rpython.rtyper.lltypesystem.lltype import (GcForwardReference, Ptr, GcArray,
      GcStruct, Void, Signed, malloc, typeOf, nullptr, typeMethod)
 
 # adapted C code
 
-@enforceargs(None, int, None)
+@signature(types.any(), types.int(), types.bool(), returns=types.none())
 def _ll_list_resize_hint_really(l, newsize, overallocate):
     """
     Ensure l.items has room for at least newsize elements.  Note that
     if allocated < newsize or newsize < (allocated >> 1) - 5:
         _ll_list_resize_hint_really(l, newsize, False)
 
-@enforceargs(None, int, None)
+
+@signature(types.any(), types.int(), types.bool(), returns=types.none())
 def _ll_list_resize_really(l, newsize, overallocate):
     """
     Ensure l.items has room for at least newsize elements, and set

rpython/rtyper/ootypesystem/ootype.py

 import py
-from py.builtin import set
-from rpython.rtyper.lltypesystem.lltype import LowLevelType, Signed, Unsigned, Float, Char
-from rpython.rtyper.lltypesystem.lltype import Bool, Void, UniChar, typeOf, \
-        Primitive, isCompatibleType, enforce, saferecursive, SignedLongLong, UnsignedLongLong
-from rpython.rtyper.lltypesystem.lltype import frozendict
-from rpython.rtyper.lltypesystem.lltype import identityhash
+
+from rpython.rlib import objectmodel, types
+from rpython.rlib.signature import signature
 from rpython.rlib.rarithmetic import intmask
-from rpython.rlib import objectmodel
+from rpython.rtyper.lltypesystem.lltype import (LowLevelType, Signed, Unsigned,
+    Float, Char, Bool, Void, UniChar, typeOf, Primitive, isCompatibleType,
+    enforce, saferecursive, SignedLongLong, UnsignedLongLong, frozendict,
+    identityhash)
 from rpython.tool.uid import uid
 
 
 
     def _example(self):
         return _class(ROOT)
-    
+
 Class = Class()
 
 class Instance(OOType):
 
     def __hash__(self):
         return object.__hash__(self)
-        
+
     def _defl(self):
         return self._null
 
             _, meth = self._lookup(name)
             if meth is not None:
                 raise TypeError("Cannot add field %r: method already exists" % name)
-        
+
             if self._superclass is not None:
                 if self._superclass._has_field(name):
                     raise TypeError("Field %r exists in superclass" % name)
             if type(defn) is not tuple:
                 if isinstance(defn, Meth):
                     raise TypeError("Attempting to store method in field")
-                
+
                 fields[name] = (defn, defn._defl())
             else:
                 ootype, default = defn
     def _init_instance(self, instance):
         if self._superclass is not None:
             self._superclass._init_instance(instance)
-        
+
         for name, (ootype, default) in self._fields.iteritems():
             instance.__dict__[name] = enforce(ootype, default)
 
 
     # this is the equivalent of the lltypesystem ll_newlist that is
     # marked as typeMethod.
+    @signature(types.any(), types.int(), returns=types.any())
     def ll_newlist(self, length):
         from rpython.rtyper.ootypesystem import rlist
         return rlist.ll_newlist(self, length)
-    ll_newlist._annenforceargs_ = (None, int)
 
     # NB: We are expecting Lists of the same ITEMTYPE to compare/hash
     # equal. We don't redefine __eq__/__hash__ since the implementations
     def __hash__(self):
         if self.ITEM is None:
             raise TypeError("Can't hash uninitialized List type.")
-        return BuiltinADTType.__hash__(self)    
+        return BuiltinADTType.__hash__(self)
 
     def __str__(self):
         return '%s(%s)' % (self.__class__.__name__,
     def _specialize(self, generic_types):
         ITEMTYPE = self._specialize_type(self.ITEM, generic_types)
         return self.__class__(ITEMTYPE)
-    
+
     def _defl(self):
         return self._null
 
     # placeholders for types
     # make sure that each derived class has his own SELFTYPE_T
     # placeholder, because we want backends to distinguish that.
-    
+
     SELFTYPE_T = object()
     ITEMTYPE_T = object()
     oopspec_name = 'list'
     def __hash__(self):
         if self.ITEM is None:
             raise TypeError("Can't hash uninitialized List type.")
-        return BuiltinADTType.__hash__(self)    
+        return BuiltinADTType.__hash__(self)
 
     def __str__(self):
         return '%s(%s)' % (self.__class__.__name__,
         self.ITEM = ITEMTYPE
         self._init_methods()
 
+    @signature(types.any(), types.int(), returns=types.any())
     def ll_newlist(self, length):
         from rpython.rtyper.ootypesystem import rlist
         return rlist.ll_newarray(self, length)
-    ll_newlist._annenforceargs_ = (None, int)
 
     def ll_convert_from_array(self, array):
         return array
 
+
 class Dict(BuiltinADTType):
     # placeholders for types
     SELFTYPE_T = object()
             return False
         if not self._is_initialized() or not other._is_initialized():
             return False # behave like a ForwardReference, i.e. compare by identity
-        return BuiltinADTType.__eq__(self, other) 
+        return BuiltinADTType.__eq__(self, other)
 
     def __ne__(self, other):
         return not (self == other)
         self._KEYTYPE = KEYTYPE
         self._VALUETYPE = VALUETYPE
         self._init_methods()
-                                           
+
 
 class CustomDict(Dict):
     def __init__(self, KEYTYPE=None, VALUETYPE=None):
         KEYTYPE = self._specialize_type(self._KEYTYPE, generic_types)
         VALUETYPE = self._specialize_type(self._VALUETYPE, generic_types)
         return self.__class__(KEYTYPE, VALUETYPE)
-    
+
 # ____________________________________________________________
 
 class _object(object):
 Class._null = nullruntimeclass
 
 class _instance(object):
-    
+
     def __init__(self, INSTANCE):
         self.__dict__["_TYPE"] = INSTANCE
         INSTANCE._init_instance(self)
         DEFINST, meth = self._TYPE._lookup(name)
         if meth is not None:
             return meth._bound(DEFINST, self)
-        
+
         self._TYPE._check_field(name)
 
         return self.__dict__[name]
         return self
 
     _enforce = _upcast
-    
+
     def _downcast(self, INSTANCE):
         assert instanceof(self, INSTANCE)
         return self
         def __getattribute__(self, name):
             if name.startswith("_"):
                 return object.__getattribute__(self, name)
-        
+
             raise RuntimeError("Access to field in null object")
 
         def __setattr__(self, name, value):
 
    def __ne__(self, other):
        return not (self == other)
-   
+
    def __hash__(self):
        return hash(frozendict(self.__dict__))
 
 
    def __eq__(self, other):
        return self is other
-   
+
    def __hash__(self):
        return id(self)
 
 
 class _meth(_callable):
     _bound_class = _bound_meth
-    
+
     def __init__(self, METHOD, **attrs):
         assert isinstance(METHOD, Meth)
         _callable.__init__(self, METHOD, **attrs)
             return True
         else:
             return False
-    
+
     def annotation_to_lltype(cls, ann):
         from rpython.annotator import model as annmodel
         return annmodel.annotation_to_lltype(ann)
         return len(self._list)
 
     def _ll_resize_ge(self, length):
-        # NOT_RPYTHON        
+        # NOT_RPYTHON
         if len(self._list) < length:
             diff = length - len(self._list)
             self._list += [self._TYPE.ITEM._defl()] * diff
 class _null_list(_null_mixin(_list), _list):
 
     def __init__(self, LIST):
-        self.__dict__["_TYPE"] = LIST 
+        self.__dict__["_TYPE"] = LIST
 
 class _array(_builtin_type):
     def __init__(self, ARRAY, length):
 class _null_array(_null_mixin(_array), _array):
 
     def __init__(self, ARRAY):
-        self.__dict__["_TYPE"] = ARRAY 
+        self.__dict__["_TYPE"] = ARRAY
 
 class _dict(_builtin_type):
     def __init__(self, DICT):
     def ll_go_next(self):
         # NOT_RPYTHON
         self._check_stamp()
-        self._index += 1        
+        self._index += 1
         if self._index >= len(self._items):
             return False
         else:
         self._check_stamp()
         assert 0 <= self._index < len(self._items)
         return self._items[self._index][0]
-    
+
     def ll_current_value(self):
         # NOT_RPYTHON
         self._check_stamp()
 class _null_record(_null_mixin(_record), _record):
 
     def __init__(self, RECORD):
-        self.__dict__["_TYPE"] = RECORD 
+        self.__dict__["_TYPE"] = RECORD
 
 
 def new(TYPE):
 
 def ooupcast(INSTANCE, instance):
     return instance._upcast(INSTANCE)
-    
+
 def oodowncast(INSTANCE, instance):
     return instance._downcast(INSTANCE)
 
 def oostring(obj, base):
     """
     Convert char, int, float, instances and str to str.
-    
+
     Base is used only for formatting int: for other types is ignored
     and should be set to -1. For int only base 8, 10 and 16 are
     supported.

rpython/rtyper/ootypesystem/rgeneric.py

-
-from rpython.rtyper.rgeneric import AbstractGenericCallableRepr
-from rpython.rtyper.ootypesystem import ootype
-
-class GenericCallableRepr(AbstractGenericCallableRepr):
-    def create_low_leveltype(self):
-        l_args = [r_arg.lowleveltype for r_arg in self.args_r]
-        l_retval = self.r_result.lowleveltype
-        return ootype.StaticMethod(l_args, l_retval)

rpython/rtyper/rexternalobj.py

-from rpython.annotator import model as annmodel
-from rpython.rtyper import extregistry
-from rpython.rtyper.lltypesystem import lltype
-
-# ExternalObjects
-
-
-class __extend__(annmodel.SomeExternalObject):
-    def rtyper_makerepr(self, rtyper):
-       # delegate to the get_repr() of the extregistrered Entry class
-        entry = extregistry.lookup_type(self.knowntype)
-        return entry.get_repr(rtyper, self)
-
-    def rtyper_makekey(self):
-        # grab all attributes of the SomeExternalObject for the key
-        attrs = lltype.frozendict(self.__dict__)
-        if 'const' in attrs:
-            del attrs['const']
-        if 'const_box' in attrs:
-            del attrs['const_box']
-        return self.__class__, attrs

rpython/rtyper/rgeneric.py

-from rpython.annotator import model as annmodel
-from rpython.rtyper.lltypesystem import lltype
-from rpython.rtyper.rmodel import Repr
-from rpython.rtyper.rpbc import AbstractFunctionsPBCRepr
-from rpython.tool.pairtype import pairtype
-
-
-class AbstractGenericCallableRepr(Repr):
-    def __init__(self, rtyper, s_generic):
-        self.rtyper = rtyper