Debian Codegraph @

pypy/module/cpyext/sequence.py

raw symbols SCIP
1
2 from rpython.rlib import rerased, jit
3 from rpython.rlib.objectmodel import keepalive_until_here
4 from pypy.interpreter.error import OperationError, oefmt
5 from pypy.objspace.std.listobject import (
6 ListStrategy, UNROLL_CUTOFF, W_ListObject, ObjectListStrategy)
7 from pypy.module.cpyext.api import (
8 cpython_api, CANNOT_FAIL, CONST_STRING, Py_ssize_t, PyObject, PyObjectP,
9 generic_cpy_call, PyVarObject, PyObject)
10 from pypy.module.cpyext.pyobject import make_ref, from_ref, as_pyobj, incref
11 from rpython.rtyper.lltypesystem import rffi, lltype
12 from pypy.objspace.std import tupleobject
13
14 from pypy.module.cpyext.tupleobject import PyTuple_Check, PyTuple_SetItem
15 from pypy.module.cpyext.pyobject import decref
16
17 from pypy.module.cpyext.dictobject import PyDict_Check
18
19 @cpython_api([PyObject, Py_ssize_t], PyObject)
20 def PySequence_Repeat(space, w_obj, count):
21 """Return the result of repeating sequence object o count times, or NULL on
22 failure. This is the equivalent of the Python expression o * count.
23 """
24 return space.mul(w_obj, space.newint(count))
25
26 @cpython_api([PyObject], rffi.INT_real, error=CANNOT_FAIL)
27 def PySequence_Check(space, w_obj):
28 """Return 1 if the object provides sequence protocol, and 0 otherwise.
29 This function always succeeds."""
30 return int(space.issequence_w(w_obj))
31
32 @cpython_api([PyObject], Py_ssize_t, error=-1)
33 def PySequence_Size(space, w_obj):
34 """
35 Returns the number of objects in sequence o on success, and -1 on failure.
36 For objects that do not provide sequence protocol, this is equivalent to the
37 Python expression len(o)."""
38 return space.len_w(w_obj)
39
40 @cpython_api([PyObject], Py_ssize_t, error=-1)
41 def PySequence_Length(space, w_obj):
42 return space.len_w(w_obj)
43
44 @cpython_api([PyObject, CONST_STRING], PyObject)
45 def PySequence_Fast(space, w_obj, m):
46 """Returns the sequence o as a tuple, unless it is already a tuple or list, in
47 which case o is returned. Use PySequence_Fast_GET_ITEM() to access the
48 members of the result. Returns NULL on failure. If the object cannot be
49 converted to a sequence, and raises a TypeError, raise a new TypeError with
50 m as the message text. If the conversion otherwise, fails, reraise the
51 original exception"""
52 if isinstance(w_obj, tupleobject.W_AbstractTupleObject):
53 return w_obj # CCC avoid the double conversion that occurs here
54 if isinstance(w_obj, W_ListObject):
55 # note: we used to call w_obj.convert_to_cpy_strategy() here,
56 # but we really have to call it from PySequence_Fast_GET_ITEM()
57 # because some people never call PySequence_Fast() if they know
58 # the object is a list.
59 return w_obj
60 try:
61 return tupleobject.W_TupleObject(space.fixedview(w_obj))
62 except OperationError as e:
63 if e.match(space, space.w_TypeError):
64 raise OperationError(space.w_TypeError, space.newtext(rffi.charp2str(m)))
65 raise e
66
67 # CCC this should be written as a C macro, at least for the tuple case
68 @cpython_api([rffi.VOIDP, Py_ssize_t], PyObject, result_is_ll=True)
69 def PySequence_Fast_GET_ITEM(space, py_obj, index):
70 """Return the ith element of o, assuming that o was returned by
71 PySequence_Fast(), o is not NULL, and that i is within bounds.
72 """
73 py_obj = rffi.cast(PyObject, py_obj)
74 if PyTuple_Check(space, py_obj):
75 from pypy.module.cpyext.tupleobject import PyTupleObject
76 py_tuple = rffi.cast(PyTupleObject, py_obj)
77 return py_tuple.c_ob_item[index]
78 else:
79 from pypy.module.cpyext.listobject import PyList_GET_ITEM
80 w_obj = from_ref(space, py_obj)
81 return PyList_GET_ITEM(space, w_obj, index)
82
83 @cpython_api([rffi.VOIDP], Py_ssize_t, error=CANNOT_FAIL)
84 def PySequence_Fast_GET_SIZE(space, py_obj):
85 """Returns the length of o, assuming that o was returned by
86 PySequence_Fast() and that o is not NULL. The size can also be
87 gotten by calling PySequence_Size() on o, but
88 PySequence_Fast_GET_SIZE() is faster because it can assume o is a list
89 or tuple."""
90 py_obj = rffi.cast(PyObject, py_obj)
91 if PyTuple_Check(space, py_obj):
92 from pypy.module.cpyext.tupleobject import PyTupleObject
93 py_varobj = rffi.cast(PyVarObject, py_obj)
94 return py_varobj.c_ob_size
95 else:
96 from pypy.module.cpyext.listobject import PyList_GET_SIZE
97 w_obj = from_ref(space, py_obj)
98 return PyList_GET_SIZE(space, w_obj)
99
100 @cpython_api([rffi.VOIDP], PyObjectP)
101 def PySequence_Fast_ITEMS(space, py_obj):
102 """Return the underlying array of PyObject pointers. Assumes that o was returned
103 by PySequence_Fast() and o is not NULL.
104
105 Note, if a list gets resized, the reallocation may relocate the items array.
106 So, only use the underlying array pointer in contexts where the sequence
107 cannot change.
108 """
109 py_obj = rffi.cast(PyObject, py_obj)
110 if PyTuple_Check(space, py_obj):
111 from pypy.module.cpyext.tupleobject import PyTupleObject
112 py_tuple = rffi.cast(PyTupleObject, py_obj)
113 return rffi.cast(PyObjectP, py_tuple.c_ob_item)
114 else:
115 from pypy.module.cpyext.listobject import get_list_storage
116 w_obj = from_ref(space, py_obj)
117 assert isinstance(w_obj, W_ListObject)
118 storage = get_list_storage(space, w_obj)
119 return rffi.cast(PyObjectP, storage._elems)
120
121 @cpython_api([PyObject, Py_ssize_t, Py_ssize_t], PyObject)
122 def PySequence_GetSlice(space, w_obj, start, end):
123 """Return the slice of sequence object o between i1 and i2, or NULL on
124 failure. This is the equivalent of the Python expression o[i1:i2]."""
125 return space.getslice(w_obj, space.newint(start), space.newint(end))
126
127 @cpython_api([PyObject, Py_ssize_t, Py_ssize_t, PyObject], rffi.INT_real, error=-1)
128 def PySequence_SetSlice(space, w_obj, start, end, w_value):
129 """Assign the sequence object v to the slice in sequence object o from i1 to
130 i2. This is the equivalent of the Python statement o[i1:i2] = v."""
131 space.setslice(w_obj, space.newint(start), space.newint(end), w_value)
132 return 0
133
134 @cpython_api([PyObject, Py_ssize_t, Py_ssize_t], rffi.INT_real, error=-1)
135 def PySequence_DelSlice(space, w_obj, start, end):
136 """Delete the slice in sequence object o from i1 to i2. Returns -1 on
137 failure. This is the equivalent of the Python statement del o[i1:i2]."""
138 space.delslice(w_obj, space.newint(start), space.newint(end))
139 return 0
140
141 @cpython_api([rffi.VOIDP, Py_ssize_t], PyObject, result_is_ll=True)
142 def PySequence_ITEM(space, w_obj, i):
143 """Return the ith element of o or NULL on failure. Macro form of
144 PySequence_GetItem() but without checking that
145 PySequence_Check(o)() is true and without adjustment for negative
146 indices.
147
148 This function used an int type for i. This might require
149 changes in your code for properly supporting 64-bit systems."""
150 # XXX we should call Py*_GET_ITEM() instead of Py*_GetItem()
151 # from here, but we cannot because we are also called from
152 # PySequence_GetItem()
153 py_obj = as_pyobj(space, w_obj)
154 if isinstance(w_obj, tupleobject.W_TupleObject):
155 from pypy.module.cpyext.tupleobject import PyTuple_GetItem
156 py_res = PyTuple_GetItem(space, py_obj, i)
157 incref(space, py_res)
158 keepalive_until_here(w_obj)
159 return py_res
160 if isinstance(w_obj, W_ListObject):
161 from pypy.module.cpyext.listobject import PyList_GetItem
162 py_res = PyList_GetItem(space, py_obj, i)
163 incref(space, py_res)
164 keepalive_until_here(w_obj)
165 return py_res
166 as_sequence = py_obj.c_ob_type.c_tp_as_sequence
167 if as_sequence and as_sequence.c_sq_item:
168 ret = generic_cpy_call(space, as_sequence.c_sq_item, w_obj, i)
169 return make_ref(space, ret)
170 w_ret = space.getitem(w_obj, space.newint(i))
171 return make_ref(space, w_ret)
172
173 @cpython_api([PyObject, Py_ssize_t], PyObject, result_is_ll=True)
174 def PySequence_GetItem(space, w_obj, i):
175 """Return the ith element of o, or NULL on failure. This is the equivalent of
176 the Python expression o[i]."""
177 if i < 0:
178 l = PySequence_Length(space, w_obj)
179 i += l
180 if i < 0:
181 # Prevent things like 'abc'[-4] from turning into 'abc'[-1]
182 # since this can end up calling space.getitem()
183 raise oefmt(space.w_IndexError,
184 "%T index out of range", w_obj)
185 return PySequence_ITEM(space, w_obj, i)
186
187 @cpython_api([PyObject], PyObject)
188 def PySequence_List(space, w_obj):
189 """Return a list object with the same contents as the arbitrary sequence o. The
190 returned list is guaranteed to be new."""
191 return space.call_function(space.w_list, w_obj)
192
193 @cpython_api([PyObject], PyObject)
194 def PySequence_Tuple(space, w_obj):
195 """Return a tuple object with the same contents as the arbitrary sequence o or
196 NULL on failure. If o is a tuple, a new reference will be returned,
197 otherwise a tuple will be constructed with the appropriate contents. This is
198 equivalent to the Python expression tuple(o)."""
199 return space.call_function(space.w_tuple, w_obj)
200
201 @cpython_api([PyObject, PyObject], PyObject)
202 def PySequence_Concat(space, w_o1, w_o2):
203 """Return the concatenation of o1 and o2 on success, and NULL on failure.
204 This is the equivalent of the Python expression o1 + o2."""
205 return space.add(w_o1, w_o2)
206
207 @cpython_api([PyObject, PyObject], PyObject)
208 def PySequence_InPlaceConcat(space, w_o1, w_o2):
209 """Return the concatenation of o1 and o2 on success, and NULL on failure.
210 The operation is done in-place when o1 supports it. This is the equivalent
211 of the Python expression o1 += o2."""
212 return space.inplace_add(w_o1, w_o2)
213
214 @cpython_api([PyObject, Py_ssize_t], PyObject)
215 def PySequence_InPlaceRepeat(space, w_o, count):
216 """Return the result of repeating sequence object o count times, or NULL on
217 failure. The operation is done in-place when o supports it. This is the
218 equivalent of the Python expression o *= count.
219
220 This function used an int type for count. This might require
221 changes in your code for properly supporting 64-bit systems."""
222 return space.inplace_mul(w_o, space.newint(count))
223
224
225 @cpython_api([PyObject, PyObject], rffi.INT_real, error=-1)
226 def PySequence_Contains(space, w_obj, w_value):
227 """Determine if o contains value. If an item in o is equal to value,
228 return 1, otherwise return 0. On error, return -1. This is
229 equivalent to the Python expression value in o."""
230 w_res = space.contains(w_obj, w_value)
231 return space.int_w(w_res)
232
233 @cpython_api([PyObject], PyObject)
234 def PySeqIter_New(space, w_seq):
235 """Return an iterator that works with a general sequence object, seq. The
236 iteration ends when the sequence raises IndexError for the subscripting
237 operation.
238 """
239 # XXX check for bad internal call
240 return space.newseqiter(w_seq)
241
242 @cpython_api([PyObject, Py_ssize_t, PyObject], rffi.INT_real, error=-1)
243 def PySequence_SetItem(space, w_o, i, w_v):
244 """Assign object v to the ith element of o. Returns -1 on failure. This
245 is the equivalent of the Python statement o[i] = v. This function does
246 not steal a reference to v."""
247 if PyDict_Check(space, w_o) or not PySequence_Check(space, w_o):
248 raise oefmt(space.w_TypeError,
249 "'%T' object does not support item assignment", w_o)
250 space.setitem(w_o, space.newint(i), w_v)
251 return 0
252
253 @cpython_api([PyObject, Py_ssize_t], rffi.INT_real, error=-1)
254 def PySequence_DelItem(space, w_o, i):
255 """Delete the ith element of object o. Returns -1 on failure. This is the
256 equivalent of the Python statement del o[i]."""
257 space.delitem(w_o, space.newint(i))
258 return 0
259
260 @cpython_api([PyObject, PyObject], Py_ssize_t, error=-1)
261 def PySequence_Index(space, w_seq, w_obj):
262 """Return the first index i for which o[i] == value. On error, return
263 -1. This is equivalent to the Python expression o.index(value).
264
265 This function returned an int type. This might require changes
266 in your code for properly supporting 64-bit systems."""
267
268 w_iter = space.iter(w_seq)
269 idx = 0
270 while True:
271 try:
272 w_next = space.next(w_iter)
273 except OperationError as e:
274 if e.match(space, space.w_StopIteration):
275 break
276 raise
277 if space.eq_w(w_next, w_obj):
278 return idx
279 idx += 1
280
281 raise oefmt(space.w_ValueError, "sequence.index(x): x not in sequence")
282
283 class CPyListStrategy(ListStrategy):
284 erase, unerase = rerased.new_erasing_pair("cpylist")
285 erase = staticmethod(erase)
286 unerase = staticmethod(unerase)
287
288 def _check_index(self, index, length):
289 if index < 0:
290 index = length + index
291 if index < 0 or index >= length:
292 raise IndexError
293 return index
294
295 def getitem(self, w_list, index):
296 storage = self.unerase(w_list.lstorage)
297 index = self._check_index(index, storage._length)
298 return from_ref(w_list.space, storage._elems[index])
299
300 def setitem(self, w_list, index, w_obj):
301 storage = self.unerase(w_list.lstorage)
302 index = self._check_index(index, storage._length)
303 py_old = storage._elems[index]
304 storage._elems[index] = make_ref(w_list.space, w_obj)
305 decref(w_list.space, py_old)
306
307 def length(self, w_list):
308 storage = self.unerase(w_list.lstorage)
309 return storage._length
310
311 def getslice(self, w_list, start, stop, step, length):
312 w_list.switch_to_object_strategy()
313 return w_list.strategy.getslice(w_list, start, stop, step, length)
314
315 def getitems(self, w_list):
316 # called when switching list strategy, so convert storage
317 storage = self.unerase(w_list.lstorage)
318 retval = [None] * storage._length
319 for i in range(storage._length):
320 retval[i] = from_ref(w_list.space, storage._elems[i])
321 return retval
322
323 @jit.unroll_safe
324 def getitems_unroll(self, w_list):
325 storage = self.unerase(w_list.lstorage)
326 retval = [None] * storage._length
327 for i in range(storage._length):
328 retval[i] = from_ref(w_list.space, storage._elems[i])
329 return retval
330
331 @jit.look_inside_iff(lambda self, w_list:
332 jit.loop_unrolling_heuristic(w_list, w_list.length(),
333 UNROLL_CUTOFF))
334 def getitems_fixedsize(self, w_list):
335 return self.getitems_unroll(w_list)
336
337 def copy_into(self, w_list, w_other):
338 w_other.strategy = self
339 w_other.lstorage = self.getstorage_copy(w_list)
340
341 def clone(self, w_list, sizehint=0):
342 storage = self.getstorage_copy(w_list)
343 w_clone = W_ListObject.from_storage_and_strategy(self.space, storage,
344 self)
345 return w_clone
346
347 def getitems_copy(self, w_list):
348 return self.getitems(w_list) # getitems copies anyway
349
350 def getstorage_copy(self, w_list):
351 lst = self.getitems(w_list)
352 return self.erase(CPyListStorage(w_list.space, lst))
353
354 #------------------------------------------
355 # all these methods fail or switch strategy and then call ListObjectStrategy's method
356
357 def setslice(self, w_list, start, stop, step, length):
358 w_list.switch_to_object_strategy()
359 w_list.strategy.setslice(w_list, start, stop, step, length)
360
361 def init_from_list_w(self, w_list, list_w):
362 raise NotImplementedError
363
364 def _resize_hint(self, w_list, hint):
365 pass
366
367 def find(self, w_list, w_item, start, stop):
368 w_list.switch_to_object_strategy()
369 return w_list.strategy.find(w_list, w_item, start, stop)
370
371 def append(self, w_list, w_item):
372 w_list.switch_to_object_strategy()
373 w_list.strategy.append(w_list, w_item)
374
375 def inplace_mul(self, w_list, times):
376 w_list.switch_to_object_strategy()
377 w_list.strategy.inplace_mul(w_list, times)
378
379 def deleteslice(self, w_list, start, step, slicelength):
380 w_list.switch_to_object_strategy()
381 w_list.strategy.deleteslice(w_list, start, step, slicelength)
382
383 def pop(self, w_list, index):
384 w_list.switch_to_object_strategy()
385 return w_list.strategy.pop(w_list, index)
386
387 def pop_end(self, w_list):
388 w_list.switch_to_object_strategy()
389 return w_list.strategy.pop_end(w_list)
390
391 def insert(self, w_list, index, w_item):
392 w_list.switch_to_object_strategy()
393 w_list.strategy.insert(w_list, index, w_item)
394
395 def extend(self, w_list, w_any):
396 w_list.switch_to_object_strategy()
397 w_list.strategy.extend(w_list, w_any)
398
399 def _extend_from_list(self, w_list, w_other):
400 w_list.switch_to_object_strategy()
401 w_list.strategy._extend_from_list(w_list, w_other)
402
403 def _extend_from_iterable(self, w_list, w_iterable):
404 w_list.switch_to_object_strategy()
405 w_list.strategy._extend_from_iterable(w_list, w_iterable)
406
407 def reverse(self, w_list):
408 w_list.switch_to_object_strategy()
409 w_list.strategy.reverse(w_list)
410
411 def sort(self, w_list, reverse):
412 w_list.switch_to_object_strategy()
413 w_list.descr_sort(w_list.space, reverse=reverse)
414
415 def is_empty_strategy(self):
416 return False
417
418
419 PyObjectList = lltype.Ptr(lltype.Array(PyObject, hints={'nolength': True}))
420
421 class CPyListStorage(object):
422 def __init__(self, space, lst):
423 self.space = space
424 self._elems = lltype.malloc(PyObjectList.TO, len(lst), flavor='raw')
425 self._length = len(lst)
426 self._allocated = len(lst)
427 for i, item in enumerate(lst):
428 self._elems[i] = make_ref(space, lst[i])
429
430 def __del__(self):
431 for i in range(self._length):
432 decref(self.space, self._elems[i])
433 lltype.free(self._elems, flavor='raw')