Author: Armin Rigo <[email protected]>
Branch: cpyext-gc-support-2
Changeset: r82216:b54a2a1a9efb
Date: 2016-02-13 16:09 +0100
http://bitbucket.org/pypy/pypy/changeset/b54a2a1a9efb/
Log: in-progress: rewrite tupleobject.py to be similar to stringobject.py
for similar reasons (documented)
diff --git a/pypy/module/cpyext/api.py b/pypy/module/cpyext/api.py
--- a/pypy/module/cpyext/api.py
+++ b/pypy/module/cpyext/api.py
@@ -497,7 +497,7 @@
GLOBALS['%s#' % (cpyname, )] = ('PyTypeObject*', pypyexpr)
for cpyname in '''PyMethodObject PyListObject PyLongObject
- PyDictObject PyTupleObject PyClassObject'''.split():
+ PyDictObject PyClassObject'''.split():
FORWARD_DECLS.append('typedef struct { PyObject_HEAD } %s'
% (cpyname, ))
build_exported_objects()
diff --git a/pypy/module/cpyext/include/tupleobject.h
b/pypy/module/cpyext/include/tupleobject.h
--- a/pypy/module/cpyext/include/tupleobject.h
+++ b/pypy/module/cpyext/include/tupleobject.h
@@ -7,11 +7,21 @@
extern "C" {
#endif
+typedef struct {
+ PyObject_HEAD
+ Py_ssize_t ob_size;
+ PyObject **ob_item; /* XXX optimize to ob_item[] */
+} PyTupleObject;
+
/* defined in varargswrapper.c */
PyAPI_FUNC(PyObject *) PyTuple_Pack(Py_ssize_t, ...);
-#define PyTuple_SET_ITEM PyTuple_SetItem
-#define PyTuple_GET_ITEM PyTuple_GetItem
+/* Macro, trading safety for speed */
+#define PyTuple_GET_ITEM(op, i) (((PyTupleObject *)(op))->ob_item[i])
+#define PyTuple_GET_SIZE(op) Py_SIZE(op)
+
+/* Macro, *only* to be used to fill in brand new tuples */
+#define PyTuple_SET_ITEM(op, i, v) (((PyTupleObject *)(op))->ob_item[i] = v)
#ifdef __cplusplus
diff --git a/pypy/module/cpyext/pyobject.py b/pypy/module/cpyext/pyobject.py
--- a/pypy/module/cpyext/pyobject.py
+++ b/pypy/module/cpyext/pyobject.py
@@ -185,24 +185,6 @@
assert py_obj
rawrefcount.create_link_pypy(w_obj, py_obj)
-def make_ref(space, w_obj):
- """
- Returns a new reference to an intepreter object.
- """
- GOES_AWAY
- if w_obj is None:
- return lltype.nullptr(PyObject.TO)
- assert isinstance(w_obj, W_Root)
- state = space.fromcache(RefcountState)
- try:
- py_obj = state.py_objects_w2r[w_obj]
- except KeyError:
- py_obj = create_ref(space, w_obj)
- track_reference(space, py_obj, w_obj)
- else:
- Py_IncRef(space, py_obj)
- return py_obj
-
def from_ref(space, ref):
"""
diff --git a/pypy/module/cpyext/test/test_tupleobject.py
b/pypy/module/cpyext/test/test_tupleobject.py
--- a/pypy/module/cpyext/test/test_tupleobject.py
+++ b/pypy/module/cpyext/test/test_tupleobject.py
@@ -1,6 +1,8 @@
import py
from pypy.module.cpyext.pyobject import PyObject, PyObjectP, make_ref, from_ref
+from pypy.module.cpyext.pyobject import as_pyobj
+from pypy.module.cpyext.tupleobject import PyTupleObject
from pypy.module.cpyext.test.test_api import BaseApiTest
from rpython.rtyper.lltypesystem import rffi, lltype
@@ -10,25 +12,35 @@
def test_tupleobject(self, space, api):
assert not api.PyTuple_Check(space.w_None)
assert api.PyTuple_SetItem(space.w_None, 0, space.w_None) == -1
- atuple = space.newtuple([0, 1, 'yay'])
+ atuple = space.newtuple([space.wrap(0), space.wrap(1),
+ space.wrap('yay')])
assert api.PyTuple_Size(atuple) == 3
- assert api.PyTuple_GET_SIZE(atuple) == 3
+ #assert api.PyTuple_GET_SIZE(atuple) == 3 --- now a C macro
raises(TypeError, api.PyTuple_Size(space.newlist([])))
api.PyErr_Clear()
def test_tuple_resize(self, space, api):
+ w_42 = space.wrap(42)
+ ar = lltype.malloc(PyObjectP.TO, 1, flavor='raw')
+
py_tuple = api.PyTuple_New(3)
- ar = lltype.malloc(PyObjectP.TO, 1, flavor='raw')
- ar[0] = rffi.cast(PyObject, make_ref(space, py_tuple))
+ rffi.cast(PyTupleObject, py_tuple).c_ob_item[0] = as_pyobj(space, w_42)
+ ar[0] = py_tuple
api._PyTuple_Resize(ar, 2)
- py_tuple = from_ref(space, ar[0])
- assert space.int_w(space.len(py_tuple)) == 2
-
+ w_tuple = from_ref(space, ar[0])
+ assert space.int_w(space.len(w_tuple)) == 2
+ assert space.int_w(space.getitem(w_tuple, space.wrap(0))) == 42
+ api.Py_DecRef(ar[0])
+
+ py_tuple = api.PyTuple_New(3)
+ rffi.cast(PyTupleObject, py_tuple).c_ob_item[0] = as_pyobj(space, w_42)
+ ar[0] = py_tuple
api._PyTuple_Resize(ar, 10)
- py_tuple = from_ref(space, ar[0])
- assert space.int_w(space.len(py_tuple)) == 10
-
+ w_tuple = from_ref(space, ar[0])
+ assert space.int_w(space.len(w_tuple)) == 10
+ assert space.int_w(space.getitem(w_tuple, space.wrap(0))) == 42
api.Py_DecRef(ar[0])
+
lltype.free(ar, flavor='raw')
def test_setitem(self, space, api):
diff --git a/pypy/module/cpyext/tupleobject.py
b/pypy/module/cpyext/tupleobject.py
--- a/pypy/module/cpyext/tupleobject.py
+++ b/pypy/module/cpyext/tupleobject.py
@@ -1,59 +1,166 @@
from pypy.interpreter.error import OperationError
from rpython.rtyper.lltypesystem import rffi, lltype
from pypy.module.cpyext.api import (cpython_api, Py_ssize_t, CANNOT_FAIL,
- build_type_checkers)
+ build_type_checkers, PyObjectFields,
+ cpython_struct, bootstrap_function)
from pypy.module.cpyext.pyobject import (PyObject, PyObjectP, Py_DecRef,
- borrow_from, make_ref, from_ref)
+ borrow_from, make_ref, from_ref, decref,
+ track_reference, make_typedescr, get_typedescr)
from pypy.module.cpyext.pyerrors import PyErr_BadInternalCall
from pypy.objspace.std.tupleobject import W_TupleObject
+##
+## Implementation of PyTupleObject
+## ===============================
+##
+## Similar to stringobject.py. The reason is only the existance of
+## W_SpecialisedTupleObject_ii and W_SpecialisedTupleObject_ff.
+## These two PyPy classes implement getitem() by returning a freshly
+## constructed W_IntObject or W_FloatObject. This is not compatible
+## with PyTuple_GetItem, which returns a borrowed reference.
+##
+## So we use this more advanced (but also likely faster) solution:
+## tuple_attach makes a real PyTupleObject with an array of N
+## 'PyObject *', which are created immediately and own a reference.
+## Then the macro PyTuple_GET_ITEM can be implemented like CPython.
+##
+
+PyTupleObjectStruct = lltype.ForwardReference()
+PyTupleObject = lltype.Ptr(PyTupleObjectStruct)
+ObjectItems = rffi.CArray(PyObject)
+PyTupleObjectFields = PyObjectFields + \
+ (("ob_size", Py_ssize_t), ("ob_item", lltype.Ptr(ObjectItems)))
+cpython_struct("PyTupleObject", PyTupleObjectFields, PyTupleObjectStruct)
+
+@bootstrap_function
+def init_stringobject(space):
+ "Type description of PyTupleObject"
+ make_typedescr(space.w_tuple.instancetypedef,
+ basestruct=PyTupleObject.TO,
+ attach=tuple_attach,
+ dealloc=tuple_dealloc,
+ realize=tuple_realize)
+
PyTuple_Check, PyTuple_CheckExact = build_type_checkers("Tuple")
+def tuple_check_ref(space, ref):
+ w_type = from_ref(space, rffi.cast(PyObject, ref.c_ob_type))
+ return (w_type is space.w_tuple or
+ space.is_true(space.issubtype(w_type, space.w_tuple)))
+
+def new_empty_tuple(space, length):
+ """
+ Allocate a PyTupleObject and its array of PyObject *, but without a
+ corresponding interpreter object. The array may be mutated, until
+ tuple_realize() is called.
+ """
+ typedescr = get_typedescr(space.w_tuple.instancetypedef)
+ py_obj = typedescr.allocate(space, space.w_tuple)
+ py_tup = rffi.cast(PyTupleObject, py_obj)
+
+ py_tup.c_ob_item = lltype.malloc(ObjectItems, length,
+ flavor='raw', zero=True)
+ py_tup.c_ob_size = length
+ return py_tup
+
+def tuple_attach(space, py_obj, w_obj):
+ """
+ Fills a newly allocated PyTupleObject with the given tuple object. The
+ buffer must not be modified.
+ """
+ items_w = space.fixedview(w_obj)
+ l = len(items_w)
+ p = lltype.malloc(ObjectItems, l, flavor='raw')
+ i = 0
+ try:
+ while i < l:
+ p[i] = make_ref(space, items_w[i])
+ i += 1
+ except:
+ while i > 0:
+ i -= 1
+ decref(space, p[i])
+ lltype.free(p, flavor='raw')
+ raise
+ py_tup = rffi.cast(PyTupleObject, py_obj)
+ py_tup.c_ob_size = l
+ py_tup.c_ob_item = p
+
+def tuple_realize(space, py_obj):
+ """
+ Creates the tuple in the interpreter. The PyTupleObject must not
+ be modified after this call.
+ """
+ py_tup = rffi.cast(PyTupleObject, py_obj)
+ l = py_tup.c_ob_size
+ p = py_tup.c_ob_item
+ items_w = [None] * l
+ for i in range(l):
+ items_w[i] = from_ref(space, p[i])
+ w_obj = space.newtuple(items_w)
+ track_reference(space, py_obj, w_obj)
+ return w_obj
+
+@cpython_api([PyObject], lltype.Void, external=False)
+def tuple_dealloc(space, py_obj):
+ """Frees allocated PyTupleObject resources.
+ """
+ py_tup = rffi.cast(PyTupleObject, py_obj)
+ p = py_tup.c_ob_item
+ if p:
+ for i in range(py_tup.c_ob_size):
+ decref(space, p[i])
+ lltype.free(p, flavor="raw")
+ from pypy.module.cpyext.object import PyObject_dealloc
+ PyObject_dealloc(space, py_obj)
+
+#_______________________________________________________________________
+
@cpython_api([Py_ssize_t], PyObject)
def PyTuple_New(space, size):
- return W_TupleObject([space.w_None] * size)
+ return rffi.cast(PyObject, new_empty_tuple(space, size))
@cpython_api([PyObject, Py_ssize_t, PyObject], rffi.INT_real, error=-1)
-def PyTuple_SetItem(space, w_t, pos, w_obj):
- if not PyTuple_Check(space, w_t):
- # XXX this should also steal a reference, test it!!!
+def PyTuple_SetItem(space, ref, index, py_obj):
+ # XXX this will not complain when changing tuples that have
+ # already been realized as a W_TupleObject, but won't update the
+ # W_TupleObject
+ if not tuple_check_ref(space, ref):
+ decref(space, py_obj)
PyErr_BadInternalCall(space)
- _setitem_tuple(w_t, pos, w_obj)
- Py_DecRef(space, w_obj) # SetItem steals a reference!
+ ref = rffi.cast(PyTupleObject, ref)
+ size = ref.c_ob_size
+ if index < 0 or index >= size:
+ raise OperationError(space.w_IndexError,
+ space.wrap("tuple assignment index out of range"))
+ old_ref = ref.c_ob_item[index]
+ ref.c_ob_item[index] = py_obj # consumes a reference
+ if old_ref:
+ decref(space, old_ref)
return 0
-def _setitem_tuple(w_t, pos, w_obj):
- # this function checks that w_t is really a W_TupleObject. It
- # should only ever be called with a freshly built tuple from
- # PyTuple_New(), which always return a W_TupleObject, even if there
- # are also other implementations of tuples.
- assert isinstance(w_t, W_TupleObject)
- w_t.wrappeditems[pos] = w_obj
-
-@cpython_api([PyObject, Py_ssize_t], PyObject)
-def PyTuple_GetItem(space, w_t, pos):
- if not PyTuple_Check(space, w_t):
+@cpython_api([PyObject, Py_ssize_t], PyObject, result_borrowed=True)
+def PyTuple_GetItem(space, ref, index):
+ if not tuple_check_ref(space, ref):
PyErr_BadInternalCall(space)
- w_obj = space.getitem(w_t, space.wrap(pos))
- return borrow_from(w_t, w_obj)
-
-@cpython_api([PyObject], Py_ssize_t, error=CANNOT_FAIL)
-def PyTuple_GET_SIZE(space, w_t):
- """Return the size of the tuple p, which must be non-NULL and point to a
tuple;
- no error checking is performed. """
- return space.int_w(space.len(w_t))
+ ref = rffi.cast(PyTupleObject, ref)
+ size = ref.c_ob_size
+ if index < 0 or index >= size:
+ raise OperationError(space.w_IndexError,
+ space.wrap("tuple index out of range"))
+ return ref.c_ob_item[index]
@cpython_api([PyObject], Py_ssize_t, error=-1)
def PyTuple_Size(space, ref):
"""Take a pointer to a tuple object, and return the size of that tuple."""
- if not PyTuple_Check(space, ref):
- raise OperationError(space.w_TypeError,
- space.wrap("expected tuple object"))
- return PyTuple_GET_SIZE(space, ref)
+ if not tuple_check_ref(space, ref):
+ PyErr_BadInternalCall(space)
+ ref = rffi.cast(PyTupleObject, ref)
+ return ref.c_ob_size
@cpython_api([PyObjectP, Py_ssize_t], rffi.INT_real, error=-1)
-def _PyTuple_Resize(space, ref, newsize):
+def _PyTuple_Resize(space, p_ref, newsize):
"""Can be used to resize a tuple. newsize will be the new length of the
tuple.
Because tuples are supposed to be immutable, this should only be used if
there
is only one reference to the object. Do not use this if the tuple may
already
@@ -64,19 +171,27 @@
this function. If the object referenced by *p is replaced, the original
*p is destroyed. On failure, returns -1 and sets *p to NULL, and
raises MemoryError or SystemError."""
- py_tuple = from_ref(space, ref[0])
- if not PyTuple_Check(space, py_tuple):
+ ref = p_ref[0]
+ if not tuple_check_ref(space, ref):
PyErr_BadInternalCall(space)
- py_newtuple = PyTuple_New(space, newsize)
-
- to_cp = newsize
- oldsize = space.int_w(space.len(py_tuple))
- if oldsize < newsize:
- to_cp = oldsize
- for i in range(to_cp):
- _setitem_tuple(py_newtuple, i, space.getitem(py_tuple, space.wrap(i)))
- Py_DecRef(space, ref[0])
- ref[0] = make_ref(space, py_newtuple)
+ ref = rffi.cast(PyTupleObject, ref)
+ oldsize = ref.c_ob_size
+ oldp = ref.c_ob_item
+ newp = lltype.malloc(ObjectItems, newsize, zero=True, flavor='raw')
+ try:
+ if oldsize < newsize:
+ to_cp = oldsize
+ else:
+ to_cp = newsize
+ for i in range(to_cp):
+ newp[i] = oldp[i]
+ except:
+ lltype.free(newp, flavor='raw')
+ raise
+ ref.c_ob_item = newp
+ ref.c_ob_size = newsize
+ lltype.free(oldp, flavor='raw')
+ # in this version, p_ref[0] never needs to be updated
return 0
@cpython_api([PyObject, Py_ssize_t, Py_ssize_t], PyObject)
_______________________________________________
pypy-commit mailing list
[email protected]
https://mail.python.org/mailman/listinfo/pypy-commit