| 1 |
// Generic primitive operations |
| 2 |
// |
| 3 |
// These are registered in mypyc.primitives.generic_ops. |
| 4 |
|
| 5 |
#include <Python.h> |
| 6 |
#include "CPy.h" |
| 7 |
|
| 8 |
CPyTagged CPyObject_Hash(PyObject *o) { |
| 9 |
Py_hash_t h = PyObject_Hash(o); |
| 10 |
if (h == -1) { |
| 11 |
return CPY_INT_TAG; |
| 12 |
} else { |
| 13 |
// This is tragically annoying. The range of hash values in |
| 14 |
// 64-bit python covers 64-bits, and our short integers only |
| 15 |
// cover 63. This means that half the time we are boxing the |
| 16 |
// result for basically no good reason. To add insult to |
| 17 |
// injury it is probably about to be immediately unboxed by a |
| 18 |
// tp_hash wrapper. |
| 19 |
return CPyTagged_FromSsize_t(h); |
| 20 |
} |
| 21 |
} |
| 22 |
|
| 23 |
PyObject *CPyObject_GetAttr3(PyObject *v, PyObject *name, PyObject *defl) |
| 24 |
{ |
| 25 |
PyObject *result = PyObject_GetAttr(v, name); |
| 26 |
if (!result && PyErr_ExceptionMatches(PyExc_AttributeError)) { |
| 27 |
PyErr_Clear(); |
| 28 |
Py_INCREF(defl); |
| 29 |
result = defl; |
| 30 |
} |
| 31 |
return result; |
| 32 |
} |
| 33 |
|
| 34 |
PyObject *CPyIter_Next(PyObject *iter) |
| 35 |
{ |
| 36 |
return (*Py_TYPE(iter)->tp_iternext)(iter); |
| 37 |
} |
| 38 |
|
| 39 |
PyObject *CPyNumber_Power(PyObject *base, PyObject *index) |
| 40 |
{ |
| 41 |
return PyNumber_Power(base, index, Py_None); |
| 42 |
} |
| 43 |
|
| 44 |
PyObject *CPyNumber_InPlacePower(PyObject *base, PyObject *index) |
| 45 |
{ |
| 46 |
return PyNumber_InPlacePower(base, index, Py_None); |
| 47 |
} |
| 48 |
|
| 49 |
PyObject *CPyObject_GetSlice(PyObject *obj, CPyTagged start, CPyTagged end) { |
| 50 |
PyObject *start_obj = CPyTagged_AsObject(start); |
| 51 |
PyObject *end_obj = CPyTagged_AsObject(end); |
| 52 |
if (unlikely(start_obj == NULL || end_obj == NULL)) { |
| 53 |
return NULL; |
| 54 |
} |
| 55 |
PyObject *slice = PySlice_New(start_obj, end_obj, NULL); |
| 56 |
Py_DECREF(start_obj); |
| 57 |
Py_DECREF(end_obj); |
| 58 |
if (unlikely(slice == NULL)) { |
| 59 |
return NULL; |
| 60 |
} |
| 61 |
PyObject *result = PyObject_GetItem(obj, slice); |
| 62 |
Py_DECREF(slice); |
| 63 |
return result; |
| 64 |
} |
| 65 |
|
| 66 |
typedef PyObject *(*SetupFunction)(PyObject *); |
| 67 |
|
| 68 |
PyObject *CPy_SetupObject(PyObject *type) { |
| 69 |
PyTypeObject *tp = (PyTypeObject *)type; |
| 70 |
PyMethodDef *def = NULL; |
| 71 |
for(; tp; tp = tp->tp_base) { |
| 72 |
def = tp->tp_methods; |
| 73 |
if (!def || !def->ml_name) { |
| 74 |
continue; |
| 75 |
} |
| 76 |
|
| 77 |
if (!strcmp(def->ml_name, "__internal_mypyc_setup")) { |
| 78 |
return ((SetupFunction)(void(*)(void))def->ml_meth)(type); |
| 79 |
} |
| 80 |
} |
| 81 |
|
| 82 |
PyErr_SetString(PyExc_RuntimeError, "Internal mypyc error: Unable to find object setup function"); |
| 83 |
return NULL; |
| 84 |
} |