Source

pypy / pypy / objspace / std / listobject.py

   1
   2
   3
   4
   5
   6
   7
   8
   9
  10
  11
  12
  13
  14
  15
  16
  17
  18
  19
  20
  21
  22
  23
  24
  25
  26
  27
  28
  29
  30
  31
  32
  33
  34
  35
  36
  37
  38
  39
  40
  41
  42
  43
  44
  45
  46
  47
  48
  49
  50
  51
  52
  53
  54
  55
  56
  57
  58
  59
  60
  61
  62
  63
  64
  65
  66
  67
  68
  69
  70
  71
  72
  73
  74
  75
  76
  77
  78
  79
  80
  81
  82
  83
  84
  85
  86
  87
  88
  89
  90
  91
  92
  93
  94
  95
  96
  97
  98
  99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
"""The builtin list implementation

Lists optimize their storage by holding certain primitive datatypes in
unwrapped form. For more information:

http://morepypy.blogspot.com/2011/10/more-compact-lists-with-list-strategies.html

"""

import operator
import sys

from pypy.interpreter.baseobjspace import W_Root
from pypy.interpreter.error import OperationError, operationerrfmt
from pypy.interpreter.gateway import (WrappedDefault, unwrap_spec, applevel,
    interp2app)
from pypy.interpreter.generator import GeneratorIterator
from pypy.interpreter.signature import Signature
from pypy.objspace.std import slicetype
from pypy.objspace.std.floatobject import W_FloatObject
from pypy.objspace.std.intobject import W_IntObject
from pypy.objspace.std.inttype import wrapint
from pypy.objspace.std.iterobject import (W_FastListIterObject,
    W_ReverseSeqIterObject)
from pypy.objspace.std.sliceobject import W_SliceObject
from pypy.objspace.std.stdtypedef import StdTypeDef
from pypy.objspace.std.stringobject import W_StringObject
from pypy.objspace.std.tupleobject import W_AbstractTupleObject
from pypy.objspace.std.unicodeobject import W_UnicodeObject
from pypy.objspace.std.util import get_positive_index, negate
from rpython.rlib import debug, jit, rerased
from rpython.rlib.listsort import make_timsort_class
from rpython.rlib.objectmodel import (
    instantiate, newlist_hint, resizelist_hint, specialize)
from rpython.tool.sourcetools import func_with_new_name

__all__ = ['W_ListObject', 'make_range_list', 'make_empty_list_with_size']


UNROLL_CUTOFF = 5


def make_range_list(space, start, step, length):
    if length <= 0:
        strategy = space.fromcache(EmptyListStrategy)
        storage = strategy.erase(None)
    else:
        strategy = space.fromcache(RangeListStrategy)
        storage = strategy.erase((start, step, length))
    return W_ListObject.from_storage_and_strategy(space, storage, strategy)


def make_empty_list(space):
    strategy = space.fromcache(EmptyListStrategy)
    storage = strategy.erase(None)
    return W_ListObject.from_storage_and_strategy(space, storage, strategy)


def make_empty_list_with_size(space, hint):
    strategy = SizeListStrategy(space, hint)
    storage = strategy.erase(None)
    return W_ListObject.from_storage_and_strategy(space, storage, strategy)


@jit.look_inside_iff(lambda space, list_w, sizehint:
        jit.loop_unrolling_heuristic(list_w, len(list_w), UNROLL_CUTOFF))
def get_strategy_from_list_objects(space, list_w, sizehint):
    if not list_w:
        if sizehint != -1:
            return SizeListStrategy(space, sizehint)
        return space.fromcache(EmptyListStrategy)

    # check for ints
    for w_obj in list_w:
        if not type(w_obj) is W_IntObject:
            break
    else:
        return space.fromcache(IntegerListStrategy)

    # check for strings
    # XXX: StringListStrategy is currently broken
    """
    for w_obj in list_w:
        if not type(w_obj) is W_StringObject:
            break
    else:
        return space.fromcache(StringListStrategy)
        """

    # check for unicode
    for w_obj in list_w:
        if not type(w_obj) is W_UnicodeObject:
            break
    else:
        return space.fromcache(UnicodeListStrategy)

    # check for floats
    for w_obj in list_w:
        if not type(w_obj) is W_FloatObject:
            break
    else:
        return space.fromcache(FloatListStrategy)

    return space.fromcache(ObjectListStrategy)


def _get_printable_location(w_type):
    return ('list__do_extend_from_iterable [w_type=%s]' %
            w_type.getname(w_type.space).encode('utf-8'))


_do_extend_jitdriver = jit.JitDriver(
    name='list__do_extend_from_iterable',
    greens=['w_type'],
    reds=['i', 'w_iterator', 'w_list'],
    get_printable_location=_get_printable_location)

def _do_extend_from_iterable(space, w_list, w_iterable):
    w_iterator = space.iter(w_iterable)
    w_type = space.type(w_iterator)
    i = 0
    while True:
        _do_extend_jitdriver.jit_merge_point(w_type=w_type,
                                             i=i,
                                             w_iterator=w_iterator,
                                             w_list=w_list)
        try:
            w_list.append(space.next(w_iterator))
        except OperationError, e:
            if not e.match(space, space.w_StopIteration):
                raise
            break
        i += 1
    return i


def list_unroll_condition(w_list1, space, w_list2):
    return (jit.loop_unrolling_heuristic(w_list1, w_list1.length(),
                                         UNROLL_CUTOFF) or
            jit.loop_unrolling_heuristic(w_list2, w_list2.length(),
                                         UNROLL_CUTOFF))


class W_ListObject(W_Root):

    def __init__(self, space, wrappeditems, sizehint=-1):
        assert isinstance(wrappeditems, list)
        self.space = space
        if space.config.objspace.std.withliststrategies:
            self.strategy = get_strategy_from_list_objects(space, wrappeditems,
                                                           sizehint)
        else:
            self.strategy = space.fromcache(ObjectListStrategy)
        self.init_from_list_w(wrappeditems)

    @staticmethod
    def from_storage_and_strategy(space, storage, strategy):
        self = instantiate(W_ListObject)
        self.space = space
        self.strategy = strategy
        self.lstorage = storage
        if not space.config.objspace.std.withliststrategies:
            self.switch_to_object_strategy()
        return self

    # XXX: StringListStrategy is currently broken
    #@staticmethod
    #def newlist_str(space, list_s):
    #    strategy = space.fromcache(StringListStrategy)
    #    storage = strategy.erase(list_s)
    #    return W_ListObject.from_storage_and_strategy(space, storage, strategy)

    @staticmethod
    def newlist_unicode(space, list_u):
        strategy = space.fromcache(UnicodeListStrategy)
        storage = strategy.erase(list_u)
        return W_ListObject.from_storage_and_strategy(space, storage, strategy)

    def __repr__(self):
        """ representation for debugging purposes """
        return "%s(%s, %s)" % (self.__class__.__name__, self.strategy,
                               self.lstorage._x)

    def unwrap(w_list, space):
        # for tests only!
        items = [space.unwrap(w_item) for w_item in w_list.getitems()]
        return list(items)

    def switch_to_object_strategy(self):
        list_w = self.getitems()
        self.strategy = self.space.fromcache(ObjectListStrategy)
        # XXX this is quite indirect
        self.init_from_list_w(list_w)

    def _temporarily_as_objects(self):
        if self.strategy is self.space.fromcache(ObjectListStrategy):
            return self
        list_w = self.getitems()
        strategy = self.space.fromcache(ObjectListStrategy)
        storage = strategy.erase(list_w)
        w_objectlist = W_ListObject.from_storage_and_strategy(
                self.space, storage, strategy)
        return w_objectlist

    # ___________________________________________________

    def init_from_list_w(self, list_w):
        """Initializes listobject by iterating through the given list of
        wrapped items, unwrapping them if neccessary and creating a
        new erased object as storage"""
        self.strategy.init_from_list_w(self, list_w)

    def clear(self, space):
        """Initializes (or overrides) the listobject as empty."""
        self.space = space
        if space.config.objspace.std.withliststrategies:
            strategy = space.fromcache(EmptyListStrategy)
        else:
            strategy = space.fromcache(ObjectListStrategy)
        self.strategy = strategy
        strategy.clear(self)

    def clone(self):
        """Returns a clone by creating a new listobject
        with the same strategy and a copy of the storage"""
        return self.strategy.clone(self)

    def _resize_hint(self, hint):
        """Ensure the underlying list has room for at least hint
        elements without changing the len() of the list"""
        return self.strategy._resize_hint(self, hint)

    def copy_into(self, other):
        """Used only when extending an EmptyList. Sets the EmptyLists
        strategy and storage according to the other W_List"""
        self.strategy.copy_into(self, other)

    def find(self, w_item, start=0, end=sys.maxint):
        """Find w_item in list[start:end]. If not found, raise ValueError"""
        return self.strategy.find(self, w_item, start, end)

    def append(self, w_item):
        """L.append(object) -- append object to end"""
        self.strategy.append(self, w_item)

    def length(self):
        return self.strategy.length(self)

    def getitem(self, index):
        """Returns the wrapped object that is found in the
        list at the given index. The index must be unwrapped.
        May raise IndexError."""
        return self.strategy.getitem(self, index)

    def getslice(self, start, stop, step, length):
        """Returns a slice of the list defined by the arguments. Arguments must
        be normalized (i.e. using normalize_simple_slice or W_Slice.indices4).
        May raise IndexError."""
        return self.strategy.getslice(self, start, stop, step, length)

    def getitems(self):
        """Returns a list of all items after wrapping them. The result can
        share with the storage, if possible."""
        return self.strategy.getitems(self)

    def getitems_fixedsize(self):
        """Returns a fixed-size list of all items after wrapping them."""
        l = self.strategy.getitems_fixedsize(self)
        debug.make_sure_not_resized(l)
        return l

    def getitems_unroll(self):
        """Returns a fixed-size list of all items after wrapping them. The JIT
        will fully unroll this function."""
        l = self.strategy.getitems_unroll(self)
        debug.make_sure_not_resized(l)
        return l

    def getitems_copy(self):
        """Returns a copy of all items in the list. Same as getitems except for
        ObjectListStrategy."""
        return self.strategy.getitems_copy(self)

    def getitems_str(self):
        """Return the items in the list as unwrapped strings. If the list does
        not use the list strategy, return None."""
        return self.strategy.getitems_str(self)

    def getitems_unicode(self):
        """Return the items in the list as unwrapped unicodes. If the list does
        not use the list strategy, return None."""
        return self.strategy.getitems_unicode(self)

    def getitems_int(self):
        """Return the items in the list as unwrapped ints. If the list does not
        use the list strategy, return None."""
        return self.strategy.getitems_int(self)
    # ___________________________________________________

    def mul(self, times):
        """Returns a copy of the list, multiplied by times.
        Argument must be unwrapped."""
        return self.strategy.mul(self, times)

    def inplace_mul(self, times):
        """Alters the list by multiplying its content by times."""
        self.strategy.inplace_mul(self, times)

    def deleteslice(self, start, step, length):
        """Deletes a slice from the list. Used in delitem and delslice.
        Arguments must be normalized (see getslice)."""
        self.strategy.deleteslice(self, start, step, length)

    def pop(self, index):
        """Pops an item from the list. Index must be normalized.
        May raise IndexError."""
        return self.strategy.pop(self, index)

    def pop_end(self):
        """ Pop the last element from the list."""
        return self.strategy.pop_end(self)

    def setitem(self, index, w_item):
        """Inserts a wrapped item at the given (unwrapped) index.
        May raise IndexError."""
        self.strategy.setitem(self, index, w_item)

    def setslice(self, start, step, slicelength, sequence_w):
        """Sets the slice of the list from start to start+step*slicelength to
        the sequence sequence_w.
        Used by setslice and setitem."""
        self.strategy.setslice(self, start, step, slicelength, sequence_w)

    def insert(self, index, w_item):
        """Inserts an item at the given position. Item must be wrapped,
        index not."""
        self.strategy.insert(self, index, w_item)

    def extend(self, w_iterable):
        '''L.extend(iterable) -- extend list by appending
        elements from the iterable'''
        self.strategy.extend(self, w_iterable)

    def reverse(self):
        """Reverses the list."""
        self.strategy.reverse(self)

    def sort(self, reverse):
        """Sorts the list ascending or descending depending on
        argument reverse. Argument must be unwrapped."""
        self.strategy.sort(self, reverse)

    # exposed to app-level

    @staticmethod
    def descr_new(space, w_listtype, __args__):
        w_obj = space.allocate_instance(W_ListObject, w_listtype)
        w_obj.clear(space)
        return w_obj

    def descr_init(self, space, __args__):
        # this is on the silly side
        w_iterable, = __args__.parse_obj(
                None, 'list', init_signature, init_defaults)
        self.clear(space)
        if w_iterable is not None:
            self.extend(w_iterable)

    def descr_repr(self, space):
        if self.length() == 0:
            return space.wrap('[]')
        ec = space.getexecutioncontext()
        w_currently_in_repr = ec._py_repr
        if w_currently_in_repr is None:
            w_currently_in_repr = ec._py_repr = space.newdict()
        return listrepr(space, w_currently_in_repr, self)

    def descr_eq(self, space, w_other):
        if not isinstance(w_other, W_ListObject):
            return space.w_NotImplemented
        return self._descr_eq(space, w_other)

    @jit.look_inside_iff(list_unroll_condition)
    def _descr_eq(self, space, w_other):
        # needs to be safe against eq_w() mutating the w_lists behind our back
        if self.length() != w_other.length():
            return space.w_False

        # XXX in theory, this can be implemented more efficiently as well.
        # let's not care for now
        i = 0
        while i < self.length() and i < w_other.length():
            if not space.eq_w(self.getitem(i), w_other.getitem(i)):
                return space.w_False
            i += 1
        return space.w_True

    descr_ne = negate(descr_eq)

    def _make_list_comparison(name):
        op = getattr(operator, name)

        def compare_unwrappeditems(self, space, w_list2):
            if not isinstance(w_list2, W_ListObject):
                return space.w_NotImplemented
            return _compare_unwrappeditems(self, space, w_list2)

        @jit.look_inside_iff(list_unroll_condition)
        def _compare_unwrappeditems(self, space, w_list2):
            # needs to be safe against eq_w() mutating the w_lists behind our
            # back
            # Search for the first index where items are different
            i = 0
            # XXX in theory, this can be implemented more efficiently as well.
            # let's not care for now
            while i < self.length() and i < w_list2.length():
                w_item1 = self.getitem(i)
                w_item2 = w_list2.getitem(i)
                if not space.eq_w(w_item1, w_item2):
                    return getattr(space, name)(w_item1, w_item2)
                i += 1
            # No more items to compare -- compare sizes
            return space.newbool(op(self.length(), w_list2.length()))

        return func_with_new_name(compare_unwrappeditems, 'descr_' + name)

    descr_lt = _make_list_comparison('lt')
    descr_le = _make_list_comparison('le')
    descr_gt = _make_list_comparison('gt')
    descr_ge = _make_list_comparison('ge')

    def descr_len(self, space):
        result = self.length()
        return wrapint(space, result)

    def descr_iter(self, space):
        return W_FastListIterObject(self)

    def descr_contains(self, space, w_obj):
        try:
            self.find(w_obj)
            return space.w_True
        except ValueError:
            return space.w_False

    def descr_add(self, space, w_list2):
        if not isinstance(w_list2, W_ListObject):
            return space.w_NotImplemented
        w_clone = self.clone()
        w_clone.extend(w_list2)
        return w_clone

    def descr_inplace_add(self, space, w_iterable):
        if isinstance(w_iterable, W_ListObject):
            self.extend(w_iterable)
            return self

        try:
            self.extend(w_iterable)
        except OperationError, e:
            if e.match(space, space.w_TypeError):
                return space.w_NotImplemented
            raise
        return self

    def descr_mul(self, space, w_times):
        try:
            times = space.getindex_w(w_times, space.w_OverflowError)
        except OperationError, e:
            if e.match(space, space.w_TypeError):
                return space.w_NotImplemented
            raise
        return self.mul(times)

    def descr_inplace_mul(self, space, w_times):
        try:
            times = space.getindex_w(w_times, space.w_OverflowError)
        except OperationError, e:
            if e.match(space, space.w_TypeError):
                return space.w_NotImplemented
            raise
        self.inplace_mul(times)
        return self

    def descr_getitem(self, space, w_index):
        if isinstance(w_index, W_SliceObject):
            # XXX consider to extend rlist's functionality?
            length = self.length()
            start, stop, step, slicelength = w_index.indices4(space, length)
            assert slicelength >= 0
            if slicelength == 0:
                return make_empty_list(space)
            return self.getslice(start, stop, step, slicelength)

        try:
            index = space.getindex_w(w_index, space.w_IndexError, "list index")
            return self.getitem(index)
        except IndexError:
            raise OperationError(space.w_IndexError,
                                 space.wrap("list index out of range"))

    def descr_setitem(self, space, w_index, w_any):
        if isinstance(w_index, W_SliceObject):
            oldsize = self.length()
            start, stop, step, slicelength = w_index.indices4(space, oldsize)
            if isinstance(w_any, W_ListObject):
                self.setslice(start, step, slicelength, w_any)
            else:
                sequence_w = space.listview(w_any)
                w_other = W_ListObject(space, sequence_w)
                self.setslice(start, step, slicelength, w_other)
            return

        idx = space.getindex_w(w_index, space.w_IndexError, "list index")
        try:
            self.setitem(idx, w_any)
        except IndexError:
            raise OperationError(space.w_IndexError,
                                 space.wrap("list index out of range"))

    def descr_delitem(self, space, w_idx):
        if isinstance(w_idx, W_SliceObject):
            start, stop, step, slicelength = w_idx.indices4(
                    space, self.length())
            self.deleteslice(start, step, slicelength)
            return

        idx = space.getindex_w(w_idx, space.w_IndexError, "list index")
        if idx < 0:
            idx += self.length()
        try:
            self.pop(idx)
        except IndexError:
            raise OperationError(space.w_IndexError,
                                 space.wrap("list index out of range"))

    def descr_reversed(self, space):
        'L.__reversed__() -- return a reverse iterator over the list'
        return W_ReverseSeqIterObject(space, self, -1)

    def descr_reverse(self, space):
        'L.reverse() -- reverse *IN PLACE*'
        self.reverse()

    def descr_count(self, space, w_value):
        '''L.count(value) -> integer -- return number of
        occurrences of value'''
        # needs to be safe against eq_w() mutating the w_list behind our back
        count = 0
        i = 0
        while i < self.length():
            if space.eq_w(self.getitem(i), w_value):
                count += 1
            i += 1
        return space.wrap(count)

    @unwrap_spec(index=int)
    def descr_insert(self, space, index, w_value):
        'L.insert(index, object) -- insert object before index'
        length = self.length()
        index = get_positive_index(index, length)
        self.insert(index, w_value)

    @unwrap_spec(index=int)
    def descr_pop(self, space, index=-1):
        '''L.pop([index]) -> item -- remove and return item at
        index (default last)'''
        length = self.length()
        if length == 0:
            raise OperationError(space.w_IndexError,
                                 space.wrap("pop from empty list"))
        # clearly differentiate between list.pop() and list.pop(index)
        if index == -1:
            return self.pop_end()  # cannot raise because list is not empty
        if index < 0:
            index += length
        try:
            return self.pop(index)
        except IndexError:
            raise OperationError(space.w_IndexError,
                                 space.wrap("pop index out of range"))

    def descr_remove(self, space, w_value):
        'L.remove(value) -- remove first occurrence of value'
        # needs to be safe against eq_w() mutating the w_list behind our back
        try:
            i = self.find(w_value, 0, sys.maxint)
        except ValueError:
            raise OperationError(space.w_ValueError,
                                 space.wrap("list.remove(x): x not in list"))
        if i < self.length():  # otherwise list was mutated
            self.pop(i)

    @unwrap_spec(w_start=WrappedDefault(0), w_stop=WrappedDefault(sys.maxint))
    def descr_index(self, space, w_value, w_start, w_stop):
        '''L.index(value, [start, [stop]]) -> integer -- return
        first index of value'''
        # needs to be safe against eq_w() mutating the w_list behind our back
        size = self.length()
        i, stop = slicetype.unwrap_start_stop(
                space, size, w_start, w_stop, True)
        try:
            i = self.find(w_value, i, stop)
        except ValueError:
            raise OperationError(space.w_ValueError,
                                 space.wrap("list.index(x): x not in list"))
        return space.wrap(i)

    @unwrap_spec(reverse=bool)
    def descr_sort(self, space, w_key=None, reverse=False):
        """ L.sort(key=None, reverse=False) -- stable
        sort *IN PLACE*"""
        has_key = not space.is_none(w_key)

        # create and setup a TimSort instance
        if 0:
            # this was the old "if has_cmp" path. We didn't remove the
            # if not to diverge too much from default, to avoid spurious
            # conflicts
            pass
        else:
            if has_key:
                sorterclass = CustomKeySort
            else:
                if self.strategy is space.fromcache(ObjectListStrategy):
                    sorterclass = SimpleSort
                else:
                    self.sort(reverse)
                    return

        sorter = sorterclass(self.getitems(), self.length())
        sorter.space = space

        try:
            # The list is temporarily made empty, so that mutations performed
            # by comparison functions can't affect the slice of memory we're
            # sorting (allowing mutations during sorting is an IndexError or
            # core-dump factory, since the storage may change).
            self.__init__(space, [])

            # wrap each item in a KeyContainer if needed
            if has_key:
                for i in range(sorter.listlength):
                    w_item = sorter.list[i]
                    w_keyitem = space.call_function(w_key, w_item)
                    sorter.list[i] = KeyContainer(w_keyitem, w_item)

            # Reverse sort stability achieved by initially reversing the list,
            # applying a stable forward sort, then reversing the final result.
            if reverse:
                sorter.list.reverse()

            # perform the sort
            sorter.sort()

            # reverse again
            if reverse:
                sorter.list.reverse()

        finally:
            # unwrap each item if needed
            if has_key:
                for i in range(sorter.listlength):
                    w_obj = sorter.list[i]
                    if isinstance(w_obj, KeyContainer):
                        sorter.list[i] = w_obj.w_item

            # check if the user mucked with the list during the sort
            mucked = self.length() > 0

            # put the items back into the list
            self.__init__(space, sorter.list)

        if mucked:
            raise OperationError(space.w_ValueError,
                                 space.wrap("list modified during sort"))

find_jmp = jit.JitDriver(greens = [], reds = 'auto', name = 'list.find')

class ListStrategy(object):
    sizehint = -1

    def __init__(self, space):
        self.space = space

    def init_from_list_w(self, w_list, list_w):
        raise NotImplementedError

    def clone(self, w_list):
        raise NotImplementedError

    def copy_into(self, w_list, w_other):
        raise NotImplementedError

    def _resize_hint(self, w_list, hint):
        raise NotImplementedError

    def find(self, w_list, w_item, start, stop):
        space = self.space
        i = start
        # needs to be safe against eq_w mutating stuff
        while i < stop and i < w_list.length():
            find_jmp.jit_merge_point()
            if space.eq_w(w_list.getitem(i), w_item):
                return i
            i += 1
        raise ValueError

    def length(self, w_list):
        raise NotImplementedError

    def getitem(self, w_list, index):
        raise NotImplementedError

    def getslice(self, w_list, start, stop, step, length):
        raise NotImplementedError

    def getitems(self, w_list):
        return self.getitems_copy(w_list)

    def getitems_copy(self, w_list):
        raise NotImplementedError

    def getitems_str(self, w_list):
        return None

    def getitems_unicode(self, w_list):
        return None

    def getitems_int(self, w_list):
        return None

    def getstorage_copy(self, w_list):
        raise NotImplementedError

    def append(self, w_list, w_item):
        raise NotImplementedError

    def mul(self, w_list, times):
        w_newlist = w_list.clone()
        w_newlist.inplace_mul(times)
        return w_newlist

    def inplace_mul(self, w_list, times):
        raise NotImplementedError

    def deleteslice(self, w_list, start, step, slicelength):
        raise NotImplementedError

    def pop(self, w_list, index):
        raise NotImplementedError

    def pop_end(self, w_list):
        return self.pop(w_list, self.length(w_list) - 1)

    def setitem(self, w_list, index, w_item):
        raise NotImplementedError

    def setslice(self, w_list, start, step, slicelength, sequence_w):
        raise NotImplementedError

    def insert(self, w_list, index, w_item):
        raise NotImplementedError

    def extend(self, w_list, w_any):
        if type(w_any) is W_ListObject or (isinstance(w_any, W_ListObject) and
                                           self.space._uses_list_iter(w_any)):
            self._extend_from_list(w_list, w_any)
        elif isinstance(w_any, GeneratorIterator):
            w_any.unpack_into_w(w_list)
        else:
            self._extend_from_iterable(w_list, w_any)

    def _extend_from_list(self, w_list, w_other):
        raise NotImplementedError

    def _extend_from_iterable(self, w_list, w_iterable):
        """Extend w_list from a generic iterable"""
        length_hint = self.space.length_hint(w_iterable, 0)
        if length_hint:
            w_list._resize_hint(w_list.length() + length_hint)

        extended = _do_extend_from_iterable(self.space, w_list, w_iterable)

        # cut back if the length hint was too large
        if extended < length_hint:
            w_list._resize_hint(w_list.length())

    def reverse(self, w_list):
        raise NotImplementedError

    def sort(self, w_list, reverse):
        raise NotImplementedError

    def is_empty_strategy(self):
        return False


class EmptyListStrategy(ListStrategy):
    """EmptyListStrategy is used when a W_List withouth elements is created.
    The storage is None. When items are added to the W_List a new RPython list
    is created and the strategy and storage of the W_List are changed depending
    to the added item.
    W_Lists do not switch back to EmptyListStrategy when becoming empty again.
    """

    _applevel_repr = "empty"

    def __init__(self, space):
        ListStrategy.__init__(self, space)

    def init_from_list_w(self, w_list, list_w):
        assert len(list_w) == 0
        w_list.lstorage = self.erase(None)

    def clear(self, w_list):
        w_list.lstorage = self.erase(None)

    erase, unerase = rerased.new_erasing_pair("empty")
    erase = staticmethod(erase)
    unerase = staticmethod(unerase)

    def clone(self, w_list):
        return W_ListObject.from_storage_and_strategy(
                self.space, w_list.lstorage, self)

    def copy_into(self, w_list, w_other):
        pass

    def _resize_hint(self, w_list, hint):
        assert hint >= 0
        if hint:
            w_list.strategy = SizeListStrategy(self.space, hint)

    def find(self, w_list, w_item, start, stop):
        raise ValueError

    def length(self, w_list):
        return 0

    def getitem(self, w_list, index):
        raise IndexError

    def getslice(self, w_list, start, stop, step, length):
        # will never be called because the empty list case is already caught in
        # getslice__List_ANY_ANY and getitem__List_Slice
        return W_ListObject(self.space, [])

    def getitems(self, w_list):
        return []

    def getitems_copy(self, w_list):
        return []
    getitems_fixedsize = func_with_new_name(getitems_copy,
                                            "getitems_fixedsize")
    getitems_unroll = getitems_fixedsize

    def getstorage_copy(self, w_list):
        return self.erase(None)

    def switch_to_correct_strategy(self, w_list, w_item):
        if type(w_item) is W_IntObject:
            strategy = self.space.fromcache(IntegerListStrategy)
        #elif type(w_item) is W_StringObject:
        #    strategy = self.space.fromcache(StringListStrategy)
        elif type(w_item) is W_UnicodeObject:
            strategy = self.space.fromcache(UnicodeListStrategy)
        elif type(w_item) is W_FloatObject:
            strategy = self.space.fromcache(FloatListStrategy)
        else:
            strategy = self.space.fromcache(ObjectListStrategy)

        storage = strategy.get_empty_storage(self.sizehint)
        w_list.strategy = strategy
        w_list.lstorage = storage

    def append(self, w_list, w_item):
        self.switch_to_correct_strategy(w_list, w_item)
        w_list.append(w_item)

    def inplace_mul(self, w_list, times):
        return

    def deleteslice(self, w_list, start, step, slicelength):
        pass

    def pop(self, w_list, index):
        # will not be called because IndexError was already raised in
        # list_pop__List_ANY
        raise IndexError

    def setitem(self, w_list, index, w_item):
        raise IndexError

    def setslice(self, w_list, start, step, slicelength, w_other):
        strategy = w_other.strategy
        storage = strategy.getstorage_copy(w_other)
        w_list.strategy = strategy
        w_list.lstorage = storage

    def sort(self, w_list, reverse):
        return

    def insert(self, w_list, index, w_item):
        assert index == 0
        self.append(w_list, w_item)

    def _extend_from_list(self, w_list, w_other):
        w_other.copy_into(w_list)

    def _extend_from_iterable(self, w_list, w_iterable):
        space = self.space
        if isinstance(w_iterable, W_AbstractTupleObject):
            w_list.__init__(space, w_iterable.getitems_copy())
            return

        intlist = space.listview_int(w_iterable)
        if intlist is not None:
            w_list.strategy = strategy = space.fromcache(IntegerListStrategy)
            # need to copy because intlist can share with w_iterable
            w_list.lstorage = strategy.erase(intlist[:])
            return

        # XXX: listview_str works for bytes but not for strings, and the
        # strategy works for strings but not for bytes. Disable it for now,
        # but we'll need to fix it
        ##strlist = space.listview_str(w_iterable)
        ##if strlist is not None:
        ##    w_list.strategy = strategy = space.fromcache(StringListStrategy)
        ##    # need to copy because intlist can share with w_iterable
        ##    w_list.lstorage = strategy.erase(strlist[:])
        ##    return

        unilist = space.listview_unicode(w_iterable)
        if unilist is not None:
            w_list.strategy = strategy = space.fromcache(UnicodeListStrategy)
            # need to copy because intlist can share with w_iterable
            w_list.lstorage = strategy.erase(unilist[:])
            return

        ListStrategy._extend_from_iterable(self, w_list, w_iterable)

    def reverse(self, w_list):
        pass

    def is_empty_strategy(self):
        return True


class SizeListStrategy(EmptyListStrategy):
    """Like empty, but when modified it'll preallocate the size to sizehint."""
    def __init__(self, space, sizehint):
        self.sizehint = sizehint
        ListStrategy.__init__(self, space)

    def _resize_hint(self, w_list, hint):
        assert hint >= 0
        self.sizehint = hint


class RangeListStrategy(ListStrategy):
    """RangeListStrategy is used when a list is created using the range method.
    The storage is a tuple containing only three integers start, step and
    length and elements are calculated based on these values.  On any operation
    destroying the range (inserting, appending non-ints) the strategy is
    switched to IntegerListStrategy."""

    _applevel_repr = "range"

    def switch_to_integer_strategy(self, w_list):
        items = self._getitems_range(w_list, False)
        strategy = w_list.strategy = self.space.fromcache(IntegerListStrategy)
        w_list.lstorage = strategy.erase(items)

    def wrap(self, intval):
        return self.space.wrap(intval)

    def unwrap(self, w_int):
        return self.space.int_w(w_int)

    def init_from_list_w(self, w_list, list_w):
        raise NotImplementedError

    erase, unerase = rerased.new_erasing_pair("range")
    erase = staticmethod(erase)
    unerase = staticmethod(unerase)

    def clone(self, w_list):
        storage = w_list.lstorage  # lstorage is tuple, no need to clone
        w_clone = W_ListObject.from_storage_and_strategy(self.space, storage,
                                                         self)
        return w_clone

    def _resize_hint(self, w_list, hint):
        # XXX: this could be supported
        assert hint >= 0

    def copy_into(self, w_list, w_other):
        w_other.strategy = self
        w_other.lstorage = w_list.lstorage

    def find(self, w_list, w_obj, startindex, stopindex):
        if type(w_obj) is W_IntObject:
            obj = self.unwrap(w_obj)
            start, step, length = self.unerase(w_list.lstorage)
            if ((step > 0 and start <= obj <= start + (length - 1) * step and
                 (start - obj) % step == 0) or
                (step < 0 and start + (length - 1) * step <= obj <= start and
                 (start - obj) % step == 0)):
                index = (obj - start) // step
            else:
                raise ValueError
            if startindex <= index < stopindex:
                return index
            raise ValueError
        return ListStrategy.find(self, w_list, w_obj, startindex, stopindex)

    def length(self, w_list):
        return self.unerase(w_list.lstorage)[2]

    def _getitem_unwrapped(self, w_list, i):
        v = self.unerase(w_list.lstorage)
        start = v[0]
        step = v[1]
        length = v[2]
        if i < 0:
            i += length
            if i < 0:
                raise IndexError
        elif i >= length:
            raise IndexError
        return start + i * step

    def getitems_int(self, w_list):
        return self._getitems_range(w_list, False)

    def getitem(self, w_list, i):
        return self.wrap(self._getitem_unwrapped(w_list, i))

    def getitems_copy(self, w_list):
        return self._getitems_range(w_list, True)

    def getstorage_copy(self, w_list):
        # tuple is unmutable
        return w_list.lstorage

    @specialize.arg(2)
    def _getitems_range(self, w_list, wrap_items):
        l = self.unerase(w_list.lstorage)
        start = l[0]
        step = l[1]
        length = l[2]
        if wrap_items:
            r = [None] * length
        else:
            r = [0] * length
        i = start
        n = 0
        while n < length:
            if wrap_items:
                r[n] = self.wrap(i)
            else:
                r[n] = i
            i += step
            n += 1

        return r

    @jit.dont_look_inside
    def getitems_fixedsize(self, w_list):
        return self._getitems_range_unroll(w_list, True)

    def getitems_unroll(self, w_list):
        return self._getitems_range_unroll(w_list, True)
    _getitems_range_unroll = jit.unroll_safe(
            func_with_new_name(_getitems_range, "_getitems_range_unroll"))

    def getslice(self, w_list, start, stop, step, length):
        self.switch_to_integer_strategy(w_list)
        return w_list.getslice(start, stop, step, length)

    def append(self, w_list, w_item):
        if type(w_item) is W_IntObject:
            self.switch_to_integer_strategy(w_list)
        else:
            w_list.switch_to_object_strategy()
        w_list.append(w_item)

    def inplace_mul(self, w_list, times):
        self.switch_to_integer_strategy(w_list)
        w_list.inplace_mul(times)

    def deleteslice(self, w_list, start, step, slicelength):
        self.switch_to_integer_strategy(w_list)
        w_list.deleteslice(start, step, slicelength)

    def pop_end(self, w_list):
        start, step, length = self.unerase(w_list.lstorage)
        w_result = self.wrap(start + (length - 1) * step)
        new = self.erase((start, step, length - 1))
        w_list.lstorage = new
        return w_result

    def pop(self, w_list, index):
        l = self.unerase(w_list.lstorage)
        start = l[0]
        step = l[1]
        length = l[2]
        if index == 0:
            w_result = self.wrap(start)
            new = self.erase((start + step, step, length - 1))
            w_list.lstorage = new
            return w_result
        elif index == length - 1:
            return self.pop_end(w_list)
        else:
            self.switch_to_integer_strategy(w_list)
            return w_list.pop(index)

    def setitem(self, w_list, index, w_item):
        self.switch_to_integer_strategy(w_list)
        w_list.setitem(index, w_item)

    def setslice(self, w_list, start, step, slicelength, sequence_w):
        self.switch_to_integer_strategy(w_list)
        w_list.setslice(start, step, slicelength, sequence_w)

    def sort(self, w_list, reverse):
        step = self.unerase(w_list.lstorage)[1]
        if step > 0 and reverse or step < 0 and not reverse:
            self.switch_to_integer_strategy(w_list)
            w_list.sort(reverse)

    def insert(self, w_list, index, w_item):
        self.switch_to_integer_strategy(w_list)
        w_list.insert(index, w_item)

    def extend(self, w_list, w_any):
        self.switch_to_integer_strategy(w_list)
        w_list.extend(w_any)

    def reverse(self, w_list):
        self.switch_to_integer_strategy(w_list)
        w_list.reverse()


class AbstractUnwrappedStrategy(object):
    _mixin_ = True

    def wrap(self, unwrapped):
        raise NotImplementedError

    def unwrap(self, wrapped):
        raise NotImplementedError

    @staticmethod
    def unerase(storage):
        raise NotImplementedError("abstract base class")

    @staticmethod
    def erase(obj):
        raise NotImplementedError("abstract base class")

    def is_correct_type(self, w_obj):
        raise NotImplementedError("abstract base class")

    def list_is_correct_type(self, w_list):
        raise NotImplementedError("abstract base class")

    @jit.look_inside_iff(lambda space, w_list, list_w:
            jit.loop_unrolling_heuristic(list_w, len(list_w), UNROLL_CUTOFF))
    def init_from_list_w(self, w_list, list_w):
        l = [self.unwrap(w_item) for w_item in list_w]
        w_list.lstorage = self.erase(l)

    def get_empty_storage(self, sizehint):
        if sizehint == -1:
            return self.erase([])
        return self.erase(newlist_hint(sizehint))

    def clone(self, w_list):
        l = self.unerase(w_list.lstorage)
        storage = self.erase(l[:])
        w_clone = W_ListObject.from_storage_and_strategy(
                self.space, storage, self)
        return w_clone

    def _resize_hint(self, w_list, hint):
        resizelist_hint(self.unerase(w_list.lstorage), hint)

    def copy_into(self, w_list, w_other):
        w_other.strategy = self
        items = self.unerase(w_list.lstorage)[:]
        w_other.lstorage = self.erase(items)

    def find(self, w_list, w_obj, start, stop):
        if self.is_correct_type(w_obj):
            return self._safe_find(w_list, self.unwrap(w_obj), start, stop)
        return ListStrategy.find(self, w_list, w_obj, start, stop)

    def _safe_find(self, w_list, obj, start, stop):
        l = self.unerase(w_list.lstorage)
        for i in range(start, min(stop, len(l))):
            val = l[i]
            if val == obj:
                return i
        raise ValueError

    def length(self, w_list):
        return len(self.unerase(w_list.lstorage))

    def getitem(self, w_list, index):
        l = self.unerase(w_list.lstorage)
        try:
            r = l[index]
        except IndexError:  # make RPython raise the exception
            raise
        return self.wrap(r)

    @jit.look_inside_iff(lambda self, w_list:
            jit.loop_unrolling_heuristic(w_list, w_list.length(),
                                         UNROLL_CUTOFF))
    def getitems_copy(self, w_list):
        return [self.wrap(item) for item in self.unerase(w_list.lstorage)]

    @jit.unroll_safe
    def getitems_unroll(self, w_list):
        return [self.wrap(item) for item in self.unerase(w_list.lstorage)]

    @jit.look_inside_iff(lambda self, w_list:
            jit.loop_unrolling_heuristic(w_list, w_list.length(),
                                         UNROLL_CUTOFF))
    def getitems_fixedsize(self, w_list):
        return self.getitems_unroll(w_list)

    def getstorage_copy(self, w_list):
        items = self.unerase(w_list.lstorage)[:]
        return self.erase(items)

    def getslice(self, w_list, start, stop, step, length):
        if step == 1 and 0 <= start <= stop:
            l = self.unerase(w_list.lstorage)
            assert start >= 0
            assert stop >= 0
            sublist = l[start:stop]
            storage = self.erase(sublist)
            return W_ListObject.from_storage_and_strategy(
                    self.space, storage, self)
        else:
            subitems_w = [self._none_value] * length
            l = self.unerase(w_list.lstorage)
            for i in range(length):
                try:
                    subitems_w[i] = l[start]
                    start += step
                except IndexError:
                    raise
            storage = self.erase(subitems_w)
            return W_ListObject.from_storage_and_strategy(
                    self.space, storage, self)

    def append(self, w_list, w_item):
        if self.is_correct_type(w_item):
            self.unerase(w_list.lstorage).append(self.unwrap(w_item))
            return

        w_list.switch_to_object_strategy()
        w_list.append(w_item)

    def insert(self, w_list, index, w_item):
        l = self.unerase(w_list.lstorage)

        if self.is_correct_type(w_item):
            l.insert(index, self.unwrap(w_item))
            return

        w_list.switch_to_object_strategy()
        w_list.insert(index, w_item)

    def _extend_from_list(self, w_list, w_other):
        l = self.unerase(w_list.lstorage)
        if self.list_is_correct_type(w_other):
            l += self.unerase(w_other.lstorage)
            return
        elif w_other.strategy.is_empty_strategy():
            return

        w_other = w_other._temporarily_as_objects()
        w_list.switch_to_object_strategy()
        w_list.extend(w_other)

    def setitem(self, w_list, index, w_item):
        l = self.unerase(w_list.lstorage)

        if self.is_correct_type(w_item):
            try:
                l[index] = self.unwrap(w_item)
            except IndexError:
                raise
            return

        w_list.switch_to_object_strategy()
        w_list.setitem(index, w_item)

    def setslice(self, w_list, start, step, slicelength, w_other):
        assert slicelength >= 0
        items = self.unerase(w_list.lstorage)

        if self is self.space.fromcache(ObjectListStrategy):
            w_other = w_other._temporarily_as_objects()
        elif not self.list_is_correct_type(w_other) and w_other.length() != 0:
            w_list.switch_to_object_strategy()
            w_other_as_object = w_other._temporarily_as_objects()
            assert (w_other_as_object.strategy is
                    self.space.fromcache(ObjectListStrategy))
            w_list.setslice(start, step, slicelength, w_other_as_object)
            return

        oldsize = len(items)
        len2 = w_other.length()
        if step == 1:  # Support list resizing for non-extended slices
            delta = slicelength - len2
            if delta < 0:
                delta = -delta
                newsize = oldsize + delta
                # XXX support this in rlist!
                items += [self._none_value] * delta
                lim = start + len2
                i = newsize - 1
                while i >= lim:
                    items[i] = items[i - delta]
                    i -= 1
            elif delta == 0:
                pass
            else:
                # start < 0 is only possible with slicelength == 0
                assert start >= 0
                del items[start:start + delta]
        elif len2 != slicelength:  # No resize for extended slices
            raise operationerrfmt(self.space.w_ValueError, "attempt to "
                  "assign sequence of size %d to extended slice of size %d",
                  len2, slicelength)

        if len2 == 0:
            other_items = []
        else:
            # at this point both w_list and w_other have the same type, so
            # self.unerase is valid for both of them
            other_items = self.unerase(w_other.lstorage)
        if other_items is items:
            if step > 0:
                # Always copy starting from the right to avoid
                # having to make a shallow copy in the case where
                # the source and destination lists are the same list.
                i = len2 - 1
                start += i * step
                while i >= 0:
                    items[start] = other_items[i]
                    start -= step
                    i -= 1
                return
            else:
                # Make a shallow copy to more easily handle the reversal case
                w_list.reverse()
                return
                #other_items = list(other_items)
        for i in range(len2):
            items[start] = other_items[i]
            start += step

    def deleteslice(self, w_list, start, step, slicelength):
        items = self.unerase(w_list.lstorage)
        if slicelength == 0:
            return

        if step < 0:
            start = start + step * (slicelength - 1)
            step = -step

        if step == 1:
            assert start >= 0
            if slicelength > 0:
                del items[start:start + slicelength]
        else:
            n = len(items)
            i = start

            for discard in range(1, slicelength):
                j = i + 1
                i += step
                while j < i:
                    items[j - discard] = items[j]
                    j += 1

            j = i + 1
            while j < n:
                items[j - slicelength] = items[j]
                j += 1
            start = n - slicelength
            assert start >= 0  # annotator hint
            del items[start:]

    def pop_end(self, w_list):
        l = self.unerase(w_list.lstorage)
        return self.wrap(l.pop())

    def pop(self, w_list, index):
        l = self.unerase(w_list.lstorage)
        # not sure if RPython raises IndexError on pop
        # so check again here
        if index < 0:
            raise IndexError
        try:
            item = l.pop(index)
        except IndexError:
            raise

        w_item = self.wrap(item)
        return w_item

    def mul(self, w_list, times):
        l = self.unerase(w_list.lstorage)
        return W_ListObject.from_storage_and_strategy(
            self.space, self.erase(l * times), self)

    def inplace_mul(self, w_list, times):
        l = self.unerase(w_list.lstorage)
        l *= times

    def reverse(self, w_list):
        self.unerase(w_list.lstorage).reverse()


class ObjectListStrategy(AbstractUnwrappedStrategy, ListStrategy):
    _none_value = None
    _applevel_repr = "object"

    def unwrap(self, w_obj):
        return w_obj

    def wrap(self, item):
        return item

    erase, unerase = rerased.new_erasing_pair("object")
    erase = staticmethod(erase)
    unerase = staticmethod(unerase)

    def is_correct_type(self, w_obj):
        return True

    def list_is_correct_type(self, w_list):
        return w_list.strategy is self.space.fromcache(ObjectListStrategy)

    def init_from_list_w(self, w_list, list_w):
        w_list.lstorage = self.erase(list_w)

    def clear(self, w_list):
        w_list.lstorage = self.erase([])

    def find(self, w_list, w_obj, start, stop):
        return ListStrategy.find(self, w_list, w_obj, start, stop)

    def getitems(self, w_list):
        return self.unerase(w_list.lstorage)


class IntegerListStrategy(AbstractUnwrappedStrategy, ListStrategy):
    _none_value = 0
    _applevel_repr = "int"

    def wrap(self, intval):
        return self.space.wrap(intval)

    def unwrap(self, w_int):
        return self.space.int_w(w_int)

    erase, unerase = rerased.new_erasing_pair("integer")
    erase = staticmethod(erase)
    unerase = staticmethod(unerase)

    def is_correct_type(self, w_obj):
        return type(w_obj) is W_IntObject

    def list_is_correct_type(self, w_list):
        return w_list.strategy is self.space.fromcache(IntegerListStrategy)

    def sort(self, w_list, reverse):
        l = self.unerase(w_list.lstorage)
        sorter = IntSort(l, len(l))
        sorter.sort()
        if reverse:
            l.reverse()

    def getitems_int(self, w_list):
        return self.unerase(w_list.lstorage)


class FloatListStrategy(AbstractUnwrappedStrategy, ListStrategy):
    _none_value = 0.0
    _applevel_repr = "float"

    def wrap(self, floatval):
        return self.space.wrap(floatval)

    def unwrap(self, w_float):
        return self.space.float_w(w_float)

    erase, unerase = rerased.new_erasing_pair("float")
    erase = staticmethod(erase)
    unerase = staticmethod(unerase)

    def is_correct_type(self, w_obj):
        return type(w_obj) is W_FloatObject

    def list_is_correct_type(self, w_list):
        return w_list.strategy is self.space.fromcache(FloatListStrategy)

    def sort(self, w_list, reverse):
        l = self.unerase(w_list.lstorage)
        sorter = FloatSort(l, len(l))
        sorter.sort()
        if reverse:
            l.reverse()


class StringListStrategy(AbstractUnwrappedStrategy, ListStrategy):
    _none_value = None
    _applevel_repr = "str"

    def wrap(self, stringval):
        return self.space.wrapbytes(stringval)

    def unwrap(self, w_string):
        return self.space.str_w(w_string)

    erase, unerase = rerased.new_erasing_pair("string")
    erase = staticmethod(erase)
    unerase = staticmethod(unerase)

    def is_correct_type(self, w_obj):
        return type(w_obj) is W_StringObject

    def list_is_correct_type(self, w_list):
        return w_list.strategy is self.space.fromcache(StringListStrategy)

    def sort(self, w_list, reverse):
        l = self.unerase(w_list.lstorage)
        sorter = StringSort(l, len(l))
        sorter.sort()
        if reverse:
            l.reverse()

    def getitems_str(self, w_list):
        return self.unerase(w_list.lstorage)


class UnicodeListStrategy(AbstractUnwrappedStrategy, ListStrategy):
    _none_value = None
    _applevel_repr = "unicode"

    def wrap(self, stringval):
        return self.space.wrap(stringval)

    def unwrap(self, w_string):
        return self.space.unicode_w(w_string)

    erase, unerase = rerased.new_erasing_pair("unicode")
    erase = staticmethod(erase)
    unerase = staticmethod(unerase)

    def is_correct_type(self, w_obj):
        return type(w_obj) is W_UnicodeObject

    def list_is_correct_type(self, w_list):
        return w_list.strategy is self.space.fromcache(UnicodeListStrategy)

    def sort(self, w_list, reverse):
        l = self.unerase(w_list.lstorage)
        sorter = UnicodeSort(l, len(l))
        sorter.sort()
        if reverse:
            l.reverse()

    def getitems_unicode(self, w_list):
        return self.unerase(w_list.lstorage)

# _______________________________________________________

init_signature = Signature(['sequence'], None, None)
init_defaults = [None]

app = applevel("""
    def listrepr(currently_in_repr, l):
        'The app-level part of repr().'
        list_id = id(l)
        if list_id in currently_in_repr:
            return '[...]'
        currently_in_repr[list_id] = 1
        try:
            return "[" + ", ".join([repr(x) for x in l]) + ']'
        finally:
            try:
                del currently_in_repr[list_id]
            except:
                pass
""", filename=__file__)

listrepr = app.interphook("listrepr")

# ____________________________________________________________
# Sorting

# Reverse a slice of a list in place, from lo up to (exclusive) hi.
# (used in sort)

TimSort = make_timsort_class()
IntBaseTimSort = make_timsort_class()
FloatBaseTimSort = make_timsort_class()
StringBaseTimSort = make_timsort_class()
UnicodeBaseTimSort = make_timsort_class()


class KeyContainer(W_Root):
    def __init__(self, w_key, w_item):
        self.w_key = w_key
        self.w_item = w_item


# NOTE: all the subclasses of TimSort should inherit from a common subclass,
#       so make sure that only SimpleSort inherits directly from TimSort.
#       This is necessary to hide the parent method TimSort.lt() from the
#       annotator.
class SimpleSort(TimSort):
    def lt(self, a, b):
        space = self.space
        return space.is_true(space.lt(a, b))


class IntSort(IntBaseTimSort):
    def lt(self, a, b):
        return a < b


class FloatSort(FloatBaseTimSort):
    def lt(self, a, b):
        return a < b

class StringSort(UnicodeBaseTimSort):
    def lt(self, a, b):
        return a < b


class UnicodeSort(UnicodeBaseTimSort):
    def lt(self, a, b):
        return a < b


class CustomCompareSort(SimpleSort):
    def lt(self, a, b):
        space = self.space
        w_cmp = self.w_cmp
        w_result = space.call_function(w_cmp, a, b)
        try:
            result = space.int_w(w_result)
        except OperationError, e:
            if e.match(space, space.w_TypeError):
                raise OperationError(space.w_TypeError,
                    space.wrap("comparison function must return int"))
            raise
        return result < 0


class CustomKeySort(SimpleSort):
    def lt(self, a, b):
        assert isinstance(a, KeyContainer)
        assert isinstance(b, KeyContainer)
        space = self.space
        return space.is_true(space.lt(a.w_key, b.w_key))


W_ListObject.typedef = StdTypeDef("list",
    __doc__ = """list() -> new list
list(sequence) -> new list initialized from sequence's items""",
    __new__ = interp2app(W_ListObject.descr_new),
    __init__ = interp2app(W_ListObject.descr_init),
    __repr__ = interp2app(W_ListObject.descr_repr),
    __hash__ = None,

    __eq__ = interp2app(W_ListObject.descr_eq),
    __ne__ = interp2app(W_ListObject.descr_ne),
    __lt__ = interp2app(W_ListObject.descr_lt),
    __le__ = interp2app(W_ListObject.descr_le),
    __gt__ = interp2app(W_ListObject.descr_gt),
    __ge__ = interp2app(W_ListObject.descr_ge),

    __len__ = interp2app(W_ListObject.descr_len),
    __iter__ = interp2app(W_ListObject.descr_iter),
    __contains__ = interp2app(W_ListObject.descr_contains),

    __add__ = interp2app(W_ListObject.descr_add),
    __iadd__ = interp2app(W_ListObject.descr_inplace_add),
    __mul__ = interp2app(W_ListObject.descr_mul),
    __rmul__ = interp2app(W_ListObject.descr_mul),
    __imul__ = interp2app(W_ListObject.descr_inplace_mul),

    __getitem__ = interp2app(W_ListObject.descr_getitem),
    __setitem__ = interp2app(W_ListObject.descr_setitem),
    __delitem__ = interp2app(W_ListObject.descr_delitem),

    sort = interp2app(W_ListObject.descr_sort),
    index = interp2app(W_ListObject.descr_index),
    append = interp2app(W_ListObject.append),
    reverse = interp2app(W_ListObject.descr_reverse),
    __reversed__ = interp2app(W_ListObject.descr_reversed),
    count = interp2app(W_ListObject.descr_count),
    pop = interp2app(W_ListObject.descr_pop),
    extend = interp2app(W_ListObject.extend),
    insert = interp2app(W_ListObject.descr_insert),
    remove = interp2app(W_ListObject.descr_remove),
)
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.