Debian Codegraph @

pypy/module/cpyext/tupleobject.py

raw symbols SCIP
1 from pypy.interpreter.error import oefmt
2 from rpython.rtyper.lltypesystem import rffi, lltype
3 from rpython.rlib.objectmodel import we_are_translated
4 from rpython.rlib.debug import fatalerror_notb
5 from pypy.module.cpyext.api import (
6 cpython_api, Py_ssize_t, build_type_checkers_flags, PyVarObject,
7 PyVarObjectFields, cpython_struct, bootstrap_function, slot_function)
8 from pypy.module.cpyext.pyobject import (
9 PyObject, PyObjectP, make_ref, from_ref, decref, incref, BaseCpyTypedescr,
10 track_reference, make_typedescr, get_typedescr, pyobj_has_w_obj)
11 from pypy.module.cpyext.state import State
12 from pypy.module.cpyext.pyerrors import PyErr_BadInternalCall
13 from pypy.objspace.std.tupleobject import W_TupleObject
14
15 ##
16 ## Implementation of PyTupleObject
17 ## ===============================
18 ##
19 ## Similar to stringobject.py. The reason is only the existance of
20 ## W_SpecialisedTupleObject_ii and W_SpecialisedTupleObject_ff.
21 ## These two PyPy classes implement getitem() by returning a freshly
22 ## constructed W_IntObject or W_FloatObject. This is not compatible
23 ## with PyTuple_GetItem, which returns a borrowed reference.
24 ##
25 ## So we use this more advanced (but also likely faster) solution:
26 ## tuple_attach makes a real PyTupleObject with an array of N
27 ## 'PyObject *', which are created immediately and own a reference.
28 ## Then the macro PyTuple_GET_ITEM can be implemented like CPython.
29 ##
30
31 PyTupleObjectStruct = lltype.ForwardReference()
32 PyTupleObject = lltype.Ptr(PyTupleObjectStruct)
33 ObjectItems = rffi.CArray(PyObject)
34 PyTupleObjectFields = PyVarObjectFields + \
35 (("ob_item", ObjectItems),)
36 cpython_struct("PyTupleObject", PyTupleObjectFields, PyTupleObjectStruct)
37
38 @bootstrap_function
39 def init_tupleobject(space):
40 "Type description of PyTupleObject"
41 state = space.fromcache(State)
42 make_typedescr(space.w_tuple.layout.typedef,
43 basestruct=PyTupleObject.TO,
44 attach=tuple_attach,
45 alloc=tuple_alloc,
46 dealloc=state.C._PyPy_tuple_dealloc,
47 realize=tuple_realize)
48
49 PyTuple_Check, PyTuple_CheckExact = build_type_checkers_flags("Tuple")
50
51 def tuple_check_ref(space, ref):
52 w_type = from_ref(space, rffi.cast(PyObject, ref.c_ob_type))
53 return (w_type is space.w_tuple or
54 space.issubtype_w(w_type, space.w_tuple))
55
56 _BAD_ITEMCOUNT = None # patched in test_badinternalcall_from_rpy
57
58 def tuple_alloc(typedescr, space, w_type, itemcount):
59 state = space.fromcache(State)
60 if w_type is space.w_tuple:
61 if not we_are_translated() and itemcount == _BAD_ITEMCOUNT:
62 itemcount = -42
63 ptup = state.ccall("PyTuple_New", itemcount)
64 if not ptup:
65 state.check_and_raise_exception(always=True)
66 return ptup
67 else:
68 return BaseCpyTypedescr.allocate(typedescr, space, w_type, itemcount)
69
70 def tuple_attach(space, py_obj, w_obj, w_userdata=None):
71 """
72 Fills a newly allocated PyTupleObject with the given tuple object. The
73 buffer must not be modified.
74 """
75 items_w = space.fixedview(w_obj)
76 py_tup = rffi.cast(PyTupleObject, py_obj)
77 py_varobj = rffi.cast(PyVarObject, py_obj)
78 length = len(items_w)
79 if py_varobj.c_ob_size < length:
80 raise oefmt(space.w_ValueError,
81 "tuple_attach called on object with ob_size %d but trying to store %d",
82 py_varobj.c_ob_size, length)
83 i = 0
84 try:
85 while i < length:
86 py_tup.c_ob_item[i] = make_ref(space, items_w[i])
87 i += 1
88 except:
89 while i > 0:
90 i -= 1
91 ob = py_tup.c_ob_item[i]
92 py_tup.c_ob_item[i] = lltype.nullptr(PyObject.TO)
93 decref(space, ob)
94 raise
95
96 def tuple_realize(space, py_obj):
97 """
98 Creates the tuple in the interpreter. The PyTupleObject must not
99 be modified after this call. We check that it does not contain
100 any NULLs at this point (which would correspond to half-broken
101 W_TupleObjects).
102 """
103 py_tup = rffi.cast(PyTupleObject, py_obj)
104 l = rffi.cast(PyVarObject, py_tup).c_ob_size
105 p = py_tup.c_ob_item
106 items_w = [None] * l
107 for i in range(l):
108 w_item = from_ref(space, p[i])
109 if w_item is None:
110 fatalerror_notb(
111 "Fatal error in cpyext, CPython compatibility layer: "
112 "converting a PyTupleObject into a W_TupleObject, "
113 "but found NULLs as items")
114 items_w[i] = w_item
115 w_type = from_ref(space, rffi.cast(PyObject, py_obj.c_ob_type))
116 w_obj = space.allocate_instance(W_TupleObject, w_type)
117 w_obj.__init__(items_w)
118 track_reference(space, py_obj, w_obj)
119 return w_obj
120
121 def tuple_from_args_w(space, args_w):
122 state = space.fromcache(State)
123 n = len(args_w)
124 py_tuple = state.ccall("PyTuple_New", n)
125 if not py_tuple:
126 state.check_and_raise_exception(always=True)
127 py_tuple = rffi.cast(PyTupleObject, py_tuple)
128 for i, w_obj in enumerate(args_w):
129 py_tuple.c_ob_item[i] = make_ref(space, w_obj)
130 return rffi.cast(PyObject, py_tuple)
131
132 @cpython_api([PyObject, Py_ssize_t, PyObject], rffi.INT_real, error=-1)
133 def PyTuple_SetItem(space, ref, index, py_obj):
134 if not tuple_check_ref(space, ref):
135 decref(space, py_obj)
136 PyErr_BadInternalCall(space)
137 tupleobj = rffi.cast(PyTupleObject, ref)
138 size = rffi.cast(PyVarObject, tupleobj).c_ob_size
139 if index < 0 or index >= size:
140 decref(space, py_obj)
141 raise oefmt(space.w_IndexError, "tuple assignment index out of range")
142 old_ref = tupleobj.c_ob_item[index]
143 if pyobj_has_w_obj(ref):
144 # similar but not quite equal to ref.c_ob_refcnt != 1 on CPython
145 decref(space, py_obj)
146 raise oefmt(space.w_SystemError, "PyTuple_SetItem called on tuple after"
147 " use of tuple")
148 tupleobj.c_ob_item[index] = py_obj # consumes a reference
149 if old_ref:
150 decref(space, old_ref)
151 return 0
152
153 @cpython_api([PyObject, Py_ssize_t], PyObject,
154 result_borrowed=True, result_is_ll=True)
155 def PyTuple_GetItem(space, ref, index):
156 if not tuple_check_ref(space, ref):
157 PyErr_BadInternalCall(space)
158 ref = rffi.cast(PyTupleObject, ref)
159 size = rffi.cast(PyVarObject, ref).c_ob_size
160 if index < 0 or index >= size:
161 raise oefmt(space.w_IndexError, "tuple index out of range")
162 return ref.c_ob_item[index] # borrowed ref
163
164 @cpython_api([PyObject], Py_ssize_t, error=-1)
165 def PyTuple_Size(space, ref):
166 """Take a pointer to a tuple object, and return the size of that tuple."""
167 if not tuple_check_ref(space, ref):
168 PyErr_BadInternalCall(space)
169 ref = rffi.cast(PyVarObject, ref)
170 return ref.c_ob_size
171
172
173 @cpython_api([PyObjectP, Py_ssize_t], rffi.INT_real, error=-1)
174 def _PyTuple_Resize(space, p_ref, newsize):
175 """Can be used to resize a tuple. newsize will be the new length of the tuple.
176 Because tuples are supposed to be immutable, this should only be used if there
177 is only one reference to the object. Do not use this if the tuple may already
178 be known to some other part of the code. The tuple will always grow or shrink
179 at the end. Think of this as destroying the old tuple and creating a new one,
180 only more efficiently. Returns 0 on success. Client code should never
181 assume that the resulting value of *p will be the same as before calling
182 this function. If the object referenced by *p is replaced, the original
183 *p is destroyed. On failure, returns -1 and sets *p to NULL, and
184 raises MemoryError or SystemError."""
185 state = space.fromcache(State)
186 ref = p_ref[0]
187 if not tuple_check_ref(space, ref):
188 PyErr_BadInternalCall(space)
189 oldref = rffi.cast(PyTupleObject, ref)
190 oldsize = rffi.cast(PyVarObject, oldref).c_ob_size
191 if oldsize == newsize:
192 return 0
193 ptup = state.ccall("PyTuple_New", newsize)
194 if not ptup:
195 state.check_and_raise_exception(always=True)
196 p_ref[0] = ptup
197 newref = rffi.cast(PyTupleObject, p_ref[0])
198 try:
199 if oldsize < newsize:
200 to_cp = oldsize
201 else:
202 to_cp = newsize
203 for i in range(to_cp):
204 ob = oldref.c_ob_item[i]
205 if ob:
206 incref(space, ob)
207 newref.c_ob_item[i] = ob
208 except:
209 decref(space, p_ref[0])
210 p_ref[0] = lltype.nullptr(PyObject.TO)
211 raise
212 finally:
213 decref(space, ref)
214 return 0
215
216 @cpython_api([PyObject, Py_ssize_t, Py_ssize_t], PyObject)
217 def PyTuple_GetSlice(space, w_obj, low, high):
218 """Take a slice of the tuple pointed to by p from low to high and return it
219 as a new tuple.
220 """
221 return space.getslice(w_obj, space.newint(low), space.newint(high))