generic_ops.c 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. // Generic primitive operations
  2. //
  3. // These are registered in mypyc.primitives.generic_ops.
  4. #include <Python.h>
  5. #include "CPy.h"
  6. CPyTagged CPyObject_Hash(PyObject *o) {
  7. Py_hash_t h = PyObject_Hash(o);
  8. if (h == -1) {
  9. return CPY_INT_TAG;
  10. } else {
  11. // This is tragically annoying. The range of hash values in
  12. // 64-bit python covers 64-bits, and our short integers only
  13. // cover 63. This means that half the time we are boxing the
  14. // result for basically no good reason. To add insult to
  15. // injury it is probably about to be immediately unboxed by a
  16. // tp_hash wrapper.
  17. return CPyTagged_FromSsize_t(h);
  18. }
  19. }
  20. PyObject *CPyObject_GetAttr3(PyObject *v, PyObject *name, PyObject *defl)
  21. {
  22. PyObject *result = PyObject_GetAttr(v, name);
  23. if (!result && PyErr_ExceptionMatches(PyExc_AttributeError)) {
  24. PyErr_Clear();
  25. Py_INCREF(defl);
  26. result = defl;
  27. }
  28. return result;
  29. }
  30. PyObject *CPyIter_Next(PyObject *iter)
  31. {
  32. return (*Py_TYPE(iter)->tp_iternext)(iter);
  33. }
  34. PyObject *CPyNumber_Power(PyObject *base, PyObject *index)
  35. {
  36. return PyNumber_Power(base, index, Py_None);
  37. }
  38. PyObject *CPyNumber_InPlacePower(PyObject *base, PyObject *index)
  39. {
  40. return PyNumber_InPlacePower(base, index, Py_None);
  41. }
  42. PyObject *CPyObject_GetSlice(PyObject *obj, CPyTagged start, CPyTagged end) {
  43. PyObject *start_obj = CPyTagged_AsObject(start);
  44. PyObject *end_obj = CPyTagged_AsObject(end);
  45. if (unlikely(start_obj == NULL || end_obj == NULL)) {
  46. return NULL;
  47. }
  48. PyObject *slice = PySlice_New(start_obj, end_obj, NULL);
  49. Py_DECREF(start_obj);
  50. Py_DECREF(end_obj);
  51. if (unlikely(slice == NULL)) {
  52. return NULL;
  53. }
  54. PyObject *result = PyObject_GetItem(obj, slice);
  55. Py_DECREF(slice);
  56. return result;
  57. }