Debian Codegraph @

pypy/objspace/std/listobject.py

raw symbols SCIP
1 """The builtin list implementation
2
3 Lists optimize their storage by holding certain primitive datatypes in
4 unwrapped form. For more information:
5
6 https://www.pypy.org/posts/2011/10/more-compact-lists-with-list-strategies-8229304944653956829.html
7
8 """
9
10 import math
11 import operator
12 import sys
13
14 from rpython.rlib import debug, jit, rerased, rutf8
15 from rpython.rlib.listsort import make_timsort_class
16 from rpython.rlib.objectmodel import (
17 import_from_mixin, instantiate, newlist_hint, resizelist_hint, specialize)
18 from rpython.rlib.rarithmetic import ovfcheck
19 from rpython.rlib import longlong2float
20 from rpython.tool.sourcetools import func_with_new_name
21 from rpython.rlib.rstring import StringBuilder
22
23 from pypy.interpreter.baseobjspace import W_Root
24 from pypy.interpreter.error import OperationError, oefmt
25 from pypy.interpreter.gateway import (
26 WrappedDefault, applevel, interp2app, unwrap_spec)
27 from pypy.interpreter.signature import Signature
28 from pypy.interpreter.typedef import TypeDef
29 from pypy.interpreter.miscutils import StringSort
30 from pypy.objspace.std.bytesobject import W_BytesObject
31 from pypy.objspace.std.floatobject import W_FloatObject
32 from pypy.objspace.std.intobject import W_IntObject
33 from pypy.objspace.std.longobject import W_LongObject
34 from pypy.objspace.std.iterobject import (
35 W_FastListIterObject, W_ReverseSeqIterObject)
36 from pypy.objspace.std.sliceobject import W_SliceObject, unwrap_start_stop
37 from pypy.objspace.std.tupleobject import W_AbstractTupleObject
38 from pypy.objspace.std.unicodeobject import W_UnicodeObject
39 from pypy.objspace.std.util import (get_positive_index, negate,
40 generic_alias_class_getitem, builtinclass_new_args_check)
41
42 __all__ = ['W_ListObject', 'make_range_list', 'make_empty_list_with_size']
43
44
45 UNROLL_CUTOFF = 5
46
47
48 def make_range_list(space, start, step, length):
49 if length <= 0:
50 strategy = space.fromcache(EmptyListStrategy)
51 storage = strategy.erase(None)
52 elif start == 0 and step == 1:
53 strategy = space.fromcache(SimpleRangeListStrategy)
54 storage = strategy.erase((length,))
55 else:
56 strategy = space.fromcache(RangeListStrategy)
57 storage = strategy.erase((start, step, length))
58 return W_ListObject.from_storage_and_strategy(space, storage, strategy)
59
60
61 def make_empty_list(space):
62 strategy = space.fromcache(EmptyListStrategy)
63 storage = strategy.erase(None)
64 return W_ListObject.from_storage_and_strategy(space, storage, strategy)
65
66
67 def make_empty_list_with_size(space, hint):
68 strategy = SizeListStrategy(space, hint)
69 storage = strategy.erase(None)
70 return W_ListObject.from_storage_and_strategy(space, storage, strategy)
71
72
73 def get_strategy_from_list_object(space, list_w, sizehint):
74 if not list_w:
75 if sizehint != -1:
76 return SizeListStrategy(space, sizehint)
77 return space.fromcache(EmptyListStrategy)
78
79 w_firstobj = list_w[0]
80
81 if is_plain_int1(w_firstobj):
82 if len(list_w) > 1:
83 return _get_strategy_from_list_object_int(space, list_w)
84 return space.fromcache(IntegerListStrategy)
85 elif type(w_firstobj) is W_FloatObject:
86 if len(list_w) > 1:
87 return _get_strategy_from_list_object_float(space, list_w)
88 return space.fromcache(FloatListStrategy)
89 elif type(w_firstobj) is W_BytesObject:
90 if len(list_w) > 1:
91 return _get_strategy_from_list_object_bytes(space, list_w)
92 return space.fromcache(BytesListStrategy)
93 elif type(w_firstobj) is W_UnicodeObject and w_firstobj.is_ascii():
94 if len(list_w) > 1:
95 return _get_strategy_from_list_object_unicode(space, list_w)
96 return space.fromcache(AsciiListStrategy)
97 return space.fromcache(ObjectListStrategy)
98
99 @jit.look_inside_iff(lambda space, list_w:
100 jit.loop_unrolling_heuristic(list_w, len(list_w), UNROLL_CUTOFF))
101 def _get_strategy_from_list_object_int(space, list_w):
102 for i in range(1, len(list_w)):
103 w_obj = list_w[i]
104 if not is_plain_int1(w_obj):
105 if type(w_obj) is W_FloatObject:
106 return _get_strategy_from_list_object_int_or_float(space, list_w)
107 return space.fromcache(ObjectListStrategy)
108 return space.fromcache(IntegerListStrategy)
109
110 @jit.look_inside_iff(lambda space, list_w:
111 jit.loop_unrolling_heuristic(list_w, len(list_w), UNROLL_CUTOFF))
112 def _get_strategy_from_list_object_float(space, list_w):
113 for i in range(1, len(list_w)):
114 w_obj = list_w[i]
115 if type(w_obj) is not W_FloatObject:
116 if is_plain_int1(w_obj):
117 return _get_strategy_from_list_object_int_or_float(space, list_w)
118 return space.fromcache(ObjectListStrategy)
119 return space.fromcache(FloatListStrategy)
120
121 @jit.look_inside_iff(lambda space, list_w:
122 jit.loop_unrolling_heuristic(list_w, len(list_w), UNROLL_CUTOFF))
123 def _get_strategy_from_list_object_bytes(space, list_w):
124 for i in range(1, len(list_w)):
125 if type(list_w[i]) is not W_BytesObject:
126 return space.fromcache(ObjectListStrategy)
127 return space.fromcache(BytesListStrategy)
128
129 @jit.look_inside_iff(lambda space, list_w:
130 jit.loop_unrolling_heuristic(list_w, len(list_w), UNROLL_CUTOFF))
131 def _get_strategy_from_list_object_unicode(space, list_w):
132 for i in range(1, len(list_w)):
133 item = list_w[i]
134 if type(item) is not W_UnicodeObject or not item.is_ascii():
135 return space.fromcache(ObjectListStrategy)
136 return space.fromcache(AsciiListStrategy)
137
138 @jit.look_inside_iff(lambda space, list_w:
139 jit.loop_unrolling_heuristic(list_w, len(list_w), UNROLL_CUTOFF))
140 def _get_strategy_from_list_object_int_or_float(space, list_w):
141 for w_obj in list_w:
142 if is_plain_int1(w_obj):
143 if longlong2float.can_encode_int32(plain_int_w(space, w_obj)):
144 continue # ok
145 elif type(w_obj) is W_FloatObject:
146 if longlong2float.can_encode_float(w_obj.float_w(space)):
147 continue # ok
148 return space.fromcache(ObjectListStrategy)
149 return space.fromcache(IntOrFloatListStrategy)
150
151
152 def _get_printable_location(strategy_type, greenkey):
153 return 'list__do_extend_from_iterable [%s, %s]' % (
154 strategy_type,
155 greenkey.iterator_greenkey_printable())
156
157
158 _do_extend_jitdriver = jit.JitDriver(
159 name='list__do_extend_from_iterable',
160 greens=['strategy_type', 'greenkey'],
161 reds='auto',
162 get_printable_location=_get_printable_location)
163
164 def _do_extend_from_iterable(space, w_list, w_iterable):
165 w_iterator = space.iter(w_iterable)
166 greenkey = space.iterator_greenkey(w_iterator)
167 i = 0
168 while True:
169 _do_extend_jitdriver.jit_merge_point(
170 greenkey=greenkey,
171 strategy_type=type(w_list.strategy))
172 try:
173 w_list.append(space.next(w_iterator))
174 except OperationError as e:
175 if not e.match(space, space.w_StopIteration):
176 raise
177 break
178 i += 1
179 return i
180
181 def _get_printable_location(strategy_type, typ):
182 return 'list.repr [%s, %s]' % (
183 strategy_type,
184 typ)
185
186 listrepr_jitdriver = jit.JitDriver(
187 name='list.repr',
188 greens=['strategy_type', 'typ'],
189 reds='auto',
190 get_printable_location=_get_printable_location)
191
192 def listrepr(space, w_currently_in_repr, w_list):
193 length = w_list.length()
194 if space.contains_w(w_currently_in_repr, w_list):
195 return space.newtext('[...]')
196 space.setitem(w_currently_in_repr, w_list, space.newint(1))
197 try:
198 return _listrepr_inner(space, w_list, length)
199 finally:
200 try:
201 space.delitem(w_currently_in_repr, w_list)
202 except OperationError as e:
203 if not e.match(space, space.w_KeyError):
204 raise
205
206 def _listrepr_inner(space, w_list, length):
207 assert length > 0
208 builder = rutf8.Utf8StringBuilder()
209 builder.append_char('[')
210 w_first = w_list.getitem(0)
211 builder.append_utf8(*space.utf8_len_w(space.repr(w_first)))
212 typ = type(w_first)
213 for i in range(1, length):
214 listrepr_jitdriver.jit_merge_point(
215 typ=typ,
216 strategy_type=type(w_list.strategy))
217 try:
218 w_item = w_list.getitem(i)
219 except IndexError:
220 # repr changed the length, stop
221 break
222 builder.append_utf8(', ', 2)
223 builder.append_utf8(*space.utf8_len_w(space.repr(w_item)))
224 builder.append_char(']')
225 return space.newutf8(builder.build(), builder.getlength())
226
227
228 def list_unroll_condition(w_list1, space, w_list2):
229 return (w_list1._unrolling_heuristic() or w_list2._unrolling_heuristic())
230
231
232 def _get_printable_location(strategy_type1, strategy_type2, typ):
233 return 'list.eq [%s, %s, %s]' % (
234 strategy_type1,
235 strategy_type2,
236 typ)
237
238
239 listeq_jitdriver = jit.JitDriver(
240 name='list.eq',
241 greens=['strategy_type1', 'strategy_type2', 'typ'],
242 reds='auto',
243 get_printable_location=_get_printable_location)
244
245 def _make_list_eq(withjitdriver):
246 def list_eq(w_list, space, w_other):
247 # needs to be safe against eq_w() mutating the w_lists behind our back
248 length = w_list.length()
249 if length != w_other.length():
250 return space.w_False
251 if not length:
252 return space.w_True
253 if withjitdriver:
254 typ = type(w_list.getitem(0))
255
256 i = 0
257 while True:
258 if withjitdriver:
259 listeq_jitdriver.jit_merge_point(
260 strategy_type1=type(w_list.strategy),
261 strategy_type2=type(w_other.strategy),
262 typ=typ,
263 )
264 try:
265 w_item1 = w_list.getitem(i)
266 w_item2 = w_other.getitem(i)
267 except IndexError:
268 break
269 if not space.eq_w(w_item1, w_item2):
270 return space.w_False
271
272 i += 1
273
274 # if the list length is different now, the list was modified by eq_w with
275 l1 = w_list.length()
276 l2 = w_other.length()
277 if l1 != l2:
278 return space.w_False
279 return space.w_True
280 return list_eq
281 _list_eq_withjitdriver = _make_list_eq(True)
282 _list_eq_unroll = jit.unroll_safe(_make_list_eq(False))
283
284
285 def list_eq(w_list, space, w_other):
286 # we can't use look_inside_iff because the jitdriver will be found in two
287 # different graphs then
288 if jit.we_are_jitted() and list_unroll_condition(w_list, space, w_other):
289 return _list_eq_unroll(w_list, space, w_other)
290 else:
291 return _list_eq_withjitdriver(w_list, space, w_other)
292
293
294 class W_ListObject(W_Root):
295 strategy = None
296
297 def __init__(self, space, wrappeditems, sizehint=-1):
298 assert isinstance(wrappeditems, list)
299 self.space = space
300 if space.config.objspace.std.withliststrategies:
301 self.strategy = get_strategy_from_list_object(space, wrappeditems,
302 sizehint)
303 else:
304 self.strategy = space.fromcache(ObjectListStrategy)
305 self.init_from_list_w(wrappeditems)
306
307 def _unrolling_heuristic(self):
308 strategy = self.strategy
309 return strategy._unrolling_heuristic(self)
310
311 @staticmethod
312 def from_storage_and_strategy(space, storage, strategy):
313 self = instantiate(W_ListObject)
314 self.space = space
315 self.strategy = strategy
316 self.lstorage = storage
317 if not space.config.objspace.std.withliststrategies:
318 self.switch_to_object_strategy()
319 return self
320
321 @staticmethod
322 def newlist_bytes(space, list_b):
323 strategy = space.fromcache(BytesListStrategy)
324 storage = strategy.erase(list_b)
325 return W_ListObject.from_storage_and_strategy(space, storage, strategy)
326
327 @staticmethod
328 def newlist_ascii(space, list_u):
329 strategy = space.fromcache(AsciiListStrategy)
330 storage = strategy.erase(list_u)
331 return W_ListObject.from_storage_and_strategy(space, storage, strategy)
332
333 @staticmethod
334 def newlist_int(space, list_i):
335 strategy = space.fromcache(IntegerListStrategy)
336 storage = strategy.erase(list_i)
337 return W_ListObject.from_storage_and_strategy(space, storage, strategy)
338
339 @staticmethod
340 def newlist_float(space, list_f):
341 strategy = space.fromcache(FloatListStrategy)
342 storage = strategy.erase(list_f)
343 return W_ListObject.from_storage_and_strategy(space, storage, strategy)
344
345 def __repr__(self):
346 """ representation for debugging purposes """
347 return "%s(%s, %s)" % (self.__class__.__name__, self.strategy,
348 self.lstorage._x)
349
350 def unwrap(w_list, space):
351 # for tests only!
352 items = [space.unwrap(w_item) for w_item in w_list.getitems()]
353 return list(items)
354
355 def switch_to_object_strategy(self):
356 object_strategy = self.space.fromcache(ObjectListStrategy)
357 if self.strategy is object_strategy:
358 return
359 list_w = self.getitems()
360 self.strategy = object_strategy
361 object_strategy.init_from_list_w(self, list_w)
362
363 def _temporarily_as_objects(self):
364 if self.strategy is self.space.fromcache(ObjectListStrategy):
365 return self
366 list_w = self.getitems()
367 strategy = self.space.fromcache(ObjectListStrategy)
368 storage = strategy.erase(list_w)
369 w_objectlist = W_ListObject.from_storage_and_strategy(
370 self.space, storage, strategy)
371 return w_objectlist
372
373 def convert_to_cpy_strategy(self, space):
374 from pypy.module.cpyext.sequence import CPyListStorage, CPyListStrategy
375
376 cpy_strategy = self.space.fromcache(CPyListStrategy)
377 if self.strategy is cpy_strategy:
378 return
379 lst = self.getitems()
380 self.strategy = cpy_strategy
381 self.lstorage = cpy_strategy.erase(CPyListStorage(space, lst))
382
383 # ___________________________________________________
384
385 def init_from_list_w(self, list_w):
386 """Initializes listobject by iterating through the given list of
387 wrapped items, unwrapping them if neccessary and creating a
388 new erased object as storage"""
389 self.strategy.init_from_list_w(self, list_w)
390
391 def clear(self, space):
392 """Initializes (or overrides) the listobject as empty."""
393 self.space = space
394 if space.config.objspace.std.withliststrategies:
395 strategy = space.fromcache(EmptyListStrategy)
396 else:
397 strategy = space.fromcache(ObjectListStrategy)
398 self.strategy = strategy
399 strategy.clear(self)
400
401 def clone(self, sizehint=0):
402 """Returns a clone by creating a new listobject
403 with the same strategy and a copy of the storage.
404 if a sizehint is given, the clone is overallocated to be that size."""
405 return self.strategy.clone(self, sizehint)
406
407 def _resize_hint(self, hint):
408 """Ensure the underlying list has room for at least hint
409 elements without changing the len() of the list"""
410 return self.strategy._resize_hint(self, hint)
411
412 def copy_into(self, other):
413 """Used only when extending an EmptyList. Sets the EmptyLists
414 strategy and storage according to the other W_List"""
415 self.strategy.copy_into(self, other)
416
417 def find_or_count(self, w_item, start=0, end=sys.maxint, count=False):
418 """Find w_item in list[start:end]. If not found, raise ValueError.
419 if count=True, count number of occurences instead"""
420 return self.strategy.find_or_count(self, w_item, start, end, count)
421
422 def append(self, w_item):
423 """Append object to the end of the list."""
424 self.strategy.append(self, w_item)
425
426 def length(self):
427 return self.strategy.length(self)
428
429 def getitem(self, index):
430 """Returns the wrapped object that is found in the
431 list at the given index. The index must be unwrapped.
432 May raise IndexError."""
433 return self.strategy.getitem(self, index)
434
435 def getslice(self, start, stop, step, length):
436 """Returns a slice of the list defined by the arguments. Arguments must
437 be normalized (i.e. using normalize_simple_slice or W_Slice.indices4).
438 May raise IndexError."""
439 return self.strategy.getslice(self, start, stop, step, length)
440
441 def getitems(self):
442 """Returns a list of all items after wrapping them. The result can
443 share with the storage, if possible."""
444 return self.strategy.getitems(self)
445
446 def getitems_fixedsize(self):
447 """Returns a fixed-size list of all items after wrapping them."""
448 l = self.strategy.getitems_fixedsize(self)
449 debug.make_sure_not_resized(l)
450 return l
451
452 def getitems_unroll(self):
453 """Returns a fixed-size list of all items after wrapping them. The JIT
454 will fully unroll this function."""
455 l = self.strategy.getitems_unroll(self)
456 debug.make_sure_not_resized(l)
457 return l
458
459 def getitems_copy(self):
460 """Returns a copy of all items in the list. Same as getitems except for
461 ObjectListStrategy."""
462 return self.strategy.getitems_copy(self)
463
464 def getitems_bytes(self):
465 """Return the items in the list as unwrapped strings. If the list does
466 not use the list strategy, return None."""
467 return self.strategy.getitems_bytes(self)
468
469 def getitems_ascii(self):
470 """Return the items in the list as unwrapped unicodes. If the list does
471 not use the list strategy, return None."""
472 return self.strategy.getitems_ascii(self)
473
474 def getitems_int(self):
475 """Return the items in the list as unwrapped ints. If the list does not
476 use the list strategy, return None."""
477 return self.strategy.getitems_int(self)
478
479 def getitems_float(self):
480 """Return the items in the list as unwrapped floats. If the list does not
481 use the list strategy, return None."""
482 return self.strategy.getitems_float(self)
483 # ___________________________________________________
484
485 def mul(self, times):
486 """Returns a copy of the list, multiplied by times.
487 Argument must be unwrapped."""
488 return self.strategy.mul(self, times)
489
490 def inplace_mul(self, times):
491 """Alters the list by multiplying its content by times."""
492 self.strategy.inplace_mul(self, times)
493
494 def deleteslice(self, start, step, length):
495 """Deletes a slice from the list. Used in delitem and delslice.
496 Arguments must be normalized (see getslice)."""
497 self.strategy.deleteslice(self, start, step, length)
498
499 def pop(self, index):
500 """Pops an item from the list. Index must be normalized.
501 May raise IndexError."""
502 return self.strategy.pop(self, index)
503
504 def pop_end(self):
505 """ Pop the last element from the list."""
506 return self.strategy.pop_end(self)
507
508 def setitem(self, index, w_item):
509 """Inserts a wrapped item at the given (unwrapped) index.
510 May raise IndexError."""
511 self.strategy.setitem(self, index, w_item)
512
513 def setslice(self, start, step, slicelength, sequence_w):
514 """Sets the slice of the list from start to start+step*slicelength to
515 the sequence sequence_w.
516 Used by setslice and setitem."""
517 self.strategy.setslice(self, start, step, slicelength, sequence_w)
518
519 def insert(self, index, w_item):
520 """Inserts an item at the given position. Item must be wrapped,
521 index not."""
522 self.strategy.insert(self, index, w_item)
523
524 def extend(self, w_iterable):
525 '''L.extend(iterable) -- extend list by appending elements from the iterable'''
526 self.strategy.extend(self, w_iterable)
527
528 def reverse(self):
529 """Reverses the list."""
530 self.strategy.reverse(self)
531
532 def sort(self, reverse):
533 """Sorts the list ascending or descending depending on
534 argument reverse. Argument must be unwrapped."""
535 self.strategy.sort(self, reverse)
536
537 def physical_size(self):
538 """ return the physical (ie overallocated size) of the underlying list.
539 """
540 # exposed in __pypy__
541 return self.strategy.physical_size(self)
542
543 def add(self, w_other):
544 """ add self to w_other """
545 return self.strategy.add(self, w_other)
546
547 # exposed to app-level
548
549 @staticmethod
550 def descr_new(space, w_listtype, w_iterable=None, __posonly__=None, __args__=None):
551 "Create and return a new object. See help(type) for accurate signature."
552 builtinclass_new_args_check(space, 'list', space.w_list, w_listtype, __args__)
553 w_obj = space.allocate_instance(W_ListObject, w_listtype)
554 w_obj.clear(space)
555 return w_obj
556
557 def descr_init(self, space, w_iterable=None, __posonly__=None, __args__=None):
558 """Initialize self. See help(type(self)) for accurate signature."""
559 if space.is_w(space.type(self), space.w_list):
560 if __args__.arguments_w:
561 raise oefmt(space.w_TypeError, "list() expected at most 1 argument, got %d", 1 + len(__args__.arguments_w))
562 if __args__.keyword_names_w:
563 raise oefmt(space.w_TypeError, "list() takes no keyword arguments")
564 self.clear(space)
565 if w_iterable is not None:
566 self.extend(w_iterable)
567
568 def descr_repr(self, space):
569 return self.strategy.repr(self)
570 if self.length() == 0:
571 return space.newtext('[]')
572 return listrepr(space, space.get_objects_in_repr(), self)
573
574 def descr_eq(self, space, w_other):
575 if not isinstance(w_other, W_ListObject):
576 return space.w_NotImplemented
577 return list_eq(self, space, w_other)
578
579 descr_ne = negate(descr_eq)
580
581 def _make_list_comparison(name):
582 op = getattr(operator, name)
583
584 def compare_unwrappeditems(self, space, w_list2):
585 if not isinstance(w_list2, W_ListObject):
586 return space.w_NotImplemented
587 return _compare_unwrappeditems(self, space, w_list2)
588
589 @jit.look_inside_iff(list_unroll_condition)
590 def _compare_unwrappeditems(self, space, w_list2):
591 # needs to be safe against eq_w() mutating the w_lists behind our
592 # back
593 # Search for the first index where items are different
594 i = 0
595 # XXX in theory, this can be implemented more efficiently as well.
596 # let's not care for now
597 while i < self.length() and i < w_list2.length():
598 w_item1 = self.getitem(i)
599 w_item2 = w_list2.getitem(i)
600 if not space.eq_w(w_item1, w_item2):
601 return getattr(space, name)(w_item1, w_item2)
602 i += 1
603 # No more items to compare -- compare sizes
604 return space.newbool(op(self.length(), w_list2.length()))
605
606 return func_with_new_name(compare_unwrappeditems, 'descr_' + name)
607
608 descr_lt = _make_list_comparison('lt')
609 descr_le = _make_list_comparison('le')
610 descr_gt = _make_list_comparison('gt')
611 descr_ge = _make_list_comparison('ge')
612
613 def descr_len(self, space):
614 result = self.length()
615 return space.newint(result)
616
617 def descr_iter(self, space):
618 return W_FastListIterObject(self)
619
620 def descr_contains(self, space, w_obj):
621 try:
622 self.find_or_count(w_obj)
623 return space.w_True
624 except ValueError:
625 return space.w_False
626
627 def descr_add(self, space, w_list2):
628 if not isinstance(w_list2, W_ListObject):
629 return space.w_NotImplemented
630 length1 = self.length()
631 if not length1:
632 # treat empty + list special, because the EmptyListStrategy.clone
633 # ignores the sizehint for now
634 return w_list2.clone()
635 sizehint = 0
636 if self.strategy is w_list2.strategy:
637 length2 = w_list2.length()
638 try:
639 sizehint = ovfcheck(length1 + length2)
640 except OverflowError:
641 raise MemoryError
642 w_clone = self.clone(sizehint=sizehint)
643 w_clone.extend(w_list2)
644 return w_clone
645
646 def descr_inplace_add(self, space, w_iterable):
647 self.extend(w_iterable)
648 return self
649
650 def descr_mul(self, space, w_times):
651 try:
652 times = space.getindex_w(w_times, space.w_OverflowError)
653 except OperationError as e:
654 if e.match(space, space.w_TypeError):
655 return space.w_NotImplemented
656 raise
657 return self.mul(times)
658
659 def descr_inplace_mul(self, space, w_times):
660 try:
661 times = space.getindex_w(w_times, space.w_OverflowError)
662 except OperationError as e:
663 if e.match(space, space.w_TypeError):
664 return space.w_NotImplemented
665 raise
666 self.inplace_mul(times)
667 return self
668
669 def _unpack_slice(self, w_index):
670 # important: unpack the slice before computing the length. the
671 # __index__ methods can mutate the list and change its length.
672 start, stop, step = w_index.unpack(self.space)
673 length = self.length()
674 return w_index.adjust_indices(start, stop, step, length)
675
676 def descr_getitem(self, space, w_index):
677 if isinstance(w_index, W_SliceObject):
678 start, stop, step, slicelength = self._unpack_slice(w_index)
679 assert slicelength >= 0
680 if slicelength == 0:
681 return make_empty_list(space)
682 return self.getslice(start, stop, step, slicelength)
683
684 try:
685 index = space.getindex_w(w_index, space.w_IndexError, "list")
686 return self.getitem(index)
687 except IndexError:
688 raise oefmt(space.w_IndexError, "list index out of range")
689
690 def descr_setitem(self, space, w_index, w_any):
691 if isinstance(w_index, W_SliceObject):
692 # special case for l[:] = l2
693 if (space.is_w(w_index.w_start, space.w_None) and
694 space.is_w(w_index.w_stop, space.w_None) and
695 space.is_w(w_index.w_step, space.w_None)):
696 # use the extend logic
697 if isinstance(w_any, W_ListObject):
698 if space.is_w(self, w_any):
699 return
700 w_other = w_any
701 else:
702 sequence_w = space.listview(w_any)
703 w_other = W_ListObject(space, sequence_w)
704 self.clear(space)
705 w_other.copy_into(self)
706 return
707
708 start, stop, step, slicelength = self._unpack_slice(w_index)
709 if isinstance(w_any, W_ListObject):
710 w_other = w_any
711 else:
712 sequence_w = space.listview(w_any)
713 w_other = W_ListObject(space, sequence_w)
714 self.setslice(start, step, slicelength, w_other)
715 return
716
717 idx = space.getindex_w(w_index, space.w_IndexError, "list")
718 try:
719 self.setitem(idx, w_any)
720 except IndexError:
721 raise oefmt(space.w_IndexError, "list index out of range")
722
723 def descr_delitem(self, space, w_idx):
724 if isinstance(w_idx, W_SliceObject):
725 start, stop, step, slicelength = self._unpack_slice(w_idx)
726 self.deleteslice(start, step, slicelength)
727 return
728
729 idx = space.getindex_w(w_idx, space.w_IndexError, "list")
730 if idx < 0:
731 idx += self.length()
732 try:
733 self.pop(idx)
734 except IndexError:
735 raise oefmt(space.w_IndexError, "list index out of range")
736
737 def descr_reversed(self, space):
738 'L.__reversed__() -- return a reverse iterator over the list'
739 return W_ReverseSeqIterObject(space, self, -1)
740
741 def descr_reverse(self, space):
742 'L.reverse() -- reverse *IN PLACE*'
743 self.reverse()
744
745 def descr_count(self, space, w_value):
746 '''L.count(value) -> integer -- return number of occurrences of value'''
747 i = self.find_or_count(w_value, count=True)
748 return space.newint(i)
749
750 @unwrap_spec(index='index')
751 def descr_insert(self, space, index, w_value):
752 'L.insert(index, object) -- insert object before index'
753 length = self.length()
754 index = get_positive_index(index, length)
755 self.insert(index, w_value)
756
757 @unwrap_spec(index='index')
758 def descr_pop(self, space, index=-1):
759 """L.pop([index]) -> item -- remove and return item at index (default last).
760 Raises IndexError if list is empty or index is out of range."""
761 length = self.length()
762 if length == 0:
763 raise oefmt(space.w_IndexError, "pop from empty list")
764 # clearly differentiate between list.pop() and list.pop(index)
765 if index == -1:
766 return self.pop_end() # cannot raise because list is not empty
767 if index < 0:
768 index += length
769 try:
770 return self.pop(index)
771 except IndexError:
772 raise oefmt(space.w_IndexError, "pop index out of range")
773
774 def descr_clear(self, space):
775 """L.clear() -> None -- remove all items from L"""
776 self.clear(space)
777
778 def descr_copy(self, space):
779 '''L.copy() -> list -- a shallow copy of L'''
780 return self.clone()
781
782 def descr_remove(self, space, w_value):
783 """L.remove(value) -> None -- remove first occurrence of value.
784 Raises ValueError if the value is not present."""
785 # needs to be safe against eq_w() mutating the w_list behind our back
786 try:
787 i = self.find_or_count(w_value, 0, sys.maxint)
788 except ValueError:
789 raise oefmt(space.w_ValueError,
790 "list.remove(): %R is not in list", w_value)
791 if i < self.length(): # otherwise list was mutated
792 self.pop(i)
793
794 @unwrap_spec(w_start=WrappedDefault(0), w_stop=WrappedDefault(sys.maxint))
795 def descr_index(self, space, w_value, w_start, w_stop):
796 """L.index(value, [start, [stop]]) -> integer -- return first index of value.
797 Raises ValueError if the value is not present."""
798 # needs to be safe against eq_w() mutating the w_list behind our back
799 size = self.length()
800 i, stop = unwrap_start_stop(space, size, w_start, w_stop)
801 # note that 'i' and 'stop' can be bigger than the length of the list
802 try:
803 i = self.find_or_count(w_value, i, stop)
804 except ValueError:
805 raise oefmt(space.w_ValueError, "%R is not in list", w_value)
806 return space.newint(i)
807
808 @unwrap_spec(reverse=int)
809 def descr_sort(self, space, w_key=None, reverse=False):
810 """L.sort(key=None, reverse=False) -> None -- stable sort *IN PLACE*"""
811 has_key = not space.is_none(w_key)
812
813 # create and setup a TimSort instance
814 if 0:
815 # this was the old "if has_cmp" path. We didn't remove the
816 # if not to diverge too much from default, to avoid spurious
817 # conflicts
818 pass
819 else:
820 if has_key:
821 sorterclass = CustomKeySort
822 else:
823 if self.strategy is space.fromcache(ObjectListStrategy):
824 sorterclass = SimpleSort
825 else:
826 self.sort(reverse)
827 return
828
829 sorter = sorterclass(self.getitems(), self.length())
830 sorter.space = space
831
832 try:
833 strategy = self.strategy
834 # The list is temporarily made empty, so that mutations performed
835 # by comparison functions can't affect the slice of memory we're
836 # sorting (allowing mutations during sorting is an IndexError or
837 # core-dump factory, since the storage may change).
838 self.__init__(space, [])
839
840 # wrap each item in a KeyContainer if needed
841 if has_key:
842 # XXX inefficient for unwrapped strategies:
843 # we wrap the elements twice, once for the key, and once to get
844 # KeyContainers. Then unwrap carefully in the __init__ call below.
845 # Could type-specialize this.
846 _compute_keys_for_sorting(strategy, sorter.list, w_key)
847
848 # Reverse sort stability achieved by initially reversing the list,
849 # applying a stable forward sort, then reversing the final result.
850 if reverse:
851 sorter.list.reverse()
852
853 # perform the sort
854 sorter.sort()
855
856 # reverse again
857 if reverse:
858 sorter.list.reverse()
859
860 finally:
861 # unwrap each item if needed
862 if has_key:
863 for i in range(sorter.listlength):
864 w_obj = sorter.list[i]
865 if isinstance(w_obj, KeyContainer):
866 sorter.list[i] = w_obj.w_item
867
868 # check if the user mucked with the list during the sort.
869 # length() > 0 catches net-positive mutations; but append+pop
870 # leaves length==0 yet the list was touched. With list strategies
871 # enabled, any mutation switches away from EmptyListStrategy and
872 # lists never switch back, so a changed strategy means mutation.
873 if space.config.objspace.std.withliststrategies:
874 mucked = self.strategy is not space.fromcache(EmptyListStrategy)
875 else:
876 mucked = self.length() > 0
877
878 # put the items back into the list
879 self.__init__(space, sorter.list)
880
881 if mucked:
882 raise oefmt(space.w_ValueError, "list modified during sort")
883
884 def get_printable_location_sortkey(strategy_type, tp):
885 return "_compute_keys_for_sorting [%s, %s]" % (strategy_type, tp.getname(tp.space), )
886
887 sortkey_jmp = jit.JitDriver(
888 greens=['strategy_type', 'tp'],
889 reds='auto',
890 name='_compute_keys_for_sorting',
891 get_printable_location=get_printable_location_sortkey)
892
893 def _compute_keys_for_sorting(strategy, list_w, w_callable):
894 space = strategy.space
895 i = 0
896 # XXX would like a new API space.greenkey_for_callable here
897 # (also in min/max and map/filter)
898 tp = space.type(w_callable)
899 while i < len(list_w):
900 # bit weird: we have a list_w at this point, but we still specialize on
901 # the strategy to distinguish the cases better
902 sortkey_jmp.jit_merge_point(tp=tp, strategy_type=type(strategy))
903 w_item = list_w[i]
904 w_keyitem = space.call_function(w_callable, w_item)
905 list_w[i] = KeyContainer(w_keyitem, w_item)
906 i += 1
907
908 def get_printable_location_find(count, strategy_type, tp):
909 if count:
910 start = "list.count"
911 else:
912 start = "list.find"
913 return "%s [%s, %s]" % (start, strategy_type, tp.getname(tp.space), )
914
915 find_or_count_jmp = jit.JitDriver(
916 greens=['count', 'strategy_type', 'tp'],
917 reds='auto',
918 name='list.find_or_count',
919 get_printable_location=get_printable_location_find)
920
921 class ListStrategy(object):
922
923 def __init__(self, space):
924 self.space = space
925
926 def get_sizehint(self):
927 return -1
928
929 def init_from_list_w(self, w_list, list_w):
930 raise NotImplementedError
931
932 def clone(self, w_list, sizehint=0):
933 raise NotImplementedError
934
935 def copy_into(self, w_list, w_other):
936 raise NotImplementedError
937
938 def _resize_hint(self, w_list, hint):
939 raise NotImplementedError
940
941 def find_or_count(self, w_list, w_item, start, stop, count):
942 space = self.space
943 i = start
944 result = 0
945 # needs to be safe against eq_w mutating stuff
946 tp = space.type(w_item)
947 while i < stop and i < w_list.length():
948 find_or_count_jmp.jit_merge_point(tp=tp, strategy_type=type(self), count=count)
949 if space.eq_w(w_list.getitem(i), w_item):
950 if count:
951 result += 1
952 else:
953 return i
954 i += 1
955 if count:
956 return result
957 # not find case, not found
958 raise ValueError
959
960 def length(self, w_list):
961 raise NotImplementedError
962
963 def getitem(self, w_list, index):
964 raise NotImplementedError
965
966 def getslice(self, w_list, start, stop, step, length):
967 raise NotImplementedError
968
969 def getitems(self, w_list):
970 return self.getitems_copy(w_list)
971
972 def getitems_copy(self, w_list):
973 raise NotImplementedError
974
975 def getitems_bytes(self, w_list):
976 return None
977
978 def getitems_ascii(self, w_list):
979 return None
980
981 def getitems_int(self, w_list):
982 return None
983
984 def getitems_float(self, w_list):
985 return None
986
987 def getstorage_copy(self, w_list):
988 raise NotImplementedError
989
990 def append(self, w_list, w_item):
991 raise NotImplementedError
992
993 def mul(self, w_list, times):
994 w_newlist = w_list.clone()
995 w_newlist.inplace_mul(times)
996 return w_newlist
997
998 def inplace_mul(self, w_list, times):
999 raise NotImplementedError
1000
1001 def deleteslice(self, w_list, start, step, slicelength):
1002 raise NotImplementedError
1003
1004 def pop(self, w_list, index):
1005 raise NotImplementedError
1006
1007 def pop_end(self, w_list):
1008 return self.pop(w_list, self.length(w_list) - 1)
1009
1010 def setitem(self, w_list, index, w_item):
1011 raise NotImplementedError
1012
1013 def setslice(self, w_list, start, step, slicelength, sequence_w):
1014 raise NotImplementedError
1015
1016 def insert(self, w_list, index, w_item):
1017 raise NotImplementedError
1018
1019 def extend(self, w_list, w_any):
1020 from pypy.objspace.std.tupleobject import W_AbstractTupleObject
1021 space = self.space
1022 if type(w_any) is W_ListObject or (isinstance(w_any, W_ListObject) and
1023 space._uses_list_iter(w_any)):
1024 self._extend_from_list(w_list, w_any)
1025 elif (isinstance(w_any, W_AbstractTupleObject) and
1026 not w_any.user_overridden_class and
1027 w_any.length() < UNROLL_CUTOFF
1028 ):
1029 self._extend_from_tuple(w_list, w_any.tolist())
1030 elif space.is_generator(w_any):
1031 w_any.unpack_into_w(w_list)
1032 else:
1033 self._extend_from_iterable(w_list, w_any)
1034
1035 def _extend_from_list(self, w_list, w_other):
1036 raise NotImplementedError
1037
1038 @jit.look_inside_iff(lambda self, w_list, tup_w:
1039 jit.loop_unrolling_heuristic(tup_w, len(tup_w), UNROLL_CUTOFF))
1040 def _extend_from_tuple(self, w_list, tup_w):
1041 try:
1042 newsize_hint = ovfcheck(w_list.length() + len(tup_w))
1043 except OverflowError:
1044 pass
1045 else:
1046 w_list._resize_hint(newsize_hint)
1047 for w_element in tup_w:
1048 w_list.append(w_element)
1049
1050 def _extend_from_iterable(self, w_list, w_iterable):
1051 """Extend w_list from a generic iterable"""
1052 length_hint = self.space.length_hint(w_iterable, 0)
1053 if length_hint:
1054 try:
1055 newsize_hint = ovfcheck(w_list.length() + length_hint)
1056 except OverflowError:
1057 pass
1058 else:
1059 w_list._resize_hint(newsize_hint)
1060
1061 extended = _do_extend_from_iterable(self.space, w_list, w_iterable)
1062
1063 # cut back if the length hint was too large
1064 if extended < length_hint:
1065 w_list._resize_hint(w_list.length())
1066
1067 def reverse(self, w_list):
1068 raise NotImplementedError
1069
1070 def sort(self, w_list, reverse):
1071 raise NotImplementedError
1072
1073 def is_empty_strategy(self):
1074 return False
1075
1076 def physical_size(self, w_list):
1077 raise oefmt(self.space.w_ValueError, "can't get physical size of list")
1078
1079 def repr(self, w_list):
1080 space = self.space
1081 if self.length(w_list) == 0:
1082 return space.newtext('[]')
1083 return listrepr(space, space.get_objects_in_repr(), w_list)
1084
1085 def _unrolling_heuristic(self, w_list):
1086 # default implementation: we will only go by size, not whether the list
1087 # is virtual
1088 size = self.length(w_list)
1089 return size == 0 or (jit.isconstant(size) and size <= UNROLL_CUTOFF)
1090
1091
1092 class EmptyListStrategy(ListStrategy):
1093 """EmptyListStrategy is used when a W_List withouth elements is created.
1094 The storage is None. When items are added to the W_List a new RPython list
1095 is created and the strategy and storage of the W_List are changed depending
1096 to the added item.
1097 W_Lists do not switch back to EmptyListStrategy when becoming empty again.
1098 """
1099
1100 def __init__(self, space):
1101 ListStrategy.__init__(self, space)
1102
1103 def init_from_list_w(self, w_list, list_w):
1104 assert len(list_w) == 0
1105 w_list.lstorage = self.erase(None)
1106
1107 def clear(self, w_list):
1108 w_list.lstorage = self.erase(None)
1109
1110 erase, unerase = rerased.new_erasing_pair("empty")
1111 erase = staticmethod(erase)
1112 unerase = staticmethod(unerase)
1113
1114 def clone(self, w_list, sizehint=0):
1115 return W_ListObject.from_storage_and_strategy(
1116 self.space, w_list.lstorage, self)
1117
1118 def copy_into(self, w_list, w_other):
1119 pass
1120
1121 def _resize_hint(self, w_list, hint):
1122 assert hint >= 0
1123 if hint:
1124 w_list.strategy = SizeListStrategy(self.space, hint)
1125
1126 def find_or_count(self, w_list, w_item, start, stop, count):
1127 if count:
1128 return 0
1129 raise ValueError
1130
1131 def length(self, w_list):
1132 return 0
1133
1134 def getitem(self, w_list, index):
1135 raise IndexError
1136
1137 def getslice(self, w_list, start, stop, step, length):
1138 # will never be called because the empty list case is already caught in
1139 # getslice__List_ANY_ANY and getitem__List_Slice
1140 return W_ListObject(self.space, [])
1141
1142 def getitems(self, w_list):
1143 return []
1144
1145 def getitems_copy(self, w_list):
1146 return []
1147 getitems_fixedsize = func_with_new_name(getitems_copy,
1148 "getitems_fixedsize")
1149 getitems_unroll = getitems_fixedsize
1150
1151 def getstorage_copy(self, w_list):
1152 return self.erase(None)
1153
1154 def switch_to_correct_strategy(self, w_list, w_item):
1155 if is_plain_int1(w_item):
1156 strategy = self.space.fromcache(IntegerListStrategy)
1157 elif type(w_item) is W_BytesObject:
1158 strategy = self.space.fromcache(BytesListStrategy)
1159 elif type(w_item) is W_UnicodeObject and w_item.is_ascii():
1160 strategy = self.space.fromcache(AsciiListStrategy)
1161 elif type(w_item) is W_FloatObject:
1162 strategy = self.space.fromcache(FloatListStrategy)
1163 else:
1164 strategy = self.space.fromcache(ObjectListStrategy)
1165
1166 storage = strategy.get_empty_storage(self.get_sizehint())
1167 w_list.strategy = strategy
1168 w_list.lstorage = storage
1169
1170 def append(self, w_list, w_item):
1171 self.switch_to_correct_strategy(w_list, w_item)
1172 w_list.append(w_item)
1173
1174 def inplace_mul(self, w_list, times):
1175 return
1176
1177 def deleteslice(self, w_list, start, step, slicelength):
1178 pass
1179
1180 def pop(self, w_list, index):
1181 # will not be called because IndexError was already raised in
1182 # list_pop__List_ANY
1183 raise IndexError
1184
1185 def setitem(self, w_list, index, w_item):
1186 raise IndexError
1187
1188 def setslice(self, w_list, start, step, slicelength, w_other):
1189 strategy = w_other.strategy
1190 if step != 1:
1191 len2 = strategy.length(w_other)
1192 if len2 == 0:
1193 return
1194 else:
1195 raise oefmt(self.space.w_ValueError,
1196 "attempt to assign sequence of size %d to extended "
1197 "slice of size %d", len2, 0)
1198 storage = strategy.getstorage_copy(w_other)
1199 w_list.strategy = strategy
1200 w_list.lstorage = storage
1201
1202 def sort(self, w_list, reverse):
1203 return
1204
1205 def insert(self, w_list, index, w_item):
1206 assert index == 0
1207 self.append(w_list, w_item)
1208
1209 def _extend_from_list(self, w_list, w_other):
1210 w_other.copy_into(w_list)
1211
1212 def _extend_from_iterable(self, w_list, w_iterable):
1213 space = self.space
1214 if (isinstance(w_iterable, W_AbstractTupleObject)
1215 and space._uses_tuple_iter(w_iterable)):
1216 w_list.__init__(space, w_iterable.getitems_copy())
1217 return
1218
1219 intlist = space.unpackiterable_int(w_iterable)
1220 if intlist is not None:
1221 w_list.strategy = strategy = space.fromcache(IntegerListStrategy)
1222 w_list.lstorage = strategy.erase(intlist)
1223 return
1224
1225 floatlist = space.unpackiterable_float(w_iterable)
1226 if floatlist is not None:
1227 w_list.strategy = strategy = space.fromcache(FloatListStrategy)
1228 w_list.lstorage = strategy.erase(floatlist)
1229 return
1230
1231 byteslist = space.listview_bytes(w_iterable)
1232 if byteslist is not None:
1233 w_list.strategy = strategy = space.fromcache(BytesListStrategy)
1234 # need to copy because intlist can share with w_iterable
1235 w_list.lstorage = strategy.erase(byteslist[:])
1236 return
1237
1238 unilist = space.listview_ascii(w_iterable)
1239 if unilist is not None:
1240 w_list.strategy = strategy = space.fromcache(AsciiListStrategy)
1241 # need to copy because intlist can share with w_iterable
1242 w_list.lstorage = strategy.erase(unilist[:])
1243 return
1244
1245 ListStrategy._extend_from_iterable(self, w_list, w_iterable)
1246
1247 def reverse(self, w_list):
1248 pass
1249
1250 def is_empty_strategy(self):
1251 return True
1252
1253 def physical_size(self, w_list):
1254 return 0
1255
1256 def repr(self, w_list):
1257 space = self.space
1258 return space.newtext('[]')
1259
1260 def _unrolling_heuristic(self, w_list):
1261 return True
1262
1263
1264 class SizeListStrategy(EmptyListStrategy):
1265 """Like empty, but when modified it'll preallocate the size to sizehint."""
1266 def __init__(self, space, sizehint):
1267 self.sizehint = sizehint
1268 ListStrategy.__init__(self, space)
1269
1270 def get_sizehint(self):
1271 return self.sizehint
1272
1273 def _resize_hint(self, w_list, hint):
1274 assert hint >= 0
1275 self.sizehint = hint
1276
1277
1278 class BaseRangeListStrategy(ListStrategy):
1279 def switch_to_integer_strategy(self, w_list):
1280 items = self._getitems_range(w_list, False)
1281 strategy = w_list.strategy = self.space.fromcache(IntegerListStrategy)
1282 w_list.lstorage = strategy.erase(items)
1283
1284 def wrap(self, intval):
1285 return self.space.newint(intval)
1286
1287 def unwrap(self, w_int):
1288 return plain_int_w(self.space, w_int)
1289
1290 def init_from_list_w(self, w_list, list_w):
1291 raise NotImplementedError
1292
1293 def clone(self, w_list, sizehint=0):
1294 storage = w_list.lstorage # lstorage is tuple, no need to clone
1295 w_clone = W_ListObject.from_storage_and_strategy(self.space, storage,
1296 self)
1297 return w_clone
1298
1299 def _resize_hint(self, w_list, hint):
1300 # XXX: this could be supported
1301 assert hint >= 0
1302
1303 def copy_into(self, w_list, w_other):
1304 w_other.strategy = self
1305 w_other.lstorage = w_list.lstorage
1306
1307 def getitem(self, w_list, i):
1308 return self.wrap(self._getitem_unwrapped(w_list, i))
1309
1310 def getitems_int(self, w_list):
1311 return self._getitems_range(w_list, False)
1312
1313 def getitems_copy(self, w_list):
1314 return self._getitems_range(w_list, True)
1315
1316 def getstorage_copy(self, w_list):
1317 # tuple is immutable
1318 return w_list.lstorage
1319
1320 @jit.dont_look_inside
1321 def getitems_fixedsize(self, w_list):
1322 return self._getitems_range_unroll(w_list, True)
1323
1324 def getitems_unroll(self, w_list):
1325 return self._getitems_range_unroll(w_list, True)
1326
1327 def getslice(self, w_list, start, stop, step, length):
1328 self.switch_to_integer_strategy(w_list)
1329 return w_list.getslice(start, stop, step, length)
1330
1331 def append(self, w_list, w_item):
1332 if is_plain_int1(w_item):
1333 self.switch_to_integer_strategy(w_list)
1334 else:
1335 w_list.switch_to_object_strategy()
1336 w_list.append(w_item)
1337
1338 def inplace_mul(self, w_list, times):
1339 self.switch_to_integer_strategy(w_list)
1340 w_list.inplace_mul(times)
1341
1342 def deleteslice(self, w_list, start, step, slicelength):
1343 self.switch_to_integer_strategy(w_list)
1344 w_list.deleteslice(start, step, slicelength)
1345
1346 def setitem(self, w_list, index, w_item):
1347 self.switch_to_integer_strategy(w_list)
1348 w_list.setitem(index, w_item)
1349
1350 def setslice(self, w_list, start, step, slicelength, sequence_w):
1351 self.switch_to_integer_strategy(w_list)
1352 w_list.setslice(start, step, slicelength, sequence_w)
1353
1354 def insert(self, w_list, index, w_item):
1355 self.switch_to_integer_strategy(w_list)
1356 w_list.insert(index, w_item)
1357
1358 def extend(self, w_list, w_any):
1359 self.switch_to_integer_strategy(w_list)
1360 w_list.extend(w_any)
1361
1362 def reverse(self, w_list):
1363 self.switch_to_integer_strategy(w_list)
1364 w_list.reverse()
1365
1366 def sort(self, w_list, reverse):
1367 step = self.step(w_list)
1368 if step > 0 and reverse or step < 0 and not reverse:
1369 self.switch_to_integer_strategy(w_list)
1370 w_list.sort(reverse)
1371
1372 # default _unrolling_heuristic is fine
1373
1374
1375 class SimpleRangeListStrategy(BaseRangeListStrategy):
1376 """SimpleRangeListStrategy is used when a list is created using the range
1377 method providing only positive length. The storage is a one element tuple
1378 with positive integer storing length."""
1379
1380 erase, unerase = rerased.new_erasing_pair("simple_range")
1381 erase = staticmethod(erase)
1382 unerase = staticmethod(unerase)
1383
1384 def find_or_count(self, w_list, w_obj, startindex, stopindex, count):
1385 if is_plain_int1(w_obj):
1386 obj = self.unwrap(w_obj)
1387 length = self.unerase(w_list.lstorage)[0]
1388 if 0 <= obj < length and startindex <= obj < stopindex:
1389 if count:
1390 return 1
1391 return obj
1392 else:
1393 if count:
1394 return 0
1395 raise ValueError
1396 return ListStrategy.find_or_count(
1397 self, w_list, w_obj, startindex, stopindex, count)
1398
1399 def length(self, w_list):
1400 return self.unerase(w_list.lstorage)[0]
1401
1402 def step(self, w_list):
1403 return 1
1404
1405 def _getitem_unwrapped(self, w_list, i):
1406 length = self.unerase(w_list.lstorage)[0]
1407 if i < 0:
1408 i += length
1409 if i < 0:
1410 raise IndexError
1411 elif i >= length:
1412 raise IndexError
1413 return i
1414
1415 @specialize.arg(2)
1416 def _getitems_range(self, w_list, wrap_items):
1417 length = self.unerase(w_list.lstorage)[0]
1418 if wrap_items:
1419 r = [None] * length
1420 else:
1421 r = [0] * length
1422 i = 0
1423 while i < length:
1424 if wrap_items:
1425 r[i] = self.wrap(i)
1426 else:
1427 r[i] = i
1428 i += 1
1429
1430 return r
1431
1432 _getitems_range_unroll = jit.unroll_safe(
1433 func_with_new_name(_getitems_range, "_getitems_range_unroll"))
1434
1435 def pop_end(self, w_list):
1436 new_length = self.unerase(w_list.lstorage)[0] - 1
1437 w_result = self.wrap(new_length)
1438 if new_length > 0:
1439 w_list.lstorage = self.erase((new_length,))
1440 else:
1441 strategy = w_list.strategy = self.space.fromcache(EmptyListStrategy)
1442 w_list.lstorage = strategy.erase(None)
1443 return w_result
1444
1445 def pop(self, w_list, index):
1446 self.switch_to_integer_strategy(w_list)
1447 return w_list.pop(index)
1448
1449
1450 class RangeListStrategy(BaseRangeListStrategy):
1451 """RangeListStrategy is used when a list is created using the range method.
1452 The storage is a tuple containing only three integers start, step and
1453 length and elements are calculated based on these values. On any operation
1454 destroying the range (inserting, appending non-ints) the strategy is
1455 switched to IntegerListStrategy."""
1456
1457 erase, unerase = rerased.new_erasing_pair("range")
1458 erase = staticmethod(erase)
1459 unerase = staticmethod(unerase)
1460
1461 def find_or_count(self, w_list, w_obj, startindex, stopindex, count):
1462 if is_plain_int1(w_obj):
1463 obj = self.unwrap(w_obj)
1464 start, step, length = self.unerase(w_list.lstorage)
1465 if ((step > 0 and start <= obj <= start + (length - 1) * step and
1466 (start - obj) % step == 0) or
1467 (step < 0 and start + (length - 1) * step <= obj <= start and
1468 (start - obj) % step == 0)):
1469 index = (obj - start) // step
1470 else:
1471 if count:
1472 return 0
1473 raise ValueError
1474 if startindex <= index < stopindex:
1475 if count:
1476 return 1
1477 return index
1478 if count:
1479 return 0
1480 raise ValueError
1481 return ListStrategy.find_or_count(
1482 self, w_list, w_obj, startindex, stopindex, count)
1483
1484 def length(self, w_list):
1485 return self.unerase(w_list.lstorage)[2]
1486
1487 def step(self, w_list):
1488 return self.unerase(w_list.lstorage)[1]
1489
1490 def _getitem_unwrapped(self, w_list, i):
1491 v = self.unerase(w_list.lstorage)
1492 start = v[0]
1493 step = v[1]
1494 length = v[2]
1495 if i < 0:
1496 i += length
1497 if i < 0:
1498 raise IndexError
1499 elif i >= length:
1500 raise IndexError
1501 return start + i * step
1502
1503 @specialize.arg(2)
1504 def _getitems_range(self, w_list, wrap_items):
1505 l = self.unerase(w_list.lstorage)
1506 start = l[0]
1507 step = l[1]
1508 length = l[2]
1509 if wrap_items:
1510 r = [None] * length
1511 else:
1512 r = [0] * length
1513 i = start
1514 n = 0
1515 while n < length:
1516 if wrap_items:
1517 r[n] = self.wrap(i)
1518 else:
1519 r[n] = i
1520 i += step
1521 n += 1
1522
1523 return r
1524
1525 _getitems_range_unroll = jit.unroll_safe(
1526 func_with_new_name(_getitems_range, "_getitems_range_unroll"))
1527
1528 def pop_end(self, w_list):
1529 start, step, length = self.unerase(w_list.lstorage)
1530 w_result = self.wrap(start + (length - 1) * step)
1531 new = self.erase((start, step, length - 1))
1532 w_list.lstorage = new
1533 return w_result
1534
1535 def pop(self, w_list, index):
1536 l = self.unerase(w_list.lstorage)
1537 start = l[0]
1538 step = l[1]
1539 length = l[2]
1540 if index == 0:
1541 w_result = self.wrap(start)
1542 new = self.erase((start + step, step, length - 1))
1543 w_list.lstorage = new
1544 return w_result
1545 elif index == length - 1:
1546 return self.pop_end(w_list)
1547 else:
1548 self.switch_to_integer_strategy(w_list)
1549 return w_list.pop(index)
1550
1551
1552 class AbstractUnwrappedStrategy(object):
1553
1554 def wrap(self, unwrapped):
1555 raise NotImplementedError
1556
1557 def unwrap(self, wrapped):
1558 raise NotImplementedError
1559
1560 def _quick_cmp(self, a, b):
1561 """ do a quick comparison between two unwrapped elements. """
1562 raise NotImplementedError("abstract base class")
1563
1564 @staticmethod
1565 def unerase(storage):
1566 raise NotImplementedError("abstract base class")
1567
1568 @staticmethod
1569 def erase(obj):
1570 raise NotImplementedError("abstract base class")
1571
1572 def is_correct_type(self, w_obj):
1573 raise NotImplementedError("abstract base class")
1574
1575 def list_is_correct_type(self, w_list):
1576 raise NotImplementedError("abstract base class")
1577
1578 def init_from_list_w(self, w_list, list_w):
1579 l = self._init_from_list_w_helper(list_w)
1580 w_list.lstorage = self.erase(l)
1581
1582 @jit.look_inside_iff(lambda space, list_w:
1583 jit.loop_unrolling_heuristic(list_w, len(list_w), UNROLL_CUTOFF))
1584 def _init_from_list_w_helper(self, list_w):
1585 return [self.unwrap(w_item) for w_item in list_w]
1586
1587 def get_empty_storage(self, sizehint):
1588 if sizehint == -1:
1589 return self.erase([])
1590 return self.erase(newlist_hint(sizehint))
1591
1592 def clone(self, w_list, sizehint=0):
1593 l = self.unerase(w_list.lstorage)
1594 if sizehint:
1595 assert sizehint >= len(l)
1596 l2 = newlist_hint(sizehint)
1597 l2.extend(l)
1598 else:
1599 l2 = l[:]
1600 storage = self.erase(l2)
1601 w_clone = W_ListObject.from_storage_and_strategy(
1602 self.space, storage, self)
1603 return w_clone
1604
1605 def _resize_hint(self, w_list, hint):
1606 resizelist_hint(self.unerase(w_list.lstorage), hint)
1607
1608 def copy_into(self, w_list, w_other):
1609 w_other.strategy = self
1610 items = self.unerase(w_list.lstorage)[:]
1611 w_other.lstorage = self.erase(items)
1612
1613 def find_or_count(self, w_list, w_obj, start, stop, count):
1614 if self.is_correct_type(w_obj):
1615 return self._safe_find_or_count(
1616 self.unerase(w_list.lstorage), self.unwrap(w_obj), start, stop, count)
1617 return ListStrategy.find_or_count(
1618 self, w_list, w_obj, start, stop, count)
1619
1620 def _safe_find_or_count(self, l, obj, start, stop, count):
1621 result = 0
1622 for i in range(start, min(stop, len(l))):
1623 val = l[i]
1624 if val == obj:
1625 if count:
1626 result += 1
1627 else:
1628 return i
1629 if count:
1630 return result
1631 raise ValueError
1632
1633 def length(self, w_list):
1634 return len(self.unerase(w_list.lstorage))
1635
1636 def getitem(self, w_list, index):
1637 l = self.unerase(w_list.lstorage)
1638 try:
1639 r = l[index]
1640 except IndexError: # make RPython raise the exception
1641 raise
1642 return self.wrap(r)
1643
1644 def getitems_copy(self, w_list):
1645 storage = self.unerase(w_list.lstorage)
1646 if len(storage) == 0:
1647 return []
1648 res = [None] * len(storage)
1649 prevvalue = storage[0]
1650 w_item = self.wrap(prevvalue)
1651 res[0] = w_item
1652 for index in range(1, len(storage)):
1653 item = storage[index]
1654 if jit.we_are_jitted() or not self._quick_cmp(item, prevvalue):
1655 prevvalue = item
1656 w_item = self.wrap(item)
1657 res[index] = w_item
1658 return res
1659
1660 getitems_unroll = jit.unroll_safe(
1661 func_with_new_name(getitems_copy, "getitems_unroll"))
1662
1663 getitems_copy = jit.look_inside_iff(lambda self, w_list:
1664 w_list._unrolling_heuristic())(getitems_copy)
1665
1666
1667 @jit.look_inside_iff(lambda self, w_list:
1668 w_list._unrolling_heuristic())
1669 def getitems_fixedsize(self, w_list):
1670 return self.getitems_unroll(w_list)
1671
1672 def getstorage_copy(self, w_list):
1673 items = self.unerase(w_list.lstorage)[:]
1674 return self.erase(items)
1675
1676 def getslice(self, w_list, start, stop, step, length):
1677 if step == 1 and 0 <= start <= stop:
1678 l = self.unerase(w_list.lstorage)
1679 assert start >= 0
1680 assert stop >= 0
1681 sublist = l[start:stop]
1682 storage = self.erase(sublist)
1683 return W_ListObject.from_storage_and_strategy(
1684 self.space, storage, self)
1685 else:
1686 subitems_w = [self._none_value] * length
1687 l = self.unerase(w_list.lstorage)
1688 self._fill_in_with_sliced_items(subitems_w, l, start, step, length)
1689 storage = self.erase(subitems_w)
1690 return W_ListObject.from_storage_and_strategy(
1691 self.space, storage, self)
1692
1693 def _fill_in_with_sliced_items(self, subitems_w, l, start, step, length):
1694 for i in range(length):
1695 try:
1696 subitems_w[i] = l[start]
1697 start += step
1698 except IndexError:
1699 raise
1700
1701 def switch_to_next_strategy(self, w_list, w_sample_item):
1702 w_list.switch_to_object_strategy()
1703
1704 def append(self, w_list, w_item):
1705 if self.is_correct_type(w_item):
1706 self.unerase(w_list.lstorage).append(self.unwrap(w_item))
1707 return
1708
1709 self.switch_to_next_strategy(w_list, w_item)
1710 w_list.append(w_item)
1711
1712 def insert(self, w_list, index, w_item):
1713 l = self.unerase(w_list.lstorage)
1714
1715 if self.is_correct_type(w_item):
1716 l.insert(index, self.unwrap(w_item))
1717 return
1718
1719 self.switch_to_next_strategy(w_list, w_item)
1720 w_list.insert(index, w_item)
1721
1722 def _extend_from_list(self, w_list, w_other):
1723 l = self.unerase(w_list.lstorage)
1724 if self.list_is_correct_type(w_other):
1725 l += self.unerase(w_other.lstorage)
1726 return
1727 elif w_other.strategy.is_empty_strategy():
1728 return
1729
1730 w_other = w_other._temporarily_as_objects()
1731 w_list.switch_to_object_strategy()
1732 w_list.extend(w_other)
1733
1734 def setitem(self, w_list, index, w_item):
1735 l = self.unerase(w_list.lstorage)
1736
1737 if self.is_correct_type(w_item):
1738 try:
1739 l[index] = self.unwrap(w_item)
1740 except IndexError:
1741 raise
1742 else:
1743 self.switch_to_next_strategy(w_list, w_item)
1744 w_list.setitem(index, w_item)
1745
1746 def setslice(self, w_list, start, step, slicelength, w_other):
1747 assert slicelength >= 0
1748 space = self.space
1749
1750 if self is space.fromcache(ObjectListStrategy):
1751 w_other = w_other._temporarily_as_objects()
1752 elif not self.list_is_correct_type(w_other) and w_other.length() != 0:
1753 w_list.switch_to_object_strategy()
1754 w_other_as_object = w_other._temporarily_as_objects()
1755 assert (w_other_as_object.strategy is
1756 space.fromcache(ObjectListStrategy))
1757 w_list.setslice(start, step, slicelength, w_other_as_object)
1758 return
1759
1760 items = self.unerase(w_list.lstorage)
1761 oldsize = len(items)
1762 len2 = w_other.length()
1763 if step == 1: # Support list resizing for non-extended slices
1764 delta = slicelength - len2
1765 if delta < 0:
1766 delta = -delta
1767 newsize = oldsize + delta
1768 # XXX support this in rlist!
1769 items += [self._none_value] * delta
1770 lim = start + len2
1771 i = newsize - 1
1772 while i >= lim:
1773 items[i] = items[i - delta]
1774 i -= 1
1775 elif delta == 0:
1776 pass
1777 else:
1778 # start < 0 is only possible with slicelength == 0
1779 assert start >= 0
1780 del items[start:start + delta]
1781 elif len2 != slicelength: # No resize for extended slices
1782 raise oefmt(space.w_ValueError,
1783 "attempt to assign sequence of size %d to extended "
1784 "slice of size %d", len2, slicelength)
1785
1786 if len2 == 0:
1787 other_items = []
1788 else:
1789 # at this point both w_list and w_other have the same type, so
1790 # self.unerase is valid for both of them
1791 other_items = self.unerase(w_other.lstorage)
1792 if other_items is items:
1793 if step > 0:
1794 # Always copy starting from the right to avoid
1795 # having to make a shallow copy in the case where
1796 # the source and destination lists are the same list.
1797 i = len2 - 1
1798 start += i * step
1799 while i >= 0:
1800 items[start] = other_items[i]
1801 start -= step
1802 i -= 1
1803 return
1804 else:
1805 # other_items is items and step is < 0, therefore:
1806 assert step == -1
1807 items.reverse()
1808 return
1809 #other_items = list(other_items)
1810 for i in range(len2):
1811 items[start] = other_items[i]
1812 start += step
1813
1814 def deleteslice(self, w_list, start, step, slicelength):
1815 items = self.unerase(w_list.lstorage)
1816 if slicelength == 0:
1817 return
1818
1819 if step < 0:
1820 start = start + step * (slicelength - 1)
1821 step = -step
1822
1823 if step == 1:
1824 assert start >= 0
1825 if slicelength > 0:
1826 del items[start:start + slicelength]
1827 else:
1828 n = len(items)
1829 i = start
1830
1831 for discard in range(1, slicelength):
1832 j = i + 1
1833 i += step
1834 while j < i:
1835 items[j - discard] = items[j]
1836 j += 1
1837
1838 j = i + 1
1839 while j < n:
1840 items[j - slicelength] = items[j]
1841 j += 1
1842 start = n - slicelength
1843 assert start >= 0 # annotator hint
1844 del items[start:]
1845
1846 def pop_end(self, w_list):
1847 l = self.unerase(w_list.lstorage)
1848 return self.wrap(l.pop())
1849
1850 def pop(self, w_list, index):
1851 l = self.unerase(w_list.lstorage)
1852 # not sure if RPython raises IndexError on pop
1853 # so check again here
1854 if index < 0:
1855 raise IndexError
1856 try:
1857 item = l.pop(index)
1858 except IndexError:
1859 raise
1860
1861 w_item = self.wrap(item)
1862 return w_item
1863
1864 def mul(self, w_list, times):
1865 l = self.unerase(w_list.lstorage)
1866 return W_ListObject.from_storage_and_strategy(
1867 self.space, self.erase(l * times), self)
1868
1869 def inplace_mul(self, w_list, times):
1870 l = self.unerase(w_list.lstorage)
1871 l *= times
1872
1873 def reverse(self, w_list):
1874 self.unerase(w_list.lstorage).reverse()
1875
1876 def physical_size(self, w_list):
1877 from rpython.rlib.objectmodel import list_get_physical_size
1878 l = self.unerase(w_list.lstorage)
1879 return list_get_physical_size(l)
1880
1881 def _unrolling_heuristic(self, w_list):
1882 storage = self.unerase(w_list.lstorage)
1883 return jit.loop_unrolling_heuristic(storage, len(storage), UNROLL_CUTOFF)
1884
1885
1886 class ObjectListStrategy(ListStrategy):
1887 import_from_mixin(AbstractUnwrappedStrategy)
1888
1889 _none_value = None
1890
1891 def unwrap(self, w_obj):
1892 return w_obj
1893
1894 def wrap(self, item):
1895 return item
1896
1897 def _quick_cmp(self, a, b):
1898 return a is b
1899
1900 erase, unerase = rerased.new_erasing_pair("object")
1901 erase = staticmethod(erase)
1902 unerase = staticmethod(unerase)
1903
1904 def getitems_copy(self, w_list):
1905 storage = self.unerase(w_list.lstorage)
1906 return storage[:]
1907
1908 def getitems_unroll(self, w_list):
1909 storage = self.unerase(w_list.lstorage)
1910 return storage[:]
1911
1912 def getitems_fixedsize(self, w_list):
1913 storage = self.unerase(w_list.lstorage)
1914 return storage[:]
1915
1916 def is_correct_type(self, w_obj):
1917 return True
1918
1919 def list_is_correct_type(self, w_list):
1920 return w_list.strategy is self.space.fromcache(ObjectListStrategy)
1921
1922 def init_from_list_w(self, w_list, list_w):
1923 w_list.lstorage = self.erase(list_w)
1924
1925 def clear(self, w_list):
1926 w_list.lstorage = self.erase([])
1927
1928 def find_or_count(self, w_list, w_obj, start, stop, count):
1929 return ListStrategy.find_or_count(
1930 self, w_list, w_obj, start, stop, count)
1931
1932 def getitems(self, w_list):
1933 return self.unerase(w_list.lstorage)
1934
1935 # no sort() method here: W_ListObject.descr_sort() handles this
1936 # case explicitly
1937
1938
1939 class IntegerListStrategy(ListStrategy):
1940 import_from_mixin(AbstractUnwrappedStrategy)
1941
1942 _none_value = 0
1943
1944 def wrap(self, intval):
1945 return self.space.newint(intval)
1946
1947 def unwrap(self, w_int):
1948 return plain_int_w(self.space, w_int)
1949
1950 def _quick_cmp(self, a, b):
1951 return a == b
1952
1953 erase, unerase = rerased.new_erasing_pair("integer")
1954 erase = staticmethod(erase)
1955 unerase = staticmethod(unerase)
1956
1957 def is_correct_type(self, w_obj):
1958 return is_plain_int1(w_obj)
1959
1960 def list_is_correct_type(self, w_list):
1961 return w_list.strategy is self.space.fromcache(IntegerListStrategy)
1962
1963 def sort(self, w_list, reverse):
1964 l = self.unerase(w_list.lstorage)
1965 sorter = IntSort(l, len(l))
1966 sorter.sort()
1967 if reverse:
1968 l.reverse()
1969
1970 def getitems_int(self, w_list):
1971 return self.unerase(w_list.lstorage)
1972
1973
1974 _base_extend_from_list = _extend_from_list
1975
1976 def _extend_from_list(self, w_list, w_other):
1977 if isinstance(w_other.strategy, BaseRangeListStrategy):
1978 l = self.unerase(w_list.lstorage)
1979 other = w_other.getitems_int()
1980 assert other is not None
1981 l += other
1982 return
1983 if (w_other.strategy is self.space.fromcache(FloatListStrategy) or
1984 w_other.strategy is self.space.fromcache(IntOrFloatListStrategy)):
1985 if self.switch_to_int_or_float_strategy(w_list):
1986 w_list.extend(w_other)
1987 return
1988 return self._base_extend_from_list(w_list, w_other)
1989
1990
1991 _base_setslice = setslice
1992
1993 def setslice(self, w_list, start, step, slicelength, w_other):
1994 if w_other.strategy is self.space.fromcache(RangeListStrategy):
1995 storage = self.erase(w_other.getitems_int())
1996 w_other = W_ListObject.from_storage_and_strategy(
1997 self.space, storage, self)
1998 if (w_other.strategy is self.space.fromcache(FloatListStrategy) or
1999 w_other.strategy is self.space.fromcache(IntOrFloatListStrategy)):
2000 if self.switch_to_int_or_float_strategy(w_list):
2001 w_list.setslice(start, step, slicelength, w_other)
2002 return
2003 return self._base_setslice(w_list, start, step, slicelength, w_other)
2004
2005
2006 @staticmethod
2007 def int_2_float_or_int(w_list):
2008 l = IntegerListStrategy.unerase(w_list.lstorage)
2009 if not longlong2float.CAN_ALWAYS_ENCODE_INT32:
2010 for intval in l:
2011 if not longlong2float.can_encode_int32(intval):
2012 raise ValueError
2013 return [longlong2float.encode_int32_into_longlong_nan(intval)
2014 for intval in l]
2015
2016 def switch_to_int_or_float_strategy(self, w_list):
2017 try:
2018 generalized_list = self.int_2_float_or_int(w_list)
2019 except ValueError:
2020 return False
2021 strategy = self.space.fromcache(IntOrFloatListStrategy)
2022 w_list.strategy = strategy
2023 w_list.lstorage = strategy.erase(generalized_list)
2024 return True
2025
2026 def switch_to_next_strategy(self, w_list, w_sample_item):
2027 if type(w_sample_item) is W_FloatObject:
2028 if self.switch_to_int_or_float_strategy(w_list):
2029 # yes, we can switch to IntOrFloatListStrategy
2030 # (ignore here the extremely unlikely case where
2031 # w_sample_item is just the wrong nonstandard NaN float;
2032 # it will caught later and yet another switch will occur)
2033 return
2034 # no, fall back to ObjectListStrategy
2035 w_list.switch_to_object_strategy()
2036
2037 def repr(self, w_list):
2038 space = self.space
2039 res = str(self.unerase(w_list.lstorage))
2040 return space.newtext(res)
2041
2042
2043 class FloatListStrategy(ListStrategy):
2044 import_from_mixin(AbstractUnwrappedStrategy)
2045
2046 _none_value = 0.0
2047
2048 def wrap(self, floatval):
2049 return self.space.newfloat(floatval)
2050
2051 def unwrap(self, w_float):
2052 return self.space.float_w(w_float)
2053
2054 erase, unerase = rerased.new_erasing_pair("float")
2055 erase = staticmethod(erase)
2056 unerase = staticmethod(unerase)
2057
2058 def _quick_cmp(self, a, b):
2059 return longlong2float.float2longlong(a) == longlong2float.float2longlong(b)
2060
2061 def is_correct_type(self, w_obj):
2062 return type(w_obj) is W_FloatObject
2063
2064 def list_is_correct_type(self, w_list):
2065 return w_list.strategy is self.space.fromcache(FloatListStrategy)
2066
2067 def sort(self, w_list, reverse):
2068 l = self.unerase(w_list.lstorage)
2069 sorter = FloatSort(l, len(l))
2070 sorter.sort()
2071 if reverse:
2072 l.reverse()
2073
2074 def getitems_float(self, w_list):
2075 return self.unerase(w_list.lstorage)
2076
2077
2078 _base_extend_from_list = _extend_from_list
2079
2080 def _extend_from_list(self, w_list, w_other):
2081 if (w_other.strategy is self.space.fromcache(IntegerListStrategy) or
2082 w_other.strategy is self.space.fromcache(IntOrFloatListStrategy)):
2083 # xxx a case that we don't optimize: [3.4].extend([9999999999999])
2084 # will cause a switch to int-or-float, followed by another
2085 # switch to object
2086 if self.switch_to_int_or_float_strategy(w_list):
2087 w_list.extend(w_other)
2088 return
2089 return self._base_extend_from_list(w_list, w_other)
2090
2091
2092 _base_setslice = setslice
2093
2094 def setslice(self, w_list, start, step, slicelength, w_other):
2095 if (w_other.strategy is self.space.fromcache(IntegerListStrategy) or
2096 w_other.strategy is self.space.fromcache(IntOrFloatListStrategy)):
2097 if self.switch_to_int_or_float_strategy(w_list):
2098 w_list.setslice(start, step, slicelength, w_other)
2099 return
2100 return self._base_setslice(w_list, start, step, slicelength, w_other)
2101
2102
2103 def _safe_find_or_count(self, l, obj, start, stop, count):
2104 stop = min(stop, len(l))
2105 result = 0
2106 if not math.isnan(obj):
2107 for i in range(start, stop):
2108 val = l[i]
2109 if val == obj:
2110 if count:
2111 result += 1
2112 else:
2113 return i
2114 else:
2115 search = longlong2float.float2longlong(obj)
2116 for i in range(start, stop):
2117 val = l[i]
2118 if longlong2float.float2longlong(val) == search:
2119 if count:
2120 result += 1
2121 else:
2122 return i
2123 if count:
2124 return result
2125 raise ValueError
2126
2127 @staticmethod
2128 def float_2_float_or_int(w_list):
2129 l = FloatListStrategy.unerase(w_list.lstorage)
2130 generalized_list = []
2131 for floatval in l:
2132 if not longlong2float.can_encode_float(floatval):
2133 raise ValueError
2134 generalized_list.append(
2135 longlong2float.float2longlong(floatval))
2136 return generalized_list
2137
2138 def switch_to_int_or_float_strategy(self, w_list):
2139 # xxx we should be able to use the same lstorage, but
2140 # there is a typing issue (float vs longlong)...
2141 try:
2142 generalized_list = self.float_2_float_or_int(w_list)
2143 except ValueError:
2144 return False
2145 strategy = self.space.fromcache(IntOrFloatListStrategy)
2146 w_list.strategy = strategy
2147 w_list.lstorage = strategy.erase(generalized_list)
2148 return True
2149
2150 def switch_to_next_strategy(self, w_list, w_sample_item):
2151 if is_plain_int1(w_sample_item):
2152 sample_intval = plain_int_w(self.space, w_sample_item)
2153 if longlong2float.can_encode_int32(sample_intval):
2154 if self.switch_to_int_or_float_strategy(w_list):
2155 # yes, we can switch to IntOrFloatListStrategy
2156 return
2157 # no, fall back to ObjectListStrategy
2158 w_list.switch_to_object_strategy()
2159
2160 def repr(self, w_list):
2161 from pypy.objspace.std.floatobject import float_repr
2162 l = self.unerase(w_list.lstorage)
2163 if len(l) == 0:
2164 return self.space.newtext('[]')
2165 b = StringBuilder()
2166 b.append('[')
2167 for i in range(len(l)):
2168 if i > 0:
2169 b.append(', ')
2170 b.append(float_repr(l[i]))
2171 b.append(']')
2172 res = b.build()
2173 return self.space.newutf8(res, len(res))
2174
2175
2176 class IntOrFloatListStrategy(ListStrategy):
2177 import_from_mixin(AbstractUnwrappedStrategy)
2178
2179 _none_value = longlong2float.float2longlong(0.0)
2180
2181 def wrap(self, llval):
2182 if longlong2float.is_int32_from_longlong_nan(llval):
2183 intval = longlong2float.decode_int32_from_longlong_nan(llval)
2184 return self.space.newint(intval)
2185 else:
2186 floatval = longlong2float.longlong2float(llval)
2187 return self.space.newfloat(floatval)
2188
2189 def unwrap(self, w_int_or_float):
2190 if is_plain_int1(w_int_or_float):
2191 intval = plain_int_w(self.space, w_int_or_float)
2192 return longlong2float.encode_int32_into_longlong_nan(intval)
2193 else:
2194 floatval = self.space.float_w(w_int_or_float)
2195 return longlong2float.float2longlong(floatval)
2196
2197 def _quick_cmp(self, a, b):
2198 return a == b
2199
2200 erase, unerase = rerased.new_erasing_pair("longlong")
2201 erase = staticmethod(erase)
2202 unerase = staticmethod(unerase)
2203
2204 def is_correct_type(self, w_obj):
2205 if is_plain_int1(w_obj):
2206 intval = plain_int_w(self.space, w_obj)
2207 return longlong2float.can_encode_int32(intval)
2208 elif type(w_obj) is W_FloatObject:
2209 floatval = self.space.float_w(w_obj)
2210 return longlong2float.can_encode_float(floatval)
2211 else:
2212 return False
2213
2214 def list_is_correct_type(self, w_list):
2215 return w_list.strategy is self.space.fromcache(IntOrFloatListStrategy)
2216
2217 def sort(self, w_list, reverse):
2218 l = self.unerase(w_list.lstorage)
2219 sorter = IntOrFloatSort(l, len(l))
2220 # Reverse sort stability achieved by initially reversing the list,
2221 # applying a stable forward sort, then reversing the final result.
2222 if reverse:
2223 l.reverse()
2224 sorter.sort()
2225 if reverse:
2226 l.reverse()
2227
2228 _base_extend_from_list = _extend_from_list
2229
2230 def _extend_longlong(self, w_list, longlong_list):
2231 l = self.unerase(w_list.lstorage)
2232 l += longlong_list
2233
2234 def _extend_from_list(self, w_list, w_other):
2235 if w_other.strategy is self.space.fromcache(IntegerListStrategy):
2236 try:
2237 longlong_list = IntegerListStrategy.int_2_float_or_int(w_other)
2238 except ValueError:
2239 pass
2240 else:
2241 return self._extend_longlong(w_list, longlong_list)
2242 if w_other.strategy is self.space.fromcache(FloatListStrategy):
2243 try:
2244 longlong_list = FloatListStrategy.float_2_float_or_int(w_other)
2245 except ValueError:
2246 pass
2247 else:
2248 return self._extend_longlong(w_list, longlong_list)
2249 return self._base_extend_from_list(w_list, w_other)
2250
2251 _base_setslice = setslice
2252
2253 def _temporary_longlong_list(self, longlong_list):
2254 storage = self.erase(longlong_list)
2255 return W_ListObject.from_storage_and_strategy(self.space, storage, self)
2256
2257 def setslice(self, w_list, start, step, slicelength, w_other):
2258 if w_other.strategy is self.space.fromcache(IntegerListStrategy):
2259 try:
2260 longlong_list = IntegerListStrategy.int_2_float_or_int(w_other)
2261 except ValueError:
2262 pass
2263 else:
2264 w_other = self._temporary_longlong_list(longlong_list)
2265 elif w_other.strategy is self.space.fromcache(FloatListStrategy):
2266 try:
2267 longlong_list = FloatListStrategy.float_2_float_or_int(w_other)
2268 except ValueError:
2269 pass
2270 else:
2271 w_other = self._temporary_longlong_list(longlong_list)
2272 return self._base_setslice(w_list, start, step, slicelength, w_other)
2273
2274 def _safe_find_or_count(self, l, obj, start, stop, count):
2275 # careful: we must consider that 0.0 == -0.0 == 0, but also
2276 # NaN == NaN if they have the same bit pattern.
2277 fobj = longlong2float.maybe_decode_longlong_as_float(obj)
2278 result = 0
2279 for i in range(start, min(stop, len(l))):
2280 llval = l[i]
2281 if llval == obj: # equal as longlongs: includes NaN == NaN
2282 if count:
2283 result += 1
2284 continue
2285 else:
2286 return i
2287 fval = longlong2float.maybe_decode_longlong_as_float(llval)
2288 if fval == fobj: # cases like 0.0 == -0.0 or 42 == 42.0
2289 if count:
2290 result += 1
2291 else:
2292 return i
2293 if count:
2294 return result
2295 raise ValueError
2296
2297 def repr(self, w_list):
2298 from pypy.objspace.std.floatobject import float_repr
2299 l = self.unerase(w_list.lstorage)
2300 if len(l) == 0:
2301 return self.space.newtext('[]')
2302 b = StringBuilder()
2303 b.append('[')
2304 for i in range(len(l)):
2305 if i > 0:
2306 b.append(', ')
2307 llval = l[i]
2308 if longlong2float.is_int32_from_longlong_nan(llval):
2309 intval = longlong2float.decode_int32_from_longlong_nan(llval)
2310 b.append(str(intval))
2311 else:
2312 floatval = longlong2float.longlong2float(llval)
2313 b.append(float_repr(floatval))
2314 b.append(']')
2315 res = b.build()
2316 return self.space.newtext(res, len(res))
2317
2318
2319 class BytesListStrategy(ListStrategy):
2320 import_from_mixin(AbstractUnwrappedStrategy)
2321
2322 _none_value = ""
2323
2324 def wrap(self, stringval):
2325 return self.space.newbytes(stringval)
2326
2327 def unwrap(self, w_string):
2328 return self.space.bytes_w(w_string)
2329
2330 def _quick_cmp(self, a, b):
2331 return a is b
2332
2333 erase, unerase = rerased.new_erasing_pair("bytes")
2334 erase = staticmethod(erase)
2335 unerase = staticmethod(unerase)
2336
2337 def is_correct_type(self, w_obj):
2338 return type(w_obj) is W_BytesObject
2339
2340 def list_is_correct_type(self, w_list):
2341 return w_list.strategy is self.space.fromcache(BytesListStrategy)
2342
2343 def sort(self, w_list, reverse):
2344 l = self.unerase(w_list.lstorage)
2345 sorter = StringSort(l, len(l))
2346 sorter.sort()
2347 if reverse:
2348 l.reverse()
2349
2350 def getitems_bytes(self, w_list):
2351 return self.unerase(w_list.lstorage)
2352
2353
2354 class AsciiListStrategy(ListStrategy):
2355 import_from_mixin(AbstractUnwrappedStrategy)
2356
2357 _none_value = ""
2358
2359 def wrap(self, stringval):
2360 assert stringval is not None
2361 return self.space.newutf8(stringval, len(stringval))
2362
2363 def unwrap(self, w_string):
2364 return self.space.utf8_w(w_string)
2365
2366 def _quick_cmp(self, a, b):
2367 return a is b
2368
2369 erase, unerase = rerased.new_erasing_pair("unicode")
2370 erase = staticmethod(erase)
2371 unerase = staticmethod(unerase)
2372
2373 def is_correct_type(self, w_obj):
2374 return type(w_obj) is W_UnicodeObject and w_obj.is_ascii()
2375
2376 def list_is_correct_type(self, w_list):
2377 return w_list.strategy is self.space.fromcache(AsciiListStrategy)
2378
2379 def sort(self, w_list, reverse):
2380 l = self.unerase(w_list.lstorage)
2381 sorter = StringSort(l, len(l))
2382 sorter.sort()
2383 if reverse:
2384 l.reverse()
2385
2386 def getitems_ascii(self, w_list):
2387 return self.unerase(w_list.lstorage)
2388
2389
2390 def is_plain_int1(w_obj):
2391 return (type(w_obj) is W_IntObject or
2392 (type(w_obj) is W_LongObject and w_obj._fits_int()))
2393
2394 def plain_int_w(space, w_obj):
2395 # like space.int_w(w_obj, allow_conversion=False). Meant to be
2396 # used only for objects for which is_plain_int1() returned True;
2397 # for that use case it should never raise.
2398 return w_obj._int_w(space)
2399
2400
2401 # ____________________________________________________________
2402 # Sorting
2403
2404 # Reverse a slice of a list in place, from lo up to (exclusive) hi.
2405 # (used in sort)
2406
2407 TimSort = make_timsort_class()
2408 IntBaseTimSort = make_timsort_class()
2409 FloatBaseTimSort = make_timsort_class()
2410 IntOrFloatBaseTimSort = make_timsort_class()
2411
2412
2413 class KeyContainer(W_Root):
2414 def __init__(self, w_key, w_item):
2415 self.w_key = w_key
2416 self.w_item = w_item
2417
2418
2419 # NOTE: all the subclasses of TimSort should inherit from a common subclass,
2420 # so make sure that only SimpleSort inherits directly from TimSort.
2421 # This is necessary to hide the parent method TimSort.lt() from the
2422 # annotator.
2423 class SimpleSort(TimSort):
2424 def lt(self, a, b):
2425 space = self.space
2426 return space.is_true(space.lt(a, b))
2427
2428
2429 class IntSort(IntBaseTimSort):
2430 def lt(self, a, b):
2431 return a < b
2432
2433
2434 class FloatSort(FloatBaseTimSort):
2435 def lt(self, a, b):
2436 return a < b
2437
2438
2439 class IntOrFloatSort(IntOrFloatBaseTimSort):
2440 def lt(self, a, b):
2441 fa = longlong2float.maybe_decode_longlong_as_float(a)
2442 fb = longlong2float.maybe_decode_longlong_as_float(b)
2443 return fa < fb
2444
2445
2446 class CustomKeySort(SimpleSort):
2447 def lt(self, a, b):
2448 assert isinstance(a, KeyContainer)
2449 assert isinstance(b, KeyContainer)
2450 space = self.space
2451 return space.is_true(space.lt(a.w_key, b.w_key))
2452
2453
2454 W_ListObject.typedef = TypeDef("list",
2455 __doc__ = """Built-in mutable sequence.
2456
2457 If no argument is given, the constructor creates a new empty list.
2458 The argument must be an iterable if specified.""",
2459 _text_signature_ = "(iterable=(), /)",
2460 __new__ = interp2app(W_ListObject.descr_new),
2461 __init__ = interp2app(W_ListObject.descr_init),
2462 __repr__ = interp2app(W_ListObject.descr_repr),
2463 __hash__ = None,
2464
2465 __eq__ = interp2app(W_ListObject.descr_eq),
2466 __ne__ = interp2app(W_ListObject.descr_ne),
2467 __lt__ = interp2app(W_ListObject.descr_lt),
2468 __le__ = interp2app(W_ListObject.descr_le),
2469 __gt__ = interp2app(W_ListObject.descr_gt),
2470 __ge__ = interp2app(W_ListObject.descr_ge),
2471
2472 __len__ = interp2app(W_ListObject.descr_len),
2473 __iter__ = interp2app(W_ListObject.descr_iter),
2474 __contains__ = interp2app(W_ListObject.descr_contains),
2475
2476 __add__ = interp2app(W_ListObject.descr_add),
2477 __iadd__ = interp2app(W_ListObject.descr_inplace_add),
2478 __mul__ = interp2app(W_ListObject.descr_mul),
2479 __rmul__ = interp2app(W_ListObject.descr_mul),
2480 __imul__ = interp2app(W_ListObject.descr_inplace_mul),
2481
2482 __getitem__ = interp2app(W_ListObject.descr_getitem),
2483 __setitem__ = interp2app(W_ListObject.descr_setitem),
2484 __delitem__ = interp2app(W_ListObject.descr_delitem),
2485
2486 __class_getitem__ = interp2app(
2487 generic_alias_class_getitem, as_classmethod=True),
2488
2489 sort = interp2app(W_ListObject.descr_sort),
2490 index = interp2app(W_ListObject.descr_index),
2491 copy = interp2app(W_ListObject.descr_copy),
2492 append = interp2app(W_ListObject.append),
2493 reverse = interp2app(W_ListObject.descr_reverse),
2494 __reversed__ = interp2app(W_ListObject.descr_reversed),
2495 count = interp2app(W_ListObject.descr_count),
2496 pop = interp2app(W_ListObject.descr_pop),
2497 clear = interp2app(W_ListObject.descr_clear),
2498 extend = interp2app(W_ListObject.extend),
2499 insert = interp2app(W_ListObject.descr_insert),
2500 remove = interp2app(W_ListObject.descr_remove),
2501 )
2502 W_ListObject.typedef.flag_sequence_bug_compat = True