list.cpp 46.6 KB
Newer Older
Marius Wachtler's avatar
Marius Wachtler committed
1
// Copyright (c) 2014-2016 Dropbox, Inc.
Kevin Modzelewski's avatar
Kevin Modzelewski committed
2
//
Kevin Modzelewski's avatar
Kevin Modzelewski committed
3 4 5
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
Kevin Modzelewski's avatar
Kevin Modzelewski committed
6
//
Kevin Modzelewski's avatar
Kevin Modzelewski committed
7
//    http://www.apache.org/licenses/LICENSE-2.0
Kevin Modzelewski's avatar
Kevin Modzelewski committed
8
//
Kevin Modzelewski's avatar
Kevin Modzelewski committed
9 10 11 12 13 14
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

15 16 17
#include "runtime/list.h"

#include <algorithm>
Kevin Modzelewski's avatar
Kevin Modzelewski committed
18
#include <cstring>
19

20
#include "capi/types.h"
21
#include "core/ast.h"
Kevin Modzelewski's avatar
Kevin Modzelewski committed
22 23 24
#include "core/common.h"
#include "core/stats.h"
#include "core/types.h"
25
#include "runtime/inline/list.h"
Kevin Modzelewski's avatar
Kevin Modzelewski committed
26 27 28 29 30 31
#include "runtime/objmodel.h"
#include "runtime/types.h"
#include "runtime/util.h"

namespace pyston {

32 33
static int list_ass_slice(PyListObject* a, Py_ssize_t ilow, Py_ssize_t ihigh, PyObject* v);

34
extern "C" int PyList_Append(PyObject* op, PyObject* newitem) noexcept {
35
    RELEASE_ASSERT(PyList_Check(op), "");
36
    try {
37
        listAppendInternal(op, newitem);
38
    } catch (ExcInfo e) {
39 40 41 42 43
        abort();
    }
    return 0;
}

44 45 46 47 48 49
extern "C" PyObject** PyList_Items(PyObject* op) noexcept {
    RELEASE_ASSERT(PyList_Check(op), "");

    return &static_cast<BoxedList*>(op)->elts->elts[0];
}

50 51 52 53 54 55 56 57 58 59
extern "C" PyObject* PyList_AsTuple(PyObject* v) noexcept {
    PyObject* w;
    PyObject** p, **q;
    Py_ssize_t n;
    if (v == NULL || !PyList_Check(v)) {
        PyErr_BadInternalCall();
        return NULL;
    }

    auto l = static_cast<BoxedList*>(v);
60
    return BoxedTuple::create(l->size, &l->elts->elts[0]);
61 62
}

Kevin Modzelewski's avatar
Kevin Modzelewski committed
63
extern "C" Box* listRepr(BoxedList* self) {
64 65
    std::vector<char> chars;
    int status = Py_ReprEnter((PyObject*)self);
66

67
    if (status != 0) {
68 69 70
        if (status < 0)
            throwCAPIException();

71
        chars.push_back('[');
72 73 74
        chars.push_back('.');
        chars.push_back('.');
        chars.push_back('.');
75 76
        chars.push_back(']');
        return boxString(llvm::StringRef(&chars[0], chars.size()));
Dong-hee,Na's avatar
Dong-hee,Na committed
77
    }
78 79 80 81 82 83 84 85 86 87 88 89
    try {
        chars.push_back('[');
        for (int i = 0; i < self->size; i++) {

            if (i > 0) {
                chars.push_back(',');
                chars.push_back(' ');
            }
            Box* r = self->elts->elts[i]->reprICAsString();
            assert(r->cls == str_cls);
            BoxedString* s = static_cast<BoxedString*>(r);
            chars.insert(chars.end(), s->s().begin(), s->s().end());
Kevin Modzelewski's avatar
Kevin Modzelewski committed
90
            Py_DECREF(s);
91
        }
92 93 94 95
        chars.push_back(']');
    } catch (ExcInfo e) {
        Py_ReprLeave((PyObject*)self);
        throw e;
Kevin Modzelewski's avatar
Kevin Modzelewski committed
96
    }
Dong-hee,Na's avatar
Dong-hee,Na committed
97
    Py_ReprLeave((PyObject*)self);
98
    return boxString(llvm::StringRef(&chars[0], chars.size()));
Kevin Modzelewski's avatar
Kevin Modzelewski committed
99 100 101 102 103 104
}

extern "C" Box* listNonzero(BoxedList* self) {
    return boxBool(self->size != 0);
}

105 106 107 108 109
extern "C" Box* listPop(BoxedList* self, Box* idx) {
    if (idx == None) {
        if (self->size == 0) {
            raiseExcHelper(IndexError, "pop from empty list");
        }
Kevin Modzelewski's avatar
Kevin Modzelewski committed
110

111 112 113 114
        self->size--;
        Box* rtn = self->elts->elts[self->size];
        return rtn;
    }
Kevin Modzelewski's avatar
Kevin Modzelewski committed
115

116 117
    int64_t n = PyInt_AsSsize_t(idx);
    if (n == -1 && PyErr_Occurred())
Kevin Modzelewski's avatar
Kevin Modzelewski committed
118
        throwCAPIException();
Kevin Modzelewski's avatar
Kevin Modzelewski committed
119 120 121 122 123 124

    if (n < 0)
        n = self->size + n;

    if (n < 0 || n >= self->size) {
        if (self->size == 0)
125
            raiseExcHelper(IndexError, "pop from empty list");
Kevin Modzelewski's avatar
Kevin Modzelewski committed
126
        else
127
            raiseExcHelper(IndexError, "pop index out of range");
Kevin Modzelewski's avatar
Kevin Modzelewski committed
128 129 130 131 132 133 134 135 136
    }

    Box* rtn = self->elts->elts[n];
    memmove(self->elts->elts + n, self->elts->elts + n + 1, (self->size - n - 1) * sizeof(Box*));
    self->size--;

    return rtn;
}

137
extern "C" Py_ssize_t PyList_Size(PyObject* self) noexcept {
138
    RELEASE_ASSERT(PyList_Check(self), "");
139 140 141
    return static_cast<BoxedList*>(self)->size;
}

Kevin Modzelewski's avatar
Kevin Modzelewski committed
142
extern "C" Box* listLen(BoxedList* self) {
143
    assert(PyList_Check(self));
144
    return boxInt(self->size);
Kevin Modzelewski's avatar
Kevin Modzelewski committed
145 146
}

147 148 149 150
static Py_ssize_t list_length(Box* self) noexcept {
    return static_cast<BoxedList*>(self)->size;
}

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
static PyObject* list_concat(PyListObject* a, PyObject* bb) noexcept {
    Py_ssize_t size;
    Py_ssize_t i;
    PyObject** src, **dest;
    PyListObject* np;
    if (!PyList_Check(bb)) {
        PyErr_Format(PyExc_TypeError, "can only concatenate list (not \"%.200s\") to list", bb->cls->tp_name);
        return NULL;
    }
#define b ((PyListObject*)bb)
    size = Py_SIZE(a) + Py_SIZE(b);
    if (size < 0)
        return PyErr_NoMemory();
    np = (PyListObject*)PyList_New(size);
    if (np == NULL) {
        return NULL;
    }
    src = a->ob_item;
    dest = np->ob_item;
    for (i = 0; i < Py_SIZE(a); i++) {
        PyObject* v = src[i];
        Py_INCREF(v);
        dest[i] = v;
    }
    src = b->ob_item;
    dest = np->ob_item + Py_SIZE(a);
    for (i = 0; i < Py_SIZE(b); i++) {
        PyObject* v = src[i];
        Py_INCREF(v);
        dest[i] = v;
    }
    return (PyObject*)np;
#undef b
}


Marius Wachtler's avatar
Marius Wachtler committed
187
Box* _listSlice(BoxedList* self, i64 start, i64 stop, i64 step, i64 length) {
Kevin Modzelewski's avatar
Kevin Modzelewski committed
188 189 190 191 192 193 194 195 196
    assert(step != 0);
    if (step > 0) {
        assert(0 <= start);
        assert(stop <= self->size);
    } else {
        assert(start < self->size);
        assert(-1 <= stop);
    }

197
    BoxedList* rtn = new BoxedList();
Marius Wachtler's avatar
Marius Wachtler committed
198 199 200
    if (length > 0) {
        rtn->ensure(length);
        copySlice(&rtn->elts->elts[0], &self->elts->elts[0], start, step, length);
201 202 203
        for (int i = 0; i < length; i++) {
            Py_INCREF(rtn->elts->elts[i]);
        }
Marius Wachtler's avatar
Marius Wachtler committed
204
        rtn->size += length;
Kevin Modzelewski's avatar
Kevin Modzelewski committed
205 206 207 208
    }
    return rtn;
}

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
static Box* list_slice(Box* o, Py_ssize_t ilow, Py_ssize_t ihigh) noexcept {
    BoxedList* a = static_cast<BoxedList*>(o);

    PyObject** src, **dest;
    Py_ssize_t i, len;
    if (ilow < 0)
        ilow = 0;
    else if (ilow > Py_SIZE(a))
        ilow = Py_SIZE(a);
    if (ihigh < ilow)
        ihigh = ilow;
    else if (ihigh > Py_SIZE(a))
        ihigh = Py_SIZE(a);
    len = ihigh - ilow;

    BoxedList* np = new BoxedList();

    np->ensure(len);
    if (len) {
        src = a->elts->elts + ilow;
        dest = np->elts->elts;
        for (i = 0; i < len; i++) {
            PyObject* v = src[i];
            Py_INCREF(v);
            dest[i] = v;
        }
    }
    np->size = len;

    return (PyObject*)np;
}

241
static inline BORROWED(Box*) listGetitemUnboxed(BoxedList* self, int64_t n) {
242
    assert(PyList_Check(self));
243 244 245 246
    if (n < 0)
        n = self->size + n;

    if (n < 0 || n >= self->size) {
247
        raiseExcHelper(IndexError, "list index out of range");
248 249 250 251 252
    }
    Box* rtn = self->elts->elts[n];
    return rtn;
}

253
extern "C" Box* listGetitemInt(BoxedList* self, BoxedInt* slice) {
254
    assert(PyInt_Check(slice));
255
    return incref(listGetitemUnboxed(self, slice->n));
256 257
}

258
extern "C" BORROWED(PyObject*) PyList_GetItem(PyObject* op, Py_ssize_t i) noexcept {
259 260 261 262
    RELEASE_ASSERT(PyList_Check(op), "");
    RELEASE_ASSERT(i >= 0, ""); // unlike list.__getitem__, PyList_GetItem doesn't do index wrapping
    try {
        return listGetitemUnboxed(static_cast<BoxedList*>(op), i);
263
    } catch (ExcInfo e) {
264 265 266 267
        abort();
    }
}

268 269 270 271 272 273 274 275 276 277
template <ExceptionStyle S> Box* listGetitemSlice(BoxedList* self, BoxedSlice* slice) {
    if (S == CAPI) {
        try {
            return listGetitemSlice<CXX>(self, slice);
        } catch (ExcInfo e) {
            setCAPIException(e);
            return NULL;
        }
    }

278
    assert(PyList_Check(self));
279
    assert(slice->cls == slice_cls);
Marius Wachtler's avatar
Marius Wachtler committed
280 281 282
    i64 start, stop, step, length;
    parseSlice(slice, self->size, &start, &stop, &step, &length);
    return _listSlice(self, start, stop, step, length);
283 284
}

285
extern "C" Box* listGetslice(BoxedList* self, Box* boxedStart, Box* boxedStop) {
286
    assert(PyList_Check(self));
287 288 289 290 291 292 293 294
    i64 start, stop, step;
    sliceIndex(boxedStart, &start);
    sliceIndex(boxedStop, &stop);

    boundSliceWithLength(&start, &stop, start, stop, self->size);
    return _listSlice(self, start, stop, 1, stop - start);
}

295 296 297 298
// Analoguous to CPython's, used for sq_ slots.
static PyObject* list_item(PyListObject* a, Py_ssize_t i) noexcept {
    try {
        BoxedList* self = (BoxedList*)a;
299
        return incref(listGetitemUnboxed(self, i));
300 301 302 303 304 305
    } catch (ExcInfo e) {
        setCAPIException(e);
        return NULL;
    }
}

306 307 308 309 310 311 312 313 314 315
template <ExceptionStyle S> Box* listGetitem(BoxedList* self, Box* slice) {
    if (S == CAPI) {
        try {
            return listGetitem<CXX>(self, slice);
        } catch (ExcInfo e) {
            setCAPIException(e);
            return NULL;
        }
    }

316
    assert(PyList_Check(self));
317 318 319 320
    if (PyIndex_Check(slice)) {
        Py_ssize_t i = PyNumber_AsSsize_t(slice, PyExc_IndexError);
        if (i == -1 && PyErr_Occurred())
            throwCAPIException();
321
        return incref(listGetitemUnboxed(self, i));
Kevin Modzelewski's avatar
Kevin Modzelewski committed
322
    } else if (slice->cls == slice_cls) {
323
        return listGetitemSlice<CXX>(self, static_cast<BoxedSlice*>(slice));
Kevin Modzelewski's avatar
Kevin Modzelewski committed
324
    } else {
325
        raiseExcHelper(TypeError, "list indices must be integers, not %s", getTypeName(slice));
Kevin Modzelewski's avatar
Kevin Modzelewski committed
326 327 328
    }
}

Kevin Modzelewski's avatar
Kevin Modzelewski committed
329 330 331 332 333 334 335 336
static void _listSetitem(BoxedList* self, int64_t n, Box* v) {
    if (n < 0)
        n = self->size + n;

    if (n < 0 || n >= self->size) {
        raiseExcHelper(IndexError, "list index out of range");
    }

337 338
    Py_INCREF(v);
    Box* prev = self->elts->elts[n];
Kevin Modzelewski's avatar
Kevin Modzelewski committed
339
    self->elts->elts[n] = v;
340
    Py_DECREF(prev);
Kevin Modzelewski's avatar
Kevin Modzelewski committed
341
}
Kevin Modzelewski's avatar
Kevin Modzelewski committed
342

343
extern "C" Box* listSetitemUnboxed(BoxedList* self, int64_t n, Box* v) {
344
    assert(PyList_Check(self));
Kevin Modzelewski's avatar
Kevin Modzelewski committed
345
    _listSetitem(self, n, v);
346
    Py_RETURN_NONE;
347
}
Kevin Modzelewski's avatar
Kevin Modzelewski committed
348

349
extern "C" Box* listSetitemInt(BoxedList* self, BoxedInt* slice, Box* v) {
350
    assert(PyInt_Check(slice));
351 352 353
    return listSetitemUnboxed(self, slice->n, v);
}

354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369
// Analoguous to CPython's, used for sq_ slots.
static int list_ass_item(PyListObject* a, Py_ssize_t i, PyObject* v) {
    PyObject* old_value;
    if (i < 0 || i >= Py_SIZE(a)) {
        PyErr_SetString(PyExc_IndexError, "list assignment index out of range");
        return -1;
    }
    if (v == NULL)
        return list_ass_slice(a, i, i + 1, v);
    Py_INCREF(v);
    old_value = a->ob_item[i];
    a->ob_item[i] = v;
    Py_DECREF(old_value);
    return 0;
}

Kevin Modzelewski's avatar
Kevin Modzelewski committed
370
extern "C" int PyList_SetItem(PyObject* op, Py_ssize_t i, PyObject* newitem) noexcept {
371 372 373 374 375 376 377 378 379 380 381
    PyObject* olditem;
    PyObject** p;
    if (!PyList_Check(op)) {
        Py_XDECREF(newitem);
        PyErr_BadInternalCall();
        return -1;
    }
    if (i < 0 || i >= Py_SIZE(op)) {
        Py_XDECREF(newitem);
        PyErr_SetString(PyExc_IndexError, "list assignment index out of range");
        return -1;
Kevin Modzelewski's avatar
Kevin Modzelewski committed
382
    }
383 384 385 386
    p = ((PyListObject*)op)->ob_item + i;
    olditem = *p;
    *p = newitem;
    Py_XDECREF(olditem);
Kevin Modzelewski's avatar
Kevin Modzelewski committed
387 388 389
    return 0;
}

390 391
Box* listIAdd(BoxedList* self, Box* _rhs);

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
// Copied from CPython's list_ass_subscript
int list_ass_ext_slice(BoxedList* self, PyObject* item, PyObject* value) {
    Py_ssize_t start, stop, step, slicelength;

    if (PySlice_GetIndicesEx((PySliceObject*)item, Py_SIZE(self), &start, &stop, &step, &slicelength) < 0) {
        return -1;
    }

    RELEASE_ASSERT(step != 1, "should have handled this elsewhere");

    /* Make sure s[5:2] = [..] inserts at the right place:
       before 5, not before 2. */
    if ((step < 0 && start < stop) || (step > 0 && start > stop))
        stop = start;

    if (value == NULL) {
        /* delete slice */
        PyObject** garbage;
        size_t cur;
        Py_ssize_t i;

        if (slicelength <= 0)
            return 0;

        if (step < 0) {
            stop = start + 1;
            start = stop + step * (slicelength - 1) - 1;
            step = -step;
        }

        assert((size_t)slicelength <= PY_SIZE_MAX / sizeof(PyObject*));

        garbage = (PyObject**)PyMem_MALLOC(slicelength * sizeof(PyObject*));
        if (!garbage) {
            PyErr_NoMemory();
            return -1;
        }

        /* drawing pictures might help understand these for
           loops. Basically, we memmove the parts of the
           list that are *not* part of the slice: step-1
           items for each item that is part of the slice,
           and then tail end of the list that was not
           covered by the slice */
        for (cur = start, i = 0; cur < (size_t)stop; cur += step, i++) {
            Py_ssize_t lim = step - 1;

            garbage[i] = PyList_GET_ITEM(self, cur);

            if (cur + step >= self->size) {
                lim = self->size - cur - 1;
            }

            memmove(self->elts->elts + cur - i, self->elts->elts + cur + 1, lim * sizeof(PyObject*));
        }
        cur = start + slicelength * step;
        if (cur < self->size) {
            memmove(self->elts->elts + cur - slicelength, self->elts->elts + cur,
                    (self->size - cur) * sizeof(PyObject*));
        }

        self->size -= slicelength;

        // list_resize(self, Py_SIZE(self));

        for (i = 0; i < slicelength; i++) {
            Py_DECREF(garbage[i]);
        }
        PyMem_FREE(garbage);

        return 0;
    } else {
        /* assign slice */
        PyObject* ins, *seq;
        PyObject** garbage, **seqitems, **selfitems;
        Py_ssize_t cur, i;

        /* protect against a[::-1] = a */
        if (self == value) {
471
            seq = list_slice(value, 0, PyList_GET_SIZE(value));
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
        } else {
            seq = PySequence_Fast(value, "must assign iterable "
                                         "to extended slice");
        }
        if (!seq)
            return -1;

        if (PySequence_Fast_GET_SIZE(seq) != slicelength) {
            PyErr_Format(PyExc_ValueError, "attempt to assign sequence of "
                                           "size %zd to extended slice of "
                                           "size %zd",
                         PySequence_Fast_GET_SIZE(seq), slicelength);
            Py_DECREF(seq);
            return -1;
        }

        if (!slicelength) {
            Py_DECREF(seq);
            return 0;
        }

        garbage = (PyObject**)PyMem_MALLOC(slicelength * sizeof(PyObject*));
        if (!garbage) {
            Py_DECREF(seq);
            PyErr_NoMemory();
            return -1;
        }

        selfitems = self->elts->elts;
        seqitems = PySequence_Fast_ITEMS(seq);
        for (cur = start, i = 0; i < slicelength; cur += step, i++) {
            garbage[i] = selfitems[cur];
            ins = seqitems[i];
            Py_INCREF(ins);
            selfitems[cur] = ins;
        }

        for (i = 0; i < slicelength; i++) {
            Py_DECREF(garbage[i]);
        }

        PyMem_FREE(garbage);
        Py_DECREF(seq);

        return 0;
    }
}

520
static inline void listSetitemSliceInt64(BoxedList* self, i64 start, i64 stop, i64 step, Box* v) {
Rudi Chen's avatar
Rudi Chen committed
521
    RELEASE_ASSERT(step == 1, "step sizes must be 1 in this code path");
522

523
    boundSliceWithLength(&start, &stop, start, stop, self->size);
524

525 526 527
    size_t v_size;
    Box** v_elts;

Kevin Modzelewski's avatar
Kevin Modzelewski committed
528
    Box* v_as_seq = nullptr;
529 530 531
    if (!v) {
        v_size = 0;
        v_elts = NULL;
532
    } else {
533 534 535 536 537
        if (self == v) { // handle self assignment by creating a copy
            v_as_seq = _listSlice(self, 0, self->size, 1, self->size);
            assert(v_as_seq->cls == list_cls);
        } else
            v_as_seq = PySequence_Fast(v, "can only assign an iterable");
538 539 540
        if (v_as_seq == NULL)
            throwCAPIException();

541
        v_size = PySequence_Fast_GET_SIZE((Box*)v_as_seq);
Kevin Modzelewski's avatar
Kevin Modzelewski committed
542 543
        // If lv->size is 0, lv->elts->elts is garbage
        if (v_size)
544
            v_elts = PySequence_Fast_ITEMS((Box*)v_as_seq);
Kevin Modzelewski's avatar
Kevin Modzelewski committed
545 546
        else
            v_elts = NULL;
547
    }
548

549
    int delts = v_size - (stop - start);
550 551 552
    int remaining_elts = self->size - stop;
    self->ensure(delts);

Kevin Modzelewski's avatar
Kevin Modzelewski committed
553 554 555 556 557
    Box** removed_elts = NULL;
    if (stop > start) {
        removed_elts = (Box**)PyMem_MALLOC((stop - start) * sizeof(Box*));
        RELEASE_ASSERT(removed_elts, "");
        memcpy(removed_elts, self->elts->elts + start, (stop - start) * sizeof(Box*));
Kevin Modzelewski's avatar
Kevin Modzelewski committed
558 559
    }

560 561 562
    memmove(self->elts->elts + start + v_size, self->elts->elts + stop, remaining_elts * sizeof(Box*));
    for (int i = 0; i < v_size; i++) {
        Box* r = v_elts[i];
563
        Py_XINCREF(r);
564 565
        self->elts->elts[start + i] = r;
    }
Kevin Modzelewski's avatar
Kevin Modzelewski committed
566

567
    self->size += delts;
Kevin Modzelewski's avatar
Kevin Modzelewski committed
568

Kevin Modzelewski's avatar
Kevin Modzelewski committed
569
    for (int i = 0; i < stop - start; i++) {
570
        Py_XDECREF(removed_elts[i]);
Kevin Modzelewski's avatar
Kevin Modzelewski committed
571 572 573 574
    }
    if (removed_elts)
        PyMem_FREE(removed_elts);

Kevin Modzelewski's avatar
Kevin Modzelewski committed
575
    Py_XDECREF(v_as_seq);
576
}
Kevin Modzelewski's avatar
Kevin Modzelewski committed
577

578
extern "C" Box* listSetitemSlice(BoxedList* self, BoxedSlice* slice, Box* v) {
579
    assert(PyList_Check(self));
580 581 582 583 584 585 586 587
    assert(slice->cls == slice_cls);

    i64 start = 0, stop = self->size, step = 1;

    sliceIndex(slice->start, &start);
    sliceIndex(slice->stop, &stop);
    sliceIndex(slice->step, &step);

Rudi Chen's avatar
Rudi Chen committed
588 589
    adjustNegativeIndicesOnObject(self, &start, &stop);

590 591 592 593
    if (step != 1) {
        int r = list_ass_ext_slice(self, slice, v);
        if (r)
            throwCAPIException();
594
        Py_RETURN_NONE;
595 596
    }

597
    listSetitemSliceInt64(self, start, stop, step, v);
598
    Py_RETURN_NONE;
599 600 601 602 603 604
}

// Analoguous to CPython's, used for sq_ slots.
static int list_ass_slice(PyListObject* a, Py_ssize_t ilow, Py_ssize_t ihigh, PyObject* v) {
    listSetitemSliceInt64((BoxedList*)a, ilow, ihigh, 1, v);
    return 0;
605 606 607 608 609 610 611 612 613 614
}

extern "C" Box* listSetslice(BoxedList* self, Box* boxedStart, Box* boxedStop, Box** args) {
    Box* value = args[0];

    i64 start = 0, stop = self->size;

    sliceIndex(boxedStart, &start);
    sliceIndex(boxedStop, &stop);

615
    listSetitemSliceInt64(self, start, stop, 1, value);
616
    Py_RETURN_NONE;
617 618
}

619
extern "C" Box* listSetitem(BoxedList* self, Box* slice, Box* v) {
620
    assert(PyList_Check(self));
621 622 623 624
    if (PyIndex_Check(slice)) {
        Py_ssize_t i = PyNumber_AsSsize_t(slice, PyExc_IndexError);
        if (i == -1 && PyErr_Occurred())
            throwCAPIException();
Kevin Modzelewski's avatar
Kevin Modzelewski committed
625
        _listSetitem(self, i, v);
626
        Py_RETURN_NONE;
627 628
    } else if (slice->cls == slice_cls) {
        return listSetitemSlice(self, static_cast<BoxedSlice*>(slice), v);
Kevin Modzelewski's avatar
Kevin Modzelewski committed
629
    } else {
630
        raiseExcHelper(TypeError, "list indices must be integers, not %s", getTypeName(slice));
Kevin Modzelewski's avatar
Kevin Modzelewski committed
631 632 633
    }
}

634 635 636 637 638 639 640 641
extern "C" Box* listDelitemInt(BoxedList* self, BoxedInt* slice) {
    int64_t n = slice->n;
    if (n < 0)
        n = self->size + n;

    if (n < 0 || n >= self->size) {
        raiseExcHelper(IndexError, "list index out of range");
    }
642
    Box* e = self->elts->elts[n];
643 644
    memmove(self->elts->elts + n, self->elts->elts + n + 1, (self->size - n - 1) * sizeof(Box*));
    self->size--;
645
    Py_DECREF(e);
646
    Py_RETURN_NONE;
647 648 649
}

extern "C" Box* listDelitemSlice(BoxedList* self, BoxedSlice* slice) {
650
    return listSetitemSlice(self, slice, NULL);
651 652
}

653 654 655 656 657
extern "C" Box* listDelslice(BoxedList* self, Box* start, Box* stop) {
    Box* args = { NULL };
    return listSetslice(self, start, stop, &args);
}

658 659
extern "C" Box* listDelitem(BoxedList* self, Box* slice) {
    Box* rtn;
660 661 662 663
    if (PyIndex_Check(slice)) {
        Py_ssize_t i = PyNumber_AsSsize_t(slice, PyExc_IndexError);
        if (i == -1 && PyErr_Occurred())
            throwCAPIException();
664
        rtn = listDelitemInt(self, (BoxedInt*)autoDecref(boxInt(i)));
665 666 667
    } else if (slice->cls == slice_cls) {
        rtn = listDelitemSlice(self, static_cast<BoxedSlice*>(slice));
    } else {
668
        raiseExcHelper(TypeError, "list indices must be integers, not %s", getTypeName(slice));
669 670 671 672 673
    }
    self->shrink();
    return rtn;
}

Kevin Modzelewski's avatar
Kevin Modzelewski committed
674 675
extern "C" Box* listInsert(BoxedList* self, Box* idx, Box* v) {
    if (idx->cls != int_cls) {
676
        raiseExcHelper(TypeError, "an integer is required");
Kevin Modzelewski's avatar
Kevin Modzelewski committed
677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693
    }

    int64_t n = static_cast<BoxedInt*>(idx)->n;
    if (n < 0)
        n = self->size + n;

    if (n >= self->size) {
        listAppendInternal(self, v);
    } else {
        if (n < 0)
            n = 0;
        assert(0 <= n && n < self->size);

        self->ensure(1);
        memmove(self->elts->elts + n + 1, self->elts->elts + n, (self->size - n) * sizeof(Box*));

        self->size++;
694
        Py_INCREF(v);
Kevin Modzelewski's avatar
Kevin Modzelewski committed
695 696 697
        self->elts->elts[n] = v;
    }

698
    Py_RETURN_NONE;
Kevin Modzelewski's avatar
Kevin Modzelewski committed
699 700
}

701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718
extern "C" int PyList_Insert(PyObject* op, Py_ssize_t where, PyObject* newitem) noexcept {
    try {
        if (!PyList_Check(op)) {
            PyErr_BadInternalCall();
            return -1;
        }
        if (newitem == NULL) {
            PyErr_BadInternalCall();
            return -1;
        }
        listInsert((BoxedList*)op, boxInt(where), newitem);
        return 0;
    } catch (ExcInfo e) {
        setCAPIException(e);
        return -1;
    }
}

Kevin Modzelewski's avatar
Kevin Modzelewski committed
719
Box* listMul(BoxedList* self, Box* rhs) {
720
    Py_ssize_t n;
721

722 723 724 725 726
    if (PyIndex_Check(rhs)) {
        n = PyNumber_AsSsize_t(rhs, PyExc_OverflowError);
        if (n == -1 && PyErr_Occurred())
            throwCAPIException();
    } else {
727
        return incref(NotImplemented);
728
    }
Kevin Modzelewski's avatar
Kevin Modzelewski committed
729 730 731 732

    int s = self->size;

    BoxedList* rtn = new BoxedList();
733
    rtn->ensure(n * s);
734
    if (s == 1) {
735
        for (long i = 0; i < n; i++) {
736 737 738
            listAppendInternal(rtn, self->elts->elts[0]);
        }
    } else {
739
        for (long i = 0; i < n; i++) {
740
            listAppendArrayInternal(rtn, &self->elts->elts[0], s);
Kevin Modzelewski's avatar
Kevin Modzelewski committed
741 742
        }
    }
743

Kevin Modzelewski's avatar
Kevin Modzelewski committed
744 745 746
    return rtn;
}

747
Box* listImul(BoxedList* self, Box* rhs) {
748
    Py_ssize_t n;
749

750 751 752 753 754
    if (PyIndex_Check(rhs)) {
        n = PyNumber_AsSsize_t(rhs, PyExc_OverflowError);
        if (n == -1 && PyErr_Occurred())
            throwCAPIException();
    } else {
755
        return incref(NotImplemented);
756
    }
757 758 759 760 761 762 763

    int s = self->size;

    self->ensure(n * s);
    if (n == 0) {
        listSetitemSliceInt64(self, 0, s, 1, NULL);
    } else if (n == 1) {
764
        return incref(self);
765 766 767 768 769 770 771 772 773 774
    } else if (s == 1) {
        for (long i = 1; i < n; i++) {
            listAppendInternal(self, self->elts->elts[0]);
        }
    } else {
        for (long i = 1; i < n; i++) {
            listAppendArrayInternal(self, &self->elts->elts[0], s);
        }
    }

775
    return incref(self);
776 777
}

778
Box* listIAdd(BoxedList* self, Box* _rhs) {
Kevin Modzelewski's avatar
Kevin Modzelewski committed
779 780 781
    if (_rhs->cls == list_cls) {
        // This branch is safe if self==rhs:
        BoxedList* rhs = static_cast<BoxedList*>(_rhs);
782

Kevin Modzelewski's avatar
Kevin Modzelewski committed
783 784
        int s1 = self->size;
        int s2 = rhs->size;
785

Kevin Modzelewski's avatar
Kevin Modzelewski committed
786
        if (s2 == 0) {
787
            return incref(self);
Kevin Modzelewski's avatar
Kevin Modzelewski committed
788
        }
789

Kevin Modzelewski's avatar
Kevin Modzelewski committed
790 791 792 793
        self->ensure(s1 + s2);

        memcpy(self->elts->elts + s1, rhs->elts->elts, sizeof(rhs->elts->elts[0]) * s2);
        self->size = s1 + s2;
Kevin Modzelewski's avatar
Kevin Modzelewski committed
794 795 796
        for (int i = 0; i < s2; i++) {
            Py_INCREF(self->elts->elts[i + s1]);
        }
Kevin Modzelewski's avatar
Kevin Modzelewski committed
797

798
        return incref(self);
Kevin Modzelewski's avatar
Kevin Modzelewski committed
799 800
    }

Marius Wachtler's avatar
Marius Wachtler committed
801 802 803 804 805 806
    if (_rhs->cls == tuple_cls) {
        BoxedTuple* rhs = static_cast<BoxedTuple*>(_rhs);

        int s1 = self->size;
        int s2 = rhs->ob_size;

Kevin Modzelewski's avatar
Kevin Modzelewski committed
807
        if (s2 == 0) {
808
            return incref(self);
Kevin Modzelewski's avatar
Kevin Modzelewski committed
809
        }
Marius Wachtler's avatar
Marius Wachtler committed
810 811 812 813 814

        self->ensure(s1 + s2);

        memcpy(self->elts->elts + s1, rhs->elts, sizeof(self->elts->elts[0]) * s2);
        self->size = s1 + s2;
Kevin Modzelewski's avatar
Kevin Modzelewski committed
815 816 817
        for (int i = 0; i < s2; i++) {
            Py_INCREF(self->elts->elts[i + s1]);
        }
Kevin Modzelewski's avatar
Kevin Modzelewski committed
818

819
        return incref(self);
Marius Wachtler's avatar
Marius Wachtler committed
820 821
    }

Kevin Modzelewski's avatar
Kevin Modzelewski committed
822 823 824
    RELEASE_ASSERT(_rhs != self, "unsupported");

    for (auto* b : _rhs->pyElements())
825
        listAppendInternalStolen(self, b);
826

827
    return incref(self);
828 829
}

Marius Wachtler's avatar
Marius Wachtler committed
830
Box* listExtend(BoxedList* self, Box* _rhs) {
831 832
    autoDecref(listIAdd(self, _rhs));
    return incref(None);
Marius Wachtler's avatar
Marius Wachtler committed
833 834
}

835
Box* listAdd(BoxedList* self, Box* _rhs) {
Kevin Modzelewski's avatar
Kevin Modzelewski committed
836
    if (!PyList_Check(_rhs)) {
837
        return incref(NotImplemented);
838
        raiseExcHelper(TypeError, "can only concatenate list (not \"%s\") to list", getTypeName(_rhs));
839 840 841 842 843 844 845 846 847 848 849 850 851
    }

    BoxedList* rhs = static_cast<BoxedList*>(_rhs);

    BoxedList* rtn = new BoxedList();

    int s1 = self->size;
    int s2 = rhs->size;
    rtn->ensure(s1 + s2);

    memcpy(rtn->elts->elts, self->elts->elts, sizeof(self->elts->elts[0]) * s1);
    memcpy(rtn->elts->elts + s1, rhs->elts->elts, sizeof(rhs->elts->elts[0]) * s2);
    rtn->size = s1 + s2;
852 853 854
    for (int i = 0; i < s1 + s2; i++) {
        Py_INCREF(rtn->elts->elts[i]);
    }
855 856 857
    return rtn;
}

858
Box* listReverse(BoxedList* self) {
859
    assert(PyList_Check(self));
860 861 862 863 864 865
    for (int i = 0, j = self->size - 1; i < j; i++, j--) {
        Box* e = self->elts->elts[i];
        self->elts->elts[i] = self->elts->elts[j];
        self->elts->elts[j] = e;
    }

866
    Py_RETURN_NONE;
867 868
}

869 870 871 872 873 874 875
extern "C" int PyList_Reverse(PyObject* v) noexcept {
    if (v == NULL || !PyList_Check(v)) {
        PyErr_BadInternalCall();
        return -1;
    }

    try {
876
        autoDecref(listReverse(static_cast<BoxedList*>(v)));
877 878 879 880 881 882 883
    } catch (ExcInfo e) {
        setCAPIException(e);
        return -1;
    }
    return 0;
}

Kevin Modzelewski's avatar
Kevin Modzelewski committed
884 885 886 887 888 889 890
class PyCmpComparer {
private:
    Box* cmp;

public:
    PyCmpComparer(Box* cmp) : cmp(cmp) {}
    bool operator()(Box* lhs, Box* rhs) {
891
        Box* r = runtimeCallInternal<CXX, NOT_REWRITABLE>(cmp, NULL, ArgPassSpec(2), lhs, rhs, NULL, NULL, NULL);
892
        AUTO_DECREF(r);
893
        if (!PyInt_Check(r))
Kevin Modzelewski's avatar
Kevin Modzelewski committed
894 895 896 897 898
            raiseExcHelper(TypeError, "comparison function must return int, not %.200s", r->cls->tp_name);
        return static_cast<BoxedInt*>(r)->n < 0;
    }
};

Kevin Modzelewski's avatar
Kevin Modzelewski committed
899
void _sortArray(Box** elts, long num_elts, Box* cmp, Box* key) {
Kevin Modzelewski's avatar
Cleanup  
Kevin Modzelewski committed
900 901 902 903 904
    // TODO(kmod): maybe we should just switch to CPython's sort.  not sure how the algorithms compare,
    // but they specifically try to support cases where __lt__ or the cmp function might end up inspecting
    // the current list being sorted.
    // I also don't know if std::stable_sort is exception-safe.

Kevin Modzelewski's avatar
Kevin Modzelewski committed
905
    if (cmp) {
Kevin Modzelewski's avatar
Kevin Modzelewski committed
906
        assert(!key);
Kevin Modzelewski's avatar
Kevin Modzelewski committed
907
        std::stable_sort<Box**, PyCmpComparer>(elts, elts + num_elts, PyCmpComparer(cmp));
Kevin Modzelewski's avatar
Kevin Modzelewski committed
908 909 910 911
    } else {
        int num_keys_added = 0;
        auto remove_keys = [&]() {
            for (int i = 0; i < num_keys_added; i++) {
Kevin Modzelewski's avatar
Kevin Modzelewski committed
912
                Box** obj_loc = &elts[i];
Kevin Modzelewski's avatar
Kevin Modzelewski committed
913
                assert((*obj_loc)->cls == tuple_cls);
Kevin Modzelewski's avatar
Kevin Modzelewski committed
914 915 916
                BoxedTuple* t = static_cast<BoxedTuple*>(*obj_loc);
                *obj_loc = t->elts[2];
                Py_DECREF(t);
Kevin Modzelewski's avatar
Kevin Modzelewski committed
917 918 919 920 921
            }
        };

        try {
            if (key) {
Kevin Modzelewski's avatar
Kevin Modzelewski committed
922 923
                for (int i = 0; i < num_elts; i++) {
                    Box** obj_loc = &elts[i];
Kevin Modzelewski's avatar
Kevin Modzelewski committed
924 925

                    Box* key_val = runtimeCall(key, ArgPassSpec(1), *obj_loc, NULL, NULL, NULL, NULL);
Kevin Modzelewski's avatar
Kevin Modzelewski committed
926 927
                    AUTO_DECREF(key_val);

Kevin Modzelewski's avatar
Kevin Modzelewski committed
928 929 930 931
                    // Add the index as part of the new tuple so that the comparison never hits the
                    // original object.
                    // TODO we could potentially make this faster by copying the CPython approach of
                    // creating special sortwrapper objects that compare only based on the key.
Kevin Modzelewski's avatar
Kevin Modzelewski committed
932
                    Box* new_obj = BoxedTuple::create({ key_val, autoDecref(boxInt(i)), *obj_loc });
Kevin Modzelewski's avatar
Kevin Modzelewski committed
933 934 935 936

                    *obj_loc = new_obj;
                    num_keys_added++;
                }
937
            }
Kevin Modzelewski's avatar
Kevin Modzelewski committed
938 939 940 941 942

            // We don't need to do a stable sort if there's a keyfunc, since we explicitly added the index
            // as part of the sort key.
            // But we might want to get rid of that approach?  CPython doesn't do that (they create special
            // wrapper objects that compare only based on the key).
Kevin Modzelewski's avatar
Kevin Modzelewski committed
943
            std::stable_sort<Box**, PyLt>(elts, elts + num_elts, PyLt());
Kevin Modzelewski's avatar
Kevin Modzelewski committed
944 945
        } catch (ExcInfo e) {
            remove_keys();
946
            throw e;
947
        }
Kevin Modzelewski's avatar
Kevin Modzelewski committed
948

949 950
        remove_keys();
    }
Kevin Modzelewski's avatar
Kevin Modzelewski committed
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
}

void listSort(BoxedList* self, Box* cmp, Box* key, Box* reverse) {
    assert(PyList_Check(self));

    if (cmp == None)
        cmp = NULL;

    if (key == None)
        key = NULL;

    RELEASE_ASSERT(!cmp || !key, "Specifying both the 'cmp' and 'key' keywords is currently not supported");

    auto orig_size = self->size;
    auto orig_elts = self->elts;

    self->elts = new (0) GCdArray();
    self->size = 0;

    try {
        _sortArray(orig_elts->elts, orig_size, cmp, key);
    } catch (ExcInfo e) {
        delete self->elts;
        self->elts = orig_elts;
        self->size = orig_size;
        throw e;
    }

    delete self->elts;
    self->elts = orig_elts;
    self->size = orig_size;
982 983

    if (nonzero(reverse)) {
Kevin Modzelewski's avatar
Kevin Modzelewski committed
984 985
        Box* r = listReverse(self);
        Py_DECREF(r);
986 987 988 989 990 991
    }
}

Box* listSortFunc(BoxedList* self, Box* cmp, Box* key, Box** _args) {
    Box* reverse = _args[0];
    listSort(self, cmp, key, reverse);
992
    Py_RETURN_NONE;
Kevin Modzelewski's avatar
Kevin Modzelewski committed
993 994
}

995 996 997 998 999 1000 1001
extern "C" int PyList_Sort(PyObject* v) noexcept {
    if (v == NULL || !PyList_Check(v)) {
        PyErr_BadInternalCall();
        return -1;
    }

    try {
1002
        listSort((BoxedList*)v, None, None, False);
1003 1004 1005 1006 1007 1008 1009 1010
    } catch (ExcInfo e) {
        setCAPIException(e);
        return -1;
    }

    return 0;
}

1011
extern "C" Box* PyList_GetSlice(PyObject* a, Py_ssize_t ilow, Py_ssize_t ihigh) noexcept {
1012
    assert(PyList_Check(a));
1013
    BoxedList* self = static_cast<BoxedList*>(a);
1014
    // Lots of extra copies here; we can do better if we need to:
1015 1016
    return listGetitemSlice<CAPI>(
        self, autoDecref(new BoxedSlice(autoDecref(boxInt(ilow)), autoDecref(boxInt(ihigh)), autoDecref(boxInt(1)))));
1017 1018
}

1019
static inline int listContainsShared(BoxedList* self, Box* elt) {
1020
    assert(PyList_Check(self));
1021

1022 1023 1024
    int size = self->size;
    for (int i = 0; i < size; i++) {
        Box* e = self->elts->elts[i];
1025

Bob Fang's avatar
Bob Fang committed
1026
        bool identity_eq = e == elt;
Bob Fang's avatar
Bob Fang committed
1027
        if (identity_eq)
1028
            return true;
1029

1030 1031 1032 1033 1034
        int r = PyObject_RichCompareBool(e, elt, Py_EQ);
        if (r == -1)
            throwCAPIException();

        if (r)
1035
            return true;
1036
    }
1037 1038 1039
    return false;
}

1040
static int list_contains(PyListObject* a, PyObject* el) noexcept {
1041 1042 1043 1044 1045 1046
    try {
        return listContainsShared((BoxedList*)a, el);
    } catch (ExcInfo e) {
        setCAPIException(e);
        return -1;
    }
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
static PyObject* list_repeat(PyListObject* a, Py_ssize_t n) noexcept {
    Py_ssize_t i, j;
    Py_ssize_t size;
    PyListObject* np;
    PyObject** p, **items;
    PyObject* elem;
    if (n < 0)
        n = 0;
    if (n > 0 && Py_SIZE(a) > PY_SSIZE_T_MAX / n)
        return PyErr_NoMemory();
    size = Py_SIZE(a) * n;
    if (size == 0)
        return PyList_New(0);
    np = (PyListObject*)PyList_New(size);
    if (np == NULL)
        return NULL;

    items = np->ob_item;
    if (Py_SIZE(a) == 1) {
        elem = a->ob_item[0];
        for (i = 0; i < n; i++) {
            items[i] = elem;
            Py_INCREF(elem);
        }
        return (PyObject*)np;
    }
    p = np->ob_item;
    items = a->ob_item;
    for (i = 0; i < n; i++) {
        for (j = 0; j < Py_SIZE(a); j++) {
            *p = items[j];
            Py_INCREF(*p);
            p++;
        }
    }
    return (PyObject*)np;
}

1087
Box* listContains(BoxedList* self, Box* elt) {
1088
    return boxBool(listContainsShared(self, elt));
1089 1090
}

1091
Box* listCount(BoxedList* self, Box* elt) {
Leandro Lameiro's avatar
Leandro Lameiro committed
1092 1093 1094 1095 1096
    int size = self->size;
    int count = 0;

    for (int i = 0; i < size; i++) {
        Box* e = self->elts->elts[i];
1097 1098 1099 1100 1101 1102

        int r = PyObject_RichCompareBool(e, elt, Py_EQ);
        if (r == -1)
            throwCAPIException();

        if (r)
Leandro Lameiro's avatar
Leandro Lameiro committed
1103 1104
            count++;
    }
1105
    return boxInt(count);
Leandro Lameiro's avatar
Leandro Lameiro committed
1106
}
1107

1108 1109
Box* listIndex(BoxedList* self, Box* elt, Box* _start, Box** args) {
    Box* _stop = (BoxedInt*)args[0];
Krzysztof Klinikowski's avatar
Krzysztof Klinikowski committed
1110

1111 1112 1113 1114 1115 1116 1117
    int64_t start = 0;
    int64_t stop = self->size;

    if (!_PyEval_SliceIndex(_start, &start))
        throwCAPIException();
    if (!_PyEval_SliceIndex(_stop, &stop))
        throwCAPIException();
1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129

    if (start < 0) {
        start += self->size;
        if (start < 0)
            start = 0;
    }

    if (stop < 0) {
        stop += self->size;
        if (stop < 0)
            stop = 0;
    }
1130
    stop = std::min(stop, self->size);
1131 1132

    for (int64_t i = start; i < stop; i++) {
Krzysztof Klinikowski's avatar
Krzysztof Klinikowski committed
1133
        Box* e = self->elts->elts[i];
1134 1135 1136 1137 1138 1139

        int r = PyObject_RichCompareBool(e, elt, Py_EQ);
        if (r == -1)
            throwCAPIException();

        if (r)
1140
            return boxInt(i);
Krzysztof Klinikowski's avatar
Krzysztof Klinikowski committed
1141 1142 1143
    }

    BoxedString* tostr = static_cast<BoxedString*>(repr(elt));
1144
    raiseExcHelper(ValueError, "%s is not in list", autoDecref(tostr)->data());
Krzysztof Klinikowski's avatar
Krzysztof Klinikowski committed
1145 1146
}

Kevin Modzelewski's avatar
Kevin Modzelewski committed
1147
Box* listRemove(BoxedList* self, Box* elt) {
1148
    assert(PyList_Check(self));
Kevin Modzelewski's avatar
Kevin Modzelewski committed
1149 1150 1151 1152

    for (int i = 0; i < self->size; i++) {
        Box* e = self->elts->elts[i];

1153 1154 1155 1156 1157
        int r = PyObject_RichCompareBool(e, elt, Py_EQ);
        if (r == -1)
            throwCAPIException();

        if (r) {
Kevin Modzelewski's avatar
Kevin Modzelewski committed
1158 1159
            memmove(self->elts->elts + i, self->elts->elts + i + 1, (self->size - i - 1) * sizeof(Box*));
            self->size--;
1160
            Py_DECREF(e);
1161
            Py_RETURN_NONE;
Kevin Modzelewski's avatar
Kevin Modzelewski committed
1162 1163 1164 1165 1166 1167
        }
    }

    raiseExcHelper(ValueError, "list.remove(x): x not in list");
}

1168
BoxedClass* list_iterator_cls = NULL;
1169 1170
BoxedClass* list_reverse_iterator_cls = NULL;

1171
Box* listInit(BoxedList* self, Box* container) {
1172
    assert(PyList_Check(self));
Kevin Modzelewski's avatar
Kevin Modzelewski committed
1173

1174
    if (container) {
Kevin Modzelewski's avatar
Kevin Modzelewski committed
1175 1176
        Box* r = listIAdd(self, container);
        Py_DECREF(r);
Kevin Modzelewski's avatar
Kevin Modzelewski committed
1177
    }
1178

1179
    Py_RETURN_NONE;
Kevin Modzelewski's avatar
Kevin Modzelewski committed
1180 1181
}

1182
extern "C" PyObject* PyList_New(Py_ssize_t size) noexcept {
1183
    try {
Kevin Modzelewski's avatar
Kevin Modzelewski committed
1184 1185 1186 1187 1188
        BoxedList* l = new BoxedList();
        if (size) {
            l->ensure(size);

            for (Py_ssize_t i = 0; i < size; i++) {
Kevin Modzelewski's avatar
Kevin Modzelewski committed
1189
                l->elts->elts[i] = NULL;
Kevin Modzelewski's avatar
Kevin Modzelewski committed
1190 1191 1192 1193
            }
            l->size = size;
        }
        return l;
1194
    } catch (ExcInfo e) {
1195 1196 1197 1198
        abort();
    }
}

1199 1200 1201 1202 1203 1204 1205
Box* _listCmp(BoxedList* lhs, BoxedList* rhs, AST_TYPE::AST_TYPE op_type) {
    int lsz = lhs->size;
    int rsz = rhs->size;

    bool is_order
        = (op_type == AST_TYPE::Lt || op_type == AST_TYPE::LtE || op_type == AST_TYPE::Gt || op_type == AST_TYPE::GtE);

1206 1207
    if (lsz != rsz) {
        if (op_type == AST_TYPE::Eq)
Kevin Modzelewski's avatar
Kevin Modzelewski committed
1208
            Py_RETURN_FALSE;
1209
        if (op_type == AST_TYPE::NotEq)
Kevin Modzelewski's avatar
Kevin Modzelewski committed
1210
            Py_RETURN_TRUE;
1211 1212
    }

1213 1214
    int n = std::min(lsz, rsz);
    for (int i = 0; i < n; i++) {
Bob Fang's avatar
Bob Fang committed
1215
        bool identity_eq = lhs->elts->elts[i] == rhs->elts->elts[i];
Bob Fang's avatar
Bob Fang committed
1216
        if (identity_eq)
1217 1218
            continue;

1219 1220 1221
        int r = PyObject_RichCompareBool(lhs->elts->elts[i], rhs->elts->elts[i], Py_EQ);
        if (r == -1)
            throwCAPIException();
1222

1223
        if (r)
1224 1225 1226 1227 1228 1229 1230
            continue;

        if (op_type == AST_TYPE::Eq) {
            return boxBool(false);
        } else if (op_type == AST_TYPE::NotEq) {
            return boxBool(true);
        } else {
1231
            Box* r = compareInternal<NOT_REWRITABLE>(lhs->elts->elts[i], rhs->elts->elts[i], op_type, NULL);
1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252
            return r;
        }
    }

    if (op_type == AST_TYPE::Lt)
        return boxBool(lsz < rsz);
    else if (op_type == AST_TYPE::LtE)
        return boxBool(lsz <= rsz);
    else if (op_type == AST_TYPE::Gt)
        return boxBool(lsz > rsz);
    else if (op_type == AST_TYPE::GtE)
        return boxBool(lsz >= rsz);
    else if (op_type == AST_TYPE::Eq)
        return boxBool(lsz == rsz);
    else if (op_type == AST_TYPE::NotEq)
        return boxBool(lsz != rsz);

    RELEASE_ASSERT(0, "%d", op_type);
}

Box* listEq(BoxedList* self, Box* rhs) {
1253
    if (!PyList_Check(rhs)) {
1254
        return incref(NotImplemented);
1255
    }
1256

1257 1258 1259
    return _listCmp(self, static_cast<BoxedList*>(rhs), AST_TYPE::Eq);
}

1260
Box* listNe(BoxedList* self, Box* rhs) {
1261
    if (!PyList_Check(rhs)) {
1262
        return incref(NotImplemented);
1263 1264 1265 1266 1267
    }

    return _listCmp(self, static_cast<BoxedList*>(rhs), AST_TYPE::NotEq);
}

1268
Box* listLt(BoxedList* self, Box* rhs) {
1269
    if (!PyList_Check(rhs)) {
1270
        return incref(NotImplemented);
1271 1272 1273 1274 1275 1276
    }

    return _listCmp(self, static_cast<BoxedList*>(rhs), AST_TYPE::Lt);
}

Box* listLe(BoxedList* self, Box* rhs) {
1277
    if (!PyList_Check(rhs)) {
1278
        return incref(NotImplemented);
1279 1280 1281 1282 1283 1284
    }

    return _listCmp(self, static_cast<BoxedList*>(rhs), AST_TYPE::LtE);
}

Box* listGt(BoxedList* self, Box* rhs) {
1285
    if (!PyList_Check(rhs)) {
1286
        return incref(NotImplemented);
1287 1288 1289 1290 1291 1292
    }

    return _listCmp(self, static_cast<BoxedList*>(rhs), AST_TYPE::Gt);
}

Box* listGe(BoxedList* self, Box* rhs) {
1293
    if (!PyList_Check(rhs)) {
1294
        return incref(NotImplemented);
1295 1296 1297 1298 1299
    }

    return _listCmp(self, static_cast<BoxedList*>(rhs), AST_TYPE::GtE);
}

Kevin Modzelewski's avatar
Kevin Modzelewski committed
1300 1301
extern "C" PyObject* _PyList_Extend(PyListObject* self, PyObject* b) noexcept {
    BoxedList* l = (BoxedList*)self;
1302
    assert(PyList_Check(l));
Kevin Modzelewski's avatar
Kevin Modzelewski committed
1303 1304

    try {
Kevin Modzelewski's avatar
Kevin Modzelewski committed
1305 1306 1307
        Box* r = listIAdd(l, b);
        Py_DECREF(r);
        Py_RETURN_NONE;
1308 1309
    } catch (ExcInfo e) {
        setCAPIException(e);
Kevin Modzelewski's avatar
Kevin Modzelewski committed
1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320
        return NULL;
    }
}

extern "C" int PyList_SetSlice(PyObject* a, Py_ssize_t ilow, Py_ssize_t ihigh, PyObject* v) noexcept {
    if (!PyList_Check(a)) {
        PyErr_BadInternalCall();
        return -1;
    }

    BoxedList* l = (BoxedList*)a;
1321
    ASSERT(PyList_Check(l), "%s", l->cls->tp_name);
Kevin Modzelewski's avatar
Kevin Modzelewski committed
1322

Kevin Modzelewski's avatar
Kevin Modzelewski committed
1323
    // TODO should just call list_ass_slice
Kevin Modzelewski's avatar
Kevin Modzelewski committed
1324
    try {
Marius Wachtler's avatar
Marius Wachtler committed
1325 1326
        adjustNegativeIndicesOnObject(l, &ilow, &ihigh);
        listSetitemSliceInt64(l, ilow, ihigh, 1, v);
Kevin Modzelewski's avatar
Kevin Modzelewski committed
1327
        return 0;
1328 1329
    } catch (ExcInfo e) {
        setCAPIException(e);
Kevin Modzelewski's avatar
Kevin Modzelewski committed
1330 1331 1332 1333
        return -1;
    }
}

1334 1335 1336 1337 1338
void BoxedList::dealloc(Box* b) noexcept {
    BoxedList* op = static_cast<BoxedList*>(b);

    Py_ssize_t i;
    PyObject_GC_UnTrack(op);
Kevin Modzelewski's avatar
Format!  
Kevin Modzelewski committed
1339
    Py_TRASHCAN_SAFE_BEGIN(op) if (op->elts != NULL) {
1340 1341 1342 1343 1344 1345 1346 1347
        /* Do it backwards, for Christian Tismer.
           There's a simple test case where somehow this reduces
           thrashing when a *very* large list is created and
           immediately deleted. */
        i = Py_SIZE(op);
        while (--i >= 0) {
            Py_XDECREF(op->elts->elts[i]);
        }
Kevin Modzelewski's avatar
Kevin Modzelewski committed
1348
        delete op->elts;
1349 1350 1351 1352 1353 1354 1355 1356 1357 1358
    }
#if 0
    if (numfree < PyList_MAXFREELIST && PyList_CheckExact(op))
        free_list[numfree++] = op;
    else
#endif
    Py_TYPE(op)->tp_free((PyObject*)op);
    Py_TRASHCAN_SAFE_END(op)
}

1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374
template <ExceptionStyle S> Box* listiterNext(Box* s) noexcept(S == CAPI) {
    Box* rtn = listiter_next(s);
    if (!rtn) {
        if (S == CAPI) {
            PyErr_SetObject(StopIteration, None);
            return NULL;
        } else
            raiseExcHelper(StopIteration, (const char*)NULL);
    }
    return rtn;
}

// force instantiation:
template Box* listiterNext<CAPI>(Box*) noexcept;
template Box* listiterNext<CXX>(Box*);

1375 1376 1377 1378
int BoxedList::traverse(Box* _o, visitproc visit, void* arg) noexcept {
    PyListObject* o = (PyListObject*)_o;
    Py_ssize_t i;

Kevin Modzelewski's avatar
Format!  
Kevin Modzelewski committed
1379
    for (i = Py_SIZE(o); --i >= 0;)
1380 1381 1382 1383 1384
        Py_VISIT(o->ob_item[i]);
    return 0;
}

int BoxedList::clear(Box* _a) noexcept {
Kevin Modzelewski's avatar
Kevin Modzelewski committed
1385
    BoxedList* a = (BoxedList*)_a;
1386
    Py_ssize_t i;
Kevin Modzelewski's avatar
Kevin Modzelewski committed
1387
    if (a->elts) {
Kevin Modzelewski's avatar
Format!  
Kevin Modzelewski committed
1388
        PyObject** item = a->elts->elts;
1389 1390 1391 1392
        /* Because XDECREF can recursively invoke operations on
           this list, we make it empty first. */
        i = Py_SIZE(a);
        Py_SIZE(a) = 0;
Kevin Modzelewski's avatar
Kevin Modzelewski committed
1393 1394 1395
        a->capacity = 0;
        auto old_elts = a->elts;
        a->elts = NULL;
1396 1397 1398
        while (--i >= 0) {
            Py_XDECREF(item[i]);
        }
Kevin Modzelewski's avatar
Kevin Modzelewski committed
1399
        delete old_elts;
1400 1401 1402 1403 1404 1405 1406
    }
    /* Never fails; the return value can be ignored.
       Note that there is no guarantee that the list is actually empty
       at this point, because XDECREF may have populated it again! */
    return 0;
}

Kevin Modzelewski's avatar
Kevin Modzelewski committed
1407
void setupList() {
1408 1409 1410 1411 1412
    static PySequenceMethods list_as_sequence;
    list_cls->tp_as_sequence = &list_as_sequence;
    static PyMappingMethods list_as_mapping;
    list_cls->tp_as_mapping = &list_as_mapping;

1413
    list_iterator_cls = BoxedClass::create(type_cls, object_cls, 0, 0, sizeof(BoxedListIterator), false, "listiterator",
1414
                                           false, (destructor)BoxedListIterator::dealloc, NULL, true,
1415 1416
                                           (traverseproc)BoxedListIterator::traverse, NOCLEAR);
    list_reverse_iterator_cls = BoxedClass::create(type_cls, object_cls, 0, 0, sizeof(BoxedListIterator), false,
1417 1418
                                                   "listreverseiterator", false, (destructor)BoxedListIterator::dealloc,
                                                   NULL, true, (traverseproc)BoxedListIterator::traverse, NOCLEAR);
1419
    list_iterator_cls->instances_are_nonzero = list_reverse_iterator_cls->instances_are_nonzero = true;
Kevin Modzelewski's avatar
Kevin Modzelewski committed
1420

1421 1422 1423 1424 1425 1426 1427 1428 1429
    list_cls->giveAttr("__len__", new BoxedFunction(FunctionMetadata::create((void*)listLen, BOXED_INT, 1)));

    FunctionMetadata* getitem = new FunctionMetadata(2, false, false);
    getitem->addVersion((void*)listGetitemInt, UNKNOWN, std::vector<ConcreteCompilerType*>{ LIST, BOXED_INT });
    getitem->addVersion((void*)listGetitemSlice<CXX>, LIST, std::vector<ConcreteCompilerType*>{ LIST, SLICE }, CXX);
    getitem->addVersion((void*)listGetitem<CXX>, UNKNOWN, std::vector<ConcreteCompilerType*>{ UNKNOWN, UNKNOWN }, CXX);
    getitem->addVersion((void*)listGetitemSlice<CAPI>, LIST, std::vector<ConcreteCompilerType*>{ LIST, SLICE }, CAPI);
    getitem->addVersion((void*)listGetitem<CAPI>, UNKNOWN, std::vector<ConcreteCompilerType*>{ UNKNOWN, UNKNOWN },
                        CAPI);
1430 1431
    list_cls->giveAttr("__getitem__", new BoxedFunction(getitem));

1432
    list_cls->giveAttr("__getslice__", new BoxedFunction(FunctionMetadata::create((void*)listGetslice, LIST, 3)));
1433

1434 1435 1436 1437
    FunctionMetadata* setitem = new FunctionMetadata(3, false, false);
    setitem->addVersion((void*)listSetitemInt, NONE, std::vector<ConcreteCompilerType*>{ LIST, BOXED_INT, UNKNOWN });
    setitem->addVersion((void*)listSetitemSlice, NONE, std::vector<ConcreteCompilerType*>{ LIST, SLICE, UNKNOWN });
    setitem->addVersion((void*)listSetitem, NONE, std::vector<ConcreteCompilerType*>{ UNKNOWN, UNKNOWN, UNKNOWN });
1438 1439
    list_cls->giveAttr("__setitem__", new BoxedFunction(setitem));

1440
    list_cls->giveAttr("__setslice__", new BoxedFunction(FunctionMetadata::create((void*)listSetslice, NONE, 4)));
1441

1442 1443 1444 1445
    FunctionMetadata* delitem = new FunctionMetadata(2, false, false);
    delitem->addVersion((void*)listDelitemInt, NONE, std::vector<ConcreteCompilerType*>{ LIST, BOXED_INT });
    delitem->addVersion((void*)listDelitemSlice, NONE, std::vector<ConcreteCompilerType*>{ LIST, SLICE });
    delitem->addVersion((void*)listDelitem, NONE, std::vector<ConcreteCompilerType*>{ UNKNOWN, UNKNOWN });
1446 1447
    list_cls->giveAttr("__delitem__", new BoxedFunction(delitem));

1448
    list_cls->giveAttr("__delslice__", new BoxedFunction(FunctionMetadata::create((void*)listDelslice, NONE, 3)));
1449

1450 1451
    list_cls->giveAttr(
        "__iter__", new BoxedFunction(FunctionMetadata::create((void*)listIter, typeFromClass(list_iterator_cls), 1)));
Kevin Modzelewski's avatar
Kevin Modzelewski committed
1452

1453 1454
    list_cls->giveAttr("__reversed__", new BoxedFunction(FunctionMetadata::create(
                                           (void*)listReversed, typeFromClass(list_reverse_iterator_cls), 1)));
1455

1456 1457 1458 1459 1460 1461
    list_cls->giveAttr("__eq__", new BoxedFunction(FunctionMetadata::create((void*)listEq, UNKNOWN, 2)));
    list_cls->giveAttr("__ne__", new BoxedFunction(FunctionMetadata::create((void*)listNe, UNKNOWN, 2)));
    list_cls->giveAttr("__lt__", new BoxedFunction(FunctionMetadata::create((void*)listLt, UNKNOWN, 2)));
    list_cls->giveAttr("__le__", new BoxedFunction(FunctionMetadata::create((void*)listLe, UNKNOWN, 2)));
    list_cls->giveAttr("__gt__", new BoxedFunction(FunctionMetadata::create((void*)listGt, UNKNOWN, 2)));
    list_cls->giveAttr("__ge__", new BoxedFunction(FunctionMetadata::create((void*)listGe, UNKNOWN, 2)));
1462

1463 1464
    list_cls->giveAttr("__repr__", new BoxedFunction(FunctionMetadata::create((void*)listRepr, STR, 1)));
    list_cls->giveAttr("__nonzero__", new BoxedFunction(FunctionMetadata::create((void*)listNonzero, BOXED_BOOL, 1)));
Kevin Modzelewski's avatar
Kevin Modzelewski committed
1465

1466 1467
    list_cls->giveAttr("pop",
                       new BoxedFunction(FunctionMetadata::create((void*)listPop, UNKNOWN, 2, false, false), { None }));
Kevin Modzelewski's avatar
Kevin Modzelewski committed
1468

1469
    list_cls->giveAttr("append", new BoxedFunction(FunctionMetadata::create((void*)listAppend, NONE, 2)));
Marius Wachtler's avatar
Marius Wachtler committed
1470
    list_cls->giveAttr("extend", new BoxedFunction(FunctionMetadata::create((void*)listExtend, NONE, 2)));
1471

1472 1473 1474 1475
    list_cls->giveAttr("insert", new BoxedFunction(FunctionMetadata::create((void*)listInsert, NONE, 3)));
    list_cls->giveAttr("__mul__", new BoxedFunction(FunctionMetadata::create((void*)listMul, UNKNOWN, 2)));
    list_cls->giveAttr("__rmul__", new BoxedFunction(FunctionMetadata::create((void*)listMul, UNKNOWN, 2)));
    list_cls->giveAttr("__imul__", new BoxedFunction(FunctionMetadata::create((void*)listImul, UNKNOWN, 2)));
Kevin Modzelewski's avatar
Kevin Modzelewski committed
1476

1477 1478
    list_cls->giveAttr("__iadd__", new BoxedFunction(FunctionMetadata::create((void*)listIAdd, UNKNOWN, 2)));
    list_cls->giveAttr("__add__", new BoxedFunction(FunctionMetadata::create((void*)listAdd, UNKNOWN, 2)));
1479

1480 1481 1482 1483 1484
    list_cls->giveAttr("sort",
                       new BoxedFunction(FunctionMetadata::create((void*)listSortFunc, NONE, 4, false, false,
                                                                  ParamNames({ "", "cmp", "key", "reverse" }, "", "")),
                                         { None, None, False }));
    list_cls->giveAttr("__contains__", new BoxedFunction(FunctionMetadata::create((void*)listContains, BOXED_BOOL, 2)));
Kevin Modzelewski's avatar
Kevin Modzelewski committed
1485

1486 1487
    list_cls->giveAttr(
        "__init__", new BoxedFunction(FunctionMetadata::create((void*)listInit, UNKNOWN, 2, false, false), { NULL }));
Kevin Modzelewski's avatar
Kevin Modzelewski committed
1488

1489 1490 1491 1492 1493 1494
    list_cls->giveAttr("count", new BoxedFunction(FunctionMetadata::create((void*)listCount, BOXED_INT, 2)));
    list_cls->giveAttr(
        "index",
        new BoxedFunction(FunctionMetadata::create((void*)listIndex, BOXED_INT, 4, false, false), { NULL, NULL }));
    list_cls->giveAttr("remove", new BoxedFunction(FunctionMetadata::create((void*)listRemove, NONE, 2)));
    list_cls->giveAttr("reverse", new BoxedFunction(FunctionMetadata::create((void*)listReverse, NONE, 1)));
1495

Kevin Modzelewski's avatar
Kevin Modzelewski committed
1496
    list_cls->giveAttrBorrowed("__hash__", None);
Kevin Modzelewski's avatar
Kevin Modzelewski committed
1497
    list_cls->freeze();
Marius Wachtler's avatar
Marius Wachtler committed
1498
    list_cls->tp_iter = listIter;
Kevin Modzelewski's avatar
Kevin Modzelewski committed
1499

1500
    list_cls->tp_as_sequence->sq_length = list_length;
1501
    list_cls->tp_as_sequence->sq_concat = (binaryfunc)list_concat;
1502 1503 1504 1505 1506
    list_cls->tp_as_sequence->sq_item = (ssizeargfunc)list_item;
    list_cls->tp_as_sequence->sq_slice = list_slice;
    list_cls->tp_as_sequence->sq_ass_item = (ssizeobjargproc)list_ass_item;
    list_cls->tp_as_sequence->sq_ass_slice = (ssizessizeobjargproc)list_ass_slice;
    list_cls->tp_as_sequence->sq_contains = (objobjproc)list_contains;
1507
    list_cls->tp_as_sequence->sq_repeat = (ssizeargfunc)list_repeat;
1508

1509 1510
    FunctionMetadata* hasnext = FunctionMetadata::create((void*)listiterHasnextUnboxed, BOOL, 1);
    hasnext->addVersion((void*)listiterHasnext, BOXED_BOOL);
Kevin Modzelewski's avatar
Kevin Modzelewski committed
1511
    list_iterator_cls->giveAttr("__hasnext__", new BoxedFunction(hasnext));
1512 1513
    list_iterator_cls->giveAttr("__iter__", new BoxedFunction(FunctionMetadata::create(
                                                (void*)listIterIter, typeFromClass(list_iterator_cls), 1)));
1514

1515 1516
    FunctionMetadata* listiter_next_func = FunctionMetadata::create((void*)listiterNext<CXX>, UNKNOWN, 1);
    listiter_next_func->addVersion((void*)listiterNext<CAPI>, UNKNOWN, CAPI);
1517
    list_iterator_cls->giveAttr("next", new BoxedFunction(listiter_next_func));
Kevin Modzelewski's avatar
Kevin Modzelewski committed
1518 1519

    list_iterator_cls->freeze();
Kevin Modzelewski's avatar
Kevin Modzelewski committed
1520
    list_iterator_cls->tpp_hasnext = listiterHasnextUnboxed;
1521
    list_iterator_cls->tp_iternext = listiter_next;
1522
    list_iterator_cls->tp_iter = PyObject_SelfIter;
1523

1524
    list_reverse_iterator_cls->giveAttr("__name__", boxString("listreverseiterator"));
1525

1526 1527
    hasnext = FunctionMetadata::create((void*)listreviterHasnextUnboxed, BOOL, 1);
    hasnext->addVersion((void*)listreviterHasnext, BOXED_BOOL);
1528 1529
    list_reverse_iterator_cls->giveAttr("__hasnext__", new BoxedFunction(hasnext));
    list_reverse_iterator_cls->giveAttr(
1530 1531 1532 1533
        "__iter__",
        new BoxedFunction(FunctionMetadata::create((void*)listIterIter, typeFromClass(list_reverse_iterator_cls), 1)));
    list_reverse_iterator_cls->giveAttr(
        "next", new BoxedFunction(FunctionMetadata::create((void*)listreviterNext, UNKNOWN, 1)));
1534 1535

    list_reverse_iterator_cls->freeze();
1536
    list_reverse_iterator_cls->tp_iternext = listreviter_next;
1537
    list_reverse_iterator_cls->tp_iter = PyObject_SelfIter;
Kevin Modzelewski's avatar
Kevin Modzelewski committed
1538 1539
}
}