Debian Codegraph @

rpython/rtyper/rlist.py

raw symbols SCIP
1 from rpython.annotator import model as annmodel
2 from rpython.flowspace.model import Constant
3 from rpython.rlib import rgc, jit, types
4 from rpython.rtyper.debug import ll_assert
5 from rpython.rlib.objectmodel import malloc_zero_filled, enforceargs, specialize
6 from rpython.rlib.signature import signature
7 from rpython.rlib.rarithmetic import ovfcheck, widen, r_uint, intmask
8 from rpython.rlib.rarithmetic import int_force_ge_zero
9 from rpython.rtyper.annlowlevel import ADTInterface
10 from rpython.rtyper.error import TyperError
11 from rpython.rtyper.lltypesystem.lltype import typeOf, Ptr, Void, Signed, Bool
12 from rpython.rtyper.lltypesystem.lltype import nullptr, Char, UniChar, Number
13 from rpython.rtyper.rmodel import Repr, IteratorRepr
14 from rpython.rtyper.rint import IntegerRepr
15 from rpython.rtyper.rstr import AbstractStringRepr, AbstractCharRepr
16 from rpython.tool.pairtype import pairtype, pair
17
18
19 ADTIFixedList = ADTInterface(None, {
20 'll_newlist': (['SELF', Signed ], 'self'),
21 'll_length': (['self' ], Signed),
22 'll_getitem_fast': (['self', Signed ], 'item'),
23 'll_setitem_fast': (['self', Signed, 'item'], Void),
24 })
25 ADTIList = ADTInterface(ADTIFixedList, {
26 # grow the length if needed, overallocating a bit
27 '_ll_resize_ge': (['self', Signed ], Void),
28 # shrink the length; if reallocating, don't keep any overallocation
29 '_ll_resize_le': (['self', Signed ], Void),
30 # resize to exactly the given size; no overallocation
31 '_ll_resize': (['self', Signed ], Void),
32 # give a hint about the size; does overallocation if growing
33 '_ll_resize_hint': (['self', Signed ], Void),
34 })
35
36
37 def dum_checkidx(): pass
38 def dum_nocheck(): pass
39
40
41 class __extend__(annmodel.SomeList):
42 def rtyper_makerepr(self, rtyper):
43 listitem = self.listdef.listitem
44 s_value = listitem.s_value
45 if (listitem.range_step is not None and not listitem.mutated and
46 not isinstance(s_value, annmodel.SomeImpossibleValue)):
47 from rpython.rtyper.lltypesystem.rrange import RangeRepr
48 return RangeRepr(listitem.range_step)
49 else:
50 # cannot do the rtyper.getrepr() call immediately, for the case
51 # of recursive structures -- i.e. if the listdef contains itself
52 from rpython.rtyper.lltypesystem.rlist import ListRepr, FixedSizeListRepr
53 item_repr = lambda: rtyper.getrepr(listitem.s_value)
54 if self.listdef.listitem.resized:
55 return ListRepr(rtyper, item_repr, listitem)
56 else:
57 return FixedSizeListRepr(rtyper, item_repr, listitem)
58
59 def rtyper_makekey(self):
60 self.listdef.listitem.dont_change_any_more = True
61 return self.__class__, self.listdef.listitem
62
63
64 class AbstractBaseListRepr(Repr):
65 eq_func_cache = None
66
67 def recast(self, llops, v):
68 return llops.convertvar(v, self.item_repr, self.external_item_repr)
69
70 def convert_const(self, listobj):
71 # get object from bound list method
72 if listobj is None:
73 return self.null_const()
74 if not isinstance(listobj, list):
75 raise TyperError("expected a list: %r" % (listobj,))
76 try:
77 key = Constant(listobj)
78 return self.list_cache[key]
79 except KeyError:
80 self.setup()
81 n = len(listobj)
82 result = self.prepare_const(n)
83 self.list_cache[key] = result
84 r_item = self.item_repr
85 if r_item.lowleveltype is not Void:
86 for i in range(n):
87 x = listobj[i]
88 result.ll_setitem_fast(i, r_item.convert_const(x))
89 return result
90
91 def null_const(self):
92 raise NotImplementedError
93
94 def prepare_const(self, nitems):
95 raise NotImplementedError
96
97 def ll_str(self, l):
98 from rpython.rtyper.annlowlevel import llstr, hlstr
99 from rpython.rlib.rstring import StringBuilder
100
101 length = l.ll_length()
102 if length == 0:
103 return llstr("[]")
104
105 buf = StringBuilder(3 * length + 2)
106 buf.append("[")
107 item_repr = self.item_repr
108 i = 0
109 while i < length:
110 if i > 0:
111 buf.append(", ")
112 item = l.ll_getitem_fast(i)
113 buf.append(hlstr(item_repr.ll_str(item)))
114 i += 1
115 buf.append("]")
116 return llstr(buf.build())
117
118 def rtype_bltn_list(self, hop):
119 v_lst = hop.inputarg(self, 0)
120 cRESLIST = hop.inputconst(Void, hop.r_result.LIST)
121 hop.exception_is_here()
122 return hop.gendirectcall(ll_copy, cRESLIST, v_lst)
123
124 def rtype_len(self, hop):
125 v_lst, = hop.inputargs(self)
126 if hop.args_s[0].listdef.listitem.resized:
127 ll_func = ll_len
128 else:
129 ll_func = ll_len_foldable
130 return hop.gendirectcall(ll_func, v_lst)
131
132 def rtype_bool(self, hop):
133 v_lst, = hop.inputargs(self)
134 if hop.args_s[0].listdef.listitem.resized:
135 ll_func = ll_list_is_true
136 else:
137 ll_func = ll_list_is_true_foldable
138 return hop.gendirectcall(ll_func, v_lst)
139
140 def rtype_method_reverse(self, hop):
141 v_lst, = hop.inputargs(self)
142 hop.exception_cannot_occur()
143 hop.gendirectcall(ll_reverse,v_lst)
144
145 def rtype_method_remove(self, hop):
146 v_lst, v_value = hop.inputargs(self, self.item_repr)
147 hop.has_implicit_exception(ValueError) # record that we know about it
148 hop.exception_is_here()
149 return hop.gendirectcall(ll_listremove, v_lst, v_value,
150 self.get_eqfunc())
151
152 def rtype_method_index(self, hop):
153 v_lst, v_value = hop.inputargs(self, self.item_repr)
154 hop.has_implicit_exception(ValueError) # record that we know about it
155 hop.exception_is_here()
156 return hop.gendirectcall(ll_listindex, v_lst, v_value, self.get_eqfunc())
157
158 def get_ll_eq_function(self):
159 result = self.eq_func_cache
160 if result is not None:
161 return result
162 def list_eq(l1, l2):
163 return ll_listeq(l1, l2, item_eq_func)
164 self.eq_func_cache = list_eq
165 # ^^^ do this first, before item_repr.get_ll_eq_function()
166 item_eq_func = self.item_repr.get_ll_eq_function()
167 return list_eq
168
169 def _get_v_maxlength(self, hop):
170 from rpython.rtyper.rint import signed_repr
171 v_iterable = hop.args_v[1]
172 s_iterable = hop.args_s[1]
173 r_iterable = hop.args_r[1]
174 hop2 = hop.copy()
175 while hop2.nb_args > 0:
176 hop2.r_s_popfirstarg()
177 hop2.v_s_insertfirstarg(v_iterable, s_iterable)
178 hop2.r_result = signed_repr
179 v_maxlength = r_iterable.rtype_len(hop2)
180 return v_maxlength
181
182
183 class AbstractListRepr(AbstractBaseListRepr):
184
185 def rtype_method_append(self, hop):
186 v_lst, v_value = hop.inputargs(self, self.item_repr)
187 hop.exception_cannot_occur()
188 hop.gendirectcall(ll_append, v_lst, v_value)
189
190 def rtype_method_insert(self, hop):
191 v_lst, v_index, v_value = hop.inputargs(self, Signed, self.item_repr)
192 arg1 = hop.args_s[1]
193 args = v_lst, v_index, v_value
194 if arg1.is_constant() and arg1.const == 0:
195 llfn = ll_prepend
196 args = v_lst, v_value
197 elif arg1.nonneg:
198 llfn = ll_insert_nonneg
199 else:
200 raise TyperError("insert() index must be proven non-negative")
201 hop.exception_cannot_occur()
202 hop.gendirectcall(llfn, *args)
203
204 def rtype_method_extend(self, hop):
205 v_lst1, v_lst2 = hop.inputargs(*hop.args_r)
206 hop.exception_cannot_occur()
207 hop.gendirectcall(ll_extend, v_lst1, v_lst2)
208
209 def rtype_method_pop(self, hop):
210 if hop.has_implicit_exception(IndexError):
211 spec = dum_checkidx
212 else:
213 spec = dum_nocheck
214 v_func = hop.inputconst(Void, spec)
215 if hop.nb_args == 2:
216 args = hop.inputargs(self, Signed)
217 assert hasattr(args[1], 'concretetype')
218 arg1 = hop.args_s[1]
219 if arg1.is_constant() and arg1.const == 0:
220 llfn = ll_pop_zero
221 args = args[:1]
222 elif hop.args_s[1].nonneg:
223 llfn = ll_pop_nonneg
224 else:
225 llfn = ll_pop
226 else:
227 args = hop.inputargs(self)
228 llfn = ll_pop_default
229 hop.exception_is_here()
230 v_res = hop.gendirectcall(llfn, v_func, *args)
231 return self.recast(hop.llops, v_res)
232
233
234 class AbstractFixedSizeListRepr(AbstractBaseListRepr):
235 pass
236
237
238 class __extend__(pairtype(AbstractBaseListRepr, Repr)):
239
240 def rtype_contains((r_lst, _), hop):
241 v_lst, v_any = hop.inputargs(r_lst, r_lst.item_repr)
242 hop.exception_cannot_occur()
243 return hop.gendirectcall(ll_listcontains, v_lst, v_any, r_lst.get_eqfunc())
244
245 class __extend__(pairtype(AbstractBaseListRepr, IntegerRepr)):
246
247 def rtype_getitem((r_lst, r_int), hop, checkidx=False):
248 v_lst, v_index = hop.inputargs(r_lst, Signed)
249 if checkidx:
250 hop.exception_is_here()
251 spec = dum_checkidx
252 else:
253 spec = dum_nocheck
254 hop.exception_cannot_occur()
255 if hop.args_s[0].listdef.listitem.mutated:
256 basegetitem = ll_getitem_fast
257 else:
258 basegetitem = ll_getitem_foldable_nonneg
259
260 if hop.args_s[1].nonneg:
261 llfn = ll_getitem_nonneg
262 else:
263 llfn = ll_getitem
264 c_func_marker = hop.inputconst(Void, spec)
265 c_basegetitem = hop.inputconst(Void, basegetitem)
266 v_res = hop.gendirectcall(llfn, c_func_marker, c_basegetitem, v_lst, v_index)
267 return r_lst.recast(hop.llops, v_res)
268
269 def rtype_getitem_idx((r_lst, r_int), hop):
270 return pair(r_lst, r_int).rtype_getitem(hop, checkidx=True)
271
272 def rtype_setitem((r_lst, r_int), hop):
273 if hop.has_implicit_exception(IndexError):
274 spec = dum_checkidx
275 else:
276 spec = dum_nocheck
277 v_func = hop.inputconst(Void, spec)
278 v_lst, v_index, v_item = hop.inputargs(r_lst, Signed, r_lst.item_repr)
279 if hop.args_s[1].nonneg:
280 llfn = ll_setitem_nonneg
281 else:
282 llfn = ll_setitem
283 hop.exception_is_here()
284 return hop.gendirectcall(llfn, v_func, v_lst, v_index, v_item)
285
286 def rtype_mul((r_lst, r_int), hop):
287 cRESLIST = hop.inputconst(Void, hop.r_result.LIST)
288 v_lst, v_factor = hop.inputargs(r_lst, Signed)
289 return hop.gendirectcall(ll_mul, cRESLIST, v_lst, v_factor)
290
291 class __extend__(pairtype(IntegerRepr, AbstractBaseListRepr)):
292 def rtype_mul((r_int, r_lst), hop):
293 cRESLIST = hop.inputconst(Void, hop.r_result.LIST)
294 v_factor, v_lst = hop.inputargs(Signed, r_lst)
295 return hop.gendirectcall(ll_mul, cRESLIST, v_lst, v_factor)
296
297 class __extend__(pairtype(AbstractListRepr, IntegerRepr)):
298
299 def rtype_delitem((r_lst, r_int), hop):
300 if hop.has_implicit_exception(IndexError):
301 spec = dum_checkidx
302 else:
303 spec = dum_nocheck
304 v_func = hop.inputconst(Void, spec)
305 v_lst, v_index = hop.inputargs(r_lst, Signed)
306 if hop.args_s[1].nonneg:
307 llfn = ll_delitem_nonneg
308 else:
309 llfn = ll_delitem
310 hop.exception_is_here()
311 return hop.gendirectcall(llfn, v_func, v_lst, v_index)
312
313 def rtype_inplace_mul((r_lst, r_int), hop):
314 v_lst, v_factor = hop.inputargs(r_lst, Signed)
315 return hop.gendirectcall(ll_inplace_mul, v_lst, v_factor)
316
317
318 class __extend__(pairtype(AbstractBaseListRepr, AbstractBaseListRepr)):
319 def convert_from_to((r_lst1, r_lst2), v, llops):
320 if r_lst1.listitem is None or r_lst2.listitem is None:
321 return NotImplemented
322 if r_lst1.listitem is not r_lst2.listitem:
323 return NotImplemented
324 return v
325
326 def rtype_eq((r_lst1, r_lst2), hop):
327 assert r_lst1.item_repr == r_lst2.item_repr
328 v_lst1, v_lst2 = hop.inputargs(r_lst1, r_lst2)
329 return hop.gendirectcall(ll_listeq, v_lst1, v_lst2, r_lst1.get_eqfunc())
330
331 def rtype_ne((r_lst1, r_lst2), hop):
332 assert r_lst1.item_repr == r_lst2.item_repr
333 v_lst1, v_lst2 = hop.inputargs(r_lst1, r_lst2)
334 flag = hop.gendirectcall(ll_listeq, v_lst1, v_lst2, r_lst1.get_eqfunc())
335 return hop.genop('bool_not', [flag], resulttype=Bool)
336
337
338 def rtype_newlist(hop, v_sizehint=None):
339 from rpython.rtyper.lltypesystem.rlist import newlist
340 nb_args = hop.nb_args
341 r_list = hop.r_result
342 r_listitem = r_list.item_repr
343 items_v = [hop.inputarg(r_listitem, arg=i) for i in range(nb_args)]
344 return newlist(hop.llops, r_list, items_v, v_sizehint=v_sizehint)
345
346 def rtype_alloc_and_set(hop):
347 r_list = hop.r_result
348 v_count, v_item = hop.inputargs(Signed, r_list.item_repr)
349 cLIST = hop.inputconst(Void, r_list.LIST)
350 return hop.gendirectcall(ll_alloc_and_set, cLIST, v_count, v_item)
351
352
353 class __extend__(pairtype(AbstractBaseListRepr, AbstractBaseListRepr)):
354
355 def rtype_add((r_lst1, r_lst2), hop):
356 v_lst1, v_lst2 = hop.inputargs(r_lst1, r_lst2)
357 cRESLIST = hop.inputconst(Void, hop.r_result.LIST)
358 return hop.gendirectcall(ll_concat, cRESLIST, v_lst1, v_lst2)
359
360 class __extend__(pairtype(AbstractListRepr, AbstractBaseListRepr)):
361
362 def rtype_inplace_add((r_lst1, r_lst2), hop):
363 v_lst1, v_lst2 = hop.inputargs(r_lst1, r_lst2)
364 hop.gendirectcall(ll_extend, v_lst1, v_lst2)
365 return v_lst1
366
367 class __extend__(pairtype(AbstractListRepr, AbstractStringRepr)):
368
369 def rtype_inplace_add((r_lst1, r_str2), hop):
370 if r_lst1.item_repr.lowleveltype not in (Char, UniChar):
371 raise TyperError('"lst += string" only supported with a list '
372 'of chars or unichars')
373 string_repr = r_str2.repr
374 v_lst1, v_str2 = hop.inputargs(r_lst1, string_repr)
375 c_strlen = hop.inputconst(Void, string_repr.ll.ll_strlen)
376 c_stritem = hop.inputconst(Void, string_repr.ll.ll_stritem_nonneg)
377 hop.gendirectcall(ll_extend_with_str, v_lst1, v_str2,
378 c_strlen, c_stritem)
379 return v_lst1
380
381 def rtype_extend_with_str_slice((r_lst1, r_str2), hop):
382 from rpython.rtyper.lltypesystem.rstr import string_repr
383 if r_lst1.item_repr.lowleveltype not in (Char, UniChar):
384 raise TyperError('"lst += string" only supported with a list '
385 'of chars or unichars')
386 v_lst1 = hop.inputarg(r_lst1, arg=0)
387 v_str2 = hop.inputarg(string_repr, arg=3)
388 kind, vlist = hop.decompose_slice_args()
389 c_strlen = hop.inputconst(Void, string_repr.ll.ll_strlen)
390 c_stritem = hop.inputconst(Void, string_repr.ll.ll_stritem_nonneg)
391 ll_fn = globals()['ll_extend_with_str_slice_%s' % kind]
392 hop.gendirectcall(ll_fn, v_lst1, v_str2, c_strlen, c_stritem, *vlist)
393 return v_lst1
394
395 class __extend__(pairtype(AbstractListRepr, AbstractCharRepr)):
396
397 def rtype_extend_with_char_count((r_lst1, r_chr2), hop):
398 from rpython.rtyper.lltypesystem.rstr import char_repr
399 if r_lst1.item_repr.lowleveltype not in (Char, UniChar):
400 raise TyperError('"lst += string" only supported with a list '
401 'of chars or unichars')
402 v_lst1, v_chr, v_count = hop.inputargs(r_lst1, char_repr, Signed)
403 hop.gendirectcall(ll_extend_with_char_count, v_lst1, v_chr, v_count)
404 return v_lst1
405
406
407 class __extend__(AbstractBaseListRepr):
408
409 def rtype_getslice(r_lst, hop):
410 cRESLIST = hop.inputconst(Void, hop.r_result.LIST)
411 v_lst = hop.inputarg(r_lst, arg=0)
412 kind, vlist = hop.decompose_slice_args()
413 ll_listslice = globals()['ll_listslice_%s' % kind]
414 return hop.gendirectcall(ll_listslice, cRESLIST, v_lst, *vlist)
415
416 def rtype_setslice(r_lst, hop):
417 v_lst = hop.inputarg(r_lst, arg=0)
418 kind, vlist = hop.decompose_slice_args()
419 if kind != 'startstop':
420 raise TyperError('list.setitem does not support %r slices' % (
421 kind,))
422 v_start, v_stop = vlist
423 v_lst2 = hop.inputarg(hop.args_r[3], arg=3)
424 hop.gendirectcall(ll_listsetslice, v_lst, v_start, v_stop, v_lst2)
425
426 def rtype_delslice(r_lst, hop):
427 v_lst = hop.inputarg(r_lst, arg=0)
428 kind, vlist = hop.decompose_slice_args()
429 ll_listdelslice = globals()['ll_listdelslice_%s' % kind]
430 return hop.gendirectcall(ll_listdelslice, v_lst, *vlist)
431
432
433 # ____________________________________________________________
434 #
435 # Iteration.
436
437 class AbstractListIteratorRepr(IteratorRepr):
438
439 def newiter(self, hop):
440 v_lst, = hop.inputargs(self.r_list)
441 citerptr = hop.inputconst(Void, self.lowleveltype)
442 return hop.gendirectcall(self.ll_listiter, citerptr, v_lst)
443
444 def rtype_next(self, hop):
445 v_iter, = hop.inputargs(self)
446 hop.has_implicit_exception(StopIteration) # record that we know about it
447 hop.exception_is_here()
448 v_res = hop.gendirectcall(self.ll_listnext, v_iter)
449 return self.r_list.recast(hop.llops, v_res)
450
451
452 # ____________________________________________________________
453 #
454 # Low-level methods. These can be run for testing, but are meant to
455 # be direct_call'ed from rtyped flow graphs, which means that they will
456 # get flowed and annotated, mostly with SomePtr.
457 #
458 # === a note about overflows ===
459 #
460 # The maximal length of RPython lists is bounded by the assumption that
461 # we can never allocate arrays more than sys.maxint bytes in size.
462 # Our arrays have a length and some GC headers, so a list of characters
463 # could come near sys.maxint in length (but not reach it). A list of
464 # pointers could only come near sys.maxint/sizeof(void*) elements. There
465 # is the list of Voids that could reach exactly sys.maxint elements,
466 # but for now let's ignore this case -- the reasoning is that even if
467 # the length of a Void list overflows, nothing bad memory-wise can be
468 # done with it. So in the sequel we don't bother checking for overflow
469 # when we compute "ll_length() + 1".
470
471
472 def _ll_zero_or_null(item):
473 # Check if 'item' is zero/null, or not.
474 T = typeOf(item)
475 if T is Char or T is UniChar:
476 check = ord(item)
477 elif isinstance(T, Number):
478 check = widen(item)
479 else:
480 check = item
481 return not check
482
483 @specialize.memo()
484 def _null_of_type(T):
485 return T._defl()
486
487 def ll_alloc_and_set(LIST, count, item):
488 count = int_force_ge_zero(count)
489 if jit.we_are_jitted():
490 return _ll_alloc_and_set_jit(LIST, count, item)
491 else:
492 return _ll_alloc_and_set_nojit(LIST, count, item)
493
494 def _ll_alloc_and_set_nojit(LIST, count, item):
495 l = LIST.ll_newlist(count)
496 if malloc_zero_filled and _ll_zero_or_null(item):
497 return l
498 i = 0
499 while i < count:
500 l.ll_setitem_fast(i, item)
501 i += 1
502 return l
503
504 def _ll_alloc_and_set_jit(LIST, count, item):
505 if _ll_zero_or_null(item):
506 # 'item' is zero/null. Do the list allocation with the
507 # function _ll_alloc_and_clear(), which the JIT knows about.
508 return _ll_alloc_and_clear(LIST, count)
509 else:
510 # 'item' is not zero/null. Do the list allocation with the
511 # function _ll_alloc_and_set_nonnull(). That function has
512 # a JIT marker to unroll it, but only if the 'count' is
513 # a not-too-large constant.
514 return _ll_alloc_and_set_nonnull(LIST, count, item)
515
516 @jit.oopspec("newlist_clear(count)")
517 def _ll_alloc_and_clear(LIST, count):
518 l = LIST.ll_newlist(count)
519 if malloc_zero_filled:
520 return l
521 zeroitem = _null_of_type(LIST.ITEM)
522 i = 0
523 while i < count:
524 l.ll_setitem_fast(i, zeroitem)
525 i += 1
526 return l
527
528 @jit.look_inside_iff(lambda LIST, count, item: jit.isconstant(count) and count < 137)
529 def _ll_alloc_and_set_nonnull(LIST, count, item):
530 l = LIST.ll_newlist(count)
531 i = 0
532 while i < count:
533 l.ll_setitem_fast(i, item)
534 i += 1
535 return l
536
537
538 # return a nullptr() if lst is a list of pointers it, else None.
539 def ll_null_item(lst):
540 LIST = typeOf(lst)
541 if isinstance(LIST, Ptr):
542 ITEM = LIST.TO.ITEM
543 if isinstance(ITEM, Ptr):
544 return nullptr(ITEM.TO)
545 return None
546
547 def listItemType(lst):
548 LIST = typeOf(lst)
549 return LIST.TO.ITEM
550
551
552 @signature(types.any(), types.any(), types.int(), types.int(), types.int(), returns=types.none())
553 def ll_arraycopy(source, dest, source_start, dest_start, length):
554 SRCTYPE = typeOf(source)
555 # lltype
556 rgc.ll_arraycopy(source.ll_items(), dest.ll_items(),
557 source_start, dest_start, length)
558
559 @signature(types.any(), types.int(), types.int(), types.int(), returns=types.none())
560 def ll_arraymove(lst, source_start, dest_start, length):
561 # copy the slice [source_start:source_stop] to the slice [dest_start:..]
562 rgc.ll_arraymove(lst.ll_items(), source_start, dest_start, length)
563
564
565 def ll_copy(RESLIST, l):
566 length = l.ll_length()
567 new_lst = RESLIST.ll_newlist(length)
568 ll_arraycopy(l, new_lst, 0, 0, length)
569 return new_lst
570 # no oopspec -- the function is inlined by the JIT
571
572 def ll_len(l):
573 return l.ll_length()
574
575 def ll_list_is_true(l):
576 # check if a list is True, allowing for None
577 return bool(l) and l.ll_length() != 0
578 # no oopspec -- the function is inlined by the JIT
579
580 def ll_len_foldable(l):
581 return l.ll_length()
582 ll_len_foldable.oopspec = 'list.len_foldable(l)'
583
584 def ll_list_is_true_foldable(l):
585 return bool(l) and ll_len_foldable(l) != 0
586 # no oopspec -- the function is inlined by the JIT
587
588 def ll_append(l, newitem):
589 length = l.ll_length()
590 l._ll_resize_ge(length+1) # see "a note about overflows" above
591 l.ll_setitem_fast(length, newitem)
592
593 # this one is for the special case of insert(0, x)
594 def ll_prepend(l, newitem):
595 length = l.ll_length()
596 l._ll_resize_ge(length+1) # see "a note about overflows" above
597 ll_arraymove(l, 0, 1, length)
598 l.ll_setitem_fast(0, newitem)
599
600 def ll_concat(RESLIST, l1, l2):
601 len1 = l1.ll_length()
602 len2 = l2.ll_length()
603 try:
604 newlength = ovfcheck(len1 + len2)
605 except OverflowError:
606 raise MemoryError
607 l = RESLIST.ll_newlist(newlength)
608 ll_arraycopy(l1, l, 0, 0, len1)
609 ll_arraycopy(l2, l, 0, len1, len2)
610 return l
611 # no oopspec -- the function is inlined by the JIT
612
613 def ll_insert_nonneg(l, index, newitem):
614 length = l.ll_length()
615 ll_assert(0 <= index, "negative list insertion index")
616 ll_assert(index <= length, "list insertion index out of bound")
617 l._ll_resize_ge(length+1) # see "a note about overflows" above
618 ll_arraymove(l, index, index + 1, length - index)
619 l.ll_setitem_fast(index, newitem)
620
621 def ll_pop_nonneg(func, l, index):
622 ll_assert(index >= 0, "unexpectedly negative list pop index")
623 if func is dum_checkidx:
624 if index >= l.ll_length():
625 raise IndexError
626 else:
627 ll_assert(index < l.ll_length(), "list pop index out of bound")
628 res = l.ll_getitem_fast(index)
629 ll_delitem_nonneg(dum_nocheck, l, index)
630 return res
631 ll_pop_nonneg.oopspec = 'list.pop(l, index)'
632
633 def ll_pop_default(func, l):
634 length = l.ll_length()
635 if func is dum_checkidx and (length == 0):
636 raise IndexError
637 ll_assert(length > 0, "pop from empty list")
638 index = length - 1
639 newlength = index
640 res = l.ll_getitem_fast(index)
641 null = ll_null_item(l)
642 if null is not None:
643 l.ll_setitem_fast(index, null)
644 l._ll_resize_le(newlength)
645 return res
646
647 def ll_pop_zero(func, l):
648 length = l.ll_length()
649 if func is dum_checkidx and (length == 0):
650 raise IndexError
651 ll_assert(length > 0, "pop(0) from empty list")
652 res = l.ll_getitem_fast(0)
653 newlength = length - 1
654 ll_arraymove(l, 1, 0, newlength)
655 null = ll_null_item(l)
656 if null is not None:
657 l.ll_setitem_fast(newlength, null)
658 l._ll_resize_le(newlength)
659 return res
660 ll_pop_zero.oopspec = 'list.pop(l, 0)'
661
662 def ll_pop(func, l, index):
663 length = l.ll_length()
664 if index < 0:
665 index += length
666 if func is dum_checkidx:
667 if index < 0 or index >= length:
668 raise IndexError
669 else:
670 ll_assert(index >= 0, "negative list pop index out of bound")
671 ll_assert(index < length, "list pop index out of bound")
672 res = l.ll_getitem_fast(index)
673 ll_delitem_nonneg(dum_nocheck, l, index)
674 return res
675
676 @jit.look_inside_iff(lambda l: jit.isvirtual(l) and jit.isconstant(l.ll_length()))
677 def ll_reverse(l):
678 length = l.ll_length()
679 i = 0
680 length_1_i = length-1-i
681 while i < length_1_i:
682 tmp = l.ll_getitem_fast(i)
683 l.ll_setitem_fast(i, l.ll_getitem_fast(length_1_i))
684 l.ll_setitem_fast(length_1_i, tmp)
685 i += 1
686 length_1_i -= 1
687
688 def ll_getitem_nonneg(func, basegetitem, l, index):
689 ll_assert(index >= 0, "unexpectedly negative list getitem index")
690 if func is dum_checkidx:
691 if index >= l.ll_length():
692 raise IndexError
693 return basegetitem(l, index)
694 ll_getitem_nonneg._always_inline_ = True
695 # no oopspec -- the function is inlined by the JIT
696
697 def ll_getitem(func, basegetitem, l, index):
698 if func is dum_checkidx:
699 length = l.ll_length() # common case: 0 <= index < length
700 if r_uint(index) >= r_uint(length):
701 # Failed, so either (-length <= index < 0), or we have to raise
702 # IndexError. First add 'length' to get the final index, then
703 # check that we now have (0 <= index < length).
704 index = r_uint(index) + r_uint(length)
705 if index >= r_uint(length):
706 raise IndexError
707 index = intmask(index)
708 else:
709 # We don't want checking, but still want to support index < 0.
710 # Only call ll_length() if needed.
711 if index < 0:
712 index += l.ll_length()
713 ll_assert(index >= 0, "negative list getitem index out of bound")
714 return basegetitem(l, index)
715 # no oopspec -- the function is inlined by the JIT
716
717 def ll_getitem_fast(l, index):
718 return l.ll_getitem_fast(index)
719 ll_getitem_fast._always_inline_ = True
720
721 def ll_getitem_foldable_nonneg(l, index):
722 ll_assert(index >= 0, "unexpectedly negative list getitem index")
723 return l.ll_getitem_fast(index)
724 ll_getitem_foldable_nonneg.oopspec = 'list.getitem_foldable(l, index)'
725
726 def ll_setitem_nonneg(func, l, index, newitem):
727 ll_assert(index >= 0, "unexpectedly negative list setitem index")
728 if func is dum_checkidx:
729 if index >= l.ll_length():
730 raise IndexError
731 l.ll_setitem_fast(index, newitem)
732 ll_setitem_nonneg._always_inline_ = True
733 # no oopspec -- the function is inlined by the JIT
734
735 def ll_setitem(func, l, index, newitem):
736 if func is dum_checkidx:
737 length = l.ll_length()
738 if r_uint(index) >= r_uint(length): # see comments in ll_getitem().
739 index = r_uint(index) + r_uint(length)
740 if index >= r_uint(length):
741 raise IndexError
742 index = intmask(index)
743 else:
744 if index < 0:
745 index += l.ll_length()
746 ll_assert(index >= 0, "negative list setitem index out of bound")
747 l.ll_setitem_fast(index, newitem)
748 # no oopspec -- the function is inlined by the JIT
749
750 @enforceargs(None, None, int)
751 def ll_delitem_nonneg(func, l, index):
752 ll_assert(index >= 0, "unexpectedly negative list delitem index")
753 length = l.ll_length()
754 if func is dum_checkidx:
755 if index >= length:
756 raise IndexError
757 else:
758 ll_assert(index < length, "list delitem index out of bound")
759 newlength = length - 1
760 ll_arraymove(l, index + 1, index, newlength - index)
761 null = ll_null_item(l)
762 if null is not None:
763 l.ll_setitem_fast(newlength, null)
764 l._ll_resize_le(newlength)
765 # no oopspec -- the function is inlined by the JIT
766
767 def ll_delitem(func, l, index):
768 if func is dum_checkidx:
769 length = l.ll_length()
770 if r_uint(index) >= r_uint(length): # see comments in ll_getitem().
771 index = r_uint(index) + r_uint(length)
772 if index >= r_uint(length):
773 raise IndexError
774 index = intmask(index)
775 else:
776 if index < 0:
777 index += l.ll_length()
778 ll_assert(index >= 0, "negative list delitem index out of bound")
779 ll_delitem_nonneg(dum_nocheck, l, index)
780 # no oopspec -- the function is inlined by the JIT
781
782 def ll_extend(l1, l2):
783 len1 = l1.ll_length()
784 len2 = l2.ll_length()
785 try:
786 newlength = ovfcheck(len1 + len2)
787 except OverflowError:
788 raise MemoryError
789 l1._ll_resize_ge(newlength)
790 ll_arraycopy(l2, l1, 0, len1, len2)
791
792 def ll_extend_with_str(lst, s, getstrlen, getstritem):
793 return ll_extend_with_str_slice_startonly(lst, s, getstrlen, getstritem, 0)
794
795 def ll_extend_with_str_slice_startonly(lst, s, getstrlen, getstritem, start):
796 len1 = lst.ll_length()
797 len2 = getstrlen(s)
798 count2 = len2 - start
799 ll_assert(start >= 0, "unexpectedly negative str slice start")
800 assert count2 >= 0, "str slice start larger than str length"
801 try:
802 newlength = ovfcheck(len1 + count2)
803 except OverflowError:
804 raise MemoryError
805 lst._ll_resize_ge(newlength)
806 i = start
807 j = len1
808 while i < len2:
809 c = getstritem(s, i)
810 if listItemType(lst) is UniChar:
811 c = unichr(ord(c))
812 lst.ll_setitem_fast(j, c)
813 i += 1
814 j += 1
815 # not inlined by the JIT -- contains a loop
816
817 def ll_extend_with_str_slice_startstop(lst, s, getstrlen, getstritem,
818 start, stop):
819 len1 = lst.ll_length()
820 len2 = getstrlen(s)
821 ll_assert(start >= 0, "unexpectedly negative str slice start")
822 ll_assert(start <= len2, "str slice start larger than str length")
823 if stop > len2:
824 stop = len2
825 count2 = stop - start
826 assert count2 >= 0, "str slice stop smaller than start"
827 try:
828 newlength = ovfcheck(len1 + count2)
829 except OverflowError:
830 raise MemoryError
831 lst._ll_resize_ge(newlength)
832 i = start
833 j = len1
834 while i < stop:
835 c = getstritem(s, i)
836 if listItemType(lst) is UniChar:
837 c = unichr(ord(c))
838 lst.ll_setitem_fast(j, c)
839 i += 1
840 j += 1
841 # not inlined by the JIT -- contains a loop
842
843 def ll_extend_with_str_slice_minusone(lst, s, getstrlen, getstritem):
844 len1 = lst.ll_length()
845 len2m1 = getstrlen(s) - 1
846 assert len2m1 >= 0, "empty string is sliced with [:-1]"
847 try:
848 newlength = ovfcheck(len1 + len2m1)
849 except OverflowError:
850 raise MemoryError
851 lst._ll_resize_ge(newlength)
852 i = 0
853 j = len1
854 while i < len2m1:
855 c = getstritem(s, i)
856 if listItemType(lst) is UniChar:
857 c = unichr(ord(c))
858 lst.ll_setitem_fast(j, c)
859 i += 1
860 j += 1
861 # not inlined by the JIT -- contains a loop
862
863 def ll_extend_with_char_count(lst, char, count):
864 if count <= 0:
865 return
866 len1 = lst.ll_length()
867 try:
868 newlength = ovfcheck(len1 + count)
869 except OverflowError:
870 raise MemoryError
871 lst._ll_resize_ge(newlength)
872 j = len1
873 if listItemType(lst) is UniChar:
874 char = unichr(ord(char))
875 while j < newlength:
876 lst.ll_setitem_fast(j, char)
877 j += 1
878
879
880 @signature(types.any(), types.any(), types.int(), returns=types.any())
881 def ll_listslice_startonly(RESLIST, l1, start):
882 len1 = l1.ll_length()
883 ll_assert(start >= 0, "unexpectedly negative list slice start")
884 ll_assert(start <= len1, "list slice start larger than list length")
885 newlength = len1 - start
886 l = RESLIST.ll_newlist(newlength)
887 ll_arraycopy(l1, l, start, 0, newlength)
888 return l
889
890
891 def ll_listslice_startstop(RESLIST, l1, start, stop):
892 length = l1.ll_length()
893 ll_assert(start >= 0, "unexpectedly negative list slice start")
894 ll_assert(start <= length, "list slice start larger than list length")
895 ll_assert(stop >= start, "list slice stop smaller than start")
896 if stop > length:
897 stop = length
898 newlength = stop - start
899 l = RESLIST.ll_newlist(newlength)
900 ll_arraycopy(l1, l, start, 0, newlength)
901 return l
902 # no oopspec -- the function is inlined by the JIT
903
904 def ll_listslice_minusone(RESLIST, l1):
905 newlength = l1.ll_length() - 1
906 ll_assert(newlength >= 0, "empty list is sliced with [:-1]")
907 l = RESLIST.ll_newlist(newlength)
908 ll_arraycopy(l1, l, 0, 0, newlength)
909 return l
910 # no oopspec -- the function is inlined by the JIT
911
912 @jit.look_inside_iff(lambda l, start: jit.isconstant(start) and jit.isvirtual(l))
913 @jit.oopspec('list.delslice_startonly(l, start)')
914 def ll_listdelslice_startonly(l, start):
915 ll_assert(start >= 0, "del l[start:] with unexpectedly negative start")
916 ll_assert(start <= l.ll_length(), "del l[start:] with start > len(l)")
917 newlength = start
918 null = ll_null_item(l)
919 if null is not None:
920 j = l.ll_length() - 1
921 while j >= newlength:
922 l.ll_setitem_fast(j, null)
923 j -= 1
924 l._ll_resize_le(newlength)
925
926 def ll_listdelslice_startstop(l, start, stop):
927 length = l.ll_length()
928 ll_assert(start >= 0, "del l[start:x] with unexpectedly negative start")
929 ll_assert(start <= length, "del l[start:x] with start > len(l)")
930 ll_assert(stop >= start, "del l[x:y] with x > y")
931 if stop > length:
932 stop = length
933 ll_arraymove(l, stop, start, length - stop)
934 newlength = length - (stop-start)
935 null = ll_null_item(l)
936 if null is not None:
937 j = length - 1
938 while j >= newlength:
939 l.ll_setitem_fast(j, null)
940 j -= 1
941 l._ll_resize_le(newlength)
942 ll_listdelslice_startstop.oopspec = 'list.delslice_startstop(l, start, stop)'
943
944 def ll_listsetslice(l1, start, stop, l2):
945 len1 = l1.ll_length()
946 len2 = l2.ll_length()
947 ll_assert(start >= 0, "l[start:x] = l with unexpectedly negative start")
948 ll_assert(start <= len1, "l[start:x] = l with start > len(l)")
949 ll_assert(stop <= len1, "stop cannot be past the end of l1")
950 if len2 == stop - start:
951 ll_arraycopy(l2, l1, 0, start, len2)
952 elif len2 < stop - start:
953 ll_arraycopy(l2, l1, 0, start, len2)
954 ll_arraycopy(l1, l1, stop, start + len2, len1 - stop)
955 l1._ll_resize_le(len1 + len2 - (stop - start))
956 else: # len2 > stop - start:
957 try:
958 newlength = ovfcheck(len1 + len2)
959 except OverflowError:
960 raise MemoryError
961 l1._ll_resize_ge(newlength)
962 ll_arraycopy(l1, l1, stop, start + len2, len1 - stop)
963 ll_arraycopy(l2, l1, 0, start, len2)
964
965
966 # ____________________________________________________________
967 #
968 # Comparison.
969
970 def listeq_unroll_case(l1, l2, eqfn):
971 if jit.isvirtual(l1) and l1.ll_length() < 10:
972 return True
973 if jit.isvirtual(l2) and l2.ll_length() < 10:
974 return True
975 return False
976
977 @jit.look_inside_iff(listeq_unroll_case)
978 def ll_listeq(l1, l2, eqfn):
979 if not l1 and not l2:
980 return True
981 if not l1 or not l2:
982 return False
983 len1 = l1.ll_length()
984 len2 = l2.ll_length()
985 if len1 != len2:
986 return False
987 j = 0
988 while j < len1:
989 if eqfn is None:
990 if l1.ll_getitem_fast(j) != l2.ll_getitem_fast(j):
991 return False
992 else:
993 if not eqfn(l1.ll_getitem_fast(j), l2.ll_getitem_fast(j)):
994 return False
995 j += 1
996 return True
997 # not inlined by the JIT -- contains a loop
998
999 def ll_listcontains(lst, obj, eqfn):
1000 lng = lst.ll_length()
1001 j = 0
1002 while j < lng:
1003 if eqfn is None:
1004 if lst.ll_getitem_fast(j) == obj:
1005 return True
1006 else:
1007 if eqfn(lst.ll_getitem_fast(j), obj):
1008 return True
1009 j += 1
1010 return False
1011 # not inlined by the JIT -- contains a loop
1012
1013 def ll_listindex(lst, obj, eqfn):
1014 lng = lst.ll_length()
1015 j = 0
1016 while j < lng:
1017 if eqfn is None:
1018 if lst.ll_getitem_fast(j) == obj:
1019 return j
1020 else:
1021 if eqfn(lst.ll_getitem_fast(j), obj):
1022 return j
1023 j += 1
1024 raise ValueError # can't say 'list.index(x): x not in list'
1025 # not inlined by the JIT -- contains a loop
1026
1027 def ll_listremove(lst, obj, eqfn):
1028 index = ll_listindex(lst, obj, eqfn) # raises ValueError if obj not in lst
1029 ll_delitem_nonneg(dum_nocheck, lst, index)
1030
1031 def ll_inplace_mul(l, factor):
1032 if factor == 1:
1033 return l
1034 length = l.ll_length()
1035 if factor < 0:
1036 factor = 0
1037 try:
1038 resultlen = ovfcheck(length * factor)
1039 except OverflowError:
1040 raise MemoryError
1041 res = l
1042 res._ll_resize(resultlen)
1043 j = length
1044 while j < resultlen:
1045 ll_arraycopy(l, res, 0, j, length)
1046 j += length
1047 return res
1048 ll_inplace_mul.oopspec = 'list.inplace_mul(l, factor)'
1049
1050 def ll_mul(RESLIST, l, factor):
1051 length = l.ll_length()
1052 factor = int_force_ge_zero(factor)
1053 if length == 1:
1054 item = l.ll_getitem_fast(0)
1055 return ll_alloc_and_set(RESLIST, factor, item)
1056 try:
1057 resultlen = ovfcheck(length * factor)
1058 except OverflowError:
1059 raise MemoryError
1060 res = RESLIST.ll_newlist(resultlen)
1061 if not resultlen:
1062 return res
1063 ll_mul_loop(RESLIST, l, res, resultlen, length, factor)
1064 return res
1065
1066 @jit.look_inside_iff(lambda _, l, res, resultlen, length, factor: jit.isvirtual(l) and
1067 jit.isconstant(factor) and factor < 10)
1068 def ll_mul_loop(RESLIST, l, res, resultlen, length, factor):
1069 # grumble, card marking mess. we would really like to use the second
1070 # loop in all cases. but due to the way the fast paths in
1071 # writebarrier_before_copy in incminimark work, this is actually much
1072 # slower
1073 if rgc._contains_gcptr(RESLIST.ITEM):
1074 j = 0
1075 while j < resultlen:
1076 ll_arraycopy(l, res, 0, j, length)
1077 j += length
1078 return
1079 else:
1080 ll_arraycopy(l, res, 0, 0, length)
1081 j = length
1082 while j < resultlen:
1083 copy_length = min(resultlen - j, j)
1084 ll_arraycopy(res, res, 0, j, copy_length)
1085 j += copy_length
1086 ll_assert(j == resultlen, "list multiplication copied too much or too little")