Beispiel #1
0
 def newlist(self, list_w):
     # make sure that the annotator thinks that the list is resized
     list_w.append(W_Root())
     #
     for w_x in list_w:
         is_root(w_x)
     return W_MyListObj()
Beispiel #2
0
 def int(self, space):
     if (type(self) is not W_LongObject
             and space.is_overloaded(self, space.w_long, '__int__')):
         return W_Root.int(self, space)
     try:
         return space.newint(self.num.toint())
     except OverflowError:
         return self.descr_long(space)
Beispiel #3
0
 def int(self, space):
     if (type(self) is not W_LongObject and
         space.is_overloaded(self, space.w_long, '__int__')):
         return W_Root.int(self, space)
     try:
         return space.newint(self.num.toint())
     except OverflowError:
         return self.descr_long(space)
Beispiel #4
0
 def int(self, space):
     if (type(self) is not W_FloatObject and
         space.is_overloaded(self, space.w_float, '__int__')):
         return W_Root.int(self, space)
     try:
         value = ovfcheck_float_to_int(self.floatval)
     except OverflowError:
         return space.long(self)
     else:
         return space.newint(value)
Beispiel #5
0
    def test_ptreq4(self):
        w2 = W_Root()

        def f(n):
            w1 = newbool(None, n >= 10)
            return int(w1 is w2) + int(w2 is w1)

        res = self.timeshift(f, [123], policy=MyPolicy())
        assert res == 0
        self.check_insns({'int_ge': 1})
Beispiel #6
0
 def immutable_unique_id(self, space):
     if self.w_instance is not None:
         return W_Root.immutable_unique_id(self, space)
     # the special-case is only for *unbound* method objects
     #
     from pypy.objspace.std.util import IDTAG_UNBOUND_METHOD as tag
     from pypy.objspace.std.util import IDTAG_SHIFT
     id = space.bigint_w(space.id(self.w_function))
     id = id.lshift(LONG_BIT).or_(space.bigint_w(space.id(self.w_class)))
     id = id.lshift(IDTAG_SHIFT).int_or_(tag)
     return space.newlong_from_rbigint(id)
Beispiel #7
0
    def __new__(cls,
                f,
                app_name=None,
                unwrap_spec=None,
                descrmismatch=None,
                as_classmethod=False,
                doc=None,
                self_type=None):

        # f must be a function whose name does NOT start with 'app_'
        if hasattr(f, 'im_func'):
            assert self_type in (None, f.im_class)
            self_type = f.im_class
            f = f.im_func
        if not isinstance(f, types.FunctionType):
            raise TypeError("function expected, got %r instead" % f)
        if app_name is None:
            if f.func_name.startswith('app_'):
                raise ValueError("function name %r suspiciously starts "
                                 "with 'app_'" % f.func_name)
            app_name = f.func_name

        if unwrap_spec is not None:
            unwrap_spec_key = tuple(unwrap_spec)
        else:
            unwrap_spec_key = None
        key = (f, self_type, unwrap_spec_key, descrmismatch, as_classmethod)
        if key in cls.instancecache:
            result = cls.instancecache[key]
            assert result.__class__ is cls
            return result
        self = W_Root.__new__(cls)
        cls.instancecache[key] = self
        self._code = BuiltinCode(f,
                                 unwrap_spec=unwrap_spec,
                                 self_type=self_type,
                                 descrmismatch=descrmismatch,
                                 doc=doc)
        self.__name__ = f.func_name
        self.name = app_name
        self.as_classmethod = as_classmethod

        if not f.func_defaults:
            self._staticdefs = []
        else:
            argnames = self._code._argnames
            defaults = f.func_defaults
            self._staticdefs = zip(argnames[-len(defaults):], defaults)
        self.self_type = self_type
        return self
Beispiel #8
0
 def is_w(self, space, other):
     if self.w_instance is not None:
         return W_Root.is_w(self, space, other)
     # The following special-case is only for *unbound* method objects.
     # Motivation: in CPython, it seems that no strange internal type
     # exists where the equivalent of ``x.method is x.method`` would
     # return True.  This is unlike unbound methods, where e.g.
     # ``list.append is list.append`` returns True.  The following code
     # is here to emulate that behaviour.  Unlike CPython, we return
     # True for all equal unbound methods, not just for built-in types.
     if not isinstance(other, Method):
         return False
     return (other.w_instance is None
             and self.w_function is other.w_function
             and self.w_class is other.w_class)
Beispiel #9
0
    def __new__(cls, f, app_name=None, unwrap_spec=None, descrmismatch=None,
                as_classmethod=False, doc=None):

        "NOT_RPYTHON"
        # f must be a function whose name does NOT start with 'app_'
        self_type = None
        if hasattr(f, 'im_func'):
            self_type = f.im_class
            f = f.im_func
        if not isinstance(f, types.FunctionType):
            raise TypeError("function expected, got %r instead" % f)
        if app_name is None:
            if f.func_name.startswith('app_'):
                raise ValueError("function name %r suspiciously starts "
                                   "with 'app_'" % f.func_name)
            app_name = f.func_name

        if unwrap_spec is not None:
            unwrap_spec_key = tuple(unwrap_spec)
        else:
            unwrap_spec_key = None
        key = (f, self_type, unwrap_spec_key, descrmismatch, as_classmethod)
        if key in cls.instancecache:
            result = cls.instancecache[key]
            assert result.__class__ is cls
            return result
        self = W_Root.__new__(cls)
        cls.instancecache[key] = self
        self._code = BuiltinCode(f, unwrap_spec=unwrap_spec,
                                 self_type=self_type,
                                 descrmismatch=descrmismatch,
                                 doc=doc)
        self.__name__ = f.func_name
        self.name = app_name
        self.as_classmethod = as_classmethod

        if not f.func_defaults:
            self._staticdefs = []
        else:
            argnames = self._code._argnames
            defaults = f.func_defaults
            self._staticdefs = zip(argnames[-len(defaults):], defaults)
        return self
Beispiel #10
0
 def int(self, space):
     if type(self) is W_LongObject:
         return self
     if not space.is_overloaded(self, space.w_int, '__int__'):
         return W_LongObject(self.num)
     return W_Root.int(self, space)
Beispiel #11
0
 def int(self, space):
     if type(self) is W_IntObject:
         return self
     if not space.is_overloaded(self, space.w_int, '__int__'):
         return space.newint(self.intval)
     return W_Root.int(self, space)
 def int(self, space):
     # this is a speed-up only, for space.int(w_float).
     if (type(self) is not W_FloatObject
             and space.is_overloaded(self, space.w_float, '__int__')):
         return W_Root.int(self, space)
     return self.descr_trunc(space)
Beispiel #13
0
class FakeSpace(ObjSpace):
    w_ValueError = W_TypeObject("ValueError")
    w_TypeError = W_TypeObject("TypeError")
    w_IndexError = W_TypeObject("IndexError")
    w_OverflowError = W_TypeObject("OverflowError")
    w_NotImplementedError = W_TypeObject("NotImplementedError")
    w_AttributeError = W_TypeObject("AttributeError")
    w_StopIteration = W_TypeObject("StopIteration")
    w_KeyError = W_TypeObject("KeyError")
    w_SystemExit = W_TypeObject("SystemExit")
    w_KeyboardInterrupt = W_TypeObject("KeyboardInterrupt")
    w_RuntimeError = W_TypeObject("RuntimeError")
    w_RecursionError = W_TypeObject("RecursionError")  # py3.5
    w_VisibleDeprecationWarning = W_TypeObject("VisibleDeprecationWarning")
    w_None = W_Root()

    w_bool = W_TypeObject("bool")
    w_int = W_TypeObject("int")
    w_float = W_TypeObject("float")
    w_list = W_TypeObject("list")
    w_long = W_TypeObject("long")
    w_tuple = W_TypeObject('tuple')
    w_slice = W_TypeObject("slice")
    w_bytes = W_TypeObject("str")
    w_text = w_bytes
    w_unicode = W_TypeObject("unicode")
    w_complex = W_TypeObject("complex")
    w_dict = W_TypeObject("dict")
    w_object = W_TypeObject("object")
    w_buffer = W_TypeObject("buffer")
    w_type = W_TypeObject("type")
    w_frozenset = W_TypeObject("frozenset")

    def __init__(self, config=None):
        """NOT_RPYTHON"""
        self.fromcache = InternalSpaceCache(self).getorbuild
        self.w_Ellipsis = special.Ellipsis()
        self.w_NotImplemented = special.NotImplemented()

        if config is None:
            from pypy.config.pypyoption import get_pypy_config
            config = get_pypy_config(translating=False)
        self.config = config

        self.interned_strings = make_weak_value_dictionary(self, str, W_Root)
        self.builtin = DictObject({})
        self.FrameClass = PyFrame
        self.threadlocals = ThreadLocals()
        self.actionflag = ActionFlag()  # changed by the signal module
        self.check_signal_action = None  # changed by the signal module

    def _freeze_(self):
        return True

    def is_none(self, w_obj):
        return w_obj is None or w_obj is self.w_None

    def issequence_w(self, w_obj):
        return isinstance(w_obj, ListObject) or isinstance(w_obj, W_NDimArray)

    def len(self, w_obj):
        if isinstance(w_obj, ListObject):
            return self.wrap(len(w_obj.items))
        elif isinstance(w_obj, DictObject):
            return self.wrap(len(w_obj.items))
        raise NotImplementedError

    def getattr(self, w_obj, w_attr):
        assert isinstance(w_attr, StringObject)
        if isinstance(w_obj, DictObject):
            return w_obj.getdictvalue(self, w_attr)
        return None

    def issubtype_w(self, w_sub, w_type):
        is_root(w_type)
        return NonConstant(True)

    def isinstance_w(self, w_obj, w_tp):
        try:
            return w_obj.tp == w_tp
        except AttributeError:
            return False

    def iter(self, w_iter):
        if isinstance(w_iter, ListObject):
            raise NotImplementedError
            #return IterObject(space, w_iter.items)
        elif isinstance(w_iter, DictObject):
            return IterDictObject(self, w_iter)

    def next(self, w_iter):
        return w_iter.next()

    def contains(self, w_iter, w_key):
        if isinstance(w_iter, DictObject):
            return self.wrap(w_key in w_iter.items)

        raise NotImplementedError

    def decode_index4(self, w_idx, size):
        if isinstance(w_idx, IntObject):
            return (self.int_w(w_idx), 0, 0, 1)
        else:
            assert isinstance(w_idx, SliceObject)
            start, stop, step = w_idx.start, w_idx.stop, w_idx.step
            if step == 0:
                return (0, size, 1, size)
            if start < 0:
                start += size
            if stop < 0:
                stop += size + 1
            if step < 0:
                start, stop = stop, start
                start -= 1
                stop -= 1
                lgt = (stop - start + 1) / step + 1
            else:
                lgt = (stop - start - 1) / step + 1
            return (start, stop, step, lgt)

    def unicode_from_object(self, w_item):
        # XXX
        return StringObject("")

    @specialize.argtype(1)
    def wrap(self, obj):
        if isinstance(obj, float):
            return FloatObject(obj)
        elif isinstance(obj, bool):
            return BoolObject(obj)
        elif isinstance(obj, int):
            return IntObject(obj)
        elif isinstance(obj, base_int):
            return LongObject(obj)
        elif isinstance(obj, W_Root):
            return obj
        elif isinstance(obj, str):
            return StringObject(obj)
        raise NotImplementedError

    def newtext(self, obj):
        return StringObject(obj)

    newbytes = newtext

    def newutf8(self, obj, l):
        raise NotImplementedError

    def newlist(self, items):
        return ListObject(items)

    def newcomplex(self, r, i):
        return ComplexObject(r, i)

    def newfloat(self, f):
        return FloatObject(f)

    def newslice(self, start, stop, step):
        return SliceObject(self.int_w(start), self.int_w(stop),
                           self.int_w(step))

    def le(self, w_obj1, w_obj2):
        assert isinstance(w_obj1, boxes.W_GenericBox)
        assert isinstance(w_obj2, boxes.W_GenericBox)
        return w_obj1.descr_le(self, w_obj2)

    def lt(self, w_obj1, w_obj2):
        assert isinstance(w_obj1, boxes.W_GenericBox)
        assert isinstance(w_obj2, boxes.W_GenericBox)
        return w_obj1.descr_lt(self, w_obj2)

    def ge(self, w_obj1, w_obj2):
        assert isinstance(w_obj1, boxes.W_GenericBox)
        assert isinstance(w_obj2, boxes.W_GenericBox)
        return w_obj1.descr_ge(self, w_obj2)

    def add(self, w_obj1, w_obj2):
        assert isinstance(w_obj1, boxes.W_GenericBox)
        assert isinstance(w_obj2, boxes.W_GenericBox)
        return w_obj1.descr_add(self, w_obj2)

    def sub(self, w_obj1, w_obj2):
        return self.wrap(1)

    def mul(self, w_obj1, w_obj2):
        assert isinstance(w_obj1, boxes.W_GenericBox)
        assert isinstance(w_obj2, boxes.W_GenericBox)
        return w_obj1.descr_mul(self, w_obj2)

    def pow(self, w_obj1, w_obj2, _):
        return self.wrap(1)

    def neg(self, w_obj1):
        return self.wrap(0)

    def repr(self, w_obj1):
        return self.wrap('fake')

    def getitem(self, obj, index):
        if isinstance(obj, DictObject):
            w_dict = obj.getdict(self)
            if w_dict is not None:
                try:
                    return w_dict[index]
                except KeyError as e:
                    raise oefmt(self.w_KeyError, "key error")

        assert isinstance(obj, ListObject)
        assert isinstance(index, IntObject)
        return obj.items[index.intval]

    def listview(self, obj, number=-1):
        assert isinstance(obj, ListObject)
        if number != -1:
            assert number == 2
            return [obj.items[0], obj.items[1]]
        return obj.items

    fixedview = listview

    def float(self, w_obj):
        if isinstance(w_obj, FloatObject):
            return w_obj
        assert isinstance(w_obj, boxes.W_GenericBox)
        return self.float(w_obj.descr_float(self))

    def float_w(self, w_obj, allow_conversion=True):
        assert isinstance(w_obj, FloatObject)
        return w_obj.floatval

    def int_w(self, w_obj, allow_conversion=True):
        if isinstance(w_obj, IntObject):
            return w_obj.intval
        elif isinstance(w_obj, FloatObject):
            return int(w_obj.floatval)
        elif isinstance(w_obj, SliceObject):
            raise oefmt(self.w_TypeError, "slice.")
        raise NotImplementedError

    def unpackcomplex(self, w_obj):
        if isinstance(w_obj, ComplexObject):
            return w_obj.r, w_obj.i
        raise NotImplementedError

    def index(self, w_obj):
        return self.wrap(self.int_w(w_obj))

    def bytes_w(self, w_obj):
        if isinstance(w_obj, StringObject):
            return w_obj.v
        raise NotImplementedError

    text_w = bytes_w

    def utf8_w(self, w_obj):
        # XXX
        if isinstance(w_obj, StringObject):
            return w_obj.v
        raise NotImplementedError

    def int(self, w_obj):
        if isinstance(w_obj, IntObject):
            return w_obj
        assert isinstance(w_obj, boxes.W_GenericBox)
        return self.int(w_obj.descr_int(self))

    def long(self, w_obj):
        if isinstance(w_obj, LongObject):
            return w_obj
        assert isinstance(w_obj, boxes.W_GenericBox)
        return self.int(w_obj.descr_long(self))

    def str(self, w_obj):
        if isinstance(w_obj, StringObject):
            return w_obj
        assert isinstance(w_obj, boxes.W_GenericBox)
        return self.str(w_obj.descr_str(self))

    def is_true(self, w_obj):
        assert isinstance(w_obj, BoolObject)
        return bool(w_obj.intval)

    def gt(self, w_lhs, w_rhs):
        return BoolObject(self.int_w(w_lhs) > self.int_w(w_rhs))

    def lt(self, w_lhs, w_rhs):
        return BoolObject(self.int_w(w_lhs) < self.int_w(w_rhs))

    def is_w(self, w_obj, w_what):
        return w_obj is w_what

    def eq_w(self, w_obj, w_what):
        return w_obj == w_what

    def issubtype(self, w_type1, w_type2):
        return BoolObject(True)

    def type(self, w_obj):
        if self.is_none(w_obj):
            return self.w_None
        try:
            return w_obj.tp
        except AttributeError:
            if isinstance(w_obj, W_NDimArray):
                return W_NDimArray
            return self.w_None

    def lookup(self, w_obj, name):
        w_type = self.type(w_obj)
        if not self.is_none(w_type):
            return w_type.lookup(name)

    def gettypefor(self, w_obj):
        return W_TypeObject(w_obj.typedef.name)

    def call_function(self, tp, w_dtype, *args):
        if tp is self.w_float:
            if isinstance(w_dtype, boxes.W_Float64Box):
                return FloatObject(float(w_dtype.value))
            if isinstance(w_dtype, boxes.W_Float32Box):
                return FloatObject(float(w_dtype.value))
            if isinstance(w_dtype, boxes.W_Int64Box):
                return FloatObject(float(int(w_dtype.value)))
            if isinstance(w_dtype, boxes.W_Int32Box):
                return FloatObject(float(int(w_dtype.value)))
            if isinstance(w_dtype, boxes.W_Int16Box):
                return FloatObject(float(int(w_dtype.value)))
            if isinstance(w_dtype, boxes.W_Int8Box):
                return FloatObject(float(int(w_dtype.value)))
            if isinstance(w_dtype, IntObject):
                return FloatObject(float(w_dtype.intval))
        if tp is self.w_int:
            if isinstance(w_dtype, FloatObject):
                return IntObject(int(w_dtype.floatval))

        return w_dtype

    @specialize.arg(2)
    def call_method(self, w_obj, s, *args):
        # XXX even the hacks have hacks
        if s == 'size':  # used in _array() but never called by tests
            return IntObject(0)
        if s == '__buffer__':
            # descr___buffer__ does not exist on W_Root
            return self.w_None
        return getattr(w_obj, 'descr_' + s)(self, *args)

    @specialize.arg(1)
    def interp_w(self, tp, what):
        assert isinstance(what, tp)
        return what

    def allocate_instance(self, klass, w_subtype):
        return instantiate(klass)

    def newtuple(self, list_w):
        return ListObject(list_w)

    def newdict(self, module=True):
        return DictObject({})

    @specialize.argtype(1)
    def newint(self, i):
        if isinstance(i, IntObject):
            return i
        if isinstance(i, base_int):
            return LongObject(i)
        return IntObject(i)

    def setitem(self, obj, index, value):
        obj.items[index] = value

    def exception_match(self, w_exc_type, w_check_class):
        assert isinstance(w_exc_type, W_TypeObject)
        assert isinstance(w_check_class, W_TypeObject)
        return w_exc_type.name == w_check_class.name

    def warn(self, w_msg, w_warn_type):
        pass
Beispiel #14
0
 def int(self, space):
     if type(self) is W_IntObject:
         return self
     if not space.is_overloaded(self, space.w_int, '__int__'):
         return space.newint(self.intval)
     return W_Root.int(self, space)
Beispiel #15
0
def w_some_obj():
    if NonConstant(False):
        return W_Root()
    return W_MyObject()
Beispiel #16
0
 def do_it(self, space, w_x):
     is_root(w_x)
     see()
     return W_Root()
Beispiel #17
0
 def int(self, space):
     # this is a speed-up only, for space.int(w_float).
     if type(self) is not W_FloatObject and space.is_overloaded(self, space.w_float, "__int__"):
         return W_Root.int(self, space)
     return self.descr_trunc(space)
Beispiel #18
0

def track_reference(space, py_obj, w_obj):
    """
    Ties together a PyObject and an interpreter object.
    The PyObject's refcnt is increased by REFCNT_FROM_PYPY.
    The reference in 'py_obj' is not stolen!  Remember to decref()
    it if you need to.
    """
    # XXX looks like a PyObject_GC_TRACK
    assert py_obj.c_ob_refcnt < rawrefcount.REFCNT_FROM_PYPY
    py_obj.c_ob_refcnt += rawrefcount.REFCNT_FROM_PYPY
    w_obj._cpyext_attach_pyobj(space, py_obj)


w_marker_deallocating = W_Root()


@jit.dont_look_inside
def from_ref(space, ref):
    """
    Finds the interpreter object corresponding to the given reference.  If the
    object is not yet realized (see bytesobject.py), creates it.
    """
    assert is_pyobj(ref)
    if not ref:
        return None
    w_obj = rawrefcount.to_obj(W_Root, ref)
    if w_obj is not None:
        if w_obj is not w_marker_deallocating:
            return w_obj
Beispiel #19
0
 def exec_code(self, space, w_globals, w_locals):
     return W_Root()
Beispiel #20
0
 def getclass(self, space):
     if self.w_userclass is None:
         return W_Root.getclass(self, space)
     return self.w_userclass
Beispiel #21
0
 def int(self, space):
     if type(self) is W_LongObject:
         return self
     if not space.is_overloaded(self, space.w_int, '__int__'):
         return W_LongObject(self.num)
     return W_Root.int(self, space)
Beispiel #22
0
 def f(n):
     w1 = newbool(None, n >= 10)
     w2 = W_Root()
     return int(w1 is w2) + int(w2 is w1)
Beispiel #23
0
 def f(n):
     if n > 5:
         w_res = newbool(None, n >= 10)
     else:
         w_res = W_Root()
     return w_res