Debian Codegraph @

mypyc/lib-rt/pythonsupport.h

raw
1 // Collects code that was copied in from cpython, for a couple of different reasons:
2 // * We wanted to modify it to produce a more efficient version for our uses
3 // * We needed to call it and it was static :(
4 // * We wanted to call it and needed to backport it
5
6 #ifndef CPY_PYTHONSUPPORT_H
7 #define CPY_PYTHONSUPPORT_H
8
9 #include <Python.h>
10 #include <stdbool.h>
11 #include "pythoncapi_compat.h"
12 #include <frameobject.h>
13 #include <assert.h>
14 #include "static_data.h"
15 #include "mypyc_util.h"
16
17 #if CPY_3_13_FEATURES
18 #ifndef Py_BUILD_CORE
19 #define Py_BUILD_CORE
20 #endif
21 #include "internal/pycore_genobject.h" // _PyGen_FetchStopIterationValue
22 #include "internal/pycore_pyerrors.h" // _PyErr_FormatFromCause, _PyErr_SetKeyError
23 #include "internal/pycore_setobject.h" // _PySet_Update
24 #endif
25
26 #if CPY_3_12_FEATURES
27 #include "internal/pycore_frame.h"
28 #endif
29
30 #ifdef __cplusplus
31 extern "C" {
32 #endif
33 #if 0
34 } // why isn't emacs smart enough to not indent this
35 #endif
36
37 PyObject* update_bases(PyObject *bases);
38 int init_subclass(PyTypeObject *type, PyObject *kwds);
39
40 Py_ssize_t
41 CPyLong_AsSsize_tAndOverflow_(PyObject *vv, int *overflow);
42
43 #if CPY_3_12_FEATURES
44
45 static inline Py_ssize_t
46 CPyLong_AsSsize_tAndOverflow(PyObject *vv, int *overflow)
47 {
48 /* This version by Tim Peters */
49 PyLongObject *v = (PyLongObject *)vv;
50 Py_ssize_t res;
51 Py_ssize_t i;
52
53 *overflow = 0;
54
55 res = -1;
56 i = CPY_LONG_TAG(v);
57
58 // TODO: Combine zero and non-zero cases helow?
59 if (likely(i == (1 << CPY_NON_SIZE_BITS))) {
60 res = CPY_LONG_DIGIT(v, 0);
61 } else if (likely(i == CPY_SIGN_ZERO)) {
62 res = 0;
63 } else if (i == ((1 << CPY_NON_SIZE_BITS) | CPY_SIGN_NEGATIVE)) {
64 res = -(sdigit)CPY_LONG_DIGIT(v, 0);
65 } else {
66 // Slow path is moved to a non-inline helper function to
67 // limit size of generated code
68 int overflow_local;
69 res = CPyLong_AsSsize_tAndOverflow_(vv, &overflow_local);
70 *overflow = overflow_local;
71 }
72 return res;
73 }
74
75 #else
76
77 // Adapted from longobject.c in Python 3.7.0
78
79 /* This function adapted from PyLong_AsLongLongAndOverflow, but with
80 * some safety checks removed and specialized to only work for objects
81 * that are already longs.
82 * About half of the win this provides, though, just comes from being
83 * able to inline the function, which in addition to saving function call
84 * overhead allows the out-parameter overflow flag to be collapsed into
85 * control flow.
86 * Additionally, we check against the possible range of CPyTagged, not of
87 * Py_ssize_t. */
88 static inline Py_ssize_t
89 CPyLong_AsSsize_tAndOverflow(PyObject *vv, int *overflow)
90 {
91 /* This version by Tim Peters */
92 PyLongObject *v = (PyLongObject *)vv;
93 Py_ssize_t res;
94 Py_ssize_t i;
95
96 *overflow = 0;
97
98 res = -1;
99 i = Py_SIZE(v);
100
101 if (likely(i == 1)) {
102 res = CPY_LONG_DIGIT(v, 0);
103 } else if (likely(i == 0)) {
104 res = 0;
105 } else if (i == -1) {
106 res = -(sdigit)CPY_LONG_DIGIT(v, 0);
107 } else {
108 // Slow path is moved to a non-inline helper function to
109 // limit size of generated code
110 int overflow_local;
111 res = CPyLong_AsSsize_tAndOverflow_(vv, &overflow_local);
112 *overflow = overflow_local;
113 }
114 return res;
115 }
116
117 #endif
118
119 // Adapted from listobject.c in Python 3.7.0
120 static int
121 list_resize(PyListObject *self, Py_ssize_t newsize)
122 {
123 PyObject **items;
124 size_t new_allocated, num_allocated_bytes;
125 Py_ssize_t allocated = self->allocated;
126
127 /* Bypass realloc() when a previous overallocation is large enough
128 to accommodate the newsize. If the newsize falls lower than half
129 the allocated size, then proceed with the realloc() to shrink the list.
130 */
131 if (allocated >= newsize && newsize >= (allocated >> 1)) {
132 assert(self->ob_item != NULL || newsize == 0);
133 Py_SET_SIZE(self, newsize);
134 return 0;
135 }
136
137 /* This over-allocates proportional to the list size, making room
138 * for additional growth. The over-allocation is mild, but is
139 * enough to give linear-time amortized behavior over a long
140 * sequence of appends() in the presence of a poorly-performing
141 * system realloc().
142 * The growth pattern is: 0, 4, 8, 16, 25, 35, 46, 58, 72, 88, ...
143 * Note: new_allocated won't overflow because the largest possible value
144 * is PY_SSIZE_T_MAX * (9 / 8) + 6 which always fits in a size_t.
145 */
146 new_allocated = (size_t)newsize + (newsize >> 3) + (newsize < 9 ? 3 : 6);
147 if (new_allocated > (size_t)PY_SSIZE_T_MAX / sizeof(PyObject *)) {
148 PyErr_NoMemory();
149 return -1;
150 }
151
152 if (newsize == 0)
153 new_allocated = 0;
154 num_allocated_bytes = new_allocated * sizeof(PyObject *);
155 items = (PyObject **)PyMem_Realloc(self->ob_item, num_allocated_bytes);
156 if (items == NULL) {
157 PyErr_NoMemory();
158 return -1;
159 }
160 self->ob_item = items;
161 Py_SET_SIZE(self, newsize);
162 self->allocated = new_allocated;
163 return 0;
164 }
165
166 // Changed to use PyList_SetSlice instead of the internal list_ass_slice
167 static PyObject *
168 list_pop_impl(PyListObject *self, Py_ssize_t index)
169 {
170 PyObject *v;
171 int status;
172
173 if (Py_SIZE(self) == 0) {
174 /* Special-case most common failure cause */
175 PyErr_SetString(PyExc_IndexError, "pop from empty list");
176 return NULL;
177 }
178 if (index < 0)
179 index += Py_SIZE(self);
180 if (index < 0 || index >= Py_SIZE(self)) {
181 PyErr_SetString(PyExc_IndexError, "pop index out of range");
182 return NULL;
183 }
184 v = self->ob_item[index];
185 if (index == Py_SIZE(self) - 1) {
186 status = list_resize(self, Py_SIZE(self) - 1);
187 if (status >= 0)
188 return v; /* and v now owns the reference the list had */
189 else
190 return NULL;
191 }
192 Py_INCREF(v);
193 status = PyList_SetSlice((PyObject *)self, index, index+1, (PyObject *)NULL);
194 if (status < 0) {
195 Py_DECREF(v);
196 return NULL;
197 }
198 return v;
199 }
200
201 // Tweaked to directly use CPyTagged
202 static CPyTagged
203 list_count(PyListObject *self, PyObject *value)
204 {
205 Py_ssize_t count = 0;
206 Py_ssize_t i;
207
208 for (i = 0; i < Py_SIZE(self); i++) {
209 int cmp = PyObject_RichCompareBool(self->ob_item[i], value, Py_EQ);
210 if (cmp > 0)
211 count++;
212 else if (cmp < 0)
213 return CPY_INT_TAG;
214 }
215 return CPyTagged_ShortFromSsize_t(count);
216 }
217
218 // Adapted from genobject.c in Python 3.7.2
219 // Copied because it wasn't in 3.5.2 and it is undocumented anyways.
220 /*
221 * Set StopIteration with specified value. Value can be arbitrary object
222 * or NULL.
223 *
224 * Returns 0 if StopIteration is set and -1 if any other exception is set.
225 */
226 static int
227 CPyGen_SetStopIterationValue(PyObject *value)
228 {
229 PyObject *e;
230
231 if (value == NULL ||
232 (!PyTuple_Check(value) && !PyExceptionInstance_Check(value)))
233 {
234 /* Delay exception instantiation if we can */
235 PyErr_SetObject(PyExc_StopIteration, value);
236 return 0;
237 }
238 /* Construct an exception instance manually with
239 * PyObject_CallOneArg and pass it to PyErr_SetObject.
240 *
241 * We do this to handle a situation when "value" is a tuple, in which
242 * case PyErr_SetObject would set the value of StopIteration to
243 * the first element of the tuple.
244 *
245 * (See PyErr_SetObject/_PyErr_CreateException code for details.)
246 */
247 e = PyObject_CallOneArg(PyExc_StopIteration, value);
248 if (e == NULL) {
249 return -1;
250 }
251 PyErr_SetObject(PyExc_StopIteration, e);
252 Py_DECREF(e);
253 return 0;
254 }
255
256 // Copied from dictobject.c and dictobject.h, these are not Public before
257 // Python 3.8. Also remove some error checks that we do in the callers.
258 typedef struct {
259 PyObject_HEAD
260 PyDictObject *dv_dict;
261 } _CPyDictViewObject;
262
263 static PyObject *
264 _CPyDictView_New(PyObject *dict, PyTypeObject *type)
265 {
266 _CPyDictViewObject *dv = PyObject_GC_New(_CPyDictViewObject, type);
267 if (dv == NULL)
268 return NULL;
269 Py_INCREF(dict);
270 dv->dv_dict = (PyDictObject *)dict;
271 PyObject_GC_Track(dv);
272 return (PyObject *)dv;
273 }
274
275 #ifdef __cplusplus
276 }
277 #endif
278
279 #if CPY_3_12_FEATURES
280
281 // These are copied from genobject.c in Python 3.12
282
283 static int
284 gen_is_coroutine(PyObject *o)
285 {
286 if (PyGen_CheckExact(o)) {
287 PyCodeObject *code = PyGen_GetCode((PyGenObject*)o);
288 if (code->co_flags & CO_ITERABLE_COROUTINE) {
289 return 1;
290 }
291 }
292 return 0;
293 }
294
295 #else
296
297 // Copied from genobject.c in Python 3.10
298 static int
299 gen_is_coroutine(PyObject *o)
300 {
301 if (PyGen_CheckExact(o)) {
302 PyCodeObject *code = (PyCodeObject *)((PyGenObject*)o)->gi_code;
303 if (code->co_flags & CO_ITERABLE_COROUTINE) {
304 return 1;
305 }
306 }
307 return 0;
308 }
309
310 #endif
311
312 /*
313 * This helper function returns an awaitable for `o`:
314 * - `o` if `o` is a coroutine-object;
315 * - `type(o)->tp_as_async->am_await(o)`
316 *
317 * Raises a TypeError if it's not possible to return
318 * an awaitable and returns NULL.
319 */
320 static PyObject *
321 CPyCoro_GetAwaitableIter(PyObject *o)
322 {
323 unaryfunc getter = NULL;
324 PyTypeObject *ot;
325
326 if (PyCoro_CheckExact(o) || gen_is_coroutine(o)) {
327 /* 'o' is a coroutine. */
328 Py_INCREF(o);
329 return o;
330 }
331
332 ot = Py_TYPE(o);
333 if (ot->tp_as_async != NULL) {
334 getter = ot->tp_as_async->am_await;
335 }
336 if (getter != NULL) {
337 PyObject *res = (*getter)(o);
338 if (res != NULL) {
339 if (PyCoro_CheckExact(res) || gen_is_coroutine(res)) {
340 /* __await__ must return an *iterator*, not
341 a coroutine or another awaitable (see PEP 492) */
342 PyErr_SetString(PyExc_TypeError,
343 "__await__() returned a coroutine");
344 Py_CLEAR(res);
345 } else if (!PyIter_Check(res)) {
346 PyErr_Format(PyExc_TypeError,
347 "__await__() returned non-iterator "
348 "of type '%.100s'",
349 Py_TYPE(res)->tp_name);
350 Py_CLEAR(res);
351 }
352 }
353 return res;
354 }
355
356 PyErr_Format(PyExc_TypeError,
357 "object %.100s can't be used in 'await' expression",
358 ot->tp_name);
359 return NULL;
360 }
361
362
363 #endif