gh-125063: Emit slices as constants in the bytecode compiler (#125064)

* Make slices marshallable

* Emit slices as constants

* Update Python/marshal.c

Co-authored-by: Peter Bierma <zintensitydev@gmail.com>

* Refactor codegen_slice into two functions so it
always has the same net effect

* Fix for free-threaded builds

* Simplify marshal loading of slices

* Only return SUCCESS/ERROR from codegen_slice

---------

Co-authored-by: Mark Shannon <mark@hotpy.org>
Co-authored-by: Peter Bierma <zintensitydev@gmail.com>
This commit is contained in:
Michael Droettboom 2024-10-08 13:18:39 -04:00 committed by GitHub
parent 7dca7322cc
commit c6127af868
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
6 changed files with 122 additions and 23 deletions

View file

@ -76,6 +76,7 @@ module marshal
#define TYPE_UNKNOWN '?'
#define TYPE_SET '<'
#define TYPE_FROZENSET '>'
#define TYPE_SLICE ':'
#define FLAG_REF '\x80' /* with a type, add obj to index */
#define TYPE_ASCII 'a'
@ -613,6 +614,13 @@ w_complex_object(PyObject *v, char flag, WFILE *p)
w_pstring(view.buf, view.len, p);
PyBuffer_Release(&view);
}
else if (PySlice_Check(v)) {
PySliceObject *slice = (PySliceObject *)v;
W_TYPE(TYPE_SLICE, p);
w_object(slice->start, p);
w_object(slice->stop, p);
w_object(slice->step, p);
}
else {
W_TYPE(TYPE_UNKNOWN, p);
p->error = WFERR_UNMARSHALLABLE;
@ -1534,6 +1542,32 @@ r_object(RFILE *p)
retval = Py_NewRef(v);
break;
case TYPE_SLICE:
{
Py_ssize_t idx = r_ref_reserve(flag, p);
PyObject *stop = NULL;
PyObject *step = NULL;
PyObject *start = r_object(p);
if (start == NULL) {
goto cleanup;
}
stop = r_object(p);
if (stop == NULL) {
goto cleanup;
}
step = r_object(p);
if (step == NULL) {
goto cleanup;
}
retval = PySlice_New(start, stop, step);
r_ref_insert(retval, idx, flag, p);
cleanup:
Py_XDECREF(start);
Py_XDECREF(stop);
Py_XDECREF(step);
break;
}
default:
/* Bogus data got written, which isn't ideal.
This will let you keep working and recover. */