diff options
author | Anton Samokhvalov <pg83@yandex.ru> | 2022-02-10 16:45:15 +0300 |
---|---|---|
committer | Daniil Cherednik <dcherednik@yandex-team.ru> | 2022-02-10 16:45:15 +0300 |
commit | 72cb13b4aff9bc9cf22e49251bc8fd143f82538f (patch) | |
tree | da2c34829458c7d4e74bdfbdf85dff449e9e7fb8 /contrib/tools/cython/Cython/Utility | |
parent | 778e51ba091dc39e7b7fcab2b9cf4dbedfb6f2b5 (diff) | |
download | ydb-72cb13b4aff9bc9cf22e49251bc8fd143f82538f.tar.gz |
Restoring authorship annotation for Anton Samokhvalov <pg83@yandex.ru>. Commit 1 of 2.
Diffstat (limited to 'contrib/tools/cython/Cython/Utility')
26 files changed, 10049 insertions, 10049 deletions
diff --git a/contrib/tools/cython/Cython/Utility/Buffer.c b/contrib/tools/cython/Cython/Utility/Buffer.c index 3c7105fa35..ca2c532868 100644 --- a/contrib/tools/cython/Cython/Utility/Buffer.c +++ b/contrib/tools/cython/Cython/Utility/Buffer.c @@ -1,166 +1,166 @@ -/////////////// BufferStructDeclare.proto /////////////// - -/* structs for buffer access */ - -typedef struct { - Py_ssize_t shape, strides, suboffsets; -} __Pyx_Buf_DimInfo; - -typedef struct { - size_t refcount; - Py_buffer pybuffer; -} __Pyx_Buffer; - -typedef struct { - __Pyx_Buffer *rcbuffer; - char *data; - __Pyx_Buf_DimInfo diminfo[{{max_dims}}]; -} __Pyx_LocalBuf_ND; - -/////////////// BufferIndexError.proto /////////////// -static void __Pyx_RaiseBufferIndexError(int axis); /*proto*/ - -/////////////// BufferIndexError /////////////// -static void __Pyx_RaiseBufferIndexError(int axis) { - PyErr_Format(PyExc_IndexError, - "Out of bounds on buffer access (axis %d)", axis); -} - -/////////////// BufferIndexErrorNogil.proto /////////////// -//@requires: BufferIndexError - -static void __Pyx_RaiseBufferIndexErrorNogil(int axis); /*proto*/ - -/////////////// BufferIndexErrorNogil /////////////// -static void __Pyx_RaiseBufferIndexErrorNogil(int axis) { - #ifdef WITH_THREAD - PyGILState_STATE gilstate = PyGILState_Ensure(); - #endif - __Pyx_RaiseBufferIndexError(axis); - #ifdef WITH_THREAD - PyGILState_Release(gilstate); - #endif -} - -/////////////// BufferFallbackError.proto /////////////// -static void __Pyx_RaiseBufferFallbackError(void); /*proto*/ - -/////////////// BufferFallbackError /////////////// -static void __Pyx_RaiseBufferFallbackError(void) { - PyErr_SetString(PyExc_ValueError, - "Buffer acquisition failed on assignment; and then reacquiring the old buffer failed too!"); -} - -/////////////// BufferFormatStructs.proto /////////////// +/////////////// BufferStructDeclare.proto /////////////// + +/* structs for buffer access */ + +typedef struct { + Py_ssize_t shape, strides, suboffsets; +} __Pyx_Buf_DimInfo; + +typedef struct { + size_t refcount; + Py_buffer pybuffer; +} __Pyx_Buffer; + +typedef struct { + __Pyx_Buffer *rcbuffer; + char *data; + __Pyx_Buf_DimInfo diminfo[{{max_dims}}]; +} __Pyx_LocalBuf_ND; + +/////////////// BufferIndexError.proto /////////////// +static void __Pyx_RaiseBufferIndexError(int axis); /*proto*/ + +/////////////// BufferIndexError /////////////// +static void __Pyx_RaiseBufferIndexError(int axis) { + PyErr_Format(PyExc_IndexError, + "Out of bounds on buffer access (axis %d)", axis); +} + +/////////////// BufferIndexErrorNogil.proto /////////////// +//@requires: BufferIndexError + +static void __Pyx_RaiseBufferIndexErrorNogil(int axis); /*proto*/ + +/////////////// BufferIndexErrorNogil /////////////// +static void __Pyx_RaiseBufferIndexErrorNogil(int axis) { + #ifdef WITH_THREAD + PyGILState_STATE gilstate = PyGILState_Ensure(); + #endif + __Pyx_RaiseBufferIndexError(axis); + #ifdef WITH_THREAD + PyGILState_Release(gilstate); + #endif +} + +/////////////// BufferFallbackError.proto /////////////// +static void __Pyx_RaiseBufferFallbackError(void); /*proto*/ + +/////////////// BufferFallbackError /////////////// +static void __Pyx_RaiseBufferFallbackError(void) { + PyErr_SetString(PyExc_ValueError, + "Buffer acquisition failed on assignment; and then reacquiring the old buffer failed too!"); +} + +/////////////// BufferFormatStructs.proto /////////////// //@proto_block: utility_code_proto_before_types - -#define IS_UNSIGNED(type) (((type) -1) > 0) - -/* Run-time type information about structs used with buffers */ -struct __Pyx_StructField_; - -#define __PYX_BUF_FLAGS_PACKED_STRUCT (1 << 0) - -typedef struct { - const char* name; /* for error messages only */ - struct __Pyx_StructField_* fields; - size_t size; /* sizeof(type) */ - size_t arraysize[8]; /* length of array in each dimension */ - int ndim; - char typegroup; /* _R_eal, _C_omplex, Signed _I_nt, _U_nsigned int, _S_truct, _P_ointer, _O_bject, c_H_ar */ - char is_unsigned; - int flags; -} __Pyx_TypeInfo; - -typedef struct __Pyx_StructField_ { - __Pyx_TypeInfo* type; - const char* name; - size_t offset; -} __Pyx_StructField; - -typedef struct { - __Pyx_StructField* field; - size_t parent_offset; -} __Pyx_BufFmt_StackElem; - -typedef struct { - __Pyx_StructField root; - __Pyx_BufFmt_StackElem* head; - size_t fmt_offset; - size_t new_count, enc_count; - size_t struct_alignment; - int is_complex; - char enc_type; - char new_packmode; - char enc_packmode; - char is_valid_array; -} __Pyx_BufFmt_Context; - - -/////////////// GetAndReleaseBuffer.proto /////////////// - -#if PY_MAJOR_VERSION < 3 - static int __Pyx_GetBuffer(PyObject *obj, Py_buffer *view, int flags); - static void __Pyx_ReleaseBuffer(Py_buffer *view); -#else - #define __Pyx_GetBuffer PyObject_GetBuffer - #define __Pyx_ReleaseBuffer PyBuffer_Release -#endif - -/////////////// GetAndReleaseBuffer /////////////// - -#if PY_MAJOR_VERSION < 3 -static int __Pyx_GetBuffer(PyObject *obj, Py_buffer *view, int flags) { - if (PyObject_CheckBuffer(obj)) return PyObject_GetBuffer(obj, view, flags); - - {{for type_ptr, getbuffer, releasebuffer in types}} - {{if getbuffer}} + +#define IS_UNSIGNED(type) (((type) -1) > 0) + +/* Run-time type information about structs used with buffers */ +struct __Pyx_StructField_; + +#define __PYX_BUF_FLAGS_PACKED_STRUCT (1 << 0) + +typedef struct { + const char* name; /* for error messages only */ + struct __Pyx_StructField_* fields; + size_t size; /* sizeof(type) */ + size_t arraysize[8]; /* length of array in each dimension */ + int ndim; + char typegroup; /* _R_eal, _C_omplex, Signed _I_nt, _U_nsigned int, _S_truct, _P_ointer, _O_bject, c_H_ar */ + char is_unsigned; + int flags; +} __Pyx_TypeInfo; + +typedef struct __Pyx_StructField_ { + __Pyx_TypeInfo* type; + const char* name; + size_t offset; +} __Pyx_StructField; + +typedef struct { + __Pyx_StructField* field; + size_t parent_offset; +} __Pyx_BufFmt_StackElem; + +typedef struct { + __Pyx_StructField root; + __Pyx_BufFmt_StackElem* head; + size_t fmt_offset; + size_t new_count, enc_count; + size_t struct_alignment; + int is_complex; + char enc_type; + char new_packmode; + char enc_packmode; + char is_valid_array; +} __Pyx_BufFmt_Context; + + +/////////////// GetAndReleaseBuffer.proto /////////////// + +#if PY_MAJOR_VERSION < 3 + static int __Pyx_GetBuffer(PyObject *obj, Py_buffer *view, int flags); + static void __Pyx_ReleaseBuffer(Py_buffer *view); +#else + #define __Pyx_GetBuffer PyObject_GetBuffer + #define __Pyx_ReleaseBuffer PyBuffer_Release +#endif + +/////////////// GetAndReleaseBuffer /////////////// + +#if PY_MAJOR_VERSION < 3 +static int __Pyx_GetBuffer(PyObject *obj, Py_buffer *view, int flags) { + if (PyObject_CheckBuffer(obj)) return PyObject_GetBuffer(obj, view, flags); + + {{for type_ptr, getbuffer, releasebuffer in types}} + {{if getbuffer}} if (__Pyx_TypeCheck(obj, {{type_ptr}})) return {{getbuffer}}(obj, view, flags); - {{endif}} - {{endfor}} - - PyErr_Format(PyExc_TypeError, "'%.200s' does not have the buffer interface", Py_TYPE(obj)->tp_name); - return -1; -} - -static void __Pyx_ReleaseBuffer(Py_buffer *view) { - PyObject *obj = view->obj; - if (!obj) return; - - if (PyObject_CheckBuffer(obj)) { - PyBuffer_Release(view); - return; - } - + {{endif}} + {{endfor}} + + PyErr_Format(PyExc_TypeError, "'%.200s' does not have the buffer interface", Py_TYPE(obj)->tp_name); + return -1; +} + +static void __Pyx_ReleaseBuffer(Py_buffer *view) { + PyObject *obj = view->obj; + if (!obj) return; + + if (PyObject_CheckBuffer(obj)) { + PyBuffer_Release(view); + return; + } + if ((0)) {} - {{for type_ptr, getbuffer, releasebuffer in types}} - {{if releasebuffer}} + {{for type_ptr, getbuffer, releasebuffer in types}} + {{if releasebuffer}} else if (__Pyx_TypeCheck(obj, {{type_ptr}})) {{releasebuffer}}(obj, view); - {{endif}} - {{endfor}} - + {{endif}} + {{endfor}} + view->obj = NULL; - Py_DECREF(obj); -} - -#endif /* PY_MAJOR_VERSION < 3 */ - - + Py_DECREF(obj); +} + +#endif /* PY_MAJOR_VERSION < 3 */ + + /////////////// BufferGetAndValidate.proto /////////////// - + #define __Pyx_GetBufferAndValidate(buf, obj, dtype, flags, nd, cast, stack) \ ((obj == Py_None || obj == NULL) ? \ (__Pyx_ZeroBuffer(buf), 0) : \ __Pyx__GetBufferAndValidate(buf, obj, dtype, flags, nd, cast, stack)) - + static int __Pyx__GetBufferAndValidate(Py_buffer* buf, PyObject* obj, __Pyx_TypeInfo* dtype, int flags, int nd, int cast, __Pyx_BufFmt_StackElem* stack); static void __Pyx_ZeroBuffer(Py_buffer* buf); static CYTHON_INLINE void __Pyx_SafeReleaseBuffer(Py_buffer* info);/*proto*/ - + static Py_ssize_t __Pyx_minusones[] = { {{ ", ".join(["-1"] * max_dims) }} }; static Py_ssize_t __Pyx_zeros[] = { {{ ", ".join(["0"] * max_dims) }} }; - + /////////////// BufferGetAndValidate /////////////// //@requires: BufferFormatCheck @@ -233,689 +233,689 @@ static const char* __Pyx_BufFmt_CheckString(__Pyx_BufFmt_Context* ctx, const cha static void __Pyx_BufFmt_Init(__Pyx_BufFmt_Context* ctx, __Pyx_BufFmt_StackElem* stack, __Pyx_TypeInfo* type); /*proto*/ - -/////////////// BufferFormatCheck /////////////// + +/////////////// BufferFormatCheck /////////////// //@requires: ModuleSetupCode.c::IsLittleEndian //@requires: BufferFormatStructs - -static void __Pyx_BufFmt_Init(__Pyx_BufFmt_Context* ctx, - __Pyx_BufFmt_StackElem* stack, - __Pyx_TypeInfo* type) { - stack[0].field = &ctx->root; - stack[0].parent_offset = 0; - ctx->root.type = type; - ctx->root.name = "buffer dtype"; - ctx->root.offset = 0; - ctx->head = stack; - ctx->head->field = &ctx->root; - ctx->fmt_offset = 0; - ctx->head->parent_offset = 0; - ctx->new_packmode = '@'; - ctx->enc_packmode = '@'; - ctx->new_count = 1; - ctx->enc_count = 0; - ctx->enc_type = 0; - ctx->is_complex = 0; - ctx->is_valid_array = 0; - ctx->struct_alignment = 0; - while (type->typegroup == 'S') { - ++ctx->head; - ctx->head->field = type->fields; - ctx->head->parent_offset = 0; - type = type->fields->type; - } -} - -static int __Pyx_BufFmt_ParseNumber(const char** ts) { - int count; - const char* t = *ts; - if (*t < '0' || *t > '9') { - return -1; - } else { - count = *t++ - '0'; + +static void __Pyx_BufFmt_Init(__Pyx_BufFmt_Context* ctx, + __Pyx_BufFmt_StackElem* stack, + __Pyx_TypeInfo* type) { + stack[0].field = &ctx->root; + stack[0].parent_offset = 0; + ctx->root.type = type; + ctx->root.name = "buffer dtype"; + ctx->root.offset = 0; + ctx->head = stack; + ctx->head->field = &ctx->root; + ctx->fmt_offset = 0; + ctx->head->parent_offset = 0; + ctx->new_packmode = '@'; + ctx->enc_packmode = '@'; + ctx->new_count = 1; + ctx->enc_count = 0; + ctx->enc_type = 0; + ctx->is_complex = 0; + ctx->is_valid_array = 0; + ctx->struct_alignment = 0; + while (type->typegroup == 'S') { + ++ctx->head; + ctx->head->field = type->fields; + ctx->head->parent_offset = 0; + type = type->fields->type; + } +} + +static int __Pyx_BufFmt_ParseNumber(const char** ts) { + int count; + const char* t = *ts; + if (*t < '0' || *t > '9') { + return -1; + } else { + count = *t++ - '0'; while (*t >= '0' && *t <= '9') { - count *= 10; - count += *t++ - '0'; - } - } - *ts = t; - return count; -} - -static int __Pyx_BufFmt_ExpectNumber(const char **ts) { - int number = __Pyx_BufFmt_ParseNumber(ts); - if (number == -1) /* First char was not a digit */ - PyErr_Format(PyExc_ValueError,\ - "Does not understand character buffer dtype format string ('%c')", **ts); - return number; -} - - -static void __Pyx_BufFmt_RaiseUnexpectedChar(char ch) { - PyErr_Format(PyExc_ValueError, - "Unexpected format string character: '%c'", ch); -} - -static const char* __Pyx_BufFmt_DescribeTypeChar(char ch, int is_complex) { - switch (ch) { + count *= 10; + count += *t++ - '0'; + } + } + *ts = t; + return count; +} + +static int __Pyx_BufFmt_ExpectNumber(const char **ts) { + int number = __Pyx_BufFmt_ParseNumber(ts); + if (number == -1) /* First char was not a digit */ + PyErr_Format(PyExc_ValueError,\ + "Does not understand character buffer dtype format string ('%c')", **ts); + return number; +} + + +static void __Pyx_BufFmt_RaiseUnexpectedChar(char ch) { + PyErr_Format(PyExc_ValueError, + "Unexpected format string character: '%c'", ch); +} + +static const char* __Pyx_BufFmt_DescribeTypeChar(char ch, int is_complex) { + switch (ch) { case '?': return "'bool'"; - case 'c': return "'char'"; - case 'b': return "'signed char'"; - case 'B': return "'unsigned char'"; - case 'h': return "'short'"; - case 'H': return "'unsigned short'"; - case 'i': return "'int'"; - case 'I': return "'unsigned int'"; - case 'l': return "'long'"; - case 'L': return "'unsigned long'"; - case 'q': return "'long long'"; - case 'Q': return "'unsigned long long'"; - case 'f': return (is_complex ? "'complex float'" : "'float'"); - case 'd': return (is_complex ? "'complex double'" : "'double'"); - case 'g': return (is_complex ? "'complex long double'" : "'long double'"); - case 'T': return "a struct"; - case 'O': return "Python object"; - case 'P': return "a pointer"; - case 's': case 'p': return "a string"; - case 0: return "end"; - default: return "unparseable format string"; - } -} - -static size_t __Pyx_BufFmt_TypeCharToStandardSize(char ch, int is_complex) { - switch (ch) { + case 'c': return "'char'"; + case 'b': return "'signed char'"; + case 'B': return "'unsigned char'"; + case 'h': return "'short'"; + case 'H': return "'unsigned short'"; + case 'i': return "'int'"; + case 'I': return "'unsigned int'"; + case 'l': return "'long'"; + case 'L': return "'unsigned long'"; + case 'q': return "'long long'"; + case 'Q': return "'unsigned long long'"; + case 'f': return (is_complex ? "'complex float'" : "'float'"); + case 'd': return (is_complex ? "'complex double'" : "'double'"); + case 'g': return (is_complex ? "'complex long double'" : "'long double'"); + case 'T': return "a struct"; + case 'O': return "Python object"; + case 'P': return "a pointer"; + case 's': case 'p': return "a string"; + case 0: return "end"; + default: return "unparseable format string"; + } +} + +static size_t __Pyx_BufFmt_TypeCharToStandardSize(char ch, int is_complex) { + switch (ch) { + case '?': case 'c': case 'b': case 'B': case 's': case 'p': return 1; + case 'h': case 'H': return 2; + case 'i': case 'I': case 'l': case 'L': return 4; + case 'q': case 'Q': return 8; + case 'f': return (is_complex ? 8 : 4); + case 'd': return (is_complex ? 16 : 8); + case 'g': { + PyErr_SetString(PyExc_ValueError, "Python does not define a standard format string size for long double ('g').."); + return 0; + } + case 'O': case 'P': return sizeof(void*); + default: + __Pyx_BufFmt_RaiseUnexpectedChar(ch); + return 0; + } +} + +static size_t __Pyx_BufFmt_TypeCharToNativeSize(char ch, int is_complex) { + switch (ch) { case '?': case 'c': case 'b': case 'B': case 's': case 'p': return 1; - case 'h': case 'H': return 2; - case 'i': case 'I': case 'l': case 'L': return 4; - case 'q': case 'Q': return 8; - case 'f': return (is_complex ? 8 : 4); - case 'd': return (is_complex ? 16 : 8); - case 'g': { - PyErr_SetString(PyExc_ValueError, "Python does not define a standard format string size for long double ('g').."); - return 0; - } - case 'O': case 'P': return sizeof(void*); - default: - __Pyx_BufFmt_RaiseUnexpectedChar(ch); - return 0; - } -} - -static size_t __Pyx_BufFmt_TypeCharToNativeSize(char ch, int is_complex) { - switch (ch) { - case '?': case 'c': case 'b': case 'B': case 's': case 'p': return 1; - case 'h': case 'H': return sizeof(short); - case 'i': case 'I': return sizeof(int); - case 'l': case 'L': return sizeof(long); - #ifdef HAVE_LONG_LONG - case 'q': case 'Q': return sizeof(PY_LONG_LONG); - #endif - case 'f': return sizeof(float) * (is_complex ? 2 : 1); - case 'd': return sizeof(double) * (is_complex ? 2 : 1); - case 'g': return sizeof(long double) * (is_complex ? 2 : 1); - case 'O': case 'P': return sizeof(void*); - default: { - __Pyx_BufFmt_RaiseUnexpectedChar(ch); - return 0; - } - } -} - -typedef struct { char c; short x; } __Pyx_st_short; -typedef struct { char c; int x; } __Pyx_st_int; -typedef struct { char c; long x; } __Pyx_st_long; -typedef struct { char c; float x; } __Pyx_st_float; -typedef struct { char c; double x; } __Pyx_st_double; -typedef struct { char c; long double x; } __Pyx_st_longdouble; -typedef struct { char c; void *x; } __Pyx_st_void_p; -#ifdef HAVE_LONG_LONG -typedef struct { char c; PY_LONG_LONG x; } __Pyx_st_longlong; -#endif - -static size_t __Pyx_BufFmt_TypeCharToAlignment(char ch, CYTHON_UNUSED int is_complex) { - switch (ch) { - case '?': case 'c': case 'b': case 'B': case 's': case 'p': return 1; - case 'h': case 'H': return sizeof(__Pyx_st_short) - sizeof(short); - case 'i': case 'I': return sizeof(__Pyx_st_int) - sizeof(int); - case 'l': case 'L': return sizeof(__Pyx_st_long) - sizeof(long); -#ifdef HAVE_LONG_LONG - case 'q': case 'Q': return sizeof(__Pyx_st_longlong) - sizeof(PY_LONG_LONG); -#endif - case 'f': return sizeof(__Pyx_st_float) - sizeof(float); - case 'd': return sizeof(__Pyx_st_double) - sizeof(double); - case 'g': return sizeof(__Pyx_st_longdouble) - sizeof(long double); - case 'P': case 'O': return sizeof(__Pyx_st_void_p) - sizeof(void*); - default: - __Pyx_BufFmt_RaiseUnexpectedChar(ch); - return 0; - } -} - -/* These are for computing the padding at the end of the struct to align - on the first member of the struct. This will probably the same as above, - but we don't have any guarantees. - */ -typedef struct { short x; char c; } __Pyx_pad_short; -typedef struct { int x; char c; } __Pyx_pad_int; -typedef struct { long x; char c; } __Pyx_pad_long; -typedef struct { float x; char c; } __Pyx_pad_float; -typedef struct { double x; char c; } __Pyx_pad_double; -typedef struct { long double x; char c; } __Pyx_pad_longdouble; -typedef struct { void *x; char c; } __Pyx_pad_void_p; -#ifdef HAVE_LONG_LONG -typedef struct { PY_LONG_LONG x; char c; } __Pyx_pad_longlong; -#endif - -static size_t __Pyx_BufFmt_TypeCharToPadding(char ch, CYTHON_UNUSED int is_complex) { - switch (ch) { - case '?': case 'c': case 'b': case 'B': case 's': case 'p': return 1; - case 'h': case 'H': return sizeof(__Pyx_pad_short) - sizeof(short); - case 'i': case 'I': return sizeof(__Pyx_pad_int) - sizeof(int); - case 'l': case 'L': return sizeof(__Pyx_pad_long) - sizeof(long); -#ifdef HAVE_LONG_LONG - case 'q': case 'Q': return sizeof(__Pyx_pad_longlong) - sizeof(PY_LONG_LONG); -#endif - case 'f': return sizeof(__Pyx_pad_float) - sizeof(float); - case 'd': return sizeof(__Pyx_pad_double) - sizeof(double); - case 'g': return sizeof(__Pyx_pad_longdouble) - sizeof(long double); - case 'P': case 'O': return sizeof(__Pyx_pad_void_p) - sizeof(void*); - default: - __Pyx_BufFmt_RaiseUnexpectedChar(ch); - return 0; - } -} - -static char __Pyx_BufFmt_TypeCharToGroup(char ch, int is_complex) { - switch (ch) { - case 'c': - return 'H'; - case 'b': case 'h': case 'i': - case 'l': case 'q': case 's': case 'p': - return 'I'; + case 'h': case 'H': return sizeof(short); + case 'i': case 'I': return sizeof(int); + case 'l': case 'L': return sizeof(long); + #ifdef HAVE_LONG_LONG + case 'q': case 'Q': return sizeof(PY_LONG_LONG); + #endif + case 'f': return sizeof(float) * (is_complex ? 2 : 1); + case 'd': return sizeof(double) * (is_complex ? 2 : 1); + case 'g': return sizeof(long double) * (is_complex ? 2 : 1); + case 'O': case 'P': return sizeof(void*); + default: { + __Pyx_BufFmt_RaiseUnexpectedChar(ch); + return 0; + } + } +} + +typedef struct { char c; short x; } __Pyx_st_short; +typedef struct { char c; int x; } __Pyx_st_int; +typedef struct { char c; long x; } __Pyx_st_long; +typedef struct { char c; float x; } __Pyx_st_float; +typedef struct { char c; double x; } __Pyx_st_double; +typedef struct { char c; long double x; } __Pyx_st_longdouble; +typedef struct { char c; void *x; } __Pyx_st_void_p; +#ifdef HAVE_LONG_LONG +typedef struct { char c; PY_LONG_LONG x; } __Pyx_st_longlong; +#endif + +static size_t __Pyx_BufFmt_TypeCharToAlignment(char ch, CYTHON_UNUSED int is_complex) { + switch (ch) { + case '?': case 'c': case 'b': case 'B': case 's': case 'p': return 1; + case 'h': case 'H': return sizeof(__Pyx_st_short) - sizeof(short); + case 'i': case 'I': return sizeof(__Pyx_st_int) - sizeof(int); + case 'l': case 'L': return sizeof(__Pyx_st_long) - sizeof(long); +#ifdef HAVE_LONG_LONG + case 'q': case 'Q': return sizeof(__Pyx_st_longlong) - sizeof(PY_LONG_LONG); +#endif + case 'f': return sizeof(__Pyx_st_float) - sizeof(float); + case 'd': return sizeof(__Pyx_st_double) - sizeof(double); + case 'g': return sizeof(__Pyx_st_longdouble) - sizeof(long double); + case 'P': case 'O': return sizeof(__Pyx_st_void_p) - sizeof(void*); + default: + __Pyx_BufFmt_RaiseUnexpectedChar(ch); + return 0; + } +} + +/* These are for computing the padding at the end of the struct to align + on the first member of the struct. This will probably the same as above, + but we don't have any guarantees. + */ +typedef struct { short x; char c; } __Pyx_pad_short; +typedef struct { int x; char c; } __Pyx_pad_int; +typedef struct { long x; char c; } __Pyx_pad_long; +typedef struct { float x; char c; } __Pyx_pad_float; +typedef struct { double x; char c; } __Pyx_pad_double; +typedef struct { long double x; char c; } __Pyx_pad_longdouble; +typedef struct { void *x; char c; } __Pyx_pad_void_p; +#ifdef HAVE_LONG_LONG +typedef struct { PY_LONG_LONG x; char c; } __Pyx_pad_longlong; +#endif + +static size_t __Pyx_BufFmt_TypeCharToPadding(char ch, CYTHON_UNUSED int is_complex) { + switch (ch) { + case '?': case 'c': case 'b': case 'B': case 's': case 'p': return 1; + case 'h': case 'H': return sizeof(__Pyx_pad_short) - sizeof(short); + case 'i': case 'I': return sizeof(__Pyx_pad_int) - sizeof(int); + case 'l': case 'L': return sizeof(__Pyx_pad_long) - sizeof(long); +#ifdef HAVE_LONG_LONG + case 'q': case 'Q': return sizeof(__Pyx_pad_longlong) - sizeof(PY_LONG_LONG); +#endif + case 'f': return sizeof(__Pyx_pad_float) - sizeof(float); + case 'd': return sizeof(__Pyx_pad_double) - sizeof(double); + case 'g': return sizeof(__Pyx_pad_longdouble) - sizeof(long double); + case 'P': case 'O': return sizeof(__Pyx_pad_void_p) - sizeof(void*); + default: + __Pyx_BufFmt_RaiseUnexpectedChar(ch); + return 0; + } +} + +static char __Pyx_BufFmt_TypeCharToGroup(char ch, int is_complex) { + switch (ch) { + case 'c': + return 'H'; + case 'b': case 'h': case 'i': + case 'l': case 'q': case 's': case 'p': + return 'I'; case '?': case 'B': case 'H': case 'I': case 'L': case 'Q': - return 'U'; - case 'f': case 'd': case 'g': - return (is_complex ? 'C' : 'R'); - case 'O': - return 'O'; - case 'P': - return 'P'; - default: { - __Pyx_BufFmt_RaiseUnexpectedChar(ch); - return 0; - } - } -} - - -static void __Pyx_BufFmt_RaiseExpected(__Pyx_BufFmt_Context* ctx) { - if (ctx->head == NULL || ctx->head->field == &ctx->root) { - const char* expected; - const char* quote; - if (ctx->head == NULL) { - expected = "end"; - quote = ""; - } else { - expected = ctx->head->field->type->name; - quote = "'"; - } - PyErr_Format(PyExc_ValueError, - "Buffer dtype mismatch, expected %s%s%s but got %s", - quote, expected, quote, - __Pyx_BufFmt_DescribeTypeChar(ctx->enc_type, ctx->is_complex)); - } else { - __Pyx_StructField* field = ctx->head->field; - __Pyx_StructField* parent = (ctx->head - 1)->field; - PyErr_Format(PyExc_ValueError, - "Buffer dtype mismatch, expected '%s' but got %s in '%s.%s'", - field->type->name, __Pyx_BufFmt_DescribeTypeChar(ctx->enc_type, ctx->is_complex), - parent->type->name, field->name); - } -} - -static int __Pyx_BufFmt_ProcessTypeChunk(__Pyx_BufFmt_Context* ctx) { - char group; - size_t size, offset, arraysize = 1; - - /* printf("processing... %s\n", ctx->head->field->type->name); */ - - if (ctx->enc_type == 0) return 0; - - /* Validate array size */ - if (ctx->head->field->type->arraysize[0]) { - int i, ndim = 0; - - /* handle strings ('s' and 'p') */ - if (ctx->enc_type == 's' || ctx->enc_type == 'p') { - ctx->is_valid_array = ctx->head->field->type->ndim == 1; - ndim = 1; - if (ctx->enc_count != ctx->head->field->type->arraysize[0]) { - PyErr_Format(PyExc_ValueError, - "Expected a dimension of size %zu, got %zu", - ctx->head->field->type->arraysize[0], ctx->enc_count); - return -1; - } - } - - if (!ctx->is_valid_array) { - PyErr_Format(PyExc_ValueError, "Expected %d dimensions, got %d", - ctx->head->field->type->ndim, ndim); - return -1; - } - for (i = 0; i < ctx->head->field->type->ndim; i++) { - arraysize *= ctx->head->field->type->arraysize[i]; - } - ctx->is_valid_array = 0; - ctx->enc_count = 1; - } - - group = __Pyx_BufFmt_TypeCharToGroup(ctx->enc_type, ctx->is_complex); - do { - __Pyx_StructField* field = ctx->head->field; - __Pyx_TypeInfo* type = field->type; - - if (ctx->enc_packmode == '@' || ctx->enc_packmode == '^') { - size = __Pyx_BufFmt_TypeCharToNativeSize(ctx->enc_type, ctx->is_complex); - } else { - size = __Pyx_BufFmt_TypeCharToStandardSize(ctx->enc_type, ctx->is_complex); - } - - if (ctx->enc_packmode == '@') { - size_t align_at = __Pyx_BufFmt_TypeCharToAlignment(ctx->enc_type, ctx->is_complex); - size_t align_mod_offset; - if (align_at == 0) return -1; - align_mod_offset = ctx->fmt_offset % align_at; - if (align_mod_offset > 0) ctx->fmt_offset += align_at - align_mod_offset; - - if (ctx->struct_alignment == 0) - ctx->struct_alignment = __Pyx_BufFmt_TypeCharToPadding(ctx->enc_type, - ctx->is_complex); - } - - if (type->size != size || type->typegroup != group) { - if (type->typegroup == 'C' && type->fields != NULL) { - /* special case -- treat as struct rather than complex number */ - size_t parent_offset = ctx->head->parent_offset + field->offset; - ++ctx->head; - ctx->head->field = type->fields; - ctx->head->parent_offset = parent_offset; - continue; - } - - if ((type->typegroup == 'H' || group == 'H') && type->size == size) { - /* special case -- chars don't care about sign */ - } else { - __Pyx_BufFmt_RaiseExpected(ctx); - return -1; - } - } - - offset = ctx->head->parent_offset + field->offset; - if (ctx->fmt_offset != offset) { - PyErr_Format(PyExc_ValueError, - "Buffer dtype mismatch; next field is at offset %" CYTHON_FORMAT_SSIZE_T "d but %" CYTHON_FORMAT_SSIZE_T "d expected", - (Py_ssize_t)ctx->fmt_offset, (Py_ssize_t)offset); - return -1; - } - - ctx->fmt_offset += size; - if (arraysize) - ctx->fmt_offset += (arraysize - 1) * size; - - --ctx->enc_count; /* Consume from buffer string */ - - /* Done checking, move to next field, pushing or popping struct stack if needed */ - while (1) { - if (field == &ctx->root) { - ctx->head = NULL; - if (ctx->enc_count != 0) { - __Pyx_BufFmt_RaiseExpected(ctx); - return -1; - } - break; /* breaks both loops as ctx->enc_count == 0 */ - } - ctx->head->field = ++field; - if (field->type == NULL) { - --ctx->head; - field = ctx->head->field; - continue; - } else if (field->type->typegroup == 'S') { - size_t parent_offset = ctx->head->parent_offset + field->offset; - if (field->type->fields->type == NULL) continue; /* empty struct */ - field = field->type->fields; - ++ctx->head; - ctx->head->field = field; - ctx->head->parent_offset = parent_offset; - break; - } else { - break; - } - } - } while (ctx->enc_count); - ctx->enc_type = 0; - ctx->is_complex = 0; - return 0; -} - -/* Parse an array in the format string (e.g. (1,2,3)) */ + return 'U'; + case 'f': case 'd': case 'g': + return (is_complex ? 'C' : 'R'); + case 'O': + return 'O'; + case 'P': + return 'P'; + default: { + __Pyx_BufFmt_RaiseUnexpectedChar(ch); + return 0; + } + } +} + + +static void __Pyx_BufFmt_RaiseExpected(__Pyx_BufFmt_Context* ctx) { + if (ctx->head == NULL || ctx->head->field == &ctx->root) { + const char* expected; + const char* quote; + if (ctx->head == NULL) { + expected = "end"; + quote = ""; + } else { + expected = ctx->head->field->type->name; + quote = "'"; + } + PyErr_Format(PyExc_ValueError, + "Buffer dtype mismatch, expected %s%s%s but got %s", + quote, expected, quote, + __Pyx_BufFmt_DescribeTypeChar(ctx->enc_type, ctx->is_complex)); + } else { + __Pyx_StructField* field = ctx->head->field; + __Pyx_StructField* parent = (ctx->head - 1)->field; + PyErr_Format(PyExc_ValueError, + "Buffer dtype mismatch, expected '%s' but got %s in '%s.%s'", + field->type->name, __Pyx_BufFmt_DescribeTypeChar(ctx->enc_type, ctx->is_complex), + parent->type->name, field->name); + } +} + +static int __Pyx_BufFmt_ProcessTypeChunk(__Pyx_BufFmt_Context* ctx) { + char group; + size_t size, offset, arraysize = 1; + + /* printf("processing... %s\n", ctx->head->field->type->name); */ + + if (ctx->enc_type == 0) return 0; + + /* Validate array size */ + if (ctx->head->field->type->arraysize[0]) { + int i, ndim = 0; + + /* handle strings ('s' and 'p') */ + if (ctx->enc_type == 's' || ctx->enc_type == 'p') { + ctx->is_valid_array = ctx->head->field->type->ndim == 1; + ndim = 1; + if (ctx->enc_count != ctx->head->field->type->arraysize[0]) { + PyErr_Format(PyExc_ValueError, + "Expected a dimension of size %zu, got %zu", + ctx->head->field->type->arraysize[0], ctx->enc_count); + return -1; + } + } + + if (!ctx->is_valid_array) { + PyErr_Format(PyExc_ValueError, "Expected %d dimensions, got %d", + ctx->head->field->type->ndim, ndim); + return -1; + } + for (i = 0; i < ctx->head->field->type->ndim; i++) { + arraysize *= ctx->head->field->type->arraysize[i]; + } + ctx->is_valid_array = 0; + ctx->enc_count = 1; + } + + group = __Pyx_BufFmt_TypeCharToGroup(ctx->enc_type, ctx->is_complex); + do { + __Pyx_StructField* field = ctx->head->field; + __Pyx_TypeInfo* type = field->type; + + if (ctx->enc_packmode == '@' || ctx->enc_packmode == '^') { + size = __Pyx_BufFmt_TypeCharToNativeSize(ctx->enc_type, ctx->is_complex); + } else { + size = __Pyx_BufFmt_TypeCharToStandardSize(ctx->enc_type, ctx->is_complex); + } + + if (ctx->enc_packmode == '@') { + size_t align_at = __Pyx_BufFmt_TypeCharToAlignment(ctx->enc_type, ctx->is_complex); + size_t align_mod_offset; + if (align_at == 0) return -1; + align_mod_offset = ctx->fmt_offset % align_at; + if (align_mod_offset > 0) ctx->fmt_offset += align_at - align_mod_offset; + + if (ctx->struct_alignment == 0) + ctx->struct_alignment = __Pyx_BufFmt_TypeCharToPadding(ctx->enc_type, + ctx->is_complex); + } + + if (type->size != size || type->typegroup != group) { + if (type->typegroup == 'C' && type->fields != NULL) { + /* special case -- treat as struct rather than complex number */ + size_t parent_offset = ctx->head->parent_offset + field->offset; + ++ctx->head; + ctx->head->field = type->fields; + ctx->head->parent_offset = parent_offset; + continue; + } + + if ((type->typegroup == 'H' || group == 'H') && type->size == size) { + /* special case -- chars don't care about sign */ + } else { + __Pyx_BufFmt_RaiseExpected(ctx); + return -1; + } + } + + offset = ctx->head->parent_offset + field->offset; + if (ctx->fmt_offset != offset) { + PyErr_Format(PyExc_ValueError, + "Buffer dtype mismatch; next field is at offset %" CYTHON_FORMAT_SSIZE_T "d but %" CYTHON_FORMAT_SSIZE_T "d expected", + (Py_ssize_t)ctx->fmt_offset, (Py_ssize_t)offset); + return -1; + } + + ctx->fmt_offset += size; + if (arraysize) + ctx->fmt_offset += (arraysize - 1) * size; + + --ctx->enc_count; /* Consume from buffer string */ + + /* Done checking, move to next field, pushing or popping struct stack if needed */ + while (1) { + if (field == &ctx->root) { + ctx->head = NULL; + if (ctx->enc_count != 0) { + __Pyx_BufFmt_RaiseExpected(ctx); + return -1; + } + break; /* breaks both loops as ctx->enc_count == 0 */ + } + ctx->head->field = ++field; + if (field->type == NULL) { + --ctx->head; + field = ctx->head->field; + continue; + } else if (field->type->typegroup == 'S') { + size_t parent_offset = ctx->head->parent_offset + field->offset; + if (field->type->fields->type == NULL) continue; /* empty struct */ + field = field->type->fields; + ++ctx->head; + ctx->head->field = field; + ctx->head->parent_offset = parent_offset; + break; + } else { + break; + } + } + } while (ctx->enc_count); + ctx->enc_type = 0; + ctx->is_complex = 0; + return 0; +} + +/* Parse an array in the format string (e.g. (1,2,3)) */ static PyObject * -__pyx_buffmt_parse_array(__Pyx_BufFmt_Context* ctx, const char** tsp) -{ - const char *ts = *tsp; +__pyx_buffmt_parse_array(__Pyx_BufFmt_Context* ctx, const char** tsp) +{ + const char *ts = *tsp; int i = 0, number, ndim; - ++ts; - if (ctx->new_count != 1) { - PyErr_SetString(PyExc_ValueError, - "Cannot handle repeated arrays in format string"); - return NULL; - } - - /* Process the previous element */ - if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; - + ++ts; + if (ctx->new_count != 1) { + PyErr_SetString(PyExc_ValueError, + "Cannot handle repeated arrays in format string"); + return NULL; + } + + /* Process the previous element */ + if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; + // store ndim now, as field advanced by __Pyx_BufFmt_ProcessTypeChunk call ndim = ctx->head->field->type->ndim; - /* Parse all numbers in the format string */ - while (*ts && *ts != ')') { - // ignore space characters (not using isspace() due to C/C++ problem on MacOS-X) - switch (*ts) { - case ' ': case '\f': case '\r': case '\n': case '\t': case '\v': continue; - default: break; /* not a 'break' in the loop */ - } - - number = __Pyx_BufFmt_ExpectNumber(&ts); - if (number == -1) return NULL; - - if (i < ndim && (size_t) number != ctx->head->field->type->arraysize[i]) - return PyErr_Format(PyExc_ValueError, - "Expected a dimension of size %zu, got %d", - ctx->head->field->type->arraysize[i], number); - - if (*ts != ',' && *ts != ')') - return PyErr_Format(PyExc_ValueError, - "Expected a comma in format string, got '%c'", *ts); - - if (*ts == ',') ts++; - i++; - } - - if (i != ndim) - return PyErr_Format(PyExc_ValueError, "Expected %d dimension(s), got %d", - ctx->head->field->type->ndim, i); - - if (!*ts) { - PyErr_SetString(PyExc_ValueError, - "Unexpected end of format string, expected ')'"); - return NULL; - } - - ctx->is_valid_array = 1; - ctx->new_count = 1; - *tsp = ++ts; - return Py_None; -} - -static const char* __Pyx_BufFmt_CheckString(__Pyx_BufFmt_Context* ctx, const char* ts) { - int got_Z = 0; - - while (1) { - /* puts(ts); */ - switch(*ts) { - case 0: - if (ctx->enc_type != 0 && ctx->head == NULL) { - __Pyx_BufFmt_RaiseExpected(ctx); - return NULL; - } - if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; - if (ctx->head != NULL) { - __Pyx_BufFmt_RaiseExpected(ctx); - return NULL; - } - return ts; - case ' ': - case '\r': - case '\n': - ++ts; - break; - case '<': + /* Parse all numbers in the format string */ + while (*ts && *ts != ')') { + // ignore space characters (not using isspace() due to C/C++ problem on MacOS-X) + switch (*ts) { + case ' ': case '\f': case '\r': case '\n': case '\t': case '\v': continue; + default: break; /* not a 'break' in the loop */ + } + + number = __Pyx_BufFmt_ExpectNumber(&ts); + if (number == -1) return NULL; + + if (i < ndim && (size_t) number != ctx->head->field->type->arraysize[i]) + return PyErr_Format(PyExc_ValueError, + "Expected a dimension of size %zu, got %d", + ctx->head->field->type->arraysize[i], number); + + if (*ts != ',' && *ts != ')') + return PyErr_Format(PyExc_ValueError, + "Expected a comma in format string, got '%c'", *ts); + + if (*ts == ',') ts++; + i++; + } + + if (i != ndim) + return PyErr_Format(PyExc_ValueError, "Expected %d dimension(s), got %d", + ctx->head->field->type->ndim, i); + + if (!*ts) { + PyErr_SetString(PyExc_ValueError, + "Unexpected end of format string, expected ')'"); + return NULL; + } + + ctx->is_valid_array = 1; + ctx->new_count = 1; + *tsp = ++ts; + return Py_None; +} + +static const char* __Pyx_BufFmt_CheckString(__Pyx_BufFmt_Context* ctx, const char* ts) { + int got_Z = 0; + + while (1) { + /* puts(ts); */ + switch(*ts) { + case 0: + if (ctx->enc_type != 0 && ctx->head == NULL) { + __Pyx_BufFmt_RaiseExpected(ctx); + return NULL; + } + if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; + if (ctx->head != NULL) { + __Pyx_BufFmt_RaiseExpected(ctx); + return NULL; + } + return ts; + case ' ': + case '\r': + case '\n': + ++ts; + break; + case '<': if (!__Pyx_Is_Little_Endian()) { - PyErr_SetString(PyExc_ValueError, "Little-endian buffer not supported on big-endian compiler"); - return NULL; - } - ctx->new_packmode = '='; - ++ts; - break; - case '>': - case '!': + PyErr_SetString(PyExc_ValueError, "Little-endian buffer not supported on big-endian compiler"); + return NULL; + } + ctx->new_packmode = '='; + ++ts; + break; + case '>': + case '!': if (__Pyx_Is_Little_Endian()) { - PyErr_SetString(PyExc_ValueError, "Big-endian buffer not supported on little-endian compiler"); - return NULL; - } - ctx->new_packmode = '='; - ++ts; - break; - case '=': - case '@': - case '^': - ctx->new_packmode = *ts++; - break; - case 'T': /* substruct */ - { - const char* ts_after_sub; - size_t i, struct_count = ctx->new_count; - size_t struct_alignment = ctx->struct_alignment; - ctx->new_count = 1; - ++ts; - if (*ts != '{') { - PyErr_SetString(PyExc_ValueError, "Buffer acquisition: Expected '{' after 'T'"); - return NULL; - } - if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; - ctx->enc_type = 0; /* Erase processed last struct element */ - ctx->enc_count = 0; - ctx->struct_alignment = 0; - ++ts; - ts_after_sub = ts; - for (i = 0; i != struct_count; ++i) { - ts_after_sub = __Pyx_BufFmt_CheckString(ctx, ts); - if (!ts_after_sub) return NULL; - } - ts = ts_after_sub; - if (struct_alignment) ctx->struct_alignment = struct_alignment; - } - break; - case '}': /* end of substruct; either repeat or move on */ - { - size_t alignment = ctx->struct_alignment; - ++ts; - if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; - ctx->enc_type = 0; /* Erase processed last struct element */ - if (alignment && ctx->fmt_offset % alignment) { - /* Pad struct on size of the first member */ - ctx->fmt_offset += alignment - (ctx->fmt_offset % alignment); - } - } - return ts; - case 'x': - if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; - ctx->fmt_offset += ctx->new_count; - ctx->new_count = 1; - ctx->enc_count = 0; - ctx->enc_type = 0; - ctx->enc_packmode = ctx->new_packmode; - ++ts; - break; - case 'Z': - got_Z = 1; - ++ts; - if (*ts != 'f' && *ts != 'd' && *ts != 'g') { - __Pyx_BufFmt_RaiseUnexpectedChar('Z'); - return NULL; - } + PyErr_SetString(PyExc_ValueError, "Big-endian buffer not supported on little-endian compiler"); + return NULL; + } + ctx->new_packmode = '='; + ++ts; + break; + case '=': + case '@': + case '^': + ctx->new_packmode = *ts++; + break; + case 'T': /* substruct */ + { + const char* ts_after_sub; + size_t i, struct_count = ctx->new_count; + size_t struct_alignment = ctx->struct_alignment; + ctx->new_count = 1; + ++ts; + if (*ts != '{') { + PyErr_SetString(PyExc_ValueError, "Buffer acquisition: Expected '{' after 'T'"); + return NULL; + } + if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; + ctx->enc_type = 0; /* Erase processed last struct element */ + ctx->enc_count = 0; + ctx->struct_alignment = 0; + ++ts; + ts_after_sub = ts; + for (i = 0; i != struct_count; ++i) { + ts_after_sub = __Pyx_BufFmt_CheckString(ctx, ts); + if (!ts_after_sub) return NULL; + } + ts = ts_after_sub; + if (struct_alignment) ctx->struct_alignment = struct_alignment; + } + break; + case '}': /* end of substruct; either repeat or move on */ + { + size_t alignment = ctx->struct_alignment; + ++ts; + if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; + ctx->enc_type = 0; /* Erase processed last struct element */ + if (alignment && ctx->fmt_offset % alignment) { + /* Pad struct on size of the first member */ + ctx->fmt_offset += alignment - (ctx->fmt_offset % alignment); + } + } + return ts; + case 'x': + if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; + ctx->fmt_offset += ctx->new_count; + ctx->new_count = 1; + ctx->enc_count = 0; + ctx->enc_type = 0; + ctx->enc_packmode = ctx->new_packmode; + ++ts; + break; + case 'Z': + got_Z = 1; + ++ts; + if (*ts != 'f' && *ts != 'd' && *ts != 'g') { + __Pyx_BufFmt_RaiseUnexpectedChar('Z'); + return NULL; + } CYTHON_FALLTHROUGH; case '?': case 'c': case 'b': case 'B': case 'h': case 'H': case 'i': case 'I': - case 'l': case 'L': case 'q': case 'Q': - case 'f': case 'd': case 'g': - case 'O': case 'p': + case 'l': case 'L': case 'q': case 'Q': + case 'f': case 'd': case 'g': + case 'O': case 'p': if ((ctx->enc_type == *ts) && (got_Z == ctx->is_complex) && (ctx->enc_packmode == ctx->new_packmode) && (!ctx->is_valid_array)) { - /* Continue pooling same type */ - ctx->enc_count += ctx->new_count; - ctx->new_count = 1; - got_Z = 0; - ++ts; - break; - } + /* Continue pooling same type */ + ctx->enc_count += ctx->new_count; + ctx->new_count = 1; + got_Z = 0; + ++ts; + break; + } CYTHON_FALLTHROUGH; - case 's': - /* 's' or new type (cannot be added to current pool) */ - if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; - ctx->enc_count = ctx->new_count; - ctx->enc_packmode = ctx->new_packmode; - ctx->enc_type = *ts; - ctx->is_complex = got_Z; - ++ts; - ctx->new_count = 1; - got_Z = 0; - break; - case ':': - ++ts; - while(*ts != ':') ++ts; - ++ts; - break; - case '(': - if (!__pyx_buffmt_parse_array(ctx, &ts)) return NULL; - break; - default: - { - int number = __Pyx_BufFmt_ExpectNumber(&ts); - if (number == -1) return NULL; - ctx->new_count = (size_t)number; - } - } - } -} - -/////////////// TypeInfoCompare.proto /////////////// -static int __pyx_typeinfo_cmp(__Pyx_TypeInfo *a, __Pyx_TypeInfo *b); - -/////////////// TypeInfoCompare /////////////// + case 's': + /* 's' or new type (cannot be added to current pool) */ + if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; + ctx->enc_count = ctx->new_count; + ctx->enc_packmode = ctx->new_packmode; + ctx->enc_type = *ts; + ctx->is_complex = got_Z; + ++ts; + ctx->new_count = 1; + got_Z = 0; + break; + case ':': + ++ts; + while(*ts != ':') ++ts; + ++ts; + break; + case '(': + if (!__pyx_buffmt_parse_array(ctx, &ts)) return NULL; + break; + default: + { + int number = __Pyx_BufFmt_ExpectNumber(&ts); + if (number == -1) return NULL; + ctx->new_count = (size_t)number; + } + } + } +} + +/////////////// TypeInfoCompare.proto /////////////// +static int __pyx_typeinfo_cmp(__Pyx_TypeInfo *a, __Pyx_TypeInfo *b); + +/////////////// TypeInfoCompare /////////////// //@requires: BufferFormatStructs // See if two dtypes are equal -static int -__pyx_typeinfo_cmp(__Pyx_TypeInfo *a, __Pyx_TypeInfo *b) -{ - int i; - - if (!a || !b) - return 0; - - if (a == b) - return 1; - - if (a->size != b->size || a->typegroup != b->typegroup || - a->is_unsigned != b->is_unsigned || a->ndim != b->ndim) { - if (a->typegroup == 'H' || b->typegroup == 'H') { - /* Special case for chars */ - return a->size == b->size; - } else { - return 0; - } - } - - if (a->ndim) { - /* Verify multidimensional C arrays */ - for (i = 0; i < a->ndim; i++) - if (a->arraysize[i] != b->arraysize[i]) - return 0; - } - - if (a->typegroup == 'S') { - /* Check for packed struct */ - if (a->flags != b->flags) - return 0; - - /* compare all struct fields */ - if (a->fields || b->fields) { - /* Check if both have fields */ - if (!(a->fields && b->fields)) - return 0; - - /* compare */ - for (i = 0; a->fields[i].type && b->fields[i].type; i++) { - __Pyx_StructField *field_a = a->fields + i; - __Pyx_StructField *field_b = b->fields + i; - - if (field_a->offset != field_b->offset || - !__pyx_typeinfo_cmp(field_a->type, field_b->type)) - return 0; - } - - /* If all fields are processed, we have a match */ - return !a->fields[i].type && !b->fields[i].type; - } - } - - return 1; -} - - -/////////////// TypeInfoToFormat.proto /////////////// -struct __pyx_typeinfo_string { - char string[3]; -}; -static struct __pyx_typeinfo_string __Pyx_TypeInfoToFormat(__Pyx_TypeInfo *type); - -/////////////// TypeInfoToFormat /////////////// +static int +__pyx_typeinfo_cmp(__Pyx_TypeInfo *a, __Pyx_TypeInfo *b) +{ + int i; + + if (!a || !b) + return 0; + + if (a == b) + return 1; + + if (a->size != b->size || a->typegroup != b->typegroup || + a->is_unsigned != b->is_unsigned || a->ndim != b->ndim) { + if (a->typegroup == 'H' || b->typegroup == 'H') { + /* Special case for chars */ + return a->size == b->size; + } else { + return 0; + } + } + + if (a->ndim) { + /* Verify multidimensional C arrays */ + for (i = 0; i < a->ndim; i++) + if (a->arraysize[i] != b->arraysize[i]) + return 0; + } + + if (a->typegroup == 'S') { + /* Check for packed struct */ + if (a->flags != b->flags) + return 0; + + /* compare all struct fields */ + if (a->fields || b->fields) { + /* Check if both have fields */ + if (!(a->fields && b->fields)) + return 0; + + /* compare */ + for (i = 0; a->fields[i].type && b->fields[i].type; i++) { + __Pyx_StructField *field_a = a->fields + i; + __Pyx_StructField *field_b = b->fields + i; + + if (field_a->offset != field_b->offset || + !__pyx_typeinfo_cmp(field_a->type, field_b->type)) + return 0; + } + + /* If all fields are processed, we have a match */ + return !a->fields[i].type && !b->fields[i].type; + } + } + + return 1; +} + + +/////////////// TypeInfoToFormat.proto /////////////// +struct __pyx_typeinfo_string { + char string[3]; +}; +static struct __pyx_typeinfo_string __Pyx_TypeInfoToFormat(__Pyx_TypeInfo *type); + +/////////////// TypeInfoToFormat /////////////// //@requires: BufferFormatStructs - + // See also MemoryView.pyx:BufferFormatFromTypeInfo -static struct __pyx_typeinfo_string __Pyx_TypeInfoToFormat(__Pyx_TypeInfo *type) { - struct __pyx_typeinfo_string result = { {0} }; - char *buf = (char *) result.string; - size_t size = type->size; - - switch (type->typegroup) { - case 'H': - *buf = 'c'; - break; - case 'I': - case 'U': - if (size == 1) +static struct __pyx_typeinfo_string __Pyx_TypeInfoToFormat(__Pyx_TypeInfo *type) { + struct __pyx_typeinfo_string result = { {0} }; + char *buf = (char *) result.string; + size_t size = type->size; + + switch (type->typegroup) { + case 'H': + *buf = 'c'; + break; + case 'I': + case 'U': + if (size == 1) *buf = (type->is_unsigned) ? 'B' : 'b'; - else if (size == 2) + else if (size == 2) *buf = (type->is_unsigned) ? 'H' : 'h'; - else if (size == 4) + else if (size == 4) *buf = (type->is_unsigned) ? 'I' : 'i'; - else if (size == 8) + else if (size == 8) *buf = (type->is_unsigned) ? 'Q' : 'q'; - break; - case 'P': - *buf = 'P'; - break; - case 'C': - { - __Pyx_TypeInfo complex_type = *type; - complex_type.typegroup = 'R'; - complex_type.size /= 2; - - *buf++ = 'Z'; - *buf = __Pyx_TypeInfoToFormat(&complex_type).string[0]; - break; - } - case 'R': - if (size == 4) - *buf = 'f'; - else if (size == 8) - *buf = 'd'; - else - *buf = 'g'; - break; - } - - return result; -} + break; + case 'P': + *buf = 'P'; + break; + case 'C': + { + __Pyx_TypeInfo complex_type = *type; + complex_type.typegroup = 'R'; + complex_type.size /= 2; + + *buf++ = 'Z'; + *buf = __Pyx_TypeInfoToFormat(&complex_type).string[0]; + break; + } + case 'R': + if (size == 4) + *buf = 'f'; + else if (size == 8) + *buf = 'd'; + else + *buf = 'g'; + break; + } + + return result; +} diff --git a/contrib/tools/cython/Cython/Utility/Builtins.c b/contrib/tools/cython/Cython/Utility/Builtins.c index 1ffb3bcebd..e21a5583ac 100644 --- a/contrib/tools/cython/Cython/Utility/Builtins.c +++ b/contrib/tools/cython/Cython/Utility/Builtins.c @@ -1,180 +1,180 @@ -/* - * Special implementations of built-in functions and methods. - * - * Optional optimisations for builtins are in Optimize.c. - * - * General object operations and protocols are in ObjectHandling.c. - */ - -//////////////////// Globals.proto //////////////////// - -static PyObject* __Pyx_Globals(void); /*proto*/ - -//////////////////// Globals //////////////////// -//@substitute: naming -//@requires: ObjectHandling.c::GetAttr - -// This is a stub implementation until we have something more complete. -// Currently, we only handle the most common case of a read-only dict -// of Python names. Supporting cdef names in the module and write -// access requires a rewrite as a dedicated class. - -static PyObject* __Pyx_Globals(void) { - Py_ssize_t i; - PyObject *names; - PyObject *globals = $moddict_cname; - Py_INCREF(globals); - names = PyObject_Dir($module_cname); - if (!names) - goto bad; - for (i = PyList_GET_SIZE(names)-1; i >= 0; i--) { -#if CYTHON_COMPILING_IN_PYPY +/* + * Special implementations of built-in functions and methods. + * + * Optional optimisations for builtins are in Optimize.c. + * + * General object operations and protocols are in ObjectHandling.c. + */ + +//////////////////// Globals.proto //////////////////// + +static PyObject* __Pyx_Globals(void); /*proto*/ + +//////////////////// Globals //////////////////// +//@substitute: naming +//@requires: ObjectHandling.c::GetAttr + +// This is a stub implementation until we have something more complete. +// Currently, we only handle the most common case of a read-only dict +// of Python names. Supporting cdef names in the module and write +// access requires a rewrite as a dedicated class. + +static PyObject* __Pyx_Globals(void) { + Py_ssize_t i; + PyObject *names; + PyObject *globals = $moddict_cname; + Py_INCREF(globals); + names = PyObject_Dir($module_cname); + if (!names) + goto bad; + for (i = PyList_GET_SIZE(names)-1; i >= 0; i--) { +#if CYTHON_COMPILING_IN_PYPY PyObject* name = PySequence_ITEM(names, i); - if (!name) - goto bad; -#else - PyObject* name = PyList_GET_ITEM(names, i); -#endif - if (!PyDict_Contains(globals, name)) { - PyObject* value = __Pyx_GetAttr($module_cname, name); - if (!value) { -#if CYTHON_COMPILING_IN_PYPY - Py_DECREF(name); -#endif - goto bad; - } - if (PyDict_SetItem(globals, name, value) < 0) { -#if CYTHON_COMPILING_IN_PYPY - Py_DECREF(name); -#endif - Py_DECREF(value); - goto bad; - } - } -#if CYTHON_COMPILING_IN_PYPY - Py_DECREF(name); -#endif - } - Py_DECREF(names); - return globals; -bad: - Py_XDECREF(names); - Py_XDECREF(globals); - return NULL; -} - -//////////////////// PyExecGlobals.proto //////////////////// - -static PyObject* __Pyx_PyExecGlobals(PyObject*); - -//////////////////// PyExecGlobals //////////////////// -//@requires: Globals -//@requires: PyExec - -static PyObject* __Pyx_PyExecGlobals(PyObject* code) { - PyObject* result; - PyObject* globals = __Pyx_Globals(); - if (unlikely(!globals)) - return NULL; - result = __Pyx_PyExec2(code, globals); - Py_DECREF(globals); - return result; -} - -//////////////////// PyExec.proto //////////////////// - -static PyObject* __Pyx_PyExec3(PyObject*, PyObject*, PyObject*); -static CYTHON_INLINE PyObject* __Pyx_PyExec2(PyObject*, PyObject*); - -//////////////////// PyExec //////////////////// -//@substitute: naming - -static CYTHON_INLINE PyObject* __Pyx_PyExec2(PyObject* o, PyObject* globals) { - return __Pyx_PyExec3(o, globals, NULL); -} - -static PyObject* __Pyx_PyExec3(PyObject* o, PyObject* globals, PyObject* locals) { - PyObject* result; - PyObject* s = 0; - char *code = 0; - - if (!globals || globals == Py_None) { - globals = $moddict_cname; - } else if (!PyDict_Check(globals)) { - PyErr_Format(PyExc_TypeError, "exec() arg 2 must be a dict, not %.200s", - Py_TYPE(globals)->tp_name); - goto bad; - } - if (!locals || locals == Py_None) { - locals = globals; - } - + if (!name) + goto bad; +#else + PyObject* name = PyList_GET_ITEM(names, i); +#endif + if (!PyDict_Contains(globals, name)) { + PyObject* value = __Pyx_GetAttr($module_cname, name); + if (!value) { +#if CYTHON_COMPILING_IN_PYPY + Py_DECREF(name); +#endif + goto bad; + } + if (PyDict_SetItem(globals, name, value) < 0) { +#if CYTHON_COMPILING_IN_PYPY + Py_DECREF(name); +#endif + Py_DECREF(value); + goto bad; + } + } +#if CYTHON_COMPILING_IN_PYPY + Py_DECREF(name); +#endif + } + Py_DECREF(names); + return globals; +bad: + Py_XDECREF(names); + Py_XDECREF(globals); + return NULL; +} + +//////////////////// PyExecGlobals.proto //////////////////// + +static PyObject* __Pyx_PyExecGlobals(PyObject*); + +//////////////////// PyExecGlobals //////////////////// +//@requires: Globals +//@requires: PyExec + +static PyObject* __Pyx_PyExecGlobals(PyObject* code) { + PyObject* result; + PyObject* globals = __Pyx_Globals(); + if (unlikely(!globals)) + return NULL; + result = __Pyx_PyExec2(code, globals); + Py_DECREF(globals); + return result; +} + +//////////////////// PyExec.proto //////////////////// + +static PyObject* __Pyx_PyExec3(PyObject*, PyObject*, PyObject*); +static CYTHON_INLINE PyObject* __Pyx_PyExec2(PyObject*, PyObject*); + +//////////////////// PyExec //////////////////// +//@substitute: naming + +static CYTHON_INLINE PyObject* __Pyx_PyExec2(PyObject* o, PyObject* globals) { + return __Pyx_PyExec3(o, globals, NULL); +} + +static PyObject* __Pyx_PyExec3(PyObject* o, PyObject* globals, PyObject* locals) { + PyObject* result; + PyObject* s = 0; + char *code = 0; + + if (!globals || globals == Py_None) { + globals = $moddict_cname; + } else if (!PyDict_Check(globals)) { + PyErr_Format(PyExc_TypeError, "exec() arg 2 must be a dict, not %.200s", + Py_TYPE(globals)->tp_name); + goto bad; + } + if (!locals || locals == Py_None) { + locals = globals; + } + if (__Pyx_PyDict_GetItemStr(globals, PYIDENT("__builtins__")) == NULL) { - if (PyDict_SetItem(globals, PYIDENT("__builtins__"), PyEval_GetBuiltins()) < 0) - goto bad; - } - - if (PyCode_Check(o)) { + if (PyDict_SetItem(globals, PYIDENT("__builtins__"), PyEval_GetBuiltins()) < 0) + goto bad; + } + + if (PyCode_Check(o)) { if (__Pyx_PyCode_HasFreeVars((PyCodeObject *)o)) { - PyErr_SetString(PyExc_TypeError, - "code object passed to exec() may not contain free variables"); - goto bad; - } + PyErr_SetString(PyExc_TypeError, + "code object passed to exec() may not contain free variables"); + goto bad; + } #if CYTHON_COMPILING_IN_PYPY || PY_VERSION_HEX < 0x030200B1 - result = PyEval_EvalCode((PyCodeObject *)o, globals, locals); - #else - result = PyEval_EvalCode(o, globals, locals); - #endif - } else { - PyCompilerFlags cf; - cf.cf_flags = 0; + result = PyEval_EvalCode((PyCodeObject *)o, globals, locals); + #else + result = PyEval_EvalCode(o, globals, locals); + #endif + } else { + PyCompilerFlags cf; + cf.cf_flags = 0; #if PY_VERSION_HEX >= 0x030800A3 cf.cf_feature_version = PY_MINOR_VERSION; #endif - if (PyUnicode_Check(o)) { - cf.cf_flags = PyCF_SOURCE_IS_UTF8; - s = PyUnicode_AsUTF8String(o); - if (!s) goto bad; - o = s; - #if PY_MAJOR_VERSION >= 3 - } else if (!PyBytes_Check(o)) { - #else - } else if (!PyString_Check(o)) { - #endif - PyErr_Format(PyExc_TypeError, - "exec: arg 1 must be string, bytes or code object, got %.200s", - Py_TYPE(o)->tp_name); - goto bad; - } - #if PY_MAJOR_VERSION >= 3 - code = PyBytes_AS_STRING(o); - #else - code = PyString_AS_STRING(o); - #endif - if (PyEval_MergeCompilerFlags(&cf)) { - result = PyRun_StringFlags(code, Py_file_input, globals, locals, &cf); - } else { - result = PyRun_String(code, Py_file_input, globals, locals); - } - Py_XDECREF(s); - } - - return result; -bad: - Py_XDECREF(s); - return 0; -} - -//////////////////// GetAttr3.proto //////////////////// - -static CYTHON_INLINE PyObject *__Pyx_GetAttr3(PyObject *, PyObject *, PyObject *); /*proto*/ - -//////////////////// GetAttr3 //////////////////// -//@requires: ObjectHandling.c::GetAttr + if (PyUnicode_Check(o)) { + cf.cf_flags = PyCF_SOURCE_IS_UTF8; + s = PyUnicode_AsUTF8String(o); + if (!s) goto bad; + o = s; + #if PY_MAJOR_VERSION >= 3 + } else if (!PyBytes_Check(o)) { + #else + } else if (!PyString_Check(o)) { + #endif + PyErr_Format(PyExc_TypeError, + "exec: arg 1 must be string, bytes or code object, got %.200s", + Py_TYPE(o)->tp_name); + goto bad; + } + #if PY_MAJOR_VERSION >= 3 + code = PyBytes_AS_STRING(o); + #else + code = PyString_AS_STRING(o); + #endif + if (PyEval_MergeCompilerFlags(&cf)) { + result = PyRun_StringFlags(code, Py_file_input, globals, locals, &cf); + } else { + result = PyRun_String(code, Py_file_input, globals, locals); + } + Py_XDECREF(s); + } + + return result; +bad: + Py_XDECREF(s); + return 0; +} + +//////////////////// GetAttr3.proto //////////////////// + +static CYTHON_INLINE PyObject *__Pyx_GetAttr3(PyObject *, PyObject *, PyObject *); /*proto*/ + +//////////////////// GetAttr3 //////////////////// +//@requires: ObjectHandling.c::GetAttr //@requires: Exceptions.c::PyThreadStateGet //@requires: Exceptions.c::PyErrFetchRestore //@requires: Exceptions.c::PyErrExceptionMatches - + static PyObject *__Pyx_GetAttr3Default(PyObject *d) { __Pyx_PyThreadState_declare __Pyx_PyThreadState_assign @@ -185,8 +185,8 @@ static PyObject *__Pyx_GetAttr3Default(PyObject *d) { return d; } -static CYTHON_INLINE PyObject *__Pyx_GetAttr3(PyObject *o, PyObject *n, PyObject *d) { - PyObject *r = __Pyx_GetAttr(o, n); +static CYTHON_INLINE PyObject *__Pyx_GetAttr3(PyObject *o, PyObject *n, PyObject *d) { + PyObject *r = __Pyx_GetAttr(o, n); return (likely(r)) ? r : __Pyx_GetAttr3Default(d); } @@ -205,37 +205,37 @@ static CYTHON_INLINE int __Pyx_HasAttr(PyObject *o, PyObject *n) { return -1; } r = __Pyx_GetAttr(o, n); - if (unlikely(!r)) { - PyErr_Clear(); + if (unlikely(!r)) { + PyErr_Clear(); return 0; } else { Py_DECREF(r); return 1; - } -} - -//////////////////// Intern.proto //////////////////// - -static PyObject* __Pyx_Intern(PyObject* s); /* proto */ - -//////////////////// Intern //////////////////// - -static PyObject* __Pyx_Intern(PyObject* s) { - if (!(likely(PyString_CheckExact(s)))) { - PyErr_Format(PyExc_TypeError, "Expected %.16s, got %.200s", "str", Py_TYPE(s)->tp_name); - return 0; - } - Py_INCREF(s); - #if PY_MAJOR_VERSION >= 3 - PyUnicode_InternInPlace(&s); - #else - PyString_InternInPlace(&s); - #endif - return s; -} - -//////////////////// abs_longlong.proto //////////////////// - + } +} + +//////////////////// Intern.proto //////////////////// + +static PyObject* __Pyx_Intern(PyObject* s); /* proto */ + +//////////////////// Intern //////////////////// + +static PyObject* __Pyx_Intern(PyObject* s) { + if (!(likely(PyString_CheckExact(s)))) { + PyErr_Format(PyExc_TypeError, "Expected %.16s, got %.200s", "str", Py_TYPE(s)->tp_name); + return 0; + } + Py_INCREF(s); + #if PY_MAJOR_VERSION >= 3 + PyUnicode_InternInPlace(&s); + #else + PyString_InternInPlace(&s); + #endif + return s; +} + +//////////////////// abs_longlong.proto //////////////////// + static CYTHON_INLINE PY_LONG_LONG __Pyx_abs_longlong(PY_LONG_LONG x) { #if defined (__cplusplus) && __cplusplus >= 201103L return std::abs(x); @@ -248,13 +248,13 @@ static CYTHON_INLINE PY_LONG_LONG __Pyx_abs_longlong(PY_LONG_LONG x) { #elif defined (__GNUC__) // gcc or clang on 64 bit windows. return __builtin_llabs(x); -#else +#else if (sizeof(PY_LONG_LONG) <= sizeof(Py_ssize_t)) return __Pyx_sst_abs(x); return (x<0) ? -x : x; -#endif -} - +#endif +} + //////////////////// py_abs.proto //////////////////// @@ -294,10 +294,10 @@ static PyObject *__Pyx_PyLong_AbsNeg(PyObject *n) { #endif -//////////////////// pow2.proto //////////////////// - -#define __Pyx_PyNumber_Power2(a, b) PyNumber_Power(a, b, Py_None) - +//////////////////// pow2.proto //////////////////// + +#define __Pyx_PyNumber_Power2(a, b) PyNumber_Power(a, b, Py_None) + //////////////////// object_ord.proto //////////////////// //@requires: TypeConversion.c::UnicodeAsUCS4 @@ -342,143 +342,143 @@ static long __Pyx__PyObject_Ord(PyObject* c) { } -//////////////////// py_dict_keys.proto //////////////////// - -static CYTHON_INLINE PyObject* __Pyx_PyDict_Keys(PyObject* d); /*proto*/ - -//////////////////// py_dict_keys //////////////////// - -static CYTHON_INLINE PyObject* __Pyx_PyDict_Keys(PyObject* d) { - if (PY_MAJOR_VERSION >= 3) +//////////////////// py_dict_keys.proto //////////////////// + +static CYTHON_INLINE PyObject* __Pyx_PyDict_Keys(PyObject* d); /*proto*/ + +//////////////////// py_dict_keys //////////////////// + +static CYTHON_INLINE PyObject* __Pyx_PyDict_Keys(PyObject* d) { + if (PY_MAJOR_VERSION >= 3) return CALL_UNBOUND_METHOD(PyDict_Type, "keys", d); - else - return PyDict_Keys(d); -} - -//////////////////// py_dict_values.proto //////////////////// - -static CYTHON_INLINE PyObject* __Pyx_PyDict_Values(PyObject* d); /*proto*/ - -//////////////////// py_dict_values //////////////////// - -static CYTHON_INLINE PyObject* __Pyx_PyDict_Values(PyObject* d) { - if (PY_MAJOR_VERSION >= 3) + else + return PyDict_Keys(d); +} + +//////////////////// py_dict_values.proto //////////////////// + +static CYTHON_INLINE PyObject* __Pyx_PyDict_Values(PyObject* d); /*proto*/ + +//////////////////// py_dict_values //////////////////// + +static CYTHON_INLINE PyObject* __Pyx_PyDict_Values(PyObject* d) { + if (PY_MAJOR_VERSION >= 3) return CALL_UNBOUND_METHOD(PyDict_Type, "values", d); - else - return PyDict_Values(d); -} - -//////////////////// py_dict_items.proto //////////////////// - -static CYTHON_INLINE PyObject* __Pyx_PyDict_Items(PyObject* d); /*proto*/ - -//////////////////// py_dict_items //////////////////// - -static CYTHON_INLINE PyObject* __Pyx_PyDict_Items(PyObject* d) { - if (PY_MAJOR_VERSION >= 3) + else + return PyDict_Values(d); +} + +//////////////////// py_dict_items.proto //////////////////// + +static CYTHON_INLINE PyObject* __Pyx_PyDict_Items(PyObject* d); /*proto*/ + +//////////////////// py_dict_items //////////////////// + +static CYTHON_INLINE PyObject* __Pyx_PyDict_Items(PyObject* d) { + if (PY_MAJOR_VERSION >= 3) return CALL_UNBOUND_METHOD(PyDict_Type, "items", d); - else - return PyDict_Items(d); -} - -//////////////////// py_dict_iterkeys.proto //////////////////// - -static CYTHON_INLINE PyObject* __Pyx_PyDict_IterKeys(PyObject* d); /*proto*/ - -//////////////////// py_dict_iterkeys //////////////////// - -static CYTHON_INLINE PyObject* __Pyx_PyDict_IterKeys(PyObject* d) { + else + return PyDict_Items(d); +} + +//////////////////// py_dict_iterkeys.proto //////////////////// + +static CYTHON_INLINE PyObject* __Pyx_PyDict_IterKeys(PyObject* d); /*proto*/ + +//////////////////// py_dict_iterkeys //////////////////// + +static CYTHON_INLINE PyObject* __Pyx_PyDict_IterKeys(PyObject* d) { if (PY_MAJOR_VERSION >= 3) return CALL_UNBOUND_METHOD(PyDict_Type, "keys", d); else return CALL_UNBOUND_METHOD(PyDict_Type, "iterkeys", d); -} - -//////////////////// py_dict_itervalues.proto //////////////////// - -static CYTHON_INLINE PyObject* __Pyx_PyDict_IterValues(PyObject* d); /*proto*/ - -//////////////////// py_dict_itervalues //////////////////// - -static CYTHON_INLINE PyObject* __Pyx_PyDict_IterValues(PyObject* d) { +} + +//////////////////// py_dict_itervalues.proto //////////////////// + +static CYTHON_INLINE PyObject* __Pyx_PyDict_IterValues(PyObject* d); /*proto*/ + +//////////////////// py_dict_itervalues //////////////////// + +static CYTHON_INLINE PyObject* __Pyx_PyDict_IterValues(PyObject* d) { if (PY_MAJOR_VERSION >= 3) return CALL_UNBOUND_METHOD(PyDict_Type, "values", d); else return CALL_UNBOUND_METHOD(PyDict_Type, "itervalues", d); -} - -//////////////////// py_dict_iteritems.proto //////////////////// - -static CYTHON_INLINE PyObject* __Pyx_PyDict_IterItems(PyObject* d); /*proto*/ - -//////////////////// py_dict_iteritems //////////////////// - -static CYTHON_INLINE PyObject* __Pyx_PyDict_IterItems(PyObject* d) { +} + +//////////////////// py_dict_iteritems.proto //////////////////// + +static CYTHON_INLINE PyObject* __Pyx_PyDict_IterItems(PyObject* d); /*proto*/ + +//////////////////// py_dict_iteritems //////////////////// + +static CYTHON_INLINE PyObject* __Pyx_PyDict_IterItems(PyObject* d) { if (PY_MAJOR_VERSION >= 3) return CALL_UNBOUND_METHOD(PyDict_Type, "items", d); else return CALL_UNBOUND_METHOD(PyDict_Type, "iteritems", d); -} - -//////////////////// py_dict_viewkeys.proto //////////////////// - -#if PY_VERSION_HEX < 0x02070000 -#error This module uses dict views, which require Python 2.7 or later -#endif -static CYTHON_INLINE PyObject* __Pyx_PyDict_ViewKeys(PyObject* d); /*proto*/ - -//////////////////// py_dict_viewkeys //////////////////// - -static CYTHON_INLINE PyObject* __Pyx_PyDict_ViewKeys(PyObject* d) { +} + +//////////////////// py_dict_viewkeys.proto //////////////////// + +#if PY_VERSION_HEX < 0x02070000 +#error This module uses dict views, which require Python 2.7 or later +#endif +static CYTHON_INLINE PyObject* __Pyx_PyDict_ViewKeys(PyObject* d); /*proto*/ + +//////////////////// py_dict_viewkeys //////////////////// + +static CYTHON_INLINE PyObject* __Pyx_PyDict_ViewKeys(PyObject* d) { if (PY_MAJOR_VERSION >= 3) return CALL_UNBOUND_METHOD(PyDict_Type, "keys", d); else return CALL_UNBOUND_METHOD(PyDict_Type, "viewkeys", d); -} - -//////////////////// py_dict_viewvalues.proto //////////////////// - -#if PY_VERSION_HEX < 0x02070000 -#error This module uses dict views, which require Python 2.7 or later -#endif -static CYTHON_INLINE PyObject* __Pyx_PyDict_ViewValues(PyObject* d); /*proto*/ - -//////////////////// py_dict_viewvalues //////////////////// - -static CYTHON_INLINE PyObject* __Pyx_PyDict_ViewValues(PyObject* d) { +} + +//////////////////// py_dict_viewvalues.proto //////////////////// + +#if PY_VERSION_HEX < 0x02070000 +#error This module uses dict views, which require Python 2.7 or later +#endif +static CYTHON_INLINE PyObject* __Pyx_PyDict_ViewValues(PyObject* d); /*proto*/ + +//////////////////// py_dict_viewvalues //////////////////// + +static CYTHON_INLINE PyObject* __Pyx_PyDict_ViewValues(PyObject* d) { if (PY_MAJOR_VERSION >= 3) return CALL_UNBOUND_METHOD(PyDict_Type, "values", d); else return CALL_UNBOUND_METHOD(PyDict_Type, "viewvalues", d); -} - -//////////////////// py_dict_viewitems.proto //////////////////// - -#if PY_VERSION_HEX < 0x02070000 -#error This module uses dict views, which require Python 2.7 or later -#endif -static CYTHON_INLINE PyObject* __Pyx_PyDict_ViewItems(PyObject* d); /*proto*/ - -//////////////////// py_dict_viewitems //////////////////// - -static CYTHON_INLINE PyObject* __Pyx_PyDict_ViewItems(PyObject* d) { +} + +//////////////////// py_dict_viewitems.proto //////////////////// + +#if PY_VERSION_HEX < 0x02070000 +#error This module uses dict views, which require Python 2.7 or later +#endif +static CYTHON_INLINE PyObject* __Pyx_PyDict_ViewItems(PyObject* d); /*proto*/ + +//////////////////// py_dict_viewitems //////////////////// + +static CYTHON_INLINE PyObject* __Pyx_PyDict_ViewItems(PyObject* d) { if (PY_MAJOR_VERSION >= 3) return CALL_UNBOUND_METHOD(PyDict_Type, "items", d); else return CALL_UNBOUND_METHOD(PyDict_Type, "viewitems", d); -} - +} + -//////////////////// pyfrozenset_new.proto //////////////////// +//////////////////// pyfrozenset_new.proto //////////////////// static CYTHON_INLINE PyObject* __Pyx_PyFrozenSet_New(PyObject* it); //////////////////// pyfrozenset_new //////////////////// -//@substitute: naming - -static CYTHON_INLINE PyObject* __Pyx_PyFrozenSet_New(PyObject* it) { - if (it) { - PyObject* result; +//@substitute: naming + +static CYTHON_INLINE PyObject* __Pyx_PyFrozenSet_New(PyObject* it) { + if (it) { + PyObject* result; #if CYTHON_COMPILING_IN_PYPY // PyPy currently lacks PyFrozenSet_CheckExact() and PyFrozenSet_New() PyObject* args; @@ -489,24 +489,24 @@ static CYTHON_INLINE PyObject* __Pyx_PyFrozenSet_New(PyObject* it) { Py_DECREF(args); return result; #else - if (PyFrozenSet_CheckExact(it)) { - Py_INCREF(it); - return it; - } - result = PyFrozenSet_New(it); - if (unlikely(!result)) - return NULL; + if (PyFrozenSet_CheckExact(it)) { + Py_INCREF(it); + return it; + } + result = PyFrozenSet_New(it); + if (unlikely(!result)) + return NULL; if ((PY_VERSION_HEX >= 0x031000A1) || likely(PySet_GET_SIZE(result))) - return result; + return result; // empty frozenset is a singleton (on Python <3.10) - // seems wasteful, but CPython does the same - Py_DECREF(result); + // seems wasteful, but CPython does the same + Py_DECREF(result); #endif - } + } #if CYTHON_USE_TYPE_SLOTS - return PyFrozenSet_Type.tp_new(&PyFrozenSet_Type, $empty_tuple, NULL); + return PyFrozenSet_Type.tp_new(&PyFrozenSet_Type, $empty_tuple, NULL); #else - return PyObject_Call((PyObject*)&PyFrozenSet_Type, $empty_tuple, NULL); + return PyObject_Call((PyObject*)&PyFrozenSet_Type, $empty_tuple, NULL); #endif } @@ -534,9 +534,9 @@ static CYTHON_INLINE int __Pyx_PySet_Update(PyObject* set, PyObject* it) { // unusual result, fall through to set.update() call below Py_DECREF(retval); } - #endif + #endif retval = CALL_UNBOUND_METHOD(PySet_Type, "update", set, it); if (unlikely(!retval)) return -1; Py_DECREF(retval); return 0; -} +} diff --git a/contrib/tools/cython/Cython/Utility/Capsule.c b/contrib/tools/cython/Cython/Utility/Capsule.c index cc4fe0d887..448e4a7304 100644 --- a/contrib/tools/cython/Cython/Utility/Capsule.c +++ b/contrib/tools/cython/Cython/Utility/Capsule.c @@ -1,20 +1,20 @@ -//////////////// Capsule.proto //////////////// - -/* Todo: wrap the rest of the functionality in similar functions */ -static CYTHON_INLINE PyObject *__pyx_capsule_create(void *p, const char *sig); - -//////////////// Capsule //////////////// - -static CYTHON_INLINE PyObject * -__pyx_capsule_create(void *p, CYTHON_UNUSED const char *sig) -{ - PyObject *cobj; - -#if PY_VERSION_HEX >= 0x02070000 - cobj = PyCapsule_New(p, sig, NULL); -#else - cobj = PyCObject_FromVoidPtr(p, NULL); -#endif - - return cobj; -} +//////////////// Capsule.proto //////////////// + +/* Todo: wrap the rest of the functionality in similar functions */ +static CYTHON_INLINE PyObject *__pyx_capsule_create(void *p, const char *sig); + +//////////////// Capsule //////////////// + +static CYTHON_INLINE PyObject * +__pyx_capsule_create(void *p, CYTHON_UNUSED const char *sig) +{ + PyObject *cobj; + +#if PY_VERSION_HEX >= 0x02070000 + cobj = PyCapsule_New(p, sig, NULL); +#else + cobj = PyCObject_FromVoidPtr(p, NULL); +#endif + + return cobj; +} diff --git a/contrib/tools/cython/Cython/Utility/CommonTypes.c b/contrib/tools/cython/Cython/Utility/CommonTypes.c index c2403cbf98..522f0a10e4 100644 --- a/contrib/tools/cython/Cython/Utility/CommonTypes.c +++ b/contrib/tools/cython/Cython/Utility/CommonTypes.c @@ -1,48 +1,48 @@ -/////////////// FetchCommonType.proto /////////////// - -static PyTypeObject* __Pyx_FetchCommonType(PyTypeObject* type); - -/////////////// FetchCommonType /////////////// - -static PyTypeObject* __Pyx_FetchCommonType(PyTypeObject* type) { - PyObject* fake_module; - PyTypeObject* cached_type = NULL; - - fake_module = PyImport_AddModule((char*) "_cython_" CYTHON_ABI); - if (!fake_module) return NULL; - Py_INCREF(fake_module); - - cached_type = (PyTypeObject*) PyObject_GetAttrString(fake_module, type->tp_name); - if (cached_type) { - if (!PyType_Check((PyObject*)cached_type)) { - PyErr_Format(PyExc_TypeError, - "Shared Cython type %.200s is not a type object", - type->tp_name); - goto bad; - } - if (cached_type->tp_basicsize != type->tp_basicsize) { - PyErr_Format(PyExc_TypeError, - "Shared Cython type %.200s has the wrong size, try recompiling", - type->tp_name); - goto bad; - } - } else { - if (!PyErr_ExceptionMatches(PyExc_AttributeError)) goto bad; - PyErr_Clear(); - if (PyType_Ready(type) < 0) goto bad; - if (PyObject_SetAttrString(fake_module, type->tp_name, (PyObject*) type) < 0) - goto bad; - Py_INCREF(type); - cached_type = type; - } - -done: - Py_DECREF(fake_module); - // NOTE: always returns owned reference, or NULL on error - return cached_type; - -bad: - Py_XDECREF(cached_type); - cached_type = NULL; - goto done; -} +/////////////// FetchCommonType.proto /////////////// + +static PyTypeObject* __Pyx_FetchCommonType(PyTypeObject* type); + +/////////////// FetchCommonType /////////////// + +static PyTypeObject* __Pyx_FetchCommonType(PyTypeObject* type) { + PyObject* fake_module; + PyTypeObject* cached_type = NULL; + + fake_module = PyImport_AddModule((char*) "_cython_" CYTHON_ABI); + if (!fake_module) return NULL; + Py_INCREF(fake_module); + + cached_type = (PyTypeObject*) PyObject_GetAttrString(fake_module, type->tp_name); + if (cached_type) { + if (!PyType_Check((PyObject*)cached_type)) { + PyErr_Format(PyExc_TypeError, + "Shared Cython type %.200s is not a type object", + type->tp_name); + goto bad; + } + if (cached_type->tp_basicsize != type->tp_basicsize) { + PyErr_Format(PyExc_TypeError, + "Shared Cython type %.200s has the wrong size, try recompiling", + type->tp_name); + goto bad; + } + } else { + if (!PyErr_ExceptionMatches(PyExc_AttributeError)) goto bad; + PyErr_Clear(); + if (PyType_Ready(type) < 0) goto bad; + if (PyObject_SetAttrString(fake_module, type->tp_name, (PyObject*) type) < 0) + goto bad; + Py_INCREF(type); + cached_type = type; + } + +done: + Py_DECREF(fake_module); + // NOTE: always returns owned reference, or NULL on error + return cached_type; + +bad: + Py_XDECREF(cached_type); + cached_type = NULL; + goto done; +} diff --git a/contrib/tools/cython/Cython/Utility/CppConvert.pyx b/contrib/tools/cython/Cython/Utility/CppConvert.pyx index 5f7859dd0e..7b6bdf9e65 100644 --- a/contrib/tools/cython/Cython/Utility/CppConvert.pyx +++ b/contrib/tools/cython/Cython/Utility/CppConvert.pyx @@ -1,212 +1,212 @@ -# TODO: Figure out how many of the pass-by-value copies the compiler can eliminate. - - -#################### string.from_py #################### - -cdef extern from *: - cdef cppclass string "{{type}}": - string() - string(char* c_str, size_t size) +# TODO: Figure out how many of the pass-by-value copies the compiler can eliminate. + + +#################### string.from_py #################### + +cdef extern from *: + cdef cppclass string "{{type}}": + string() + string(char* c_str, size_t size) cdef const char* __Pyx_PyObject_AsStringAndSize(object, Py_ssize_t*) except NULL - -@cname("{{cname}}") -cdef string {{cname}}(object o) except *: + +@cname("{{cname}}") +cdef string {{cname}}(object o) except *: cdef Py_ssize_t length = 0 cdef const char* data = __Pyx_PyObject_AsStringAndSize(o, &length) - return string(data, length) - - -#################### string.to_py #################### - -#cimport cython -#from libcpp.string cimport string -cdef extern from *: - cdef cppclass string "{{type}}": - char* data() - size_t size() - + return string(data, length) + + +#################### string.to_py #################### + +#cimport cython +#from libcpp.string cimport string +cdef extern from *: + cdef cppclass string "{{type}}": + char* data() + size_t size() + {{for py_type in ['PyObject', 'PyUnicode', 'PyStr', 'PyBytes', 'PyByteArray']}} cdef extern from *: cdef object __Pyx_{{py_type}}_FromStringAndSize(const char*, size_t) - + @cname("{{cname.replace("PyObject", py_type, 1)}}") cdef inline object {{cname.replace("PyObject", py_type, 1)}}(const string& s): return __Pyx_{{py_type}}_FromStringAndSize(s.data(), s.size()) {{endfor}} - - -#################### vector.from_py #################### - -cdef extern from *: - cdef cppclass vector "std::vector" [T]: - void push_back(T&) - -@cname("{{cname}}") -cdef vector[X] {{cname}}(object o) except *: - cdef vector[X] v - for item in o: + + +#################### vector.from_py #################### + +cdef extern from *: + cdef cppclass vector "std::vector" [T]: + void push_back(T&) + +@cname("{{cname}}") +cdef vector[X] {{cname}}(object o) except *: + cdef vector[X] v + for item in o: v.push_back(<X>item) - return v - - -#################### vector.to_py #################### - -cdef extern from *: - cdef cppclass vector "const std::vector" [T]: - size_t size() - T& operator[](size_t) - -@cname("{{cname}}") -cdef object {{cname}}(vector[X]& v): + return v + + +#################### vector.to_py #################### + +cdef extern from *: + cdef cppclass vector "const std::vector" [T]: + size_t size() + T& operator[](size_t) + +@cname("{{cname}}") +cdef object {{cname}}(vector[X]& v): return [v[i] for i in range(v.size())] - - -#################### list.from_py #################### - -cdef extern from *: - cdef cppclass cpp_list "std::list" [T]: - void push_back(T&) - -@cname("{{cname}}") -cdef cpp_list[X] {{cname}}(object o) except *: - cdef cpp_list[X] l - for item in o: + + +#################### list.from_py #################### + +cdef extern from *: + cdef cppclass cpp_list "std::list" [T]: + void push_back(T&) + +@cname("{{cname}}") +cdef cpp_list[X] {{cname}}(object o) except *: + cdef cpp_list[X] l + for item in o: l.push_back(<X>item) - return l - - -#################### list.to_py #################### - -cimport cython - -cdef extern from *: - cdef cppclass cpp_list "std::list" [T]: - cppclass const_iterator: - T& operator*() - const_iterator operator++() - bint operator!=(const_iterator) - const_iterator begin() - const_iterator end() - -@cname("{{cname}}") -cdef object {{cname}}(const cpp_list[X]& v): - o = [] - cdef cpp_list[X].const_iterator iter = v.begin() - while iter != v.end(): + return l + + +#################### list.to_py #################### + +cimport cython + +cdef extern from *: + cdef cppclass cpp_list "std::list" [T]: + cppclass const_iterator: + T& operator*() + const_iterator operator++() + bint operator!=(const_iterator) + const_iterator begin() + const_iterator end() + +@cname("{{cname}}") +cdef object {{cname}}(const cpp_list[X]& v): + o = [] + cdef cpp_list[X].const_iterator iter = v.begin() + while iter != v.end(): o.append(cython.operator.dereference(iter)) - cython.operator.preincrement(iter) - return o - - -#################### set.from_py #################### - -cdef extern from *: - cdef cppclass set "std::{{maybe_unordered}}set" [T]: - void insert(T&) - -@cname("{{cname}}") -cdef set[X] {{cname}}(object o) except *: - cdef set[X] s - for item in o: + cython.operator.preincrement(iter) + return o + + +#################### set.from_py #################### + +cdef extern from *: + cdef cppclass set "std::{{maybe_unordered}}set" [T]: + void insert(T&) + +@cname("{{cname}}") +cdef set[X] {{cname}}(object o) except *: + cdef set[X] s + for item in o: s.insert(<X>item) - return s - - -#################### set.to_py #################### - -cimport cython - -cdef extern from *: - cdef cppclass cpp_set "std::{{maybe_unordered}}set" [T]: - cppclass const_iterator: - T& operator*() - const_iterator operator++() - bint operator!=(const_iterator) - const_iterator begin() - const_iterator end() - -@cname("{{cname}}") -cdef object {{cname}}(const cpp_set[X]& s): - o = set() - cdef cpp_set[X].const_iterator iter = s.begin() - while iter != s.end(): + return s + + +#################### set.to_py #################### + +cimport cython + +cdef extern from *: + cdef cppclass cpp_set "std::{{maybe_unordered}}set" [T]: + cppclass const_iterator: + T& operator*() + const_iterator operator++() + bint operator!=(const_iterator) + const_iterator begin() + const_iterator end() + +@cname("{{cname}}") +cdef object {{cname}}(const cpp_set[X]& s): + o = set() + cdef cpp_set[X].const_iterator iter = s.begin() + while iter != s.end(): o.add(cython.operator.dereference(iter)) - cython.operator.preincrement(iter) - return o - -#################### pair.from_py #################### - -cdef extern from *: - cdef cppclass pair "std::pair" [T, U]: - pair() - pair(T&, U&) - -@cname("{{cname}}") -cdef pair[X,Y] {{cname}}(object o) except *: - x, y = o + cython.operator.preincrement(iter) + return o + +#################### pair.from_py #################### + +cdef extern from *: + cdef cppclass pair "std::pair" [T, U]: + pair() + pair(T&, U&) + +@cname("{{cname}}") +cdef pair[X,Y] {{cname}}(object o) except *: + x, y = o return pair[X,Y](<X>x, <Y>y) - - -#################### pair.to_py #################### - -cdef extern from *: - cdef cppclass pair "std::pair" [T, U]: - T first - U second - -@cname("{{cname}}") -cdef object {{cname}}(const pair[X,Y]& p): + + +#################### pair.to_py #################### + +cdef extern from *: + cdef cppclass pair "std::pair" [T, U]: + T first + U second + +@cname("{{cname}}") +cdef object {{cname}}(const pair[X,Y]& p): return p.first, p.second - - -#################### map.from_py #################### - -cdef extern from *: - cdef cppclass pair "std::pair" [T, U]: - pair(T&, U&) - cdef cppclass map "std::{{maybe_unordered}}map" [T, U]: - void insert(pair[T, U]&) - cdef cppclass vector "std::vector" [T]: - pass - - -@cname("{{cname}}") -cdef map[X,Y] {{cname}}(object o) except *: - cdef dict d = o - cdef map[X,Y] m - for key, value in d.iteritems(): + + +#################### map.from_py #################### + +cdef extern from *: + cdef cppclass pair "std::pair" [T, U]: + pair(T&, U&) + cdef cppclass map "std::{{maybe_unordered}}map" [T, U]: + void insert(pair[T, U]&) + cdef cppclass vector "std::vector" [T]: + pass + + +@cname("{{cname}}") +cdef map[X,Y] {{cname}}(object o) except *: + cdef dict d = o + cdef map[X,Y] m + for key, value in d.iteritems(): m.insert(pair[X,Y](<X>key, <Y>value)) - return m - - -#################### map.to_py #################### -# TODO: Work out const so that this can take a const -# reference rather than pass by value. - -cimport cython - -cdef extern from *: - cdef cppclass map "std::{{maybe_unordered}}map" [T, U]: - cppclass value_type: - T first - U second - cppclass const_iterator: - value_type& operator*() - const_iterator operator++() - bint operator!=(const_iterator) - const_iterator begin() - const_iterator end() - -@cname("{{cname}}") -cdef object {{cname}}(const map[X,Y]& s): - o = {} - cdef const map[X,Y].value_type *key_value - cdef map[X,Y].const_iterator iter = s.begin() - while iter != s.end(): - key_value = &cython.operator.dereference(iter) + return m + + +#################### map.to_py #################### +# TODO: Work out const so that this can take a const +# reference rather than pass by value. + +cimport cython + +cdef extern from *: + cdef cppclass map "std::{{maybe_unordered}}map" [T, U]: + cppclass value_type: + T first + U second + cppclass const_iterator: + value_type& operator*() + const_iterator operator++() + bint operator!=(const_iterator) + const_iterator begin() + const_iterator end() + +@cname("{{cname}}") +cdef object {{cname}}(const map[X,Y]& s): + o = {} + cdef const map[X,Y].value_type *key_value + cdef map[X,Y].const_iterator iter = s.begin() + while iter != s.end(): + key_value = &cython.operator.dereference(iter) o[key_value.first] = key_value.second - cython.operator.preincrement(iter) - return o + cython.operator.preincrement(iter) + return o #################### complex.from_py #################### diff --git a/contrib/tools/cython/Cython/Utility/CppSupport.cpp b/contrib/tools/cython/Cython/Utility/CppSupport.cpp index b8fcff0643..b215b924b4 100644 --- a/contrib/tools/cython/Cython/Utility/CppSupport.cpp +++ b/contrib/tools/cython/Cython/Utility/CppSupport.cpp @@ -1,51 +1,51 @@ -/////////////// CppExceptionConversion.proto /////////////// - -#ifndef __Pyx_CppExn2PyErr -#include <new> -#include <typeinfo> -#include <stdexcept> -#include <ios> - -static void __Pyx_CppExn2PyErr() { - // Catch a handful of different errors here and turn them into the - // equivalent Python errors. - try { - if (PyErr_Occurred()) - ; // let the latest Python exn pass through and ignore the current one - else - throw; - } catch (const std::bad_alloc& exn) { - PyErr_SetString(PyExc_MemoryError, exn.what()); - } catch (const std::bad_cast& exn) { - PyErr_SetString(PyExc_TypeError, exn.what()); +/////////////// CppExceptionConversion.proto /////////////// + +#ifndef __Pyx_CppExn2PyErr +#include <new> +#include <typeinfo> +#include <stdexcept> +#include <ios> + +static void __Pyx_CppExn2PyErr() { + // Catch a handful of different errors here and turn them into the + // equivalent Python errors. + try { + if (PyErr_Occurred()) + ; // let the latest Python exn pass through and ignore the current one + else + throw; + } catch (const std::bad_alloc& exn) { + PyErr_SetString(PyExc_MemoryError, exn.what()); + } catch (const std::bad_cast& exn) { + PyErr_SetString(PyExc_TypeError, exn.what()); } catch (const std::bad_typeid& exn) { PyErr_SetString(PyExc_TypeError, exn.what()); - } catch (const std::domain_error& exn) { - PyErr_SetString(PyExc_ValueError, exn.what()); - } catch (const std::invalid_argument& exn) { - PyErr_SetString(PyExc_ValueError, exn.what()); - } catch (const std::ios_base::failure& exn) { - // Unfortunately, in standard C++ we have no way of distinguishing EOF - // from other errors here; be careful with the exception mask - PyErr_SetString(PyExc_IOError, exn.what()); - } catch (const std::out_of_range& exn) { - // Change out_of_range to IndexError - PyErr_SetString(PyExc_IndexError, exn.what()); - } catch (const std::overflow_error& exn) { - PyErr_SetString(PyExc_OverflowError, exn.what()); - } catch (const std::range_error& exn) { - PyErr_SetString(PyExc_ArithmeticError, exn.what()); - } catch (const std::underflow_error& exn) { - PyErr_SetString(PyExc_ArithmeticError, exn.what()); - } catch (const std::exception& exn) { - PyErr_SetString(PyExc_RuntimeError, exn.what()); - } - catch (...) - { - PyErr_SetString(PyExc_RuntimeError, "Unknown exception"); - } -} -#endif + } catch (const std::domain_error& exn) { + PyErr_SetString(PyExc_ValueError, exn.what()); + } catch (const std::invalid_argument& exn) { + PyErr_SetString(PyExc_ValueError, exn.what()); + } catch (const std::ios_base::failure& exn) { + // Unfortunately, in standard C++ we have no way of distinguishing EOF + // from other errors here; be careful with the exception mask + PyErr_SetString(PyExc_IOError, exn.what()); + } catch (const std::out_of_range& exn) { + // Change out_of_range to IndexError + PyErr_SetString(PyExc_IndexError, exn.what()); + } catch (const std::overflow_error& exn) { + PyErr_SetString(PyExc_OverflowError, exn.what()); + } catch (const std::range_error& exn) { + PyErr_SetString(PyExc_ArithmeticError, exn.what()); + } catch (const std::underflow_error& exn) { + PyErr_SetString(PyExc_ArithmeticError, exn.what()); + } catch (const std::exception& exn) { + PyErr_SetString(PyExc_RuntimeError, exn.what()); + } + catch (...) + { + PyErr_SetString(PyExc_RuntimeError, "Unknown exception"); + } +} +#endif /////////////// PythranConversion.proto /////////////// diff --git a/contrib/tools/cython/Cython/Utility/CythonFunction.c b/contrib/tools/cython/Cython/Utility/CythonFunction.c index d51b308a8d..d36cc6b8cf 100644 --- a/contrib/tools/cython/Cython/Utility/CythonFunction.c +++ b/contrib/tools/cython/Cython/Utility/CythonFunction.c @@ -1,265 +1,265 @@ - + //////////////////// CythonFunctionShared.proto //////////////////// - -#define __Pyx_CyFunction_USED 1 - -#define __Pyx_CYFUNCTION_STATICMETHOD 0x01 -#define __Pyx_CYFUNCTION_CLASSMETHOD 0x02 -#define __Pyx_CYFUNCTION_CCLASS 0x04 - -#define __Pyx_CyFunction_GetClosure(f) \ - (((__pyx_CyFunctionObject *) (f))->func_closure) -#define __Pyx_CyFunction_GetClassObj(f) \ - (((__pyx_CyFunctionObject *) (f))->func_classobj) - -#define __Pyx_CyFunction_Defaults(type, f) \ - ((type *)(((__pyx_CyFunctionObject *) (f))->defaults)) -#define __Pyx_CyFunction_SetDefaultsGetter(f, g) \ - ((__pyx_CyFunctionObject *) (f))->defaults_getter = (g) - - -typedef struct { - PyCFunctionObject func; -#if PY_VERSION_HEX < 0x030500A0 - PyObject *func_weakreflist; -#endif - PyObject *func_dict; - PyObject *func_name; - PyObject *func_qualname; - PyObject *func_doc; - PyObject *func_globals; - PyObject *func_code; - PyObject *func_closure; - // No-args super() class cell - PyObject *func_classobj; - - // Dynamic default args and annotations - void *defaults; - int defaults_pyobjects; + +#define __Pyx_CyFunction_USED 1 + +#define __Pyx_CYFUNCTION_STATICMETHOD 0x01 +#define __Pyx_CYFUNCTION_CLASSMETHOD 0x02 +#define __Pyx_CYFUNCTION_CCLASS 0x04 + +#define __Pyx_CyFunction_GetClosure(f) \ + (((__pyx_CyFunctionObject *) (f))->func_closure) +#define __Pyx_CyFunction_GetClassObj(f) \ + (((__pyx_CyFunctionObject *) (f))->func_classobj) + +#define __Pyx_CyFunction_Defaults(type, f) \ + ((type *)(((__pyx_CyFunctionObject *) (f))->defaults)) +#define __Pyx_CyFunction_SetDefaultsGetter(f, g) \ + ((__pyx_CyFunctionObject *) (f))->defaults_getter = (g) + + +typedef struct { + PyCFunctionObject func; +#if PY_VERSION_HEX < 0x030500A0 + PyObject *func_weakreflist; +#endif + PyObject *func_dict; + PyObject *func_name; + PyObject *func_qualname; + PyObject *func_doc; + PyObject *func_globals; + PyObject *func_code; + PyObject *func_closure; + // No-args super() class cell + PyObject *func_classobj; + + // Dynamic default args and annotations + void *defaults; + int defaults_pyobjects; size_t defaults_size; // used by FusedFunction for copying defaults - int flags; - - // Defaults info - PyObject *defaults_tuple; /* Const defaults tuple */ - PyObject *defaults_kwdict; /* Const kwonly defaults dict */ - PyObject *(*defaults_getter)(PyObject *); - PyObject *func_annotations; /* function annotations dict */ -} __pyx_CyFunctionObject; - -static PyTypeObject *__pyx_CyFunctionType = 0; - + int flags; + + // Defaults info + PyObject *defaults_tuple; /* Const defaults tuple */ + PyObject *defaults_kwdict; /* Const kwonly defaults dict */ + PyObject *(*defaults_getter)(PyObject *); + PyObject *func_annotations; /* function annotations dict */ +} __pyx_CyFunctionObject; + +static PyTypeObject *__pyx_CyFunctionType = 0; + #define __Pyx_CyFunction_Check(obj) (__Pyx_TypeCheck(obj, __pyx_CyFunctionType)) static PyObject *__Pyx_CyFunction_Init(__pyx_CyFunctionObject* op, PyMethodDef *ml, - int flags, PyObject* qualname, - PyObject *self, - PyObject *module, PyObject *globals, - PyObject* code); - -static CYTHON_INLINE void *__Pyx_CyFunction_InitDefaults(PyObject *m, - size_t size, - int pyobjects); -static CYTHON_INLINE void __Pyx_CyFunction_SetDefaultsTuple(PyObject *m, - PyObject *tuple); -static CYTHON_INLINE void __Pyx_CyFunction_SetDefaultsKwDict(PyObject *m, - PyObject *dict); -static CYTHON_INLINE void __Pyx_CyFunction_SetAnnotationsDict(PyObject *m, - PyObject *dict); - - + int flags, PyObject* qualname, + PyObject *self, + PyObject *module, PyObject *globals, + PyObject* code); + +static CYTHON_INLINE void *__Pyx_CyFunction_InitDefaults(PyObject *m, + size_t size, + int pyobjects); +static CYTHON_INLINE void __Pyx_CyFunction_SetDefaultsTuple(PyObject *m, + PyObject *tuple); +static CYTHON_INLINE void __Pyx_CyFunction_SetDefaultsKwDict(PyObject *m, + PyObject *dict); +static CYTHON_INLINE void __Pyx_CyFunction_SetAnnotationsDict(PyObject *m, + PyObject *dict); + + static int __pyx_CyFunction_init(void); - + //////////////////// CythonFunctionShared //////////////////// -//@substitute: naming +//@substitute: naming //@requires: CommonStructures.c::FetchCommonType -////@requires: ObjectHandling.c::PyObjectGetAttrStr - +////@requires: ObjectHandling.c::PyObjectGetAttrStr + #include <structmember.h> -static PyObject * -__Pyx_CyFunction_get_doc(__pyx_CyFunctionObject *op, CYTHON_UNUSED void *closure) -{ - if (unlikely(op->func_doc == NULL)) { - if (op->func.m_ml->ml_doc) { -#if PY_MAJOR_VERSION >= 3 - op->func_doc = PyUnicode_FromString(op->func.m_ml->ml_doc); -#else - op->func_doc = PyString_FromString(op->func.m_ml->ml_doc); -#endif - if (unlikely(op->func_doc == NULL)) - return NULL; - } else { - Py_INCREF(Py_None); - return Py_None; - } - } - Py_INCREF(op->func_doc); - return op->func_doc; -} - -static int +static PyObject * +__Pyx_CyFunction_get_doc(__pyx_CyFunctionObject *op, CYTHON_UNUSED void *closure) +{ + if (unlikely(op->func_doc == NULL)) { + if (op->func.m_ml->ml_doc) { +#if PY_MAJOR_VERSION >= 3 + op->func_doc = PyUnicode_FromString(op->func.m_ml->ml_doc); +#else + op->func_doc = PyString_FromString(op->func.m_ml->ml_doc); +#endif + if (unlikely(op->func_doc == NULL)) + return NULL; + } else { + Py_INCREF(Py_None); + return Py_None; + } + } + Py_INCREF(op->func_doc); + return op->func_doc; +} + +static int __Pyx_CyFunction_set_doc(__pyx_CyFunctionObject *op, PyObject *value, CYTHON_UNUSED void *context) -{ - PyObject *tmp = op->func_doc; - if (value == NULL) { - // Mark as deleted - value = Py_None; - } - Py_INCREF(value); - op->func_doc = value; - Py_XDECREF(tmp); - return 0; -} - -static PyObject * +{ + PyObject *tmp = op->func_doc; + if (value == NULL) { + // Mark as deleted + value = Py_None; + } + Py_INCREF(value); + op->func_doc = value; + Py_XDECREF(tmp); + return 0; +} + +static PyObject * __Pyx_CyFunction_get_name(__pyx_CyFunctionObject *op, CYTHON_UNUSED void *context) -{ - if (unlikely(op->func_name == NULL)) { -#if PY_MAJOR_VERSION >= 3 - op->func_name = PyUnicode_InternFromString(op->func.m_ml->ml_name); -#else - op->func_name = PyString_InternFromString(op->func.m_ml->ml_name); -#endif - if (unlikely(op->func_name == NULL)) - return NULL; - } - Py_INCREF(op->func_name); - return op->func_name; -} - -static int +{ + if (unlikely(op->func_name == NULL)) { +#if PY_MAJOR_VERSION >= 3 + op->func_name = PyUnicode_InternFromString(op->func.m_ml->ml_name); +#else + op->func_name = PyString_InternFromString(op->func.m_ml->ml_name); +#endif + if (unlikely(op->func_name == NULL)) + return NULL; + } + Py_INCREF(op->func_name); + return op->func_name; +} + +static int __Pyx_CyFunction_set_name(__pyx_CyFunctionObject *op, PyObject *value, CYTHON_UNUSED void *context) -{ - PyObject *tmp; - -#if PY_MAJOR_VERSION >= 3 +{ + PyObject *tmp; + +#if PY_MAJOR_VERSION >= 3 if (unlikely(value == NULL || !PyUnicode_Check(value))) -#else +#else if (unlikely(value == NULL || !PyString_Check(value))) -#endif +#endif { - PyErr_SetString(PyExc_TypeError, - "__name__ must be set to a string object"); - return -1; - } - tmp = op->func_name; - Py_INCREF(value); - op->func_name = value; - Py_XDECREF(tmp); - return 0; -} - -static PyObject * + PyErr_SetString(PyExc_TypeError, + "__name__ must be set to a string object"); + return -1; + } + tmp = op->func_name; + Py_INCREF(value); + op->func_name = value; + Py_XDECREF(tmp); + return 0; +} + +static PyObject * __Pyx_CyFunction_get_qualname(__pyx_CyFunctionObject *op, CYTHON_UNUSED void *context) -{ - Py_INCREF(op->func_qualname); - return op->func_qualname; -} - -static int +{ + Py_INCREF(op->func_qualname); + return op->func_qualname; +} + +static int __Pyx_CyFunction_set_qualname(__pyx_CyFunctionObject *op, PyObject *value, CYTHON_UNUSED void *context) -{ - PyObject *tmp; - -#if PY_MAJOR_VERSION >= 3 +{ + PyObject *tmp; + +#if PY_MAJOR_VERSION >= 3 if (unlikely(value == NULL || !PyUnicode_Check(value))) -#else +#else if (unlikely(value == NULL || !PyString_Check(value))) -#endif +#endif { - PyErr_SetString(PyExc_TypeError, - "__qualname__ must be set to a string object"); - return -1; - } - tmp = op->func_qualname; - Py_INCREF(value); - op->func_qualname = value; - Py_XDECREF(tmp); - return 0; -} - -static PyObject * -__Pyx_CyFunction_get_self(__pyx_CyFunctionObject *m, CYTHON_UNUSED void *closure) -{ - PyObject *self; - - self = m->func_closure; - if (self == NULL) - self = Py_None; - Py_INCREF(self); - return self; -} - -static PyObject * + PyErr_SetString(PyExc_TypeError, + "__qualname__ must be set to a string object"); + return -1; + } + tmp = op->func_qualname; + Py_INCREF(value); + op->func_qualname = value; + Py_XDECREF(tmp); + return 0; +} + +static PyObject * +__Pyx_CyFunction_get_self(__pyx_CyFunctionObject *m, CYTHON_UNUSED void *closure) +{ + PyObject *self; + + self = m->func_closure; + if (self == NULL) + self = Py_None; + Py_INCREF(self); + return self; +} + +static PyObject * __Pyx_CyFunction_get_dict(__pyx_CyFunctionObject *op, CYTHON_UNUSED void *context) -{ - if (unlikely(op->func_dict == NULL)) { - op->func_dict = PyDict_New(); - if (unlikely(op->func_dict == NULL)) - return NULL; - } - Py_INCREF(op->func_dict); - return op->func_dict; -} - -static int +{ + if (unlikely(op->func_dict == NULL)) { + op->func_dict = PyDict_New(); + if (unlikely(op->func_dict == NULL)) + return NULL; + } + Py_INCREF(op->func_dict); + return op->func_dict; +} + +static int __Pyx_CyFunction_set_dict(__pyx_CyFunctionObject *op, PyObject *value, CYTHON_UNUSED void *context) -{ - PyObject *tmp; - - if (unlikely(value == NULL)) { - PyErr_SetString(PyExc_TypeError, - "function's dictionary may not be deleted"); - return -1; - } - if (unlikely(!PyDict_Check(value))) { - PyErr_SetString(PyExc_TypeError, - "setting function's dictionary to a non-dict"); - return -1; - } - tmp = op->func_dict; - Py_INCREF(value); - op->func_dict = value; - Py_XDECREF(tmp); - return 0; -} - -static PyObject * +{ + PyObject *tmp; + + if (unlikely(value == NULL)) { + PyErr_SetString(PyExc_TypeError, + "function's dictionary may not be deleted"); + return -1; + } + if (unlikely(!PyDict_Check(value))) { + PyErr_SetString(PyExc_TypeError, + "setting function's dictionary to a non-dict"); + return -1; + } + tmp = op->func_dict; + Py_INCREF(value); + op->func_dict = value; + Py_XDECREF(tmp); + return 0; +} + +static PyObject * __Pyx_CyFunction_get_globals(__pyx_CyFunctionObject *op, CYTHON_UNUSED void *context) -{ - Py_INCREF(op->func_globals); - return op->func_globals; -} - -static PyObject * +{ + Py_INCREF(op->func_globals); + return op->func_globals; +} + +static PyObject * __Pyx_CyFunction_get_closure(CYTHON_UNUSED __pyx_CyFunctionObject *op, CYTHON_UNUSED void *context) -{ - Py_INCREF(Py_None); - return Py_None; -} - -static PyObject * +{ + Py_INCREF(Py_None); + return Py_None; +} + +static PyObject * __Pyx_CyFunction_get_code(__pyx_CyFunctionObject *op, CYTHON_UNUSED void *context) -{ - PyObject* result = (op->func_code) ? op->func_code : Py_None; - Py_INCREF(result); - return result; -} - -static int -__Pyx_CyFunction_init_defaults(__pyx_CyFunctionObject *op) { +{ + PyObject* result = (op->func_code) ? op->func_code : Py_None; + Py_INCREF(result); + return result; +} + +static int +__Pyx_CyFunction_init_defaults(__pyx_CyFunctionObject *op) { int result = 0; - PyObject *res = op->defaults_getter((PyObject *) op); - if (unlikely(!res)) - return -1; - - // Cache result + PyObject *res = op->defaults_getter((PyObject *) op); + if (unlikely(!res)) + return -1; + + // Cache result #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS - op->defaults_tuple = PyTuple_GET_ITEM(res, 0); - Py_INCREF(op->defaults_tuple); - op->defaults_kwdict = PyTuple_GET_ITEM(res, 1); - Py_INCREF(op->defaults_kwdict); + op->defaults_tuple = PyTuple_GET_ITEM(res, 0); + Py_INCREF(op->defaults_tuple); + op->defaults_kwdict = PyTuple_GET_ITEM(res, 1); + Py_INCREF(op->defaults_kwdict); #else op->defaults_tuple = PySequence_ITEM(res, 0); if (unlikely(!op->defaults_tuple)) result = -1; @@ -268,254 +268,254 @@ __Pyx_CyFunction_init_defaults(__pyx_CyFunctionObject *op) { if (unlikely(!op->defaults_kwdict)) result = -1; } #endif - Py_DECREF(res); + Py_DECREF(res); return result; -} - -static int +} + +static int __Pyx_CyFunction_set_defaults(__pyx_CyFunctionObject *op, PyObject* value, CYTHON_UNUSED void *context) { - PyObject* tmp; - if (!value) { - // del => explicit None to prevent rebuilding - value = Py_None; - } else if (value != Py_None && !PyTuple_Check(value)) { - PyErr_SetString(PyExc_TypeError, - "__defaults__ must be set to a tuple object"); - return -1; - } - Py_INCREF(value); - tmp = op->defaults_tuple; - op->defaults_tuple = value; - Py_XDECREF(tmp); - return 0; -} - -static PyObject * + PyObject* tmp; + if (!value) { + // del => explicit None to prevent rebuilding + value = Py_None; + } else if (value != Py_None && !PyTuple_Check(value)) { + PyErr_SetString(PyExc_TypeError, + "__defaults__ must be set to a tuple object"); + return -1; + } + Py_INCREF(value); + tmp = op->defaults_tuple; + op->defaults_tuple = value; + Py_XDECREF(tmp); + return 0; +} + +static PyObject * __Pyx_CyFunction_get_defaults(__pyx_CyFunctionObject *op, CYTHON_UNUSED void *context) { - PyObject* result = op->defaults_tuple; - if (unlikely(!result)) { - if (op->defaults_getter) { - if (__Pyx_CyFunction_init_defaults(op) < 0) return NULL; - result = op->defaults_tuple; - } else { - result = Py_None; - } - } - Py_INCREF(result); - return result; -} - -static int + PyObject* result = op->defaults_tuple; + if (unlikely(!result)) { + if (op->defaults_getter) { + if (__Pyx_CyFunction_init_defaults(op) < 0) return NULL; + result = op->defaults_tuple; + } else { + result = Py_None; + } + } + Py_INCREF(result); + return result; +} + +static int __Pyx_CyFunction_set_kwdefaults(__pyx_CyFunctionObject *op, PyObject* value, CYTHON_UNUSED void *context) { - PyObject* tmp; - if (!value) { - // del => explicit None to prevent rebuilding - value = Py_None; - } else if (value != Py_None && !PyDict_Check(value)) { - PyErr_SetString(PyExc_TypeError, - "__kwdefaults__ must be set to a dict object"); - return -1; - } - Py_INCREF(value); - tmp = op->defaults_kwdict; - op->defaults_kwdict = value; - Py_XDECREF(tmp); - return 0; -} - -static PyObject * + PyObject* tmp; + if (!value) { + // del => explicit None to prevent rebuilding + value = Py_None; + } else if (value != Py_None && !PyDict_Check(value)) { + PyErr_SetString(PyExc_TypeError, + "__kwdefaults__ must be set to a dict object"); + return -1; + } + Py_INCREF(value); + tmp = op->defaults_kwdict; + op->defaults_kwdict = value; + Py_XDECREF(tmp); + return 0; +} + +static PyObject * __Pyx_CyFunction_get_kwdefaults(__pyx_CyFunctionObject *op, CYTHON_UNUSED void *context) { - PyObject* result = op->defaults_kwdict; - if (unlikely(!result)) { - if (op->defaults_getter) { - if (__Pyx_CyFunction_init_defaults(op) < 0) return NULL; - result = op->defaults_kwdict; - } else { - result = Py_None; - } - } - Py_INCREF(result); - return result; -} - -static int + PyObject* result = op->defaults_kwdict; + if (unlikely(!result)) { + if (op->defaults_getter) { + if (__Pyx_CyFunction_init_defaults(op) < 0) return NULL; + result = op->defaults_kwdict; + } else { + result = Py_None; + } + } + Py_INCREF(result); + return result; +} + +static int __Pyx_CyFunction_set_annotations(__pyx_CyFunctionObject *op, PyObject* value, CYTHON_UNUSED void *context) { - PyObject* tmp; - if (!value || value == Py_None) { - value = NULL; - } else if (!PyDict_Check(value)) { - PyErr_SetString(PyExc_TypeError, - "__annotations__ must be set to a dict object"); - return -1; - } - Py_XINCREF(value); - tmp = op->func_annotations; - op->func_annotations = value; - Py_XDECREF(tmp); - return 0; -} - -static PyObject * + PyObject* tmp; + if (!value || value == Py_None) { + value = NULL; + } else if (!PyDict_Check(value)) { + PyErr_SetString(PyExc_TypeError, + "__annotations__ must be set to a dict object"); + return -1; + } + Py_XINCREF(value); + tmp = op->func_annotations; + op->func_annotations = value; + Py_XDECREF(tmp); + return 0; +} + +static PyObject * __Pyx_CyFunction_get_annotations(__pyx_CyFunctionObject *op, CYTHON_UNUSED void *context) { - PyObject* result = op->func_annotations; - if (unlikely(!result)) { - result = PyDict_New(); - if (unlikely(!result)) return NULL; - op->func_annotations = result; - } - Py_INCREF(result); - return result; -} - -//#if PY_VERSION_HEX >= 0x030400C1 -//static PyObject * + PyObject* result = op->func_annotations; + if (unlikely(!result)) { + result = PyDict_New(); + if (unlikely(!result)) return NULL; + op->func_annotations = result; + } + Py_INCREF(result); + return result; +} + +//#if PY_VERSION_HEX >= 0x030400C1 +//static PyObject * //__Pyx_CyFunction_get_signature(__pyx_CyFunctionObject *op, CYTHON_UNUSED void *context) { -// PyObject *inspect_module, *signature_class, *signature; -// // from inspect import Signature -// inspect_module = PyImport_ImportModuleLevelObject(PYIDENT("inspect"), NULL, NULL, NULL, 0); -// if (unlikely(!inspect_module)) -// goto bad; -// signature_class = __Pyx_PyObject_GetAttrStr(inspect_module, PYIDENT("Signature")); -// Py_DECREF(inspect_module); -// if (unlikely(!signature_class)) -// goto bad; -// // return Signature.from_function(op) -// signature = PyObject_CallMethodObjArgs(signature_class, PYIDENT("from_function"), op, NULL); -// Py_DECREF(signature_class); -// if (likely(signature)) -// return signature; -//bad: -// // make sure we raise an AttributeError from this property on any errors -// if (!PyErr_ExceptionMatches(PyExc_AttributeError)) -// PyErr_SetString(PyExc_AttributeError, "failed to calculate __signature__"); -// return NULL; -//} -//#endif - -static PyGetSetDef __pyx_CyFunction_getsets[] = { - {(char *) "func_doc", (getter)__Pyx_CyFunction_get_doc, (setter)__Pyx_CyFunction_set_doc, 0, 0}, - {(char *) "__doc__", (getter)__Pyx_CyFunction_get_doc, (setter)__Pyx_CyFunction_set_doc, 0, 0}, - {(char *) "func_name", (getter)__Pyx_CyFunction_get_name, (setter)__Pyx_CyFunction_set_name, 0, 0}, - {(char *) "__name__", (getter)__Pyx_CyFunction_get_name, (setter)__Pyx_CyFunction_set_name, 0, 0}, - {(char *) "__qualname__", (getter)__Pyx_CyFunction_get_qualname, (setter)__Pyx_CyFunction_set_qualname, 0, 0}, - {(char *) "__self__", (getter)__Pyx_CyFunction_get_self, 0, 0, 0}, - {(char *) "func_dict", (getter)__Pyx_CyFunction_get_dict, (setter)__Pyx_CyFunction_set_dict, 0, 0}, - {(char *) "__dict__", (getter)__Pyx_CyFunction_get_dict, (setter)__Pyx_CyFunction_set_dict, 0, 0}, - {(char *) "func_globals", (getter)__Pyx_CyFunction_get_globals, 0, 0, 0}, - {(char *) "__globals__", (getter)__Pyx_CyFunction_get_globals, 0, 0, 0}, - {(char *) "func_closure", (getter)__Pyx_CyFunction_get_closure, 0, 0, 0}, - {(char *) "__closure__", (getter)__Pyx_CyFunction_get_closure, 0, 0, 0}, - {(char *) "func_code", (getter)__Pyx_CyFunction_get_code, 0, 0, 0}, - {(char *) "__code__", (getter)__Pyx_CyFunction_get_code, 0, 0, 0}, - {(char *) "func_defaults", (getter)__Pyx_CyFunction_get_defaults, (setter)__Pyx_CyFunction_set_defaults, 0, 0}, - {(char *) "__defaults__", (getter)__Pyx_CyFunction_get_defaults, (setter)__Pyx_CyFunction_set_defaults, 0, 0}, - {(char *) "__kwdefaults__", (getter)__Pyx_CyFunction_get_kwdefaults, (setter)__Pyx_CyFunction_set_kwdefaults, 0, 0}, - {(char *) "__annotations__", (getter)__Pyx_CyFunction_get_annotations, (setter)__Pyx_CyFunction_set_annotations, 0, 0}, -//#if PY_VERSION_HEX >= 0x030400C1 -// {(char *) "__signature__", (getter)__Pyx_CyFunction_get_signature, 0, 0, 0}, -//#endif - {0, 0, 0, 0, 0} -}; - -static PyMemberDef __pyx_CyFunction_members[] = { +// PyObject *inspect_module, *signature_class, *signature; +// // from inspect import Signature +// inspect_module = PyImport_ImportModuleLevelObject(PYIDENT("inspect"), NULL, NULL, NULL, 0); +// if (unlikely(!inspect_module)) +// goto bad; +// signature_class = __Pyx_PyObject_GetAttrStr(inspect_module, PYIDENT("Signature")); +// Py_DECREF(inspect_module); +// if (unlikely(!signature_class)) +// goto bad; +// // return Signature.from_function(op) +// signature = PyObject_CallMethodObjArgs(signature_class, PYIDENT("from_function"), op, NULL); +// Py_DECREF(signature_class); +// if (likely(signature)) +// return signature; +//bad: +// // make sure we raise an AttributeError from this property on any errors +// if (!PyErr_ExceptionMatches(PyExc_AttributeError)) +// PyErr_SetString(PyExc_AttributeError, "failed to calculate __signature__"); +// return NULL; +//} +//#endif + +static PyGetSetDef __pyx_CyFunction_getsets[] = { + {(char *) "func_doc", (getter)__Pyx_CyFunction_get_doc, (setter)__Pyx_CyFunction_set_doc, 0, 0}, + {(char *) "__doc__", (getter)__Pyx_CyFunction_get_doc, (setter)__Pyx_CyFunction_set_doc, 0, 0}, + {(char *) "func_name", (getter)__Pyx_CyFunction_get_name, (setter)__Pyx_CyFunction_set_name, 0, 0}, + {(char *) "__name__", (getter)__Pyx_CyFunction_get_name, (setter)__Pyx_CyFunction_set_name, 0, 0}, + {(char *) "__qualname__", (getter)__Pyx_CyFunction_get_qualname, (setter)__Pyx_CyFunction_set_qualname, 0, 0}, + {(char *) "__self__", (getter)__Pyx_CyFunction_get_self, 0, 0, 0}, + {(char *) "func_dict", (getter)__Pyx_CyFunction_get_dict, (setter)__Pyx_CyFunction_set_dict, 0, 0}, + {(char *) "__dict__", (getter)__Pyx_CyFunction_get_dict, (setter)__Pyx_CyFunction_set_dict, 0, 0}, + {(char *) "func_globals", (getter)__Pyx_CyFunction_get_globals, 0, 0, 0}, + {(char *) "__globals__", (getter)__Pyx_CyFunction_get_globals, 0, 0, 0}, + {(char *) "func_closure", (getter)__Pyx_CyFunction_get_closure, 0, 0, 0}, + {(char *) "__closure__", (getter)__Pyx_CyFunction_get_closure, 0, 0, 0}, + {(char *) "func_code", (getter)__Pyx_CyFunction_get_code, 0, 0, 0}, + {(char *) "__code__", (getter)__Pyx_CyFunction_get_code, 0, 0, 0}, + {(char *) "func_defaults", (getter)__Pyx_CyFunction_get_defaults, (setter)__Pyx_CyFunction_set_defaults, 0, 0}, + {(char *) "__defaults__", (getter)__Pyx_CyFunction_get_defaults, (setter)__Pyx_CyFunction_set_defaults, 0, 0}, + {(char *) "__kwdefaults__", (getter)__Pyx_CyFunction_get_kwdefaults, (setter)__Pyx_CyFunction_set_kwdefaults, 0, 0}, + {(char *) "__annotations__", (getter)__Pyx_CyFunction_get_annotations, (setter)__Pyx_CyFunction_set_annotations, 0, 0}, +//#if PY_VERSION_HEX >= 0x030400C1 +// {(char *) "__signature__", (getter)__Pyx_CyFunction_get_signature, 0, 0, 0}, +//#endif + {0, 0, 0, 0, 0} +}; + +static PyMemberDef __pyx_CyFunction_members[] = { {(char *) "__module__", T_OBJECT, offsetof(PyCFunctionObject, m_module), PY_WRITE_RESTRICTED, 0}, - {0, 0, 0, 0, 0} -}; - -static PyObject * -__Pyx_CyFunction_reduce(__pyx_CyFunctionObject *m, CYTHON_UNUSED PyObject *args) -{ -#if PY_MAJOR_VERSION >= 3 + {0, 0, 0, 0, 0} +}; + +static PyObject * +__Pyx_CyFunction_reduce(__pyx_CyFunctionObject *m, CYTHON_UNUSED PyObject *args) +{ +#if PY_MAJOR_VERSION >= 3 Py_INCREF(m->func_qualname); return m->func_qualname; -#else - return PyString_FromString(m->func.m_ml->ml_name); -#endif -} - -static PyMethodDef __pyx_CyFunction_methods[] = { - {"__reduce__", (PyCFunction)__Pyx_CyFunction_reduce, METH_VARARGS, 0}, - {0, 0, 0, 0} -}; - - -#if PY_VERSION_HEX < 0x030500A0 -#define __Pyx_CyFunction_weakreflist(cyfunc) ((cyfunc)->func_weakreflist) -#else -#define __Pyx_CyFunction_weakreflist(cyfunc) ((cyfunc)->func.m_weakreflist) -#endif - +#else + return PyString_FromString(m->func.m_ml->ml_name); +#endif +} + +static PyMethodDef __pyx_CyFunction_methods[] = { + {"__reduce__", (PyCFunction)__Pyx_CyFunction_reduce, METH_VARARGS, 0}, + {0, 0, 0, 0} +}; + + +#if PY_VERSION_HEX < 0x030500A0 +#define __Pyx_CyFunction_weakreflist(cyfunc) ((cyfunc)->func_weakreflist) +#else +#define __Pyx_CyFunction_weakreflist(cyfunc) ((cyfunc)->func.m_weakreflist) +#endif + static PyObject *__Pyx_CyFunction_Init(__pyx_CyFunctionObject *op, PyMethodDef *ml, int flags, PyObject* qualname, PyObject *closure, PyObject *module, PyObject* globals, PyObject* code) { if (unlikely(op == NULL)) - return NULL; - op->flags = flags; - __Pyx_CyFunction_weakreflist(op) = NULL; - op->func.m_ml = ml; - op->func.m_self = (PyObject *) op; - Py_XINCREF(closure); - op->func_closure = closure; - Py_XINCREF(module); - op->func.m_module = module; - op->func_dict = NULL; - op->func_name = NULL; - Py_INCREF(qualname); - op->func_qualname = qualname; - op->func_doc = NULL; - op->func_classobj = NULL; - op->func_globals = globals; - Py_INCREF(op->func_globals); - Py_XINCREF(code); - op->func_code = code; - // Dynamic Default args - op->defaults_pyobjects = 0; + return NULL; + op->flags = flags; + __Pyx_CyFunction_weakreflist(op) = NULL; + op->func.m_ml = ml; + op->func.m_self = (PyObject *) op; + Py_XINCREF(closure); + op->func_closure = closure; + Py_XINCREF(module); + op->func.m_module = module; + op->func_dict = NULL; + op->func_name = NULL; + Py_INCREF(qualname); + op->func_qualname = qualname; + op->func_doc = NULL; + op->func_classobj = NULL; + op->func_globals = globals; + Py_INCREF(op->func_globals); + Py_XINCREF(code); + op->func_code = code; + // Dynamic Default args + op->defaults_pyobjects = 0; op->defaults_size = 0; - op->defaults = NULL; - op->defaults_tuple = NULL; - op->defaults_kwdict = NULL; - op->defaults_getter = NULL; - op->func_annotations = NULL; - return (PyObject *) op; -} - -static int -__Pyx_CyFunction_clear(__pyx_CyFunctionObject *m) -{ - Py_CLEAR(m->func_closure); - Py_CLEAR(m->func.m_module); - Py_CLEAR(m->func_dict); - Py_CLEAR(m->func_name); - Py_CLEAR(m->func_qualname); - Py_CLEAR(m->func_doc); - Py_CLEAR(m->func_globals); - Py_CLEAR(m->func_code); - Py_CLEAR(m->func_classobj); - Py_CLEAR(m->defaults_tuple); - Py_CLEAR(m->defaults_kwdict); - Py_CLEAR(m->func_annotations); - - if (m->defaults) { - PyObject **pydefaults = __Pyx_CyFunction_Defaults(PyObject *, m); - int i; - - for (i = 0; i < m->defaults_pyobjects; i++) - Py_XDECREF(pydefaults[i]); - + op->defaults = NULL; + op->defaults_tuple = NULL; + op->defaults_kwdict = NULL; + op->defaults_getter = NULL; + op->func_annotations = NULL; + return (PyObject *) op; +} + +static int +__Pyx_CyFunction_clear(__pyx_CyFunctionObject *m) +{ + Py_CLEAR(m->func_closure); + Py_CLEAR(m->func.m_module); + Py_CLEAR(m->func_dict); + Py_CLEAR(m->func_name); + Py_CLEAR(m->func_qualname); + Py_CLEAR(m->func_doc); + Py_CLEAR(m->func_globals); + Py_CLEAR(m->func_code); + Py_CLEAR(m->func_classobj); + Py_CLEAR(m->defaults_tuple); + Py_CLEAR(m->defaults_kwdict); + Py_CLEAR(m->func_annotations); + + if (m->defaults) { + PyObject **pydefaults = __Pyx_CyFunction_Defaults(PyObject *, m); + int i; + + for (i = 0; i < m->defaults_pyobjects; i++) + Py_XDECREF(pydefaults[i]); + PyObject_Free(m->defaults); - m->defaults = NULL; - } - - return 0; -} - + m->defaults = NULL; + } + + return 0; +} + static void __Pyx__CyFunction_dealloc(__pyx_CyFunctionObject *m) -{ - if (__Pyx_CyFunction_weakreflist(m) != NULL) - PyObject_ClearWeakRefs((PyObject *) m); - __Pyx_CyFunction_clear(m); - PyObject_GC_Del(m); -} - +{ + if (__Pyx_CyFunction_weakreflist(m) != NULL) + PyObject_ClearWeakRefs((PyObject *) m); + __Pyx_CyFunction_clear(m); + PyObject_GC_Del(m); +} + static void __Pyx_CyFunction_dealloc(PyObject *obj) { __pyx_CyFunctionObject *m = (__pyx_CyFunctionObject *) obj; @@ -523,92 +523,92 @@ static void __Pyx_CyFunction_dealloc(PyObject *obj) __Pyx__CyFunction_dealloc(m); } -static int __Pyx_CyFunction_traverse(__pyx_CyFunctionObject *m, visitproc visit, void *arg) -{ - Py_VISIT(m->func_closure); - Py_VISIT(m->func.m_module); - Py_VISIT(m->func_dict); - Py_VISIT(m->func_name); - Py_VISIT(m->func_qualname); - Py_VISIT(m->func_doc); - Py_VISIT(m->func_globals); - Py_VISIT(m->func_code); - Py_VISIT(m->func_classobj); - Py_VISIT(m->defaults_tuple); - Py_VISIT(m->defaults_kwdict); - - if (m->defaults) { - PyObject **pydefaults = __Pyx_CyFunction_Defaults(PyObject *, m); - int i; - - for (i = 0; i < m->defaults_pyobjects; i++) - Py_VISIT(pydefaults[i]); - } - - return 0; -} - -static PyObject *__Pyx_CyFunction_descr_get(PyObject *func, PyObject *obj, PyObject *type) -{ +static int __Pyx_CyFunction_traverse(__pyx_CyFunctionObject *m, visitproc visit, void *arg) +{ + Py_VISIT(m->func_closure); + Py_VISIT(m->func.m_module); + Py_VISIT(m->func_dict); + Py_VISIT(m->func_name); + Py_VISIT(m->func_qualname); + Py_VISIT(m->func_doc); + Py_VISIT(m->func_globals); + Py_VISIT(m->func_code); + Py_VISIT(m->func_classobj); + Py_VISIT(m->defaults_tuple); + Py_VISIT(m->defaults_kwdict); + + if (m->defaults) { + PyObject **pydefaults = __Pyx_CyFunction_Defaults(PyObject *, m); + int i; + + for (i = 0; i < m->defaults_pyobjects; i++) + Py_VISIT(pydefaults[i]); + } + + return 0; +} + +static PyObject *__Pyx_CyFunction_descr_get(PyObject *func, PyObject *obj, PyObject *type) +{ #if PY_MAJOR_VERSION < 3 - __pyx_CyFunctionObject *m = (__pyx_CyFunctionObject *) func; - - if (m->flags & __Pyx_CYFUNCTION_STATICMETHOD) { - Py_INCREF(func); - return func; - } - - if (m->flags & __Pyx_CYFUNCTION_CLASSMETHOD) { - if (type == NULL) - type = (PyObject *)(Py_TYPE(obj)); + __pyx_CyFunctionObject *m = (__pyx_CyFunctionObject *) func; + + if (m->flags & __Pyx_CYFUNCTION_STATICMETHOD) { + Py_INCREF(func); + return func; + } + + if (m->flags & __Pyx_CYFUNCTION_CLASSMETHOD) { + if (type == NULL) + type = (PyObject *)(Py_TYPE(obj)); return __Pyx_PyMethod_New(func, type, (PyObject *)(Py_TYPE(type))); - } - - if (obj == Py_None) - obj = NULL; + } + + if (obj == Py_None) + obj = NULL; #endif return __Pyx_PyMethod_New(func, obj, type); -} - -static PyObject* -__Pyx_CyFunction_repr(__pyx_CyFunctionObject *op) -{ -#if PY_MAJOR_VERSION >= 3 - return PyUnicode_FromFormat("<cyfunction %U at %p>", - op->func_qualname, (void *)op); -#else - return PyString_FromFormat("<cyfunction %s at %p>", - PyString_AsString(op->func_qualname), (void *)op); -#endif -} - +} + +static PyObject* +__Pyx_CyFunction_repr(__pyx_CyFunctionObject *op) +{ +#if PY_MAJOR_VERSION >= 3 + return PyUnicode_FromFormat("<cyfunction %U at %p>", + op->func_qualname, (void *)op); +#else + return PyString_FromFormat("<cyfunction %s at %p>", + PyString_AsString(op->func_qualname), (void *)op); +#endif +} + static PyObject * __Pyx_CyFunction_CallMethod(PyObject *func, PyObject *self, PyObject *arg, PyObject *kw) { // originally copied from PyCFunction_Call() in CPython's Objects/methodobject.c - PyCFunctionObject* f = (PyCFunctionObject*)func; + PyCFunctionObject* f = (PyCFunctionObject*)func; PyCFunction meth = f->m_ml->ml_meth; - Py_ssize_t size; - + Py_ssize_t size; + switch (f->m_ml->ml_flags & (METH_VARARGS | METH_KEYWORDS | METH_NOARGS | METH_O)) { - case METH_VARARGS: + case METH_VARARGS: if (likely(kw == NULL || PyDict_Size(kw) == 0)) - return (*meth)(self, arg); - break; - case METH_VARARGS | METH_KEYWORDS: + return (*meth)(self, arg); + break; + case METH_VARARGS | METH_KEYWORDS: return (*(PyCFunctionWithKeywords)(void*)meth)(self, arg, kw); - case METH_NOARGS: + case METH_NOARGS: if (likely(kw == NULL || PyDict_Size(kw) == 0)) { - size = PyTuple_GET_SIZE(arg); + size = PyTuple_GET_SIZE(arg); if (likely(size == 0)) - return (*meth)(self, NULL); - PyErr_Format(PyExc_TypeError, + return (*meth)(self, NULL); + PyErr_Format(PyExc_TypeError, "%.200s() takes no arguments (%" CYTHON_FORMAT_SSIZE_T "d given)", - f->m_ml->ml_name, size); - return NULL; - } - break; - case METH_O: + f->m_ml->ml_name, size); + return NULL; + } + break; + case METH_O: if (likely(kw == NULL || PyDict_Size(kw) == 0)) { - size = PyTuple_GET_SIZE(arg); + size = PyTuple_GET_SIZE(arg); if (likely(size == 1)) { PyObject *result, *arg0; #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS @@ -622,28 +622,28 @@ static PyObject * __Pyx_CyFunction_CallMethod(PyObject *func, PyObject *self, Py #endif return result; } - PyErr_Format(PyExc_TypeError, + PyErr_Format(PyExc_TypeError, "%.200s() takes exactly one argument (%" CYTHON_FORMAT_SSIZE_T "d given)", - f->m_ml->ml_name, size); - return NULL; - } - break; - default: - PyErr_SetString(PyExc_SystemError, "Bad call flags in " - "__Pyx_CyFunction_Call. METH_OLDARGS is no " - "longer supported!"); - - return NULL; - } - PyErr_Format(PyExc_TypeError, "%.200s() takes no keyword arguments", - f->m_ml->ml_name); - return NULL; -} + f->m_ml->ml_name, size); + return NULL; + } + break; + default: + PyErr_SetString(PyExc_SystemError, "Bad call flags in " + "__Pyx_CyFunction_Call. METH_OLDARGS is no " + "longer supported!"); + + return NULL; + } + PyErr_Format(PyExc_TypeError, "%.200s() takes no keyword arguments", + f->m_ml->ml_name); + return NULL; +} static CYTHON_INLINE PyObject *__Pyx_CyFunction_Call(PyObject *func, PyObject *arg, PyObject *kw) { return __Pyx_CyFunction_CallMethod(func, ((PyCFunctionObject*)func)->m_self, arg, kw); -} - +} + static PyObject *__Pyx_CyFunction_CallAsMethod(PyObject *func, PyObject *args, PyObject *kw) { PyObject *result; __pyx_CyFunctionObject *cyfunc = (__pyx_CyFunctionObject *) func; @@ -672,65 +672,65 @@ static PyObject *__Pyx_CyFunction_CallAsMethod(PyObject *func, PyObject *args, P return result; } -static PyTypeObject __pyx_CyFunctionType_type = { - PyVarObject_HEAD_INIT(0, 0) - "cython_function_or_method", /*tp_name*/ - sizeof(__pyx_CyFunctionObject), /*tp_basicsize*/ - 0, /*tp_itemsize*/ - (destructor) __Pyx_CyFunction_dealloc, /*tp_dealloc*/ - 0, /*tp_print*/ - 0, /*tp_getattr*/ - 0, /*tp_setattr*/ -#if PY_MAJOR_VERSION < 3 - 0, /*tp_compare*/ -#else - 0, /*reserved*/ -#endif - (reprfunc) __Pyx_CyFunction_repr, /*tp_repr*/ - 0, /*tp_as_number*/ - 0, /*tp_as_sequence*/ - 0, /*tp_as_mapping*/ - 0, /*tp_hash*/ +static PyTypeObject __pyx_CyFunctionType_type = { + PyVarObject_HEAD_INIT(0, 0) + "cython_function_or_method", /*tp_name*/ + sizeof(__pyx_CyFunctionObject), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + (destructor) __Pyx_CyFunction_dealloc, /*tp_dealloc*/ + 0, /*tp_print*/ + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ +#if PY_MAJOR_VERSION < 3 + 0, /*tp_compare*/ +#else + 0, /*reserved*/ +#endif + (reprfunc) __Pyx_CyFunction_repr, /*tp_repr*/ + 0, /*tp_as_number*/ + 0, /*tp_as_sequence*/ + 0, /*tp_as_mapping*/ + 0, /*tp_hash*/ __Pyx_CyFunction_CallAsMethod, /*tp_call*/ - 0, /*tp_str*/ - 0, /*tp_getattro*/ - 0, /*tp_setattro*/ - 0, /*tp_as_buffer*/ - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /*tp_flags*/ - 0, /*tp_doc*/ - (traverseproc) __Pyx_CyFunction_traverse, /*tp_traverse*/ - (inquiry) __Pyx_CyFunction_clear, /*tp_clear*/ - 0, /*tp_richcompare*/ -#if PY_VERSION_HEX < 0x030500A0 - offsetof(__pyx_CyFunctionObject, func_weakreflist), /*tp_weaklistoffset*/ -#else - offsetof(PyCFunctionObject, m_weakreflist), /*tp_weaklistoffset*/ -#endif - 0, /*tp_iter*/ - 0, /*tp_iternext*/ - __pyx_CyFunction_methods, /*tp_methods*/ - __pyx_CyFunction_members, /*tp_members*/ - __pyx_CyFunction_getsets, /*tp_getset*/ - 0, /*tp_base*/ - 0, /*tp_dict*/ - __Pyx_CyFunction_descr_get, /*tp_descr_get*/ - 0, /*tp_descr_set*/ - offsetof(__pyx_CyFunctionObject, func_dict),/*tp_dictoffset*/ - 0, /*tp_init*/ - 0, /*tp_alloc*/ - 0, /*tp_new*/ - 0, /*tp_free*/ - 0, /*tp_is_gc*/ - 0, /*tp_bases*/ - 0, /*tp_mro*/ - 0, /*tp_cache*/ - 0, /*tp_subclasses*/ - 0, /*tp_weaklist*/ - 0, /*tp_del*/ - 0, /*tp_version_tag*/ -#if PY_VERSION_HEX >= 0x030400a1 - 0, /*tp_finalize*/ -#endif + 0, /*tp_str*/ + 0, /*tp_getattro*/ + 0, /*tp_setattro*/ + 0, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /*tp_flags*/ + 0, /*tp_doc*/ + (traverseproc) __Pyx_CyFunction_traverse, /*tp_traverse*/ + (inquiry) __Pyx_CyFunction_clear, /*tp_clear*/ + 0, /*tp_richcompare*/ +#if PY_VERSION_HEX < 0x030500A0 + offsetof(__pyx_CyFunctionObject, func_weakreflist), /*tp_weaklistoffset*/ +#else + offsetof(PyCFunctionObject, m_weakreflist), /*tp_weaklistoffset*/ +#endif + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + __pyx_CyFunction_methods, /*tp_methods*/ + __pyx_CyFunction_members, /*tp_members*/ + __pyx_CyFunction_getsets, /*tp_getset*/ + 0, /*tp_base*/ + 0, /*tp_dict*/ + __Pyx_CyFunction_descr_get, /*tp_descr_get*/ + 0, /*tp_descr_set*/ + offsetof(__pyx_CyFunctionObject, func_dict),/*tp_dictoffset*/ + 0, /*tp_init*/ + 0, /*tp_alloc*/ + 0, /*tp_new*/ + 0, /*tp_free*/ + 0, /*tp_is_gc*/ + 0, /*tp_bases*/ + 0, /*tp_mro*/ + 0, /*tp_cache*/ + 0, /*tp_subclasses*/ + 0, /*tp_weaklist*/ + 0, /*tp_del*/ + 0, /*tp_version_tag*/ +#if PY_VERSION_HEX >= 0x030400a1 + 0, /*tp_finalize*/ +#endif #if PY_VERSION_HEX >= 0x030800b1 && (!CYTHON_COMPILING_IN_PYPY || PYPY_VERSION_NUM >= 0x07030800) 0, /*tp_vectorcall*/ #endif @@ -740,47 +740,47 @@ static PyTypeObject __pyx_CyFunctionType_type = { #if CYTHON_COMPILING_IN_PYPY && PY_VERSION_HEX >= 0x03090000 0, /*tp_pypy_flags*/ #endif -}; - - +}; + + static int __pyx_CyFunction_init(void) { - __pyx_CyFunctionType = __Pyx_FetchCommonType(&__pyx_CyFunctionType_type); + __pyx_CyFunctionType = __Pyx_FetchCommonType(&__pyx_CyFunctionType_type); if (unlikely(__pyx_CyFunctionType == NULL)) { - return -1; - } - return 0; -} - -static CYTHON_INLINE void *__Pyx_CyFunction_InitDefaults(PyObject *func, size_t size, int pyobjects) { - __pyx_CyFunctionObject *m = (__pyx_CyFunctionObject *) func; - + return -1; + } + return 0; +} + +static CYTHON_INLINE void *__Pyx_CyFunction_InitDefaults(PyObject *func, size_t size, int pyobjects) { + __pyx_CyFunctionObject *m = (__pyx_CyFunctionObject *) func; + m->defaults = PyObject_Malloc(size); if (unlikely(!m->defaults)) - return PyErr_NoMemory(); - memset(m->defaults, 0, size); - m->defaults_pyobjects = pyobjects; + return PyErr_NoMemory(); + memset(m->defaults, 0, size); + m->defaults_pyobjects = pyobjects; m->defaults_size = size; - return m->defaults; -} - -static CYTHON_INLINE void __Pyx_CyFunction_SetDefaultsTuple(PyObject *func, PyObject *tuple) { - __pyx_CyFunctionObject *m = (__pyx_CyFunctionObject *) func; - m->defaults_tuple = tuple; - Py_INCREF(tuple); -} - -static CYTHON_INLINE void __Pyx_CyFunction_SetDefaultsKwDict(PyObject *func, PyObject *dict) { - __pyx_CyFunctionObject *m = (__pyx_CyFunctionObject *) func; - m->defaults_kwdict = dict; - Py_INCREF(dict); -} - -static CYTHON_INLINE void __Pyx_CyFunction_SetAnnotationsDict(PyObject *func, PyObject *dict) { - __pyx_CyFunctionObject *m = (__pyx_CyFunctionObject *) func; - m->func_annotations = dict; - Py_INCREF(dict); -} - + return m->defaults; +} + +static CYTHON_INLINE void __Pyx_CyFunction_SetDefaultsTuple(PyObject *func, PyObject *tuple) { + __pyx_CyFunctionObject *m = (__pyx_CyFunctionObject *) func; + m->defaults_tuple = tuple; + Py_INCREF(tuple); +} + +static CYTHON_INLINE void __Pyx_CyFunction_SetDefaultsKwDict(PyObject *func, PyObject *dict) { + __pyx_CyFunctionObject *m = (__pyx_CyFunctionObject *) func; + m->defaults_kwdict = dict; + Py_INCREF(dict); +} + +static CYTHON_INLINE void __Pyx_CyFunction_SetAnnotationsDict(PyObject *func, PyObject *dict) { + __pyx_CyFunctionObject *m = (__pyx_CyFunctionObject *) func; + m->func_annotations = dict; + Py_INCREF(dict); +} + //////////////////// CythonFunction.proto //////////////////// @@ -806,15 +806,15 @@ static PyObject *__Pyx_CyFunction_New(PyMethodDef *ml, int flags, PyObject* qual } -//////////////////// CyFunctionClassCell.proto //////////////////// +//////////////////// CyFunctionClassCell.proto //////////////////// static int __Pyx_CyFunction_InitClassCell(PyObject *cyfunctions, PyObject *classobj);/*proto*/ - -//////////////////// CyFunctionClassCell //////////////////// + +//////////////////// CyFunctionClassCell //////////////////// //@requires: CythonFunctionShared - + static int __Pyx_CyFunction_InitClassCell(PyObject *cyfunctions, PyObject *classobj) { Py_ssize_t i, count = PyList_GET_SIZE(cyfunctions); - + for (i = 0; i < count; i++) { __pyx_CyFunctionObject *m = (__pyx_CyFunctionObject *) #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS @@ -825,44 +825,44 @@ static int __Pyx_CyFunction_InitClassCell(PyObject *cyfunctions, PyObject *class return -1; #endif Py_INCREF(classobj); - m->func_classobj = classobj; + m->func_classobj = classobj; #if !(CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS) Py_DECREF((PyObject*)m); #endif - } + } return 0; -} - - -//////////////////// FusedFunction.proto //////////////////// - -typedef struct { - __pyx_CyFunctionObject func; - PyObject *__signatures__; - PyObject *type; - PyObject *self; -} __pyx_FusedFunctionObject; - +} + + +//////////////////// FusedFunction.proto //////////////////// + +typedef struct { + __pyx_CyFunctionObject func; + PyObject *__signatures__; + PyObject *type; + PyObject *self; +} __pyx_FusedFunctionObject; + static PyObject *__pyx_FusedFunction_New(PyMethodDef *ml, int flags, PyObject *qualname, PyObject *closure, - PyObject *module, PyObject *globals, - PyObject *code); - -static int __pyx_FusedFunction_clear(__pyx_FusedFunctionObject *self); -static PyTypeObject *__pyx_FusedFunctionType = NULL; -static int __pyx_FusedFunction_init(void); - -#define __Pyx_FusedFunction_USED - -//////////////////// FusedFunction //////////////////// + PyObject *module, PyObject *globals, + PyObject *code); + +static int __pyx_FusedFunction_clear(__pyx_FusedFunctionObject *self); +static PyTypeObject *__pyx_FusedFunctionType = NULL; +static int __pyx_FusedFunction_init(void); + +#define __Pyx_FusedFunction_USED + +//////////////////// FusedFunction //////////////////// //@requires: CythonFunctionShared - -static PyObject * + +static PyObject * __pyx_FusedFunction_New(PyMethodDef *ml, int flags, PyObject *qualname, PyObject *closure, - PyObject *module, PyObject *globals, - PyObject *code) -{ + PyObject *module, PyObject *globals, + PyObject *code) +{ PyObject *op = __Pyx_CyFunction_Init( // __pyx_CyFunctionObject is correct below since that's the cast that we want. PyObject_GC_New(__pyx_CyFunctionObject, __pyx_FusedFunctionType), @@ -876,8 +876,8 @@ __pyx_FusedFunction_New(PyMethodDef *ml, int flags, PyObject_GC_Track(op); } return op; -} - +} + static void __pyx_FusedFunction_dealloc(__pyx_FusedFunctionObject *self) { @@ -886,56 +886,56 @@ __pyx_FusedFunction_dealloc(__pyx_FusedFunctionObject *self) Py_CLEAR(self->type); Py_CLEAR(self->__signatures__); __Pyx__CyFunction_dealloc((__pyx_CyFunctionObject *) self); -} - -static int -__pyx_FusedFunction_traverse(__pyx_FusedFunctionObject *self, - visitproc visit, - void *arg) -{ - Py_VISIT(self->self); - Py_VISIT(self->type); - Py_VISIT(self->__signatures__); - return __Pyx_CyFunction_traverse((__pyx_CyFunctionObject *) self, visit, arg); -} - -static int -__pyx_FusedFunction_clear(__pyx_FusedFunctionObject *self) -{ - Py_CLEAR(self->self); - Py_CLEAR(self->type); - Py_CLEAR(self->__signatures__); - return __Pyx_CyFunction_clear((__pyx_CyFunctionObject *) self); -} - - -static PyObject * -__pyx_FusedFunction_descr_get(PyObject *self, PyObject *obj, PyObject *type) -{ - __pyx_FusedFunctionObject *func, *meth; - - func = (__pyx_FusedFunctionObject *) self; - - if (func->self || func->func.flags & __Pyx_CYFUNCTION_STATICMETHOD) { - // Do not allow rebinding and don't do anything for static methods - Py_INCREF(self); - return self; - } - - if (obj == Py_None) - obj = NULL; - +} + +static int +__pyx_FusedFunction_traverse(__pyx_FusedFunctionObject *self, + visitproc visit, + void *arg) +{ + Py_VISIT(self->self); + Py_VISIT(self->type); + Py_VISIT(self->__signatures__); + return __Pyx_CyFunction_traverse((__pyx_CyFunctionObject *) self, visit, arg); +} + +static int +__pyx_FusedFunction_clear(__pyx_FusedFunctionObject *self) +{ + Py_CLEAR(self->self); + Py_CLEAR(self->type); + Py_CLEAR(self->__signatures__); + return __Pyx_CyFunction_clear((__pyx_CyFunctionObject *) self); +} + + +static PyObject * +__pyx_FusedFunction_descr_get(PyObject *self, PyObject *obj, PyObject *type) +{ + __pyx_FusedFunctionObject *func, *meth; + + func = (__pyx_FusedFunctionObject *) self; + + if (func->self || func->func.flags & __Pyx_CYFUNCTION_STATICMETHOD) { + // Do not allow rebinding and don't do anything for static methods + Py_INCREF(self); + return self; + } + + if (obj == Py_None) + obj = NULL; + meth = (__pyx_FusedFunctionObject *) __pyx_FusedFunction_New( - ((PyCFunctionObject *) func)->m_ml, - ((__pyx_CyFunctionObject *) func)->flags, - ((__pyx_CyFunctionObject *) func)->func_qualname, - ((__pyx_CyFunctionObject *) func)->func_closure, - ((PyCFunctionObject *) func)->m_module, - ((__pyx_CyFunctionObject *) func)->func_globals, - ((__pyx_CyFunctionObject *) func)->func_code); - if (!meth) - return NULL; - + ((PyCFunctionObject *) func)->m_ml, + ((__pyx_CyFunctionObject *) func)->flags, + ((__pyx_CyFunctionObject *) func)->func_qualname, + ((__pyx_CyFunctionObject *) func)->func_closure, + ((PyCFunctionObject *) func)->m_module, + ((__pyx_CyFunctionObject *) func)->func_globals, + ((__pyx_CyFunctionObject *) func)->func_code); + if (!meth) + return NULL; + // defaults needs copying fully rather than just copying the pointer // since otherwise it will be freed on destruction of meth despite // belonging to func rather than meth @@ -956,184 +956,184 @@ __pyx_FusedFunction_descr_get(PyObject *self, PyObject *obj, PyObject *type) Py_XINCREF(pydefaults[i]); } - Py_XINCREF(func->func.func_classobj); - meth->func.func_classobj = func->func.func_classobj; - - Py_XINCREF(func->__signatures__); - meth->__signatures__ = func->__signatures__; - - Py_XINCREF(type); - meth->type = type; - - Py_XINCREF(func->func.defaults_tuple); - meth->func.defaults_tuple = func->func.defaults_tuple; - - if (func->func.flags & __Pyx_CYFUNCTION_CLASSMETHOD) - obj = type; - - Py_XINCREF(obj); - meth->self = obj; - - return (PyObject *) meth; -} - -static PyObject * -_obj_to_str(PyObject *obj) -{ - if (PyType_Check(obj)) - return PyObject_GetAttr(obj, PYIDENT("__name__")); - else - return PyObject_Str(obj); -} - -static PyObject * -__pyx_FusedFunction_getitem(__pyx_FusedFunctionObject *self, PyObject *idx) -{ - PyObject *signature = NULL; - PyObject *unbound_result_func; - PyObject *result_func = NULL; - - if (self->__signatures__ == NULL) { - PyErr_SetString(PyExc_TypeError, "Function is not fused"); - return NULL; - } - - if (PyTuple_Check(idx)) { - PyObject *list = PyList_New(0); - Py_ssize_t n = PyTuple_GET_SIZE(idx); - PyObject *sep = NULL; - int i; - + Py_XINCREF(func->func.func_classobj); + meth->func.func_classobj = func->func.func_classobj; + + Py_XINCREF(func->__signatures__); + meth->__signatures__ = func->__signatures__; + + Py_XINCREF(type); + meth->type = type; + + Py_XINCREF(func->func.defaults_tuple); + meth->func.defaults_tuple = func->func.defaults_tuple; + + if (func->func.flags & __Pyx_CYFUNCTION_CLASSMETHOD) + obj = type; + + Py_XINCREF(obj); + meth->self = obj; + + return (PyObject *) meth; +} + +static PyObject * +_obj_to_str(PyObject *obj) +{ + if (PyType_Check(obj)) + return PyObject_GetAttr(obj, PYIDENT("__name__")); + else + return PyObject_Str(obj); +} + +static PyObject * +__pyx_FusedFunction_getitem(__pyx_FusedFunctionObject *self, PyObject *idx) +{ + PyObject *signature = NULL; + PyObject *unbound_result_func; + PyObject *result_func = NULL; + + if (self->__signatures__ == NULL) { + PyErr_SetString(PyExc_TypeError, "Function is not fused"); + return NULL; + } + + if (PyTuple_Check(idx)) { + PyObject *list = PyList_New(0); + Py_ssize_t n = PyTuple_GET_SIZE(idx); + PyObject *sep = NULL; + int i; + if (unlikely(!list)) - return NULL; - - for (i = 0; i < n; i++) { + return NULL; + + for (i = 0; i < n; i++) { int ret; PyObject *string; #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS - PyObject *item = PyTuple_GET_ITEM(idx, i); + PyObject *item = PyTuple_GET_ITEM(idx, i); #else PyObject *item = PySequence_ITEM(idx, i); if (unlikely(!item)) goto __pyx_err; #endif - string = _obj_to_str(item); + string = _obj_to_str(item); #if !(CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS) Py_DECREF(item); #endif if (unlikely(!string)) goto __pyx_err; ret = PyList_Append(list, string); - Py_DECREF(string); + Py_DECREF(string); if (unlikely(ret < 0)) goto __pyx_err; - } - - sep = PyUnicode_FromString("|"); + } + + sep = PyUnicode_FromString("|"); if (likely(sep)) - signature = PyUnicode_Join(sep, list); -__pyx_err: -; - Py_DECREF(list); - Py_XDECREF(sep); - } else { - signature = _obj_to_str(idx); - } - - if (!signature) - return NULL; - - unbound_result_func = PyObject_GetItem(self->__signatures__, signature); - - if (unbound_result_func) { - if (self->self || self->type) { - __pyx_FusedFunctionObject *unbound = (__pyx_FusedFunctionObject *) unbound_result_func; - - // TODO: move this to InitClassCell - Py_CLEAR(unbound->func.func_classobj); - Py_XINCREF(self->func.func_classobj); - unbound->func.func_classobj = self->func.func_classobj; - - result_func = __pyx_FusedFunction_descr_get(unbound_result_func, - self->self, self->type); - } else { - result_func = unbound_result_func; - Py_INCREF(result_func); - } - } - - Py_DECREF(signature); - Py_XDECREF(unbound_result_func); - - return result_func; -} - -static PyObject * -__pyx_FusedFunction_callfunction(PyObject *func, PyObject *args, PyObject *kw) -{ - __pyx_CyFunctionObject *cyfunc = (__pyx_CyFunctionObject *) func; - int static_specialized = (cyfunc->flags & __Pyx_CYFUNCTION_STATICMETHOD && - !((__pyx_FusedFunctionObject *) func)->__signatures__); - - if (cyfunc->flags & __Pyx_CYFUNCTION_CCLASS && !static_specialized) { + signature = PyUnicode_Join(sep, list); +__pyx_err: +; + Py_DECREF(list); + Py_XDECREF(sep); + } else { + signature = _obj_to_str(idx); + } + + if (!signature) + return NULL; + + unbound_result_func = PyObject_GetItem(self->__signatures__, signature); + + if (unbound_result_func) { + if (self->self || self->type) { + __pyx_FusedFunctionObject *unbound = (__pyx_FusedFunctionObject *) unbound_result_func; + + // TODO: move this to InitClassCell + Py_CLEAR(unbound->func.func_classobj); + Py_XINCREF(self->func.func_classobj); + unbound->func.func_classobj = self->func.func_classobj; + + result_func = __pyx_FusedFunction_descr_get(unbound_result_func, + self->self, self->type); + } else { + result_func = unbound_result_func; + Py_INCREF(result_func); + } + } + + Py_DECREF(signature); + Py_XDECREF(unbound_result_func); + + return result_func; +} + +static PyObject * +__pyx_FusedFunction_callfunction(PyObject *func, PyObject *args, PyObject *kw) +{ + __pyx_CyFunctionObject *cyfunc = (__pyx_CyFunctionObject *) func; + int static_specialized = (cyfunc->flags & __Pyx_CYFUNCTION_STATICMETHOD && + !((__pyx_FusedFunctionObject *) func)->__signatures__); + + if (cyfunc->flags & __Pyx_CYFUNCTION_CCLASS && !static_specialized) { return __Pyx_CyFunction_CallAsMethod(func, args, kw); - } else { + } else { return __Pyx_CyFunction_Call(func, args, kw); - } -} - -// Note: the 'self' from method binding is passed in in the args tuple, -// whereas PyCFunctionObject's m_self is passed in as the first -// argument to the C function. For extension methods we need -// to pass 'self' as 'm_self' and not as the first element of the -// args tuple. - -static PyObject * -__pyx_FusedFunction_call(PyObject *func, PyObject *args, PyObject *kw) -{ - __pyx_FusedFunctionObject *binding_func = (__pyx_FusedFunctionObject *) func; - Py_ssize_t argc = PyTuple_GET_SIZE(args); - PyObject *new_args = NULL; - __pyx_FusedFunctionObject *new_func = NULL; - PyObject *result = NULL; - PyObject *self = NULL; - int is_staticmethod = binding_func->func.flags & __Pyx_CYFUNCTION_STATICMETHOD; - int is_classmethod = binding_func->func.flags & __Pyx_CYFUNCTION_CLASSMETHOD; - - if (binding_func->self) { - // Bound method call, put 'self' in the args tuple - Py_ssize_t i; - new_args = PyTuple_New(argc + 1); - if (!new_args) - return NULL; - - self = binding_func->self; + } +} + +// Note: the 'self' from method binding is passed in in the args tuple, +// whereas PyCFunctionObject's m_self is passed in as the first +// argument to the C function. For extension methods we need +// to pass 'self' as 'm_self' and not as the first element of the +// args tuple. + +static PyObject * +__pyx_FusedFunction_call(PyObject *func, PyObject *args, PyObject *kw) +{ + __pyx_FusedFunctionObject *binding_func = (__pyx_FusedFunctionObject *) func; + Py_ssize_t argc = PyTuple_GET_SIZE(args); + PyObject *new_args = NULL; + __pyx_FusedFunctionObject *new_func = NULL; + PyObject *result = NULL; + PyObject *self = NULL; + int is_staticmethod = binding_func->func.flags & __Pyx_CYFUNCTION_STATICMETHOD; + int is_classmethod = binding_func->func.flags & __Pyx_CYFUNCTION_CLASSMETHOD; + + if (binding_func->self) { + // Bound method call, put 'self' in the args tuple + Py_ssize_t i; + new_args = PyTuple_New(argc + 1); + if (!new_args) + return NULL; + + self = binding_func->self; #if !(CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS) - Py_INCREF(self); + Py_INCREF(self); #endif Py_INCREF(self); - PyTuple_SET_ITEM(new_args, 0, self); - - for (i = 0; i < argc; i++) { + PyTuple_SET_ITEM(new_args, 0, self); + + for (i = 0; i < argc; i++) { #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS - PyObject *item = PyTuple_GET_ITEM(args, i); - Py_INCREF(item); + PyObject *item = PyTuple_GET_ITEM(args, i); + Py_INCREF(item); #else PyObject *item = PySequence_ITEM(args, i); if (unlikely(!item)) goto bad; #endif - PyTuple_SET_ITEM(new_args, i + 1, item); - } - - args = new_args; - } else if (binding_func->type) { - // Unbound method call - if (argc < 1) { - PyErr_SetString(PyExc_TypeError, "Need at least one argument, 0 given."); - return NULL; - } + PyTuple_SET_ITEM(new_args, i + 1, item); + } + + args = new_args; + } else if (binding_func->type) { + // Unbound method call + if (argc < 1) { + PyErr_SetString(PyExc_TypeError, "Need at least one argument, 0 given."); + return NULL; + } #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS - self = PyTuple_GET_ITEM(args, 0); + self = PyTuple_GET_ITEM(args, 0); #else self = PySequence_ITEM(args, 0); if (unlikely(!self)) return NULL; #endif - } - + } + if (self && !is_classmethod && !is_staticmethod) { int is_instance = PyObject_IsInstance(self, binding_func->type); if (unlikely(!is_instance)) { @@ -1145,13 +1145,13 @@ __pyx_FusedFunction_call(PyObject *func, PyObject *args, PyObject *kw) } else if (unlikely(is_instance == -1)) { goto bad; } - } + } #if !(CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS) Py_XDECREF(self); self = NULL; #endif - - if (binding_func->__signatures__) { + + if (binding_func->__signatures__) { PyObject *tup; if (is_staticmethod && binding_func->func.flags & __Pyx_CYFUNCTION_CCLASS) { // FIXME: this seems wrong, but we must currently pass the signatures dict as 'self' argument @@ -1168,101 +1168,101 @@ __pyx_FusedFunction_call(PyObject *func, PyObject *args, PyObject *kw) if (unlikely(!tup)) goto bad; new_func = (__pyx_FusedFunctionObject *) __pyx_FusedFunction_callfunction(func, tup, NULL); } - Py_DECREF(tup); - + Py_DECREF(tup); + if (unlikely(!new_func)) goto bad; - - Py_XINCREF(binding_func->func.func_classobj); - Py_CLEAR(new_func->func.func_classobj); - new_func->func.func_classobj = binding_func->func.func_classobj; - - func = (PyObject *) new_func; - } - - result = __pyx_FusedFunction_callfunction(func, args, kw); + + Py_XINCREF(binding_func->func.func_classobj); + Py_CLEAR(new_func->func.func_classobj); + new_func->func.func_classobj = binding_func->func.func_classobj; + + func = (PyObject *) new_func; + } + + result = __pyx_FusedFunction_callfunction(func, args, kw); bad: #if !(CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS) Py_XDECREF(self); #endif - Py_XDECREF(new_args); - Py_XDECREF((PyObject *) new_func); - return result; -} - -static PyMemberDef __pyx_FusedFunction_members[] = { - {(char *) "__signatures__", - T_OBJECT, - offsetof(__pyx_FusedFunctionObject, __signatures__), - READONLY, - 0}, - {0, 0, 0, 0, 0}, -}; - -static PyMappingMethods __pyx_FusedFunction_mapping_methods = { - 0, - (binaryfunc) __pyx_FusedFunction_getitem, - 0, -}; - -static PyTypeObject __pyx_FusedFunctionType_type = { - PyVarObject_HEAD_INIT(0, 0) - "fused_cython_function", /*tp_name*/ - sizeof(__pyx_FusedFunctionObject), /*tp_basicsize*/ - 0, /*tp_itemsize*/ - (destructor) __pyx_FusedFunction_dealloc, /*tp_dealloc*/ - 0, /*tp_print*/ - 0, /*tp_getattr*/ - 0, /*tp_setattr*/ -#if PY_MAJOR_VERSION < 3 - 0, /*tp_compare*/ -#else - 0, /*reserved*/ -#endif - 0, /*tp_repr*/ - 0, /*tp_as_number*/ - 0, /*tp_as_sequence*/ - &__pyx_FusedFunction_mapping_methods, /*tp_as_mapping*/ - 0, /*tp_hash*/ - (ternaryfunc) __pyx_FusedFunction_call, /*tp_call*/ - 0, /*tp_str*/ - 0, /*tp_getattro*/ - 0, /*tp_setattro*/ - 0, /*tp_as_buffer*/ - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC | Py_TPFLAGS_BASETYPE, /*tp_flags*/ - 0, /*tp_doc*/ - (traverseproc) __pyx_FusedFunction_traverse, /*tp_traverse*/ - (inquiry) __pyx_FusedFunction_clear,/*tp_clear*/ - 0, /*tp_richcompare*/ - 0, /*tp_weaklistoffset*/ - 0, /*tp_iter*/ - 0, /*tp_iternext*/ - 0, /*tp_methods*/ - __pyx_FusedFunction_members, /*tp_members*/ - // __doc__ is None for the fused function type, but we need it to be - // a descriptor for the instance's __doc__, so rebuild descriptors in our subclass - __pyx_CyFunction_getsets, /*tp_getset*/ + Py_XDECREF(new_args); + Py_XDECREF((PyObject *) new_func); + return result; +} + +static PyMemberDef __pyx_FusedFunction_members[] = { + {(char *) "__signatures__", + T_OBJECT, + offsetof(__pyx_FusedFunctionObject, __signatures__), + READONLY, + 0}, + {0, 0, 0, 0, 0}, +}; + +static PyMappingMethods __pyx_FusedFunction_mapping_methods = { + 0, + (binaryfunc) __pyx_FusedFunction_getitem, + 0, +}; + +static PyTypeObject __pyx_FusedFunctionType_type = { + PyVarObject_HEAD_INIT(0, 0) + "fused_cython_function", /*tp_name*/ + sizeof(__pyx_FusedFunctionObject), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + (destructor) __pyx_FusedFunction_dealloc, /*tp_dealloc*/ + 0, /*tp_print*/ + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ +#if PY_MAJOR_VERSION < 3 + 0, /*tp_compare*/ +#else + 0, /*reserved*/ +#endif + 0, /*tp_repr*/ + 0, /*tp_as_number*/ + 0, /*tp_as_sequence*/ + &__pyx_FusedFunction_mapping_methods, /*tp_as_mapping*/ + 0, /*tp_hash*/ + (ternaryfunc) __pyx_FusedFunction_call, /*tp_call*/ + 0, /*tp_str*/ + 0, /*tp_getattro*/ + 0, /*tp_setattro*/ + 0, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC | Py_TPFLAGS_BASETYPE, /*tp_flags*/ + 0, /*tp_doc*/ + (traverseproc) __pyx_FusedFunction_traverse, /*tp_traverse*/ + (inquiry) __pyx_FusedFunction_clear,/*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + 0, /*tp_methods*/ + __pyx_FusedFunction_members, /*tp_members*/ + // __doc__ is None for the fused function type, but we need it to be + // a descriptor for the instance's __doc__, so rebuild descriptors in our subclass + __pyx_CyFunction_getsets, /*tp_getset*/ // NOTE: tp_base may be changed later during module initialisation when importing CyFunction across modules. - &__pyx_CyFunctionType_type, /*tp_base*/ - 0, /*tp_dict*/ - __pyx_FusedFunction_descr_get, /*tp_descr_get*/ - 0, /*tp_descr_set*/ - 0, /*tp_dictoffset*/ - 0, /*tp_init*/ - 0, /*tp_alloc*/ - 0, /*tp_new*/ - 0, /*tp_free*/ - 0, /*tp_is_gc*/ - 0, /*tp_bases*/ - 0, /*tp_mro*/ - 0, /*tp_cache*/ - 0, /*tp_subclasses*/ - 0, /*tp_weaklist*/ - 0, /*tp_del*/ - 0, /*tp_version_tag*/ -#if PY_VERSION_HEX >= 0x030400a1 - 0, /*tp_finalize*/ -#endif + &__pyx_CyFunctionType_type, /*tp_base*/ + 0, /*tp_dict*/ + __pyx_FusedFunction_descr_get, /*tp_descr_get*/ + 0, /*tp_descr_set*/ + 0, /*tp_dictoffset*/ + 0, /*tp_init*/ + 0, /*tp_alloc*/ + 0, /*tp_new*/ + 0, /*tp_free*/ + 0, /*tp_is_gc*/ + 0, /*tp_bases*/ + 0, /*tp_mro*/ + 0, /*tp_cache*/ + 0, /*tp_subclasses*/ + 0, /*tp_weaklist*/ + 0, /*tp_del*/ + 0, /*tp_version_tag*/ +#if PY_VERSION_HEX >= 0x030400a1 + 0, /*tp_finalize*/ +#endif #if PY_VERSION_HEX >= 0x030800b1 && (!CYTHON_COMPILING_IN_PYPY || PYPY_VERSION_NUM >= 0x07030800) 0, /*tp_vectorcall*/ #endif @@ -1272,66 +1272,66 @@ static PyTypeObject __pyx_FusedFunctionType_type = { #if CYTHON_COMPILING_IN_PYPY && PY_VERSION_HEX >= 0x03090000 0, /*tp_pypy_flags*/ #endif -}; - -static int __pyx_FusedFunction_init(void) { +}; + +static int __pyx_FusedFunction_init(void) { // Set base from __Pyx_FetchCommonTypeFromSpec, in case it's different from the local static value. __pyx_FusedFunctionType_type.tp_base = __pyx_CyFunctionType; - __pyx_FusedFunctionType = __Pyx_FetchCommonType(&__pyx_FusedFunctionType_type); - if (__pyx_FusedFunctionType == NULL) { - return -1; - } - return 0; -} - -//////////////////// ClassMethod.proto //////////////////// - -#include "descrobject.h" + __pyx_FusedFunctionType = __Pyx_FetchCommonType(&__pyx_FusedFunctionType_type); + if (__pyx_FusedFunctionType == NULL) { + return -1; + } + return 0; +} + +//////////////////// ClassMethod.proto //////////////////// + +#include "descrobject.h" static CYTHON_UNUSED PyObject* __Pyx_Method_ClassMethod(PyObject *method); /*proto*/ - -//////////////////// ClassMethod //////////////////// - -static PyObject* __Pyx_Method_ClassMethod(PyObject *method) { + +//////////////////// ClassMethod //////////////////// + +static PyObject* __Pyx_Method_ClassMethod(PyObject *method) { #if CYTHON_COMPILING_IN_PYPY && PYPY_VERSION_NUM <= 0x05080000 - if (PyObject_TypeCheck(method, &PyWrapperDescr_Type)) { - // cdef classes - return PyClassMethod_New(method); - } -#else + if (PyObject_TypeCheck(method, &PyWrapperDescr_Type)) { + // cdef classes + return PyClassMethod_New(method); + } +#else #if CYTHON_COMPILING_IN_PYSTON || CYTHON_COMPILING_IN_PYPY // special C-API function only in Pyston and PyPy >= 5.9 if (PyMethodDescr_Check(method)) #else #if PY_MAJOR_VERSION == 2 // PyMethodDescr_Type is not exposed in the CPython C-API in Py2. - static PyTypeObject *methoddescr_type = NULL; - if (methoddescr_type == NULL) { - PyObject *meth = PyObject_GetAttrString((PyObject*)&PyList_Type, "append"); - if (!meth) return NULL; - methoddescr_type = Py_TYPE(meth); - Py_DECREF(meth); - } + static PyTypeObject *methoddescr_type = NULL; + if (methoddescr_type == NULL) { + PyObject *meth = PyObject_GetAttrString((PyObject*)&PyList_Type, "append"); + if (!meth) return NULL; + methoddescr_type = Py_TYPE(meth); + Py_DECREF(meth); + } #else PyTypeObject *methoddescr_type = &PyMethodDescr_Type; #endif if (__Pyx_TypeCheck(method, methoddescr_type)) #endif { - // cdef classes - PyMethodDescrObject *descr = (PyMethodDescrObject *)method; - #if PY_VERSION_HEX < 0x03020000 - PyTypeObject *d_type = descr->d_type; - #else - PyTypeObject *d_type = descr->d_common.d_type; - #endif - return PyDescr_NewClassMethod(d_type, descr->d_method); - } -#endif - else if (PyMethod_Check(method)) { - // python classes - return PyClassMethod_New(PyMethod_GET_FUNCTION(method)); - } + // cdef classes + PyMethodDescrObject *descr = (PyMethodDescrObject *)method; + #if PY_VERSION_HEX < 0x03020000 + PyTypeObject *d_type = descr->d_type; + #else + PyTypeObject *d_type = descr->d_common.d_type; + #endif + return PyDescr_NewClassMethod(d_type, descr->d_method); + } +#endif + else if (PyMethod_Check(method)) { + // python classes + return PyClassMethod_New(PyMethod_GET_FUNCTION(method)); + } else { - return PyClassMethod_New(method); - } -} + return PyClassMethod_New(method); + } +} diff --git a/contrib/tools/cython/Cython/Utility/Embed.c b/contrib/tools/cython/Cython/Utility/Embed.c index 60da8f2330..114847b946 100644 --- a/contrib/tools/cython/Cython/Utility/Embed.c +++ b/contrib/tools/cython/Cython/Utility/Embed.c @@ -1,45 +1,45 @@ -//////////////////// MainFunction //////////////////// - -#ifdef __FreeBSD__ -#include <floatingpoint.h> -#endif - +//////////////////// MainFunction //////////////////// + +#ifdef __FreeBSD__ +#include <floatingpoint.h> +#endif + #if PY_MAJOR_VERSION < 3 void Py_InitArgcArgv(int argc, char **argv); #else void Py_InitArgcArgv(int argc, wchar_t **argv); #endif -#if PY_MAJOR_VERSION < 3 -int %(main_method)s(int argc, char** argv) { -#elif defined(WIN32) || defined(MS_WINDOWS) -int %(wmain_method)s(int argc, wchar_t **argv) { -#else -static int __Pyx_main(int argc, wchar_t **argv) { -#endif - /* 754 requires that FP exceptions run in "no stop" mode by default, - * and until C vendors implement C99's ways to control FP exceptions, - * Python requires non-stop mode. Alas, some platforms enable FP - * exceptions by default. Here we disable them. - */ -#ifdef __FreeBSD__ - fp_except_t m; - - m = fpgetmask(); - fpsetmask(m & ~FP_X_OFL); -#endif +#if PY_MAJOR_VERSION < 3 +int %(main_method)s(int argc, char** argv) { +#elif defined(WIN32) || defined(MS_WINDOWS) +int %(wmain_method)s(int argc, wchar_t **argv) { +#else +static int __Pyx_main(int argc, wchar_t **argv) { +#endif + /* 754 requires that FP exceptions run in "no stop" mode by default, + * and until C vendors implement C99's ways to control FP exceptions, + * Python requires non-stop mode. Alas, some platforms enable FP + * exceptions by default. Here we disable them. + */ +#ifdef __FreeBSD__ + fp_except_t m; + + m = fpgetmask(); + fpsetmask(m & ~FP_X_OFL); +#endif if (argc && argv) { Py_InitArgcArgv(argc, argv); - Py_SetProgramName(argv[0]); + Py_SetProgramName(argv[0]); } - Py_Initialize(); - if (argc && argv) - PySys_SetArgv(argc, argv); - { /* init module '%(module_name)s' as '__main__' */ - PyObject* m = NULL; - %(module_is_main)s = 1; - #if PY_MAJOR_VERSION < 3 - init%(module_name)s(); + Py_Initialize(); + if (argc && argv) + PySys_SetArgv(argc, argv); + { /* init module '%(module_name)s' as '__main__' */ + PyObject* m = NULL; + %(module_is_main)s = 1; + #if PY_MAJOR_VERSION < 3 + init%(module_name)s(); #elif CYTHON_PEP489_MULTI_PHASE_INIT m = PyInit_%(module_name)s(); if (!PyModule_Check(m)) { @@ -54,174 +54,174 @@ static int __Pyx_main(int argc, wchar_t **argv) { if (m) PyModule_ExecDef(m, mdef); } } - #else - m = PyInit_%(module_name)s(); - #endif - if (PyErr_Occurred()) { - PyErr_Print(); /* This exits with the right code if SystemExit. */ - #if PY_MAJOR_VERSION < 3 - if (Py_FlushLine()) PyErr_Clear(); - #endif - return 1; - } - Py_XDECREF(m); - } + #else + m = PyInit_%(module_name)s(); + #endif + if (PyErr_Occurred()) { + PyErr_Print(); /* This exits with the right code if SystemExit. */ + #if PY_MAJOR_VERSION < 3 + if (Py_FlushLine()) PyErr_Clear(); + #endif + return 1; + } + Py_XDECREF(m); + } #if PY_VERSION_HEX < 0x03060000 - Py_Finalize(); + Py_Finalize(); #else if (Py_FinalizeEx() < 0) return 2; #endif - return 0; -} - - -#if PY_MAJOR_VERSION >= 3 && !defined(WIN32) && !defined(MS_WINDOWS) -#include <locale.h> - -static wchar_t* -__Pyx_char2wchar(char* arg) -{ - wchar_t *res; -#ifdef HAVE_BROKEN_MBSTOWCS - /* Some platforms have a broken implementation of - * mbstowcs which does not count the characters that - * would result from conversion. Use an upper bound. - */ - size_t argsize = strlen(arg); -#else - size_t argsize = mbstowcs(NULL, arg, 0); -#endif - size_t count; - unsigned char *in; - wchar_t *out; -#ifdef HAVE_MBRTOWC - mbstate_t mbs; -#endif - if (argsize != (size_t)-1) { - res = (wchar_t *)malloc((argsize+1)*sizeof(wchar_t)); - if (!res) - goto oom; - count = mbstowcs(res, arg, argsize+1); - if (count != (size_t)-1) { - wchar_t *tmp; - /* Only use the result if it contains no - surrogate characters. */ - for (tmp = res; *tmp != 0 && - (*tmp < 0xd800 || *tmp > 0xdfff); tmp++) - ; - if (*tmp == 0) - return res; - } - free(res); - } - /* Conversion failed. Fall back to escaping with surrogateescape. */ -#ifdef HAVE_MBRTOWC - /* Try conversion with mbrtwoc (C99), and escape non-decodable bytes. */ - - /* Overallocate; as multi-byte characters are in the argument, the - actual output could use less memory. */ - argsize = strlen(arg) + 1; + return 0; +} + + +#if PY_MAJOR_VERSION >= 3 && !defined(WIN32) && !defined(MS_WINDOWS) +#include <locale.h> + +static wchar_t* +__Pyx_char2wchar(char* arg) +{ + wchar_t *res; +#ifdef HAVE_BROKEN_MBSTOWCS + /* Some platforms have a broken implementation of + * mbstowcs which does not count the characters that + * would result from conversion. Use an upper bound. + */ + size_t argsize = strlen(arg); +#else + size_t argsize = mbstowcs(NULL, arg, 0); +#endif + size_t count; + unsigned char *in; + wchar_t *out; +#ifdef HAVE_MBRTOWC + mbstate_t mbs; +#endif + if (argsize != (size_t)-1) { + res = (wchar_t *)malloc((argsize+1)*sizeof(wchar_t)); + if (!res) + goto oom; + count = mbstowcs(res, arg, argsize+1); + if (count != (size_t)-1) { + wchar_t *tmp; + /* Only use the result if it contains no + surrogate characters. */ + for (tmp = res; *tmp != 0 && + (*tmp < 0xd800 || *tmp > 0xdfff); tmp++) + ; + if (*tmp == 0) + return res; + } + free(res); + } + /* Conversion failed. Fall back to escaping with surrogateescape. */ +#ifdef HAVE_MBRTOWC + /* Try conversion with mbrtwoc (C99), and escape non-decodable bytes. */ + + /* Overallocate; as multi-byte characters are in the argument, the + actual output could use less memory. */ + argsize = strlen(arg) + 1; res = (wchar_t *)malloc(argsize*sizeof(wchar_t)); - if (!res) goto oom; - in = (unsigned char*)arg; - out = res; - memset(&mbs, 0, sizeof mbs); - while (argsize) { - size_t converted = mbrtowc(out, (char*)in, argsize, &mbs); - if (converted == 0) - /* Reached end of string; null char stored. */ - break; - if (converted == (size_t)-2) { - /* Incomplete character. This should never happen, - since we provide everything that we have - - unless there is a bug in the C library, or I - misunderstood how mbrtowc works. */ - fprintf(stderr, "unexpected mbrtowc result -2\\n"); + if (!res) goto oom; + in = (unsigned char*)arg; + out = res; + memset(&mbs, 0, sizeof mbs); + while (argsize) { + size_t converted = mbrtowc(out, (char*)in, argsize, &mbs); + if (converted == 0) + /* Reached end of string; null char stored. */ + break; + if (converted == (size_t)-2) { + /* Incomplete character. This should never happen, + since we provide everything that we have - + unless there is a bug in the C library, or I + misunderstood how mbrtowc works. */ + fprintf(stderr, "unexpected mbrtowc result -2\\n"); free(res); - return NULL; - } - if (converted == (size_t)-1) { - /* Conversion error. Escape as UTF-8b, and start over - in the initial shift state. */ - *out++ = 0xdc00 + *in++; - argsize--; - memset(&mbs, 0, sizeof mbs); - continue; - } - if (*out >= 0xd800 && *out <= 0xdfff) { - /* Surrogate character. Escape the original - byte sequence with surrogateescape. */ - argsize -= converted; - while (converted--) - *out++ = 0xdc00 + *in++; - continue; - } - /* successfully converted some bytes */ - in += converted; - argsize -= converted; - out++; - } -#else - /* Cannot use C locale for escaping; manually escape as if charset - is ASCII (i.e. escape all bytes > 128. This will still roundtrip - correctly in the locale's charset, which must be an ASCII superset. */ + return NULL; + } + if (converted == (size_t)-1) { + /* Conversion error. Escape as UTF-8b, and start over + in the initial shift state. */ + *out++ = 0xdc00 + *in++; + argsize--; + memset(&mbs, 0, sizeof mbs); + continue; + } + if (*out >= 0xd800 && *out <= 0xdfff) { + /* Surrogate character. Escape the original + byte sequence with surrogateescape. */ + argsize -= converted; + while (converted--) + *out++ = 0xdc00 + *in++; + continue; + } + /* successfully converted some bytes */ + in += converted; + argsize -= converted; + out++; + } +#else + /* Cannot use C locale for escaping; manually escape as if charset + is ASCII (i.e. escape all bytes > 128. This will still roundtrip + correctly in the locale's charset, which must be an ASCII superset. */ res = (wchar_t *)malloc((strlen(arg)+1)*sizeof(wchar_t)); - if (!res) goto oom; - in = (unsigned char*)arg; - out = res; - while(*in) - if(*in < 128) - *out++ = *in++; - else - *out++ = 0xdc00 + *in++; - *out = 0; -#endif - return res; -oom: - fprintf(stderr, "out of memory\\n"); - return NULL; -} - -int -%(main_method)s(int argc, char **argv) -{ - if (!argc) { - return __Pyx_main(0, NULL); - } - else { + if (!res) goto oom; + in = (unsigned char*)arg; + out = res; + while(*in) + if(*in < 128) + *out++ = *in++; + else + *out++ = 0xdc00 + *in++; + *out = 0; +#endif + return res; +oom: + fprintf(stderr, "out of memory\\n"); + return NULL; +} + +int +%(main_method)s(int argc, char **argv) +{ + if (!argc) { + return __Pyx_main(0, NULL); + } + else { int i, res; - wchar_t **argv_copy = (wchar_t **)malloc(sizeof(wchar_t*)*argc); + wchar_t **argv_copy = (wchar_t **)malloc(sizeof(wchar_t*)*argc); /* We need a second copy, as Python might modify the first one. */ - wchar_t **argv_copy2 = (wchar_t **)malloc(sizeof(wchar_t*)*argc); + wchar_t **argv_copy2 = (wchar_t **)malloc(sizeof(wchar_t*)*argc); char *oldloc = strdup(setlocale(LC_ALL, NULL)); if (!argv_copy || !argv_copy2 || !oldloc) { - fprintf(stderr, "out of memory\\n"); + fprintf(stderr, "out of memory\\n"); free(argv_copy); free(argv_copy2); free(oldloc); - return 1; - } + return 1; + } res = 0; - setlocale(LC_ALL, ""); - for (i = 0; i < argc; i++) { - argv_copy2[i] = argv_copy[i] = __Pyx_char2wchar(argv[i]); + setlocale(LC_ALL, ""); + for (i = 0; i < argc; i++) { + argv_copy2[i] = argv_copy[i] = __Pyx_char2wchar(argv[i]); if (!argv_copy[i]) res = 1; /* failure, but continue to simplify cleanup */ - } - setlocale(LC_ALL, oldloc); - free(oldloc); + } + setlocale(LC_ALL, oldloc); + free(oldloc); if (res == 0) res = __Pyx_main(argc, argv_copy); - for (i = 0; i < argc; i++) { + for (i = 0; i < argc; i++) { #if PY_VERSION_HEX < 0x03050000 - free(argv_copy2[i]); + free(argv_copy2[i]); #else PyMem_RawFree(argv_copy2[i]); #endif - } - free(argv_copy); - free(argv_copy2); - return res; - } -} -#endif + } + free(argv_copy); + free(argv_copy2); + return res; + } +} +#endif diff --git a/contrib/tools/cython/Cython/Utility/Exceptions.c b/contrib/tools/cython/Cython/Utility/Exceptions.c index b0411f6956..e2961f1992 100644 --- a/contrib/tools/cython/Cython/Utility/Exceptions.c +++ b/contrib/tools/cython/Cython/Utility/Exceptions.c @@ -1,10 +1,10 @@ -// Exception raising code -// -// Exceptions are raised by __Pyx_Raise() and stored as plain -// type/value/tb in PyThreadState->curexc_*. When being caught by an -// 'except' statement, curexc_* is moved over to exc_* by -// __Pyx_GetException() - +// Exception raising code +// +// Exceptions are raised by __Pyx_Raise() and stored as plain +// type/value/tb in PyThreadState->curexc_*. When being caught by an +// 'except' statement, curexc_* is moved over to exc_* by +// __Pyx_GetException() + /////////////// PyThreadStateGet.proto /////////////// //@substitute: naming @@ -58,10 +58,10 @@ static CYTHON_INLINE int __Pyx_PyErr_ExceptionMatchesInState(PyThreadState* tsta } #endif -/////////////// PyErrFetchRestore.proto /////////////// +/////////////// PyErrFetchRestore.proto /////////////// //@substitute: naming //@requires: PyThreadStateGet - + #if CYTHON_FAST_THREAD_STATE #define __Pyx_PyErr_Clear() __Pyx_ErrRestore(NULL, NULL, NULL) #define __Pyx_ErrRestoreWithState(type, value, tb) __Pyx_ErrRestoreInState(PyThreadState_GET(), type, value, tb) @@ -70,7 +70,7 @@ static CYTHON_INLINE int __Pyx_PyErr_ExceptionMatchesInState(PyThreadState* tsta #define __Pyx_ErrFetch(type, value, tb) __Pyx_ErrFetchInState($local_tstate_cname, type, value, tb) static CYTHON_INLINE void __Pyx_ErrRestoreInState(PyThreadState *tstate, PyObject *type, PyObject *value, PyObject *tb); /*proto*/ static CYTHON_INLINE void __Pyx_ErrFetchInState(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb); /*proto*/ - + #if CYTHON_COMPILING_IN_CPYTHON #define __Pyx_PyErr_SetNone(exc) (Py_INCREF(exc), __Pyx_ErrRestore((exc), NULL, NULL)) #else @@ -88,133 +88,133 @@ static CYTHON_INLINE void __Pyx_ErrFetchInState(PyThreadState *tstate, PyObject #define __Pyx_ErrFetch(type, value, tb) PyErr_Fetch(type, value, tb) #endif -/////////////// PyErrFetchRestore /////////////// - +/////////////// PyErrFetchRestore /////////////// + #if CYTHON_FAST_THREAD_STATE static CYTHON_INLINE void __Pyx_ErrRestoreInState(PyThreadState *tstate, PyObject *type, PyObject *value, PyObject *tb) { - PyObject *tmp_type, *tmp_value, *tmp_tb; - tmp_type = tstate->curexc_type; - tmp_value = tstate->curexc_value; - tmp_tb = tstate->curexc_traceback; - tstate->curexc_type = type; - tstate->curexc_value = value; - tstate->curexc_traceback = tb; - Py_XDECREF(tmp_type); - Py_XDECREF(tmp_value); - Py_XDECREF(tmp_tb); -} - + PyObject *tmp_type, *tmp_value, *tmp_tb; + tmp_type = tstate->curexc_type; + tmp_value = tstate->curexc_value; + tmp_tb = tstate->curexc_traceback; + tstate->curexc_type = type; + tstate->curexc_value = value; + tstate->curexc_traceback = tb; + Py_XDECREF(tmp_type); + Py_XDECREF(tmp_value); + Py_XDECREF(tmp_tb); +} + static CYTHON_INLINE void __Pyx_ErrFetchInState(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb) { - *type = tstate->curexc_type; - *value = tstate->curexc_value; - *tb = tstate->curexc_traceback; - tstate->curexc_type = 0; - tstate->curexc_value = 0; - tstate->curexc_traceback = 0; + *type = tstate->curexc_type; + *value = tstate->curexc_value; + *tb = tstate->curexc_traceback; + tstate->curexc_type = 0; + tstate->curexc_value = 0; + tstate->curexc_traceback = 0; } -#endif - -/////////////// RaiseException.proto /////////////// - -static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject *cause); /*proto*/ - -/////////////// RaiseException /////////////// -//@requires: PyErrFetchRestore +#endif + +/////////////// RaiseException.proto /////////////// + +static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject *cause); /*proto*/ + +/////////////// RaiseException /////////////// +//@requires: PyErrFetchRestore //@requires: PyThreadStateGet - -// The following function is based on do_raise() from ceval.c. There -// are separate versions for Python2 and Python3 as exception handling -// has changed quite a lot between the two versions. - -#if PY_MAJOR_VERSION < 3 -static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, - CYTHON_UNUSED PyObject *cause) { + +// The following function is based on do_raise() from ceval.c. There +// are separate versions for Python2 and Python3 as exception handling +// has changed quite a lot between the two versions. + +#if PY_MAJOR_VERSION < 3 +static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, + CYTHON_UNUSED PyObject *cause) { __Pyx_PyThreadState_declare - /* 'cause' is only used in Py3 */ - Py_XINCREF(type); - if (!value || value == Py_None) - value = NULL; - else - Py_INCREF(value); - - if (!tb || tb == Py_None) - tb = NULL; - else { - Py_INCREF(tb); - if (!PyTraceBack_Check(tb)) { - PyErr_SetString(PyExc_TypeError, - "raise: arg 3 must be a traceback or None"); - goto raise_error; - } - } - - if (PyType_Check(type)) { - /* instantiate the type now (we don't know when and how it will be caught) */ -#if CYTHON_COMPILING_IN_PYPY - /* PyPy can't handle value == NULL */ - if (!value) { - Py_INCREF(Py_None); - value = Py_None; - } -#endif - PyErr_NormalizeException(&type, &value, &tb); - - } else { - /* Raising an instance. The value should be a dummy. */ - if (value) { - PyErr_SetString(PyExc_TypeError, - "instance exception may not have a separate value"); - goto raise_error; - } - /* Normalize to raise <class>, <instance> */ - value = type; - type = (PyObject*) Py_TYPE(type); - Py_INCREF(type); - if (!PyType_IsSubtype((PyTypeObject *)type, (PyTypeObject *)PyExc_BaseException)) { - PyErr_SetString(PyExc_TypeError, - "raise: exception class must be a subclass of BaseException"); - goto raise_error; - } - } - + /* 'cause' is only used in Py3 */ + Py_XINCREF(type); + if (!value || value == Py_None) + value = NULL; + else + Py_INCREF(value); + + if (!tb || tb == Py_None) + tb = NULL; + else { + Py_INCREF(tb); + if (!PyTraceBack_Check(tb)) { + PyErr_SetString(PyExc_TypeError, + "raise: arg 3 must be a traceback or None"); + goto raise_error; + } + } + + if (PyType_Check(type)) { + /* instantiate the type now (we don't know when and how it will be caught) */ +#if CYTHON_COMPILING_IN_PYPY + /* PyPy can't handle value == NULL */ + if (!value) { + Py_INCREF(Py_None); + value = Py_None; + } +#endif + PyErr_NormalizeException(&type, &value, &tb); + + } else { + /* Raising an instance. The value should be a dummy. */ + if (value) { + PyErr_SetString(PyExc_TypeError, + "instance exception may not have a separate value"); + goto raise_error; + } + /* Normalize to raise <class>, <instance> */ + value = type; + type = (PyObject*) Py_TYPE(type); + Py_INCREF(type); + if (!PyType_IsSubtype((PyTypeObject *)type, (PyTypeObject *)PyExc_BaseException)) { + PyErr_SetString(PyExc_TypeError, + "raise: exception class must be a subclass of BaseException"); + goto raise_error; + } + } + __Pyx_PyThreadState_assign - __Pyx_ErrRestore(type, value, tb); - return; -raise_error: - Py_XDECREF(value); - Py_XDECREF(type); - Py_XDECREF(tb); - return; -} - -#else /* Python 3+ */ - -static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject *cause) { - PyObject* owned_instance = NULL; - if (tb == Py_None) { - tb = 0; - } else if (tb && !PyTraceBack_Check(tb)) { - PyErr_SetString(PyExc_TypeError, - "raise: arg 3 must be a traceback or None"); - goto bad; - } - if (value == Py_None) - value = 0; - - if (PyExceptionInstance_Check(type)) { - if (value) { - PyErr_SetString(PyExc_TypeError, - "instance exception may not have a separate value"); - goto bad; - } - value = type; - type = (PyObject*) Py_TYPE(value); - } else if (PyExceptionClass_Check(type)) { - // make sure value is an exception instance of type - PyObject *instance_class = NULL; - if (value && PyExceptionInstance_Check(value)) { - instance_class = (PyObject*) Py_TYPE(value); - if (instance_class != type) { + __Pyx_ErrRestore(type, value, tb); + return; +raise_error: + Py_XDECREF(value); + Py_XDECREF(type); + Py_XDECREF(tb); + return; +} + +#else /* Python 3+ */ + +static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject *cause) { + PyObject* owned_instance = NULL; + if (tb == Py_None) { + tb = 0; + } else if (tb && !PyTraceBack_Check(tb)) { + PyErr_SetString(PyExc_TypeError, + "raise: arg 3 must be a traceback or None"); + goto bad; + } + if (value == Py_None) + value = 0; + + if (PyExceptionInstance_Check(type)) { + if (value) { + PyErr_SetString(PyExc_TypeError, + "instance exception may not have a separate value"); + goto bad; + } + value = type; + type = (PyObject*) Py_TYPE(value); + } else if (PyExceptionClass_Check(type)) { + // make sure value is an exception instance of type + PyObject *instance_class = NULL; + if (value && PyExceptionInstance_Check(value)) { + instance_class = (PyObject*) Py_TYPE(value); + if (instance_class != type) { int is_subclass = PyObject_IsSubclass(instance_class, type); if (!is_subclass) { instance_class = NULL; @@ -222,68 +222,68 @@ static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject // error on subclass test goto bad; } else { - // believe the instance - type = instance_class; - } - } - } - if (!instance_class) { - // instantiate the type now (we don't know when and how it will be caught) - // assuming that 'value' is an argument to the type's constructor - // not using PyErr_NormalizeException() to avoid ref-counting problems - PyObject *args; - if (!value) - args = PyTuple_New(0); - else if (PyTuple_Check(value)) { - Py_INCREF(value); - args = value; - } else - args = PyTuple_Pack(1, value); - if (!args) - goto bad; - owned_instance = PyObject_Call(type, args, NULL); - Py_DECREF(args); - if (!owned_instance) - goto bad; - value = owned_instance; - if (!PyExceptionInstance_Check(value)) { - PyErr_Format(PyExc_TypeError, - "calling %R should have returned an instance of " - "BaseException, not %R", - type, Py_TYPE(value)); - goto bad; - } - } - } else { - PyErr_SetString(PyExc_TypeError, - "raise: exception class must be a subclass of BaseException"); - goto bad; - } - - if (cause) { - PyObject *fixed_cause; - if (cause == Py_None) { - // raise ... from None - fixed_cause = NULL; - } else if (PyExceptionClass_Check(cause)) { - fixed_cause = PyObject_CallObject(cause, NULL); - if (fixed_cause == NULL) - goto bad; - } else if (PyExceptionInstance_Check(cause)) { - fixed_cause = cause; - Py_INCREF(fixed_cause); - } else { - PyErr_SetString(PyExc_TypeError, - "exception causes must derive from " - "BaseException"); - goto bad; - } - PyException_SetCause(value, fixed_cause); - } - - PyErr_SetObject(type, value); - - if (tb) { + // believe the instance + type = instance_class; + } + } + } + if (!instance_class) { + // instantiate the type now (we don't know when and how it will be caught) + // assuming that 'value' is an argument to the type's constructor + // not using PyErr_NormalizeException() to avoid ref-counting problems + PyObject *args; + if (!value) + args = PyTuple_New(0); + else if (PyTuple_Check(value)) { + Py_INCREF(value); + args = value; + } else + args = PyTuple_Pack(1, value); + if (!args) + goto bad; + owned_instance = PyObject_Call(type, args, NULL); + Py_DECREF(args); + if (!owned_instance) + goto bad; + value = owned_instance; + if (!PyExceptionInstance_Check(value)) { + PyErr_Format(PyExc_TypeError, + "calling %R should have returned an instance of " + "BaseException, not %R", + type, Py_TYPE(value)); + goto bad; + } + } + } else { + PyErr_SetString(PyExc_TypeError, + "raise: exception class must be a subclass of BaseException"); + goto bad; + } + + if (cause) { + PyObject *fixed_cause; + if (cause == Py_None) { + // raise ... from None + fixed_cause = NULL; + } else if (PyExceptionClass_Check(cause)) { + fixed_cause = PyObject_CallObject(cause, NULL); + if (fixed_cause == NULL) + goto bad; + } else if (PyExceptionInstance_Check(cause)) { + fixed_cause = cause; + Py_INCREF(fixed_cause); + } else { + PyErr_SetString(PyExc_TypeError, + "exception causes must derive from " + "BaseException"); + goto bad; + } + PyException_SetCause(value, fixed_cause); + } + + PyErr_SetObject(type, value); + + if (tb) { #if CYTHON_COMPILING_IN_PYPY PyObject *tmp_type, *tmp_value, *tmp_tb; PyErr_Fetch(&tmp_type, &tmp_value, &tmp_tb); @@ -292,21 +292,21 @@ static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject Py_XDECREF(tmp_tb); #else PyThreadState *tstate = __Pyx_PyThreadState_Current; - PyObject* tmp_tb = tstate->curexc_traceback; - if (tb != tmp_tb) { - Py_INCREF(tb); - tstate->curexc_traceback = tb; - Py_XDECREF(tmp_tb); - } -#endif - } - -bad: - Py_XDECREF(owned_instance); - return; -} + PyObject* tmp_tb = tstate->curexc_traceback; + if (tb != tmp_tb) { + Py_INCREF(tb); + tstate->curexc_traceback = tb; + Py_XDECREF(tmp_tb); + } #endif - + } + +bad: + Py_XDECREF(owned_instance); + return; +} +#endif + /////////////// GetTopmostException.proto /////////////// @@ -332,58 +332,58 @@ __Pyx_PyErr_GetTopmostException(PyThreadState *tstate) #endif -/////////////// GetException.proto /////////////// +/////////////// GetException.proto /////////////// //@substitute: naming //@requires: PyThreadStateGet - + #if CYTHON_FAST_THREAD_STATE #define __Pyx_GetException(type, value, tb) __Pyx__GetException($local_tstate_cname, type, value, tb) static int __Pyx__GetException(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb); /*proto*/ #else -static int __Pyx_GetException(PyObject **type, PyObject **value, PyObject **tb); /*proto*/ +static int __Pyx_GetException(PyObject **type, PyObject **value, PyObject **tb); /*proto*/ #endif - -/////////////// GetException /////////////// - + +/////////////// GetException /////////////// + #if CYTHON_FAST_THREAD_STATE static int __Pyx__GetException(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb) #else static int __Pyx_GetException(PyObject **type, PyObject **value, PyObject **tb) #endif { - PyObject *local_type, *local_value, *local_tb; + PyObject *local_type, *local_value, *local_tb; #if CYTHON_FAST_THREAD_STATE - PyObject *tmp_type, *tmp_value, *tmp_tb; - local_type = tstate->curexc_type; - local_value = tstate->curexc_value; - local_tb = tstate->curexc_traceback; - tstate->curexc_type = 0; - tstate->curexc_value = 0; - tstate->curexc_traceback = 0; -#else - PyErr_Fetch(&local_type, &local_value, &local_tb); -#endif - PyErr_NormalizeException(&local_type, &local_value, &local_tb); + PyObject *tmp_type, *tmp_value, *tmp_tb; + local_type = tstate->curexc_type; + local_value = tstate->curexc_value; + local_tb = tstate->curexc_traceback; + tstate->curexc_type = 0; + tstate->curexc_value = 0; + tstate->curexc_traceback = 0; +#else + PyErr_Fetch(&local_type, &local_value, &local_tb); +#endif + PyErr_NormalizeException(&local_type, &local_value, &local_tb); #if CYTHON_FAST_THREAD_STATE - if (unlikely(tstate->curexc_type)) -#else - if (unlikely(PyErr_Occurred())) -#endif - goto bad; - #if PY_MAJOR_VERSION >= 3 - if (local_tb) { - if (unlikely(PyException_SetTraceback(local_value, local_tb) < 0)) - goto bad; - } - #endif - // traceback may be NULL for freshly raised exceptions - Py_XINCREF(local_tb); - // exception state may be temporarily empty in parallel loops (race condition) - Py_XINCREF(local_type); - Py_XINCREF(local_value); - *type = local_type; - *value = local_value; - *tb = local_tb; + if (unlikely(tstate->curexc_type)) +#else + if (unlikely(PyErr_Occurred())) +#endif + goto bad; + #if PY_MAJOR_VERSION >= 3 + if (local_tb) { + if (unlikely(PyException_SetTraceback(local_value, local_tb) < 0)) + goto bad; + } + #endif + // traceback may be NULL for freshly raised exceptions + Py_XINCREF(local_tb); + // exception state may be temporarily empty in parallel loops (race condition) + Py_XINCREF(local_type); + Py_XINCREF(local_value); + *type = local_type; + *value = local_value; + *tb = local_tb; #if CYTHON_FAST_THREAD_STATE #if CYTHON_USE_EXC_INFO_STACK { @@ -396,95 +396,95 @@ static int __Pyx_GetException(PyObject **type, PyObject **value, PyObject **tb) exc_info->exc_traceback = local_tb; } #else - tmp_type = tstate->exc_type; - tmp_value = tstate->exc_value; - tmp_tb = tstate->exc_traceback; - tstate->exc_type = local_type; - tstate->exc_value = local_value; - tstate->exc_traceback = local_tb; + tmp_type = tstate->exc_type; + tmp_value = tstate->exc_value; + tmp_tb = tstate->exc_traceback; + tstate->exc_type = local_type; + tstate->exc_value = local_value; + tstate->exc_traceback = local_tb; #endif - // Make sure tstate is in a consistent state when we XDECREF - // these objects (DECREF may run arbitrary code). - Py_XDECREF(tmp_type); - Py_XDECREF(tmp_value); - Py_XDECREF(tmp_tb); -#else - PyErr_SetExcInfo(local_type, local_value, local_tb); -#endif - return 0; -bad: - *type = 0; - *value = 0; - *tb = 0; - Py_XDECREF(local_type); - Py_XDECREF(local_value); - Py_XDECREF(local_tb); - return -1; -} - -/////////////// ReRaiseException.proto /////////////// - -static CYTHON_INLINE void __Pyx_ReraiseException(void); /*proto*/ - + // Make sure tstate is in a consistent state when we XDECREF + // these objects (DECREF may run arbitrary code). + Py_XDECREF(tmp_type); + Py_XDECREF(tmp_value); + Py_XDECREF(tmp_tb); +#else + PyErr_SetExcInfo(local_type, local_value, local_tb); +#endif + return 0; +bad: + *type = 0; + *value = 0; + *tb = 0; + Py_XDECREF(local_type); + Py_XDECREF(local_value); + Py_XDECREF(local_tb); + return -1; +} + +/////////////// ReRaiseException.proto /////////////// + +static CYTHON_INLINE void __Pyx_ReraiseException(void); /*proto*/ + /////////////// ReRaiseException /////////////// //@requires: GetTopmostException - -static CYTHON_INLINE void __Pyx_ReraiseException(void) { - PyObject *type = NULL, *value = NULL, *tb = NULL; + +static CYTHON_INLINE void __Pyx_ReraiseException(void) { + PyObject *type = NULL, *value = NULL, *tb = NULL; #if CYTHON_FAST_THREAD_STATE - PyThreadState *tstate = PyThreadState_GET(); + PyThreadState *tstate = PyThreadState_GET(); #if CYTHON_USE_EXC_INFO_STACK _PyErr_StackItem *exc_info = __Pyx_PyErr_GetTopmostException(tstate); type = exc_info->exc_type; value = exc_info->exc_value; tb = exc_info->exc_traceback; #else - type = tstate->exc_type; - value = tstate->exc_value; - tb = tstate->exc_traceback; + type = tstate->exc_type; + value = tstate->exc_value; + tb = tstate->exc_traceback; #endif -#else - PyErr_GetExcInfo(&type, &value, &tb); -#endif - if (!type || type == Py_None) { +#else + PyErr_GetExcInfo(&type, &value, &tb); +#endif + if (!type || type == Py_None) { #if !CYTHON_FAST_THREAD_STATE - Py_XDECREF(type); - Py_XDECREF(value); - Py_XDECREF(tb); -#endif - // message copied from Py3 - PyErr_SetString(PyExc_RuntimeError, - "No active exception to reraise"); - } else { + Py_XDECREF(type); + Py_XDECREF(value); + Py_XDECREF(tb); +#endif + // message copied from Py3 + PyErr_SetString(PyExc_RuntimeError, + "No active exception to reraise"); + } else { #if CYTHON_FAST_THREAD_STATE - Py_INCREF(type); - Py_XINCREF(value); - Py_XINCREF(tb); - -#endif - PyErr_Restore(type, value, tb); - } -} - -/////////////// SaveResetException.proto /////////////// + Py_INCREF(type); + Py_XINCREF(value); + Py_XINCREF(tb); + +#endif + PyErr_Restore(type, value, tb); + } +} + +/////////////// SaveResetException.proto /////////////// //@substitute: naming //@requires: PyThreadStateGet - + #if CYTHON_FAST_THREAD_STATE #define __Pyx_ExceptionSave(type, value, tb) __Pyx__ExceptionSave($local_tstate_cname, type, value, tb) static CYTHON_INLINE void __Pyx__ExceptionSave(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb); /*proto*/ #define __Pyx_ExceptionReset(type, value, tb) __Pyx__ExceptionReset($local_tstate_cname, type, value, tb) static CYTHON_INLINE void __Pyx__ExceptionReset(PyThreadState *tstate, PyObject *type, PyObject *value, PyObject *tb); /*proto*/ - + #else #define __Pyx_ExceptionSave(type, value, tb) PyErr_GetExcInfo(type, value, tb) #define __Pyx_ExceptionReset(type, value, tb) PyErr_SetExcInfo(type, value, tb) #endif -/////////////// SaveResetException /////////////// +/////////////// SaveResetException /////////////// //@requires: GetTopmostException - + #if CYTHON_FAST_THREAD_STATE static CYTHON_INLINE void __Pyx__ExceptionSave(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb) { #if CYTHON_USE_EXC_INFO_STACK @@ -493,17 +493,17 @@ static CYTHON_INLINE void __Pyx__ExceptionSave(PyThreadState *tstate, PyObject * *value = exc_info->exc_value; *tb = exc_info->exc_traceback; #else - *type = tstate->exc_type; - *value = tstate->exc_value; - *tb = tstate->exc_traceback; + *type = tstate->exc_type; + *value = tstate->exc_value; + *tb = tstate->exc_traceback; #endif - Py_XINCREF(*type); - Py_XINCREF(*value); - Py_XINCREF(*tb); -} - + Py_XINCREF(*type); + Py_XINCREF(*value); + Py_XINCREF(*tb); +} + static CYTHON_INLINE void __Pyx__ExceptionReset(PyThreadState *tstate, PyObject *type, PyObject *value, PyObject *tb) { - PyObject *tmp_type, *tmp_value, *tmp_tb; + PyObject *tmp_type, *tmp_value, *tmp_tb; #if CYTHON_USE_EXC_INFO_STACK _PyErr_StackItem *exc_info = tstate->exc_info; @@ -514,35 +514,35 @@ static CYTHON_INLINE void __Pyx__ExceptionReset(PyThreadState *tstate, PyObject exc_info->exc_value = value; exc_info->exc_traceback = tb; #else - tmp_type = tstate->exc_type; - tmp_value = tstate->exc_value; - tmp_tb = tstate->exc_traceback; - tstate->exc_type = type; - tstate->exc_value = value; - tstate->exc_traceback = tb; + tmp_type = tstate->exc_type; + tmp_value = tstate->exc_value; + tmp_tb = tstate->exc_traceback; + tstate->exc_type = type; + tstate->exc_value = value; + tstate->exc_traceback = tb; #endif - Py_XDECREF(tmp_type); - Py_XDECREF(tmp_value); - Py_XDECREF(tmp_tb); + Py_XDECREF(tmp_type); + Py_XDECREF(tmp_value); + Py_XDECREF(tmp_tb); } -#endif - -/////////////// SwapException.proto /////////////// +#endif + +/////////////// SwapException.proto /////////////// //@substitute: naming //@requires: PyThreadStateGet - + #if CYTHON_FAST_THREAD_STATE #define __Pyx_ExceptionSwap(type, value, tb) __Pyx__ExceptionSwap($local_tstate_cname, type, value, tb) static CYTHON_INLINE void __Pyx__ExceptionSwap(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb); /*proto*/ #else -static CYTHON_INLINE void __Pyx_ExceptionSwap(PyObject **type, PyObject **value, PyObject **tb); /*proto*/ +static CYTHON_INLINE void __Pyx_ExceptionSwap(PyObject **type, PyObject **value, PyObject **tb); /*proto*/ #endif - -/////////////// SwapException /////////////// - + +/////////////// SwapException /////////////// + #if CYTHON_FAST_THREAD_STATE static CYTHON_INLINE void __Pyx__ExceptionSwap(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb) { - PyObject *tmp_type, *tmp_value, *tmp_tb; + PyObject *tmp_type, *tmp_value, *tmp_tb; #if CYTHON_USE_EXC_INFO_STACK _PyErr_StackItem *exc_info = tstate->exc_info; @@ -554,13 +554,13 @@ static CYTHON_INLINE void __Pyx__ExceptionSwap(PyThreadState *tstate, PyObject * exc_info->exc_value = *value; exc_info->exc_traceback = *tb; #else - tmp_type = tstate->exc_type; - tmp_value = tstate->exc_value; - tmp_tb = tstate->exc_traceback; - - tstate->exc_type = *type; - tstate->exc_value = *value; - tstate->exc_traceback = *tb; + tmp_type = tstate->exc_type; + tmp_value = tstate->exc_value; + tmp_tb = tstate->exc_traceback; + + tstate->exc_type = *type; + tstate->exc_value = *value; + tstate->exc_traceback = *tb; #endif *type = tmp_type; @@ -568,33 +568,33 @@ static CYTHON_INLINE void __Pyx__ExceptionSwap(PyThreadState *tstate, PyObject * *tb = tmp_tb; } -#else +#else static CYTHON_INLINE void __Pyx_ExceptionSwap(PyObject **type, PyObject **value, PyObject **tb) { PyObject *tmp_type, *tmp_value, *tmp_tb; - PyErr_GetExcInfo(&tmp_type, &tmp_value, &tmp_tb); - PyErr_SetExcInfo(*type, *value, *tb); - *type = tmp_type; - *value = tmp_value; - *tb = tmp_tb; -} + PyErr_GetExcInfo(&tmp_type, &tmp_value, &tmp_tb); + PyErr_SetExcInfo(*type, *value, *tb); + *type = tmp_type; + *value = tmp_value; + *tb = tmp_tb; +} #endif - -/////////////// WriteUnraisableException.proto /////////////// - -static void __Pyx_WriteUnraisable(const char *name, int clineno, - int lineno, const char *filename, + +/////////////// WriteUnraisableException.proto /////////////// + +static void __Pyx_WriteUnraisable(const char *name, int clineno, + int lineno, const char *filename, int full_traceback, int nogil); /*proto*/ - -/////////////// WriteUnraisableException /////////////// -//@requires: PyErrFetchRestore + +/////////////// WriteUnraisableException /////////////// +//@requires: PyErrFetchRestore //@requires: PyThreadStateGet - -static void __Pyx_WriteUnraisable(const char *name, CYTHON_UNUSED int clineno, - CYTHON_UNUSED int lineno, CYTHON_UNUSED const char *filename, + +static void __Pyx_WriteUnraisable(const char *name, CYTHON_UNUSED int clineno, + CYTHON_UNUSED int lineno, CYTHON_UNUSED const char *filename, int full_traceback, CYTHON_UNUSED int nogil) { - PyObject *old_exc, *old_val, *old_tb; - PyObject *ctx; + PyObject *old_exc, *old_val, *old_tb; + PyObject *ctx; __Pyx_PyThreadState_declare #ifdef WITH_THREAD PyGILState_STATE state; @@ -606,32 +606,32 @@ static void __Pyx_WriteUnraisable(const char *name, CYTHON_UNUSED int clineno, #endif #endif __Pyx_PyThreadState_assign - __Pyx_ErrFetch(&old_exc, &old_val, &old_tb); - if (full_traceback) { - Py_XINCREF(old_exc); - Py_XINCREF(old_val); - Py_XINCREF(old_tb); - __Pyx_ErrRestore(old_exc, old_val, old_tb); - PyErr_PrintEx(1); - } - #if PY_MAJOR_VERSION < 3 - ctx = PyString_FromString(name); - #else - ctx = PyUnicode_FromString(name); - #endif - __Pyx_ErrRestore(old_exc, old_val, old_tb); - if (!ctx) { - PyErr_WriteUnraisable(Py_None); - } else { - PyErr_WriteUnraisable(ctx); - Py_DECREF(ctx); - } + __Pyx_ErrFetch(&old_exc, &old_val, &old_tb); + if (full_traceback) { + Py_XINCREF(old_exc); + Py_XINCREF(old_val); + Py_XINCREF(old_tb); + __Pyx_ErrRestore(old_exc, old_val, old_tb); + PyErr_PrintEx(1); + } + #if PY_MAJOR_VERSION < 3 + ctx = PyString_FromString(name); + #else + ctx = PyUnicode_FromString(name); + #endif + __Pyx_ErrRestore(old_exc, old_val, old_tb); + if (!ctx) { + PyErr_WriteUnraisable(Py_None); + } else { + PyErr_WriteUnraisable(ctx); + Py_DECREF(ctx); + } #ifdef WITH_THREAD if (nogil) PyGILState_Release(state); #endif -} - +} + /////////////// CLineInTraceback.proto /////////////// #ifdef CYTHON_CLINE_IN_TRACEBACK /* 0 or 1 to disable/enable C line display in tracebacks at C compile time */ @@ -692,109 +692,109 @@ static int __Pyx_CLineForTraceback(CYTHON_NCP_UNUSED PyThreadState *tstate, int } #endif -/////////////// AddTraceback.proto /////////////// - -static void __Pyx_AddTraceback(const char *funcname, int c_line, - int py_line, const char *filename); /*proto*/ - -/////////////// AddTraceback /////////////// -//@requires: ModuleSetupCode.c::CodeObjectCache +/////////////// AddTraceback.proto /////////////// + +static void __Pyx_AddTraceback(const char *funcname, int c_line, + int py_line, const char *filename); /*proto*/ + +/////////////// AddTraceback /////////////// +//@requires: ModuleSetupCode.c::CodeObjectCache //@requires: CLineInTraceback -//@substitute: naming - -#include "compile.h" -#include "frameobject.h" -#include "traceback.h" - -static PyCodeObject* __Pyx_CreateCodeObjectForTraceback( - const char *funcname, int c_line, - int py_line, const char *filename) { +//@substitute: naming + +#include "compile.h" +#include "frameobject.h" +#include "traceback.h" + +static PyCodeObject* __Pyx_CreateCodeObjectForTraceback( + const char *funcname, int c_line, + int py_line, const char *filename) { PyCodeObject *py_code = NULL; PyObject *py_funcname = NULL; #if PY_MAJOR_VERSION < 3 PyObject *py_srcfile = NULL; - - py_srcfile = PyString_FromString(filename); + + py_srcfile = PyString_FromString(filename); if (!py_srcfile) goto bad; - #endif + #endif - if (c_line) { - #if PY_MAJOR_VERSION < 3 - py_funcname = PyString_FromFormat( "%s (%s:%d)", funcname, $cfilenm_cname, c_line); + if (c_line) { + #if PY_MAJOR_VERSION < 3 + py_funcname = PyString_FromFormat( "%s (%s:%d)", funcname, $cfilenm_cname, c_line); if (!py_funcname) goto bad; - #else - py_funcname = PyUnicode_FromFormat( "%s (%s:%d)", funcname, $cfilenm_cname, c_line); + #else + py_funcname = PyUnicode_FromFormat( "%s (%s:%d)", funcname, $cfilenm_cname, c_line); if (!py_funcname) goto bad; funcname = PyUnicode_AsUTF8(py_funcname); if (!funcname) goto bad; - #endif - } - else { - #if PY_MAJOR_VERSION < 3 - py_funcname = PyString_FromString(funcname); + #endif + } + else { + #if PY_MAJOR_VERSION < 3 + py_funcname = PyString_FromString(funcname); if (!py_funcname) goto bad; - #endif - } + #endif + } #if PY_MAJOR_VERSION < 3 - py_code = __Pyx_PyCode_New( - 0, /*int argcount,*/ - 0, /*int kwonlyargcount,*/ - 0, /*int nlocals,*/ - 0, /*int stacksize,*/ - 0, /*int flags,*/ - $empty_bytes, /*PyObject *code,*/ - $empty_tuple, /*PyObject *consts,*/ - $empty_tuple, /*PyObject *names,*/ - $empty_tuple, /*PyObject *varnames,*/ - $empty_tuple, /*PyObject *freevars,*/ - $empty_tuple, /*PyObject *cellvars,*/ - py_srcfile, /*PyObject *filename,*/ - py_funcname, /*PyObject *name,*/ - py_line, /*int firstlineno,*/ - $empty_bytes /*PyObject *lnotab*/ - ); - Py_DECREF(py_srcfile); + py_code = __Pyx_PyCode_New( + 0, /*int argcount,*/ + 0, /*int kwonlyargcount,*/ + 0, /*int nlocals,*/ + 0, /*int stacksize,*/ + 0, /*int flags,*/ + $empty_bytes, /*PyObject *code,*/ + $empty_tuple, /*PyObject *consts,*/ + $empty_tuple, /*PyObject *names,*/ + $empty_tuple, /*PyObject *varnames,*/ + $empty_tuple, /*PyObject *freevars,*/ + $empty_tuple, /*PyObject *cellvars,*/ + py_srcfile, /*PyObject *filename,*/ + py_funcname, /*PyObject *name,*/ + py_line, /*int firstlineno,*/ + $empty_bytes /*PyObject *lnotab*/ + ); + Py_DECREF(py_srcfile); #else py_code = PyCode_NewEmpty(filename, funcname, py_line); #endif Py_XDECREF(py_funcname); // XDECREF since it's only set on Py3 if cline - return py_code; -bad: + return py_code; +bad: Py_XDECREF(py_funcname); #if PY_MAJOR_VERSION < 3 - Py_XDECREF(py_srcfile); + Py_XDECREF(py_srcfile); #endif - return NULL; -} - -static void __Pyx_AddTraceback(const char *funcname, int c_line, - int py_line, const char *filename) { - PyCodeObject *py_code = 0; - PyFrameObject *py_frame = 0; + return NULL; +} + +static void __Pyx_AddTraceback(const char *funcname, int c_line, + int py_line, const char *filename) { + PyCodeObject *py_code = 0; + PyFrameObject *py_frame = 0; PyThreadState *tstate = __Pyx_PyThreadState_Current; - + if (c_line) { c_line = __Pyx_CLineForTraceback(tstate, c_line); } // Negate to avoid collisions between py and c lines. py_code = $global_code_object_cache_find(c_line ? -c_line : py_line); - if (!py_code) { - py_code = __Pyx_CreateCodeObjectForTraceback( - funcname, c_line, py_line, filename); - if (!py_code) goto bad; + if (!py_code) { + py_code = __Pyx_CreateCodeObjectForTraceback( + funcname, c_line, py_line, filename); + if (!py_code) goto bad; $global_code_object_cache_insert(c_line ? -c_line : py_line, py_code); - } - py_frame = PyFrame_New( + } + py_frame = PyFrame_New( tstate, /*PyThreadState *tstate,*/ py_code, /*PyCodeObject *code,*/ $moddict_cname, /*PyObject *globals,*/ 0 /*PyObject *locals*/ - ); - if (!py_frame) goto bad; + ); + if (!py_frame) goto bad; __Pyx_PyFrame_SetLineNumber(py_frame, py_line); - PyTraceBack_Here(py_frame); -bad: - Py_XDECREF(py_code); - Py_XDECREF(py_frame); -} + PyTraceBack_Here(py_frame); +bad: + Py_XDECREF(py_code); + Py_XDECREF(py_frame); +} diff --git a/contrib/tools/cython/Cython/Utility/ExtensionTypes.c b/contrib/tools/cython/Cython/Utility/ExtensionTypes.c index 0d8c41dee1..7687d1150d 100644 --- a/contrib/tools/cython/Cython/Utility/ExtensionTypes.c +++ b/contrib/tools/cython/Cython/Utility/ExtensionTypes.c @@ -1,5 +1,5 @@ /////////////// PyType_Ready.proto /////////////// - + static int __Pyx_PyType_Ready(PyTypeObject *t); /////////////// PyType_Ready /////////////// @@ -119,58 +119,58 @@ static int __Pyx_PyType_Ready(PyTypeObject *t) { return r; } -/////////////// CallNextTpDealloc.proto /////////////// - -static void __Pyx_call_next_tp_dealloc(PyObject* obj, destructor current_tp_dealloc); - -/////////////// CallNextTpDealloc /////////////// - -static void __Pyx_call_next_tp_dealloc(PyObject* obj, destructor current_tp_dealloc) { - PyTypeObject* type = Py_TYPE(obj); - /* try to find the first parent type that has a different tp_dealloc() function */ - while (type && type->tp_dealloc != current_tp_dealloc) - type = type->tp_base; - while (type && type->tp_dealloc == current_tp_dealloc) - type = type->tp_base; - if (type) - type->tp_dealloc(obj); -} - -/////////////// CallNextTpTraverse.proto /////////////// - -static int __Pyx_call_next_tp_traverse(PyObject* obj, visitproc v, void *a, traverseproc current_tp_traverse); - -/////////////// CallNextTpTraverse /////////////// - -static int __Pyx_call_next_tp_traverse(PyObject* obj, visitproc v, void *a, traverseproc current_tp_traverse) { - PyTypeObject* type = Py_TYPE(obj); - /* try to find the first parent type that has a different tp_traverse() function */ - while (type && type->tp_traverse != current_tp_traverse) - type = type->tp_base; - while (type && type->tp_traverse == current_tp_traverse) - type = type->tp_base; - if (type && type->tp_traverse) - return type->tp_traverse(obj, v, a); - // FIXME: really ignore? - return 0; -} - -/////////////// CallNextTpClear.proto /////////////// - -static void __Pyx_call_next_tp_clear(PyObject* obj, inquiry current_tp_dealloc); - -/////////////// CallNextTpClear /////////////// - -static void __Pyx_call_next_tp_clear(PyObject* obj, inquiry current_tp_clear) { - PyTypeObject* type = Py_TYPE(obj); - /* try to find the first parent type that has a different tp_clear() function */ - while (type && type->tp_clear != current_tp_clear) - type = type->tp_base; - while (type && type->tp_clear == current_tp_clear) - type = type->tp_base; - if (type && type->tp_clear) - type->tp_clear(obj); -} +/////////////// CallNextTpDealloc.proto /////////////// + +static void __Pyx_call_next_tp_dealloc(PyObject* obj, destructor current_tp_dealloc); + +/////////////// CallNextTpDealloc /////////////// + +static void __Pyx_call_next_tp_dealloc(PyObject* obj, destructor current_tp_dealloc) { + PyTypeObject* type = Py_TYPE(obj); + /* try to find the first parent type that has a different tp_dealloc() function */ + while (type && type->tp_dealloc != current_tp_dealloc) + type = type->tp_base; + while (type && type->tp_dealloc == current_tp_dealloc) + type = type->tp_base; + if (type) + type->tp_dealloc(obj); +} + +/////////////// CallNextTpTraverse.proto /////////////// + +static int __Pyx_call_next_tp_traverse(PyObject* obj, visitproc v, void *a, traverseproc current_tp_traverse); + +/////////////// CallNextTpTraverse /////////////// + +static int __Pyx_call_next_tp_traverse(PyObject* obj, visitproc v, void *a, traverseproc current_tp_traverse) { + PyTypeObject* type = Py_TYPE(obj); + /* try to find the first parent type that has a different tp_traverse() function */ + while (type && type->tp_traverse != current_tp_traverse) + type = type->tp_base; + while (type && type->tp_traverse == current_tp_traverse) + type = type->tp_base; + if (type && type->tp_traverse) + return type->tp_traverse(obj, v, a); + // FIXME: really ignore? + return 0; +} + +/////////////// CallNextTpClear.proto /////////////// + +static void __Pyx_call_next_tp_clear(PyObject* obj, inquiry current_tp_dealloc); + +/////////////// CallNextTpClear /////////////// + +static void __Pyx_call_next_tp_clear(PyObject* obj, inquiry current_tp_clear) { + PyTypeObject* type = Py_TYPE(obj); + /* try to find the first parent type that has a different tp_clear() function */ + while (type && type->tp_clear != current_tp_clear) + type = type->tp_base; + while (type && type->tp_clear == current_tp_clear) + type = type->tp_base; + if (type && type->tp_clear) + type->tp_clear(obj); +} /////////////// SetupReduce.proto /////////////// diff --git a/contrib/tools/cython/Cython/Utility/FunctionArguments.c b/contrib/tools/cython/Cython/Utility/FunctionArguments.c index 8333d93666..ff75ad4426 100644 --- a/contrib/tools/cython/Cython/Utility/FunctionArguments.c +++ b/contrib/tools/cython/Cython/Utility/FunctionArguments.c @@ -1,109 +1,109 @@ -//////////////////// ArgTypeTest.proto //////////////////// - - +//////////////////// ArgTypeTest.proto //////////////////// + + #define __Pyx_ArgTypeTest(obj, type, none_allowed, name, exact) \ ((likely((Py_TYPE(obj) == type) | (none_allowed && (obj == Py_None)))) ? 1 : \ __Pyx__ArgTypeTest(obj, type, name, exact)) static int __Pyx__ArgTypeTest(PyObject *obj, PyTypeObject *type, const char *name, int exact); /*proto*/ -//////////////////// ArgTypeTest //////////////////// - +//////////////////// ArgTypeTest //////////////////// + static int __Pyx__ArgTypeTest(PyObject *obj, PyTypeObject *type, const char *name, int exact) -{ - if (unlikely(!type)) { - PyErr_SetString(PyExc_SystemError, "Missing type object"); - return 0; - } - else if (exact) { - #if PY_MAJOR_VERSION == 2 +{ + if (unlikely(!type)) { + PyErr_SetString(PyExc_SystemError, "Missing type object"); + return 0; + } + else if (exact) { + #if PY_MAJOR_VERSION == 2 if ((type == &PyBaseString_Type) && likely(__Pyx_PyBaseString_CheckExact(obj))) return 1; - #endif - } - else { + #endif + } + else { if (likely(__Pyx_TypeCheck(obj, type))) return 1; - } + } PyErr_Format(PyExc_TypeError, "Argument '%.200s' has incorrect type (expected %.200s, got %.200s)", name, type->tp_name, Py_TYPE(obj)->tp_name); - return 0; -} - -//////////////////// RaiseArgTupleInvalid.proto //////////////////// - -static void __Pyx_RaiseArgtupleInvalid(const char* func_name, int exact, - Py_ssize_t num_min, Py_ssize_t num_max, Py_ssize_t num_found); /*proto*/ - -//////////////////// RaiseArgTupleInvalid //////////////////// - -// __Pyx_RaiseArgtupleInvalid raises the correct exception when too -// many or too few positional arguments were found. This handles -// Py_ssize_t formatting correctly. - -static void __Pyx_RaiseArgtupleInvalid( - const char* func_name, - int exact, - Py_ssize_t num_min, - Py_ssize_t num_max, - Py_ssize_t num_found) -{ - Py_ssize_t num_expected; - const char *more_or_less; - - if (num_found < num_min) { - num_expected = num_min; - more_or_less = "at least"; - } else { - num_expected = num_max; - more_or_less = "at most"; - } - if (exact) { - more_or_less = "exactly"; - } - PyErr_Format(PyExc_TypeError, - "%.200s() takes %.8s %" CYTHON_FORMAT_SSIZE_T "d positional argument%.1s (%" CYTHON_FORMAT_SSIZE_T "d given)", - func_name, more_or_less, num_expected, - (num_expected == 1) ? "" : "s", num_found); -} - - -//////////////////// RaiseKeywordRequired.proto //////////////////// - + return 0; +} + +//////////////////// RaiseArgTupleInvalid.proto //////////////////// + +static void __Pyx_RaiseArgtupleInvalid(const char* func_name, int exact, + Py_ssize_t num_min, Py_ssize_t num_max, Py_ssize_t num_found); /*proto*/ + +//////////////////// RaiseArgTupleInvalid //////////////////// + +// __Pyx_RaiseArgtupleInvalid raises the correct exception when too +// many or too few positional arguments were found. This handles +// Py_ssize_t formatting correctly. + +static void __Pyx_RaiseArgtupleInvalid( + const char* func_name, + int exact, + Py_ssize_t num_min, + Py_ssize_t num_max, + Py_ssize_t num_found) +{ + Py_ssize_t num_expected; + const char *more_or_less; + + if (num_found < num_min) { + num_expected = num_min; + more_or_less = "at least"; + } else { + num_expected = num_max; + more_or_less = "at most"; + } + if (exact) { + more_or_less = "exactly"; + } + PyErr_Format(PyExc_TypeError, + "%.200s() takes %.8s %" CYTHON_FORMAT_SSIZE_T "d positional argument%.1s (%" CYTHON_FORMAT_SSIZE_T "d given)", + func_name, more_or_less, num_expected, + (num_expected == 1) ? "" : "s", num_found); +} + + +//////////////////// RaiseKeywordRequired.proto //////////////////// + static void __Pyx_RaiseKeywordRequired(const char* func_name, PyObject* kw_name); /*proto*/ - -//////////////////// RaiseKeywordRequired //////////////////// - + +//////////////////// RaiseKeywordRequired //////////////////// + static void __Pyx_RaiseKeywordRequired(const char* func_name, PyObject* kw_name) { - PyErr_Format(PyExc_TypeError, - #if PY_MAJOR_VERSION >= 3 - "%s() needs keyword-only argument %U", func_name, kw_name); - #else - "%s() needs keyword-only argument %s", func_name, - PyString_AS_STRING(kw_name)); - #endif -} - - -//////////////////// RaiseDoubleKeywords.proto //////////////////// - -static void __Pyx_RaiseDoubleKeywordsError(const char* func_name, PyObject* kw_name); /*proto*/ - -//////////////////// RaiseDoubleKeywords //////////////////// - -static void __Pyx_RaiseDoubleKeywordsError( - const char* func_name, - PyObject* kw_name) -{ - PyErr_Format(PyExc_TypeError, - #if PY_MAJOR_VERSION >= 3 - "%s() got multiple values for keyword argument '%U'", func_name, kw_name); - #else - "%s() got multiple values for keyword argument '%s'", func_name, - PyString_AsString(kw_name)); - #endif -} - - + PyErr_Format(PyExc_TypeError, + #if PY_MAJOR_VERSION >= 3 + "%s() needs keyword-only argument %U", func_name, kw_name); + #else + "%s() needs keyword-only argument %s", func_name, + PyString_AS_STRING(kw_name)); + #endif +} + + +//////////////////// RaiseDoubleKeywords.proto //////////////////// + +static void __Pyx_RaiseDoubleKeywordsError(const char* func_name, PyObject* kw_name); /*proto*/ + +//////////////////// RaiseDoubleKeywords //////////////////// + +static void __Pyx_RaiseDoubleKeywordsError( + const char* func_name, + PyObject* kw_name) +{ + PyErr_Format(PyExc_TypeError, + #if PY_MAJOR_VERSION >= 3 + "%s() got multiple values for keyword argument '%U'", func_name, kw_name); + #else + "%s() got multiple values for keyword argument '%s'", func_name, + PyString_AsString(kw_name)); + #endif +} + + //////////////////// RaiseMappingExpected.proto //////////////////// static void __Pyx_RaiseMappingExpectedError(PyObject* arg); /*proto*/ @@ -115,186 +115,186 @@ static void __Pyx_RaiseMappingExpectedError(PyObject* arg) { } -//////////////////// KeywordStringCheck.proto //////////////////// - +//////////////////// KeywordStringCheck.proto //////////////////// + static int __Pyx_CheckKeywordStrings(PyObject *kwdict, const char* function_name, int kw_allowed); /*proto*/ - -//////////////////// KeywordStringCheck //////////////////// - -// __Pyx_CheckKeywordStrings raises an error if non-string keywords -// were passed to a function, or if any keywords were passed to a -// function that does not accept them. - + +//////////////////// KeywordStringCheck //////////////////// + +// __Pyx_CheckKeywordStrings raises an error if non-string keywords +// were passed to a function, or if any keywords were passed to a +// function that does not accept them. + static int __Pyx_CheckKeywordStrings( - PyObject *kwdict, - const char* function_name, - int kw_allowed) -{ - PyObject* key = 0; - Py_ssize_t pos = 0; -#if CYTHON_COMPILING_IN_PYPY - /* PyPy appears to check keywords at call time, not at unpacking time => not much to do here */ - if (!kw_allowed && PyDict_Next(kwdict, &pos, &key, 0)) - goto invalid_keyword; - return 1; -#else - while (PyDict_Next(kwdict, &pos, &key, 0)) { - #if PY_MAJOR_VERSION < 3 + PyObject *kwdict, + const char* function_name, + int kw_allowed) +{ + PyObject* key = 0; + Py_ssize_t pos = 0; +#if CYTHON_COMPILING_IN_PYPY + /* PyPy appears to check keywords at call time, not at unpacking time => not much to do here */ + if (!kw_allowed && PyDict_Next(kwdict, &pos, &key, 0)) + goto invalid_keyword; + return 1; +#else + while (PyDict_Next(kwdict, &pos, &key, 0)) { + #if PY_MAJOR_VERSION < 3 if (unlikely(!PyString_Check(key))) - #endif - if (unlikely(!PyUnicode_Check(key))) - goto invalid_keyword_type; - } - if ((!kw_allowed) && unlikely(key)) - goto invalid_keyword; - return 1; -invalid_keyword_type: - PyErr_Format(PyExc_TypeError, - "%.200s() keywords must be strings", function_name); - return 0; -#endif -invalid_keyword: - PyErr_Format(PyExc_TypeError, - #if PY_MAJOR_VERSION < 3 - "%.200s() got an unexpected keyword argument '%.200s'", - function_name, PyString_AsString(key)); - #else - "%s() got an unexpected keyword argument '%U'", - function_name, key); - #endif - return 0; -} - - -//////////////////// ParseKeywords.proto //////////////////// - -static int __Pyx_ParseOptionalKeywords(PyObject *kwds, PyObject **argnames[], \ - PyObject *kwds2, PyObject *values[], Py_ssize_t num_pos_args, \ - const char* function_name); /*proto*/ - -//////////////////// ParseKeywords //////////////////// -//@requires: RaiseDoubleKeywords - -// __Pyx_ParseOptionalKeywords copies the optional/unknown keyword -// arguments from the kwds dict into kwds2. If kwds2 is NULL, unknown -// keywords will raise an invalid keyword error. -// -// Three kinds of errors are checked: 1) non-string keywords, 2) -// unexpected keywords and 3) overlap with positional arguments. -// -// If num_posargs is greater 0, it denotes the number of positional -// arguments that were passed and that must therefore not appear -// amongst the keywords as well. -// -// This method does not check for required keyword arguments. - -static int __Pyx_ParseOptionalKeywords( - PyObject *kwds, - PyObject **argnames[], - PyObject *kwds2, - PyObject *values[], - Py_ssize_t num_pos_args, - const char* function_name) -{ - PyObject *key = 0, *value = 0; - Py_ssize_t pos = 0; - PyObject*** name; - PyObject*** first_kw_arg = argnames + num_pos_args; - - while (PyDict_Next(kwds, &pos, &key, &value)) { - name = first_kw_arg; - while (*name && (**name != key)) name++; - if (*name) { - values[name-argnames] = value; - continue; - } - - name = first_kw_arg; - #if PY_MAJOR_VERSION < 3 + #endif + if (unlikely(!PyUnicode_Check(key))) + goto invalid_keyword_type; + } + if ((!kw_allowed) && unlikely(key)) + goto invalid_keyword; + return 1; +invalid_keyword_type: + PyErr_Format(PyExc_TypeError, + "%.200s() keywords must be strings", function_name); + return 0; +#endif +invalid_keyword: + PyErr_Format(PyExc_TypeError, + #if PY_MAJOR_VERSION < 3 + "%.200s() got an unexpected keyword argument '%.200s'", + function_name, PyString_AsString(key)); + #else + "%s() got an unexpected keyword argument '%U'", + function_name, key); + #endif + return 0; +} + + +//////////////////// ParseKeywords.proto //////////////////// + +static int __Pyx_ParseOptionalKeywords(PyObject *kwds, PyObject **argnames[], \ + PyObject *kwds2, PyObject *values[], Py_ssize_t num_pos_args, \ + const char* function_name); /*proto*/ + +//////////////////// ParseKeywords //////////////////// +//@requires: RaiseDoubleKeywords + +// __Pyx_ParseOptionalKeywords copies the optional/unknown keyword +// arguments from the kwds dict into kwds2. If kwds2 is NULL, unknown +// keywords will raise an invalid keyword error. +// +// Three kinds of errors are checked: 1) non-string keywords, 2) +// unexpected keywords and 3) overlap with positional arguments. +// +// If num_posargs is greater 0, it denotes the number of positional +// arguments that were passed and that must therefore not appear +// amongst the keywords as well. +// +// This method does not check for required keyword arguments. + +static int __Pyx_ParseOptionalKeywords( + PyObject *kwds, + PyObject **argnames[], + PyObject *kwds2, + PyObject *values[], + Py_ssize_t num_pos_args, + const char* function_name) +{ + PyObject *key = 0, *value = 0; + Py_ssize_t pos = 0; + PyObject*** name; + PyObject*** first_kw_arg = argnames + num_pos_args; + + while (PyDict_Next(kwds, &pos, &key, &value)) { + name = first_kw_arg; + while (*name && (**name != key)) name++; + if (*name) { + values[name-argnames] = value; + continue; + } + + name = first_kw_arg; + #if PY_MAJOR_VERSION < 3 if (likely(PyString_Check(key))) { - while (*name) { - if ((CYTHON_COMPILING_IN_PYPY || PyString_GET_SIZE(**name) == PyString_GET_SIZE(key)) - && _PyString_Eq(**name, key)) { - values[name-argnames] = value; - break; - } - name++; - } - if (*name) continue; - else { - // not found after positional args, check for duplicate - PyObject*** argname = argnames; - while (argname != first_kw_arg) { - if ((**argname == key) || ( - (CYTHON_COMPILING_IN_PYPY || PyString_GET_SIZE(**argname) == PyString_GET_SIZE(key)) - && _PyString_Eq(**argname, key))) { - goto arg_passed_twice; - } - argname++; - } - } - } else - #endif - if (likely(PyUnicode_Check(key))) { - while (*name) { - int cmp = (**name == key) ? 0 : - #if !CYTHON_COMPILING_IN_PYPY && PY_MAJOR_VERSION >= 3 + while (*name) { + if ((CYTHON_COMPILING_IN_PYPY || PyString_GET_SIZE(**name) == PyString_GET_SIZE(key)) + && _PyString_Eq(**name, key)) { + values[name-argnames] = value; + break; + } + name++; + } + if (*name) continue; + else { + // not found after positional args, check for duplicate + PyObject*** argname = argnames; + while (argname != first_kw_arg) { + if ((**argname == key) || ( + (CYTHON_COMPILING_IN_PYPY || PyString_GET_SIZE(**argname) == PyString_GET_SIZE(key)) + && _PyString_Eq(**argname, key))) { + goto arg_passed_twice; + } + argname++; + } + } + } else + #endif + if (likely(PyUnicode_Check(key))) { + while (*name) { + int cmp = (**name == key) ? 0 : + #if !CYTHON_COMPILING_IN_PYPY && PY_MAJOR_VERSION >= 3 (__Pyx_PyUnicode_GET_LENGTH(**name) != __Pyx_PyUnicode_GET_LENGTH(key)) ? 1 : - #endif + #endif // In Py2, we may need to convert the argument name from str to unicode for comparison. - PyUnicode_Compare(**name, key); - if (cmp < 0 && unlikely(PyErr_Occurred())) goto bad; - if (cmp == 0) { - values[name-argnames] = value; - break; - } - name++; - } - if (*name) continue; - else { - // not found after positional args, check for duplicate - PyObject*** argname = argnames; - while (argname != first_kw_arg) { - int cmp = (**argname == key) ? 0 : - #if !CYTHON_COMPILING_IN_PYPY && PY_MAJOR_VERSION >= 3 + PyUnicode_Compare(**name, key); + if (cmp < 0 && unlikely(PyErr_Occurred())) goto bad; + if (cmp == 0) { + values[name-argnames] = value; + break; + } + name++; + } + if (*name) continue; + else { + // not found after positional args, check for duplicate + PyObject*** argname = argnames; + while (argname != first_kw_arg) { + int cmp = (**argname == key) ? 0 : + #if !CYTHON_COMPILING_IN_PYPY && PY_MAJOR_VERSION >= 3 (__Pyx_PyUnicode_GET_LENGTH(**argname) != __Pyx_PyUnicode_GET_LENGTH(key)) ? 1 : - #endif - // need to convert argument name from bytes to unicode for comparison - PyUnicode_Compare(**argname, key); - if (cmp < 0 && unlikely(PyErr_Occurred())) goto bad; - if (cmp == 0) goto arg_passed_twice; - argname++; - } - } - } else - goto invalid_keyword_type; - - if (kwds2) { - if (unlikely(PyDict_SetItem(kwds2, key, value))) goto bad; - } else { - goto invalid_keyword; - } - } - return 0; -arg_passed_twice: - __Pyx_RaiseDoubleKeywordsError(function_name, key); - goto bad; -invalid_keyword_type: - PyErr_Format(PyExc_TypeError, - "%.200s() keywords must be strings", function_name); - goto bad; -invalid_keyword: - PyErr_Format(PyExc_TypeError, - #if PY_MAJOR_VERSION < 3 - "%.200s() got an unexpected keyword argument '%.200s'", - function_name, PyString_AsString(key)); - #else - "%s() got an unexpected keyword argument '%U'", - function_name, key); - #endif -bad: - return -1; -} + #endif + // need to convert argument name from bytes to unicode for comparison + PyUnicode_Compare(**argname, key); + if (cmp < 0 && unlikely(PyErr_Occurred())) goto bad; + if (cmp == 0) goto arg_passed_twice; + argname++; + } + } + } else + goto invalid_keyword_type; + + if (kwds2) { + if (unlikely(PyDict_SetItem(kwds2, key, value))) goto bad; + } else { + goto invalid_keyword; + } + } + return 0; +arg_passed_twice: + __Pyx_RaiseDoubleKeywordsError(function_name, key); + goto bad; +invalid_keyword_type: + PyErr_Format(PyExc_TypeError, + "%.200s() keywords must be strings", function_name); + goto bad; +invalid_keyword: + PyErr_Format(PyExc_TypeError, + #if PY_MAJOR_VERSION < 3 + "%.200s() got an unexpected keyword argument '%.200s'", + function_name, PyString_AsString(key)); + #else + "%s() got an unexpected keyword argument '%U'", + function_name, key); + #endif +bad: + return -1; +} //////////////////// MergeKeywords.proto //////////////////// diff --git a/contrib/tools/cython/Cython/Utility/ImportExport.c b/contrib/tools/cython/Cython/Utility/ImportExport.c index 532ec326f6..e227dd1652 100644 --- a/contrib/tools/cython/Cython/Utility/ImportExport.c +++ b/contrib/tools/cython/Cython/Utility/ImportExport.c @@ -1,110 +1,110 @@ -/////////////// PyIdentifierFromString.proto /////////////// - -#if !defined(__Pyx_PyIdentifier_FromString) -#if PY_MAJOR_VERSION < 3 - #define __Pyx_PyIdentifier_FromString(s) PyString_FromString(s) -#else - #define __Pyx_PyIdentifier_FromString(s) PyUnicode_FromString(s) -#endif -#endif - - -/////////////// Import.proto /////////////// - -static PyObject *__Pyx_Import(PyObject *name, PyObject *from_list, int level); /*proto*/ - -/////////////// Import /////////////// -//@requires: ObjectHandling.c::PyObjectGetAttrStr -//@substitute: naming - -static PyObject *__Pyx_Import(PyObject *name, PyObject *from_list, int level) { - PyObject *empty_list = 0; - PyObject *module = 0; - PyObject *global_dict = 0; - PyObject *empty_dict = 0; - PyObject *list; +/////////////// PyIdentifierFromString.proto /////////////// + +#if !defined(__Pyx_PyIdentifier_FromString) +#if PY_MAJOR_VERSION < 3 + #define __Pyx_PyIdentifier_FromString(s) PyString_FromString(s) +#else + #define __Pyx_PyIdentifier_FromString(s) PyUnicode_FromString(s) +#endif +#endif + + +/////////////// Import.proto /////////////// + +static PyObject *__Pyx_Import(PyObject *name, PyObject *from_list, int level); /*proto*/ + +/////////////// Import /////////////// +//@requires: ObjectHandling.c::PyObjectGetAttrStr +//@substitute: naming + +static PyObject *__Pyx_Import(PyObject *name, PyObject *from_list, int level) { + PyObject *empty_list = 0; + PyObject *module = 0; + PyObject *global_dict = 0; + PyObject *empty_dict = 0; + PyObject *list; #if PY_MAJOR_VERSION < 3 - PyObject *py_import; - py_import = __Pyx_PyObject_GetAttrStr($builtins_cname, PYIDENT("__import__")); - if (!py_import) - goto bad; - #endif - if (from_list) - list = from_list; - else { - empty_list = PyList_New(0); - if (!empty_list) - goto bad; - list = empty_list; - } - global_dict = PyModule_GetDict($module_cname); - if (!global_dict) - goto bad; - empty_dict = PyDict_New(); - if (!empty_dict) - goto bad; - { - #if PY_MAJOR_VERSION >= 3 - if (level == -1) { + PyObject *py_import; + py_import = __Pyx_PyObject_GetAttrStr($builtins_cname, PYIDENT("__import__")); + if (!py_import) + goto bad; + #endif + if (from_list) + list = from_list; + else { + empty_list = PyList_New(0); + if (!empty_list) + goto bad; + list = empty_list; + } + global_dict = PyModule_GetDict($module_cname); + if (!global_dict) + goto bad; + empty_dict = PyDict_New(); + if (!empty_dict) + goto bad; + { + #if PY_MAJOR_VERSION >= 3 + if (level == -1) { // Avoid C compiler warning if strchr() evaluates to false at compile time. if ((1) && (strchr(__Pyx_MODULE_NAME, '.'))) { - /* try package relative import first */ - module = PyImport_ImportModuleLevelObject( - name, global_dict, empty_dict, list, 1); - if (!module) { - if (!PyErr_ExceptionMatches(PyExc_ImportError)) - goto bad; - PyErr_Clear(); - } - } - level = 0; /* try absolute import on failure */ - } - #endif - if (!module) { + /* try package relative import first */ + module = PyImport_ImportModuleLevelObject( + name, global_dict, empty_dict, list, 1); + if (!module) { + if (!PyErr_ExceptionMatches(PyExc_ImportError)) + goto bad; + PyErr_Clear(); + } + } + level = 0; /* try absolute import on failure */ + } + #endif + if (!module) { #if PY_MAJOR_VERSION < 3 - PyObject *py_level = PyInt_FromLong(level); - if (!py_level) - goto bad; - module = PyObject_CallFunctionObjArgs(py_import, + PyObject *py_level = PyInt_FromLong(level); + if (!py_level) + goto bad; + module = PyObject_CallFunctionObjArgs(py_import, name, global_dict, empty_dict, list, py_level, (PyObject *)NULL); - Py_DECREF(py_level); - #else - module = PyImport_ImportModuleLevelObject( - name, global_dict, empty_dict, list, level); - #endif - } - } -bad: + Py_DECREF(py_level); + #else + module = PyImport_ImportModuleLevelObject( + name, global_dict, empty_dict, list, level); + #endif + } + } +bad: #if PY_MAJOR_VERSION < 3 - Py_XDECREF(py_import); - #endif - Py_XDECREF(empty_list); - Py_XDECREF(empty_dict); - return module; -} - - -/////////////// ImportFrom.proto /////////////// - -static PyObject* __Pyx_ImportFrom(PyObject* module, PyObject* name); /*proto*/ - -/////////////// ImportFrom /////////////// -//@requires: ObjectHandling.c::PyObjectGetAttrStr - -static PyObject* __Pyx_ImportFrom(PyObject* module, PyObject* name) { - PyObject* value = __Pyx_PyObject_GetAttrStr(module, name); - if (unlikely(!value) && PyErr_ExceptionMatches(PyExc_AttributeError)) { - PyErr_Format(PyExc_ImportError, - #if PY_MAJOR_VERSION < 3 - "cannot import name %.230s", PyString_AS_STRING(name)); - #else - "cannot import name %S", name); - #endif - } - return value; -} - - + Py_XDECREF(py_import); + #endif + Py_XDECREF(empty_list); + Py_XDECREF(empty_dict); + return module; +} + + +/////////////// ImportFrom.proto /////////////// + +static PyObject* __Pyx_ImportFrom(PyObject* module, PyObject* name); /*proto*/ + +/////////////// ImportFrom /////////////// +//@requires: ObjectHandling.c::PyObjectGetAttrStr + +static PyObject* __Pyx_ImportFrom(PyObject* module, PyObject* name) { + PyObject* value = __Pyx_PyObject_GetAttrStr(module, name); + if (unlikely(!value) && PyErr_ExceptionMatches(PyExc_AttributeError)) { + PyErr_Format(PyExc_ImportError, + #if PY_MAJOR_VERSION < 3 + "cannot import name %.230s", PyString_AS_STRING(name)); + #else + "cannot import name %S", name); + #endif + } + return value; +} + + /////////////// ImportStar /////////////// //@substitute: naming @@ -224,95 +224,95 @@ bad: } -/////////////// SetPackagePathFromImportLib.proto /////////////// - +/////////////// SetPackagePathFromImportLib.proto /////////////// + // PY_VERSION_HEX >= 0x03030000 #if PY_MAJOR_VERSION >= 3 && !CYTHON_PEP489_MULTI_PHASE_INIT -static int __Pyx_SetPackagePathFromImportLib(const char* parent_package_name, PyObject *module_name); -#else -#define __Pyx_SetPackagePathFromImportLib(a, b) 0 -#endif - -/////////////// SetPackagePathFromImportLib /////////////// -//@requires: ObjectHandling.c::PyObjectGetAttrStr -//@substitute: naming - +static int __Pyx_SetPackagePathFromImportLib(const char* parent_package_name, PyObject *module_name); +#else +#define __Pyx_SetPackagePathFromImportLib(a, b) 0 +#endif + +/////////////// SetPackagePathFromImportLib /////////////// +//@requires: ObjectHandling.c::PyObjectGetAttrStr +//@substitute: naming + // PY_VERSION_HEX >= 0x03030000 #if PY_MAJOR_VERSION >= 3 && !CYTHON_PEP489_MULTI_PHASE_INIT -static int __Pyx_SetPackagePathFromImportLib(const char* parent_package_name, PyObject *module_name) { - PyObject *importlib, *loader, *osmod, *ossep, *parts, *package_path; - PyObject *path = NULL, *file_path = NULL; - int result; - if (parent_package_name) { - PyObject *package = PyImport_ImportModule(parent_package_name); - if (unlikely(!package)) - goto bad; - path = PyObject_GetAttrString(package, "__path__"); - Py_DECREF(package); - if (unlikely(!path) || unlikely(path == Py_None)) - goto bad; - } else { - path = Py_None; Py_INCREF(Py_None); - } - // package_path = [importlib.find_loader(module_name, path).path.rsplit(os.sep, 1)[0]] - importlib = PyImport_ImportModule("importlib"); - if (unlikely(!importlib)) - goto bad; - loader = PyObject_CallMethod(importlib, "find_loader", "(OO)", module_name, path); - Py_DECREF(importlib); - Py_DECREF(path); path = NULL; - if (unlikely(!loader)) - goto bad; - file_path = PyObject_GetAttrString(loader, "path"); - Py_DECREF(loader); - if (unlikely(!file_path)) - goto bad; - - if (unlikely(PyObject_SetAttrString($module_cname, "__file__", file_path) < 0)) - goto bad; - - osmod = PyImport_ImportModule("os"); - if (unlikely(!osmod)) - goto bad; - ossep = PyObject_GetAttrString(osmod, "sep"); - Py_DECREF(osmod); - if (unlikely(!ossep)) - goto bad; - parts = PyObject_CallMethod(file_path, "rsplit", "(Oi)", ossep, 1); - Py_DECREF(file_path); file_path = NULL; - Py_DECREF(ossep); - if (unlikely(!parts)) - goto bad; - package_path = Py_BuildValue("[O]", PyList_GET_ITEM(parts, 0)); - Py_DECREF(parts); - if (unlikely(!package_path)) - goto bad; - goto set_path; - -bad: - PyErr_WriteUnraisable(module_name); - Py_XDECREF(path); - Py_XDECREF(file_path); - - // set an empty path list on failure - PyErr_Clear(); - package_path = PyList_New(0); - if (unlikely(!package_path)) - return -1; - -set_path: - result = PyObject_SetAttrString($module_cname, "__path__", package_path); - Py_DECREF(package_path); - return result; -} -#endif - - -/////////////// TypeImport.proto /////////////// - +static int __Pyx_SetPackagePathFromImportLib(const char* parent_package_name, PyObject *module_name) { + PyObject *importlib, *loader, *osmod, *ossep, *parts, *package_path; + PyObject *path = NULL, *file_path = NULL; + int result; + if (parent_package_name) { + PyObject *package = PyImport_ImportModule(parent_package_name); + if (unlikely(!package)) + goto bad; + path = PyObject_GetAttrString(package, "__path__"); + Py_DECREF(package); + if (unlikely(!path) || unlikely(path == Py_None)) + goto bad; + } else { + path = Py_None; Py_INCREF(Py_None); + } + // package_path = [importlib.find_loader(module_name, path).path.rsplit(os.sep, 1)[0]] + importlib = PyImport_ImportModule("importlib"); + if (unlikely(!importlib)) + goto bad; + loader = PyObject_CallMethod(importlib, "find_loader", "(OO)", module_name, path); + Py_DECREF(importlib); + Py_DECREF(path); path = NULL; + if (unlikely(!loader)) + goto bad; + file_path = PyObject_GetAttrString(loader, "path"); + Py_DECREF(loader); + if (unlikely(!file_path)) + goto bad; + + if (unlikely(PyObject_SetAttrString($module_cname, "__file__", file_path) < 0)) + goto bad; + + osmod = PyImport_ImportModule("os"); + if (unlikely(!osmod)) + goto bad; + ossep = PyObject_GetAttrString(osmod, "sep"); + Py_DECREF(osmod); + if (unlikely(!ossep)) + goto bad; + parts = PyObject_CallMethod(file_path, "rsplit", "(Oi)", ossep, 1); + Py_DECREF(file_path); file_path = NULL; + Py_DECREF(ossep); + if (unlikely(!parts)) + goto bad; + package_path = Py_BuildValue("[O]", PyList_GET_ITEM(parts, 0)); + Py_DECREF(parts); + if (unlikely(!package_path)) + goto bad; + goto set_path; + +bad: + PyErr_WriteUnraisable(module_name); + Py_XDECREF(path); + Py_XDECREF(file_path); + + // set an empty path list on failure + PyErr_Clear(); + package_path = PyList_New(0); + if (unlikely(!package_path)) + return -1; + +set_path: + result = PyObject_SetAttrString($module_cname, "__path__", package_path); + Py_DECREF(package_path); + return result; +} +#endif + + +/////////////// TypeImport.proto /////////////// + #ifndef __PYX_HAVE_RT_ImportType_proto #define __PYX_HAVE_RT_ImportType_proto - + enum __Pyx_ImportType_CheckSize { __Pyx_ImportType_CheckSize_Error = 0, __Pyx_ImportType_CheckSize_Warn = 1, @@ -323,55 +323,55 @@ static PyTypeObject *__Pyx_ImportType(PyObject* module, const char *module_name, #endif -/////////////// TypeImport /////////////// - -#ifndef __PYX_HAVE_RT_ImportType -#define __PYX_HAVE_RT_ImportType +/////////////// TypeImport /////////////// + +#ifndef __PYX_HAVE_RT_ImportType +#define __PYX_HAVE_RT_ImportType static PyTypeObject *__Pyx_ImportType(PyObject *module, const char *module_name, const char *class_name, size_t size, enum __Pyx_ImportType_CheckSize check_size) -{ - PyObject *result = 0; - char warning[200]; - Py_ssize_t basicsize; -#ifdef Py_LIMITED_API - PyObject *py_basicsize; -#endif - +{ + PyObject *result = 0; + char warning[200]; + Py_ssize_t basicsize; +#ifdef Py_LIMITED_API + PyObject *py_basicsize; +#endif + result = PyObject_GetAttrString(module, class_name); - if (!result) - goto bad; - if (!PyType_Check(result)) { - PyErr_Format(PyExc_TypeError, - "%.200s.%.200s is not a type object", - module_name, class_name); - goto bad; - } -#ifndef Py_LIMITED_API - basicsize = ((PyTypeObject *)result)->tp_basicsize; -#else - py_basicsize = PyObject_GetAttrString(result, "__basicsize__"); - if (!py_basicsize) - goto bad; - basicsize = PyLong_AsSsize_t(py_basicsize); - Py_DECREF(py_basicsize); - py_basicsize = 0; - if (basicsize == (Py_ssize_t)-1 && PyErr_Occurred()) - goto bad; -#endif + if (!result) + goto bad; + if (!PyType_Check(result)) { + PyErr_Format(PyExc_TypeError, + "%.200s.%.200s is not a type object", + module_name, class_name); + goto bad; + } +#ifndef Py_LIMITED_API + basicsize = ((PyTypeObject *)result)->tp_basicsize; +#else + py_basicsize = PyObject_GetAttrString(result, "__basicsize__"); + if (!py_basicsize) + goto bad; + basicsize = PyLong_AsSsize_t(py_basicsize); + Py_DECREF(py_basicsize); + py_basicsize = 0; + if (basicsize == (Py_ssize_t)-1 && PyErr_Occurred()) + goto bad; +#endif if ((size_t)basicsize < size) { PyErr_Format(PyExc_ValueError, "%.200s.%.200s size changed, may indicate binary incompatibility. " "Expected %zd from C header, got %zd from PyObject", module_name, class_name, size, basicsize); goto bad; - } + } if (check_size == __Pyx_ImportType_CheckSize_Error && (size_t)basicsize != size) { - PyErr_Format(PyExc_ValueError, + PyErr_Format(PyExc_ValueError, "%.200s.%.200s size changed, may indicate binary incompatibility. " "Expected %zd from C header, got %zd from PyObject", module_name, class_name, size, basicsize); - goto bad; - } + goto bad; + } else if (check_size == __Pyx_ImportType_CheckSize_Warn && (size_t)basicsize > size) { PyOS_snprintf(warning, sizeof(warning), "%s.%s size changed, may indicate binary incompatibility. " @@ -380,262 +380,262 @@ static PyTypeObject *__Pyx_ImportType(PyObject *module, const char *module_name, if (PyErr_WarnEx(NULL, warning, 0) < 0) goto bad; } /* check_size == __Pyx_ImportType_CheckSize_Ignore does not warn nor error */ - return (PyTypeObject *)result; -bad: - Py_XDECREF(result); - return NULL; -} -#endif - -/////////////// FunctionImport.proto /////////////// - -static int __Pyx_ImportFunction(PyObject *module, const char *funcname, void (**f)(void), const char *sig); /*proto*/ - -/////////////// FunctionImport /////////////// -//@substitute: naming - -#ifndef __PYX_HAVE_RT_ImportFunction -#define __PYX_HAVE_RT_ImportFunction -static int __Pyx_ImportFunction(PyObject *module, const char *funcname, void (**f)(void), const char *sig) { - PyObject *d = 0; - PyObject *cobj = 0; - union { - void (*fp)(void); - void *p; - } tmp; - - d = PyObject_GetAttrString(module, (char *)"$api_name"); - if (!d) - goto bad; - cobj = PyDict_GetItemString(d, funcname); - if (!cobj) { - PyErr_Format(PyExc_ImportError, - "%.200s does not export expected C function %.200s", - PyModule_GetName(module), funcname); - goto bad; - } -#if PY_VERSION_HEX >= 0x02070000 - if (!PyCapsule_IsValid(cobj, sig)) { - PyErr_Format(PyExc_TypeError, - "C function %.200s.%.200s has wrong signature (expected %.500s, got %.500s)", - PyModule_GetName(module), funcname, sig, PyCapsule_GetName(cobj)); - goto bad; - } - tmp.p = PyCapsule_GetPointer(cobj, sig); -#else - {const char *desc, *s1, *s2; - desc = (const char *)PyCObject_GetDesc(cobj); - if (!desc) - goto bad; - s1 = desc; s2 = sig; - while (*s1 != '\0' && *s1 == *s2) { s1++; s2++; } - if (*s1 != *s2) { - PyErr_Format(PyExc_TypeError, - "C function %.200s.%.200s has wrong signature (expected %.500s, got %.500s)", - PyModule_GetName(module), funcname, sig, desc); - goto bad; - } - tmp.p = PyCObject_AsVoidPtr(cobj);} -#endif - *f = tmp.fp; - if (!(*f)) - goto bad; - Py_DECREF(d); - return 0; -bad: - Py_XDECREF(d); - return -1; -} -#endif - -/////////////// FunctionExport.proto /////////////// - -static int __Pyx_ExportFunction(const char *name, void (*f)(void), const char *sig); /*proto*/ - -/////////////// FunctionExport /////////////// -//@substitute: naming - -static int __Pyx_ExportFunction(const char *name, void (*f)(void), const char *sig) { - PyObject *d = 0; - PyObject *cobj = 0; - union { - void (*fp)(void); - void *p; - } tmp; - - d = PyObject_GetAttrString($module_cname, (char *)"$api_name"); - if (!d) { - PyErr_Clear(); - d = PyDict_New(); - if (!d) - goto bad; - Py_INCREF(d); - if (PyModule_AddObject($module_cname, (char *)"$api_name", d) < 0) - goto bad; - } - tmp.fp = f; -#if PY_VERSION_HEX >= 0x02070000 - cobj = PyCapsule_New(tmp.p, sig, 0); -#else - cobj = PyCObject_FromVoidPtrAndDesc(tmp.p, (void *)sig, 0); -#endif - if (!cobj) - goto bad; - if (PyDict_SetItemString(d, name, cobj) < 0) - goto bad; - Py_DECREF(cobj); - Py_DECREF(d); - return 0; -bad: - Py_XDECREF(cobj); - Py_XDECREF(d); - return -1; -} - -/////////////// VoidPtrImport.proto /////////////// - -static int __Pyx_ImportVoidPtr(PyObject *module, const char *name, void **p, const char *sig); /*proto*/ - -/////////////// VoidPtrImport /////////////// -//@substitute: naming - -#ifndef __PYX_HAVE_RT_ImportVoidPtr -#define __PYX_HAVE_RT_ImportVoidPtr -static int __Pyx_ImportVoidPtr(PyObject *module, const char *name, void **p, const char *sig) { - PyObject *d = 0; - PyObject *cobj = 0; - - d = PyObject_GetAttrString(module, (char *)"$api_name"); - if (!d) - goto bad; - cobj = PyDict_GetItemString(d, name); - if (!cobj) { - PyErr_Format(PyExc_ImportError, - "%.200s does not export expected C variable %.200s", - PyModule_GetName(module), name); - goto bad; - } -#if PY_VERSION_HEX >= 0x02070000 - if (!PyCapsule_IsValid(cobj, sig)) { - PyErr_Format(PyExc_TypeError, - "C variable %.200s.%.200s has wrong signature (expected %.500s, got %.500s)", - PyModule_GetName(module), name, sig, PyCapsule_GetName(cobj)); - goto bad; - } - *p = PyCapsule_GetPointer(cobj, sig); -#else - {const char *desc, *s1, *s2; - desc = (const char *)PyCObject_GetDesc(cobj); - if (!desc) - goto bad; - s1 = desc; s2 = sig; - while (*s1 != '\0' && *s1 == *s2) { s1++; s2++; } - if (*s1 != *s2) { - PyErr_Format(PyExc_TypeError, - "C variable %.200s.%.200s has wrong signature (expected %.500s, got %.500s)", - PyModule_GetName(module), name, sig, desc); - goto bad; - } - *p = PyCObject_AsVoidPtr(cobj);} -#endif - if (!(*p)) - goto bad; - Py_DECREF(d); - return 0; -bad: - Py_XDECREF(d); - return -1; -} -#endif - -/////////////// VoidPtrExport.proto /////////////// - -static int __Pyx_ExportVoidPtr(PyObject *name, void *p, const char *sig); /*proto*/ - -/////////////// VoidPtrExport /////////////// -//@substitute: naming -//@requires: ObjectHandling.c::PyObjectSetAttrStr - -static int __Pyx_ExportVoidPtr(PyObject *name, void *p, const char *sig) { - PyObject *d; - PyObject *cobj = 0; - - d = PyDict_GetItem($moddict_cname, PYIDENT("$api_name")); - Py_XINCREF(d); - if (!d) { - d = PyDict_New(); - if (!d) - goto bad; - if (__Pyx_PyObject_SetAttrStr($module_cname, PYIDENT("$api_name"), d) < 0) - goto bad; - } -#if PY_VERSION_HEX >= 0x02070000 - cobj = PyCapsule_New(p, sig, 0); -#else - cobj = PyCObject_FromVoidPtrAndDesc(p, (void *)sig, 0); -#endif - if (!cobj) - goto bad; - if (PyDict_SetItem(d, name, cobj) < 0) - goto bad; - Py_DECREF(cobj); - Py_DECREF(d); - return 0; -bad: - Py_XDECREF(cobj); - Py_XDECREF(d); - return -1; -} - - -/////////////// SetVTable.proto /////////////// - -static int __Pyx_SetVtable(PyObject *dict, void *vtable); /*proto*/ - -/////////////// SetVTable /////////////// - -static int __Pyx_SetVtable(PyObject *dict, void *vtable) { -#if PY_VERSION_HEX >= 0x02070000 - PyObject *ob = PyCapsule_New(vtable, 0, 0); -#else - PyObject *ob = PyCObject_FromVoidPtr(vtable, 0); -#endif - if (!ob) - goto bad; - if (PyDict_SetItem(dict, PYIDENT("__pyx_vtable__"), ob) < 0) - goto bad; - Py_DECREF(ob); - return 0; -bad: - Py_XDECREF(ob); - return -1; -} - - -/////////////// GetVTable.proto /////////////// - -static void* __Pyx_GetVtable(PyObject *dict); /*proto*/ - -/////////////// GetVTable /////////////// - -static void* __Pyx_GetVtable(PyObject *dict) { - void* ptr; - PyObject *ob = PyObject_GetItem(dict, PYIDENT("__pyx_vtable__")); - if (!ob) - goto bad; -#if PY_VERSION_HEX >= 0x02070000 - ptr = PyCapsule_GetPointer(ob, 0); -#else - ptr = PyCObject_AsVoidPtr(ob); -#endif - if (!ptr && !PyErr_Occurred()) - PyErr_SetString(PyExc_RuntimeError, "invalid vtable found for imported type"); - Py_DECREF(ob); - return ptr; -bad: - Py_XDECREF(ob); - return NULL; -} + return (PyTypeObject *)result; +bad: + Py_XDECREF(result); + return NULL; +} +#endif + +/////////////// FunctionImport.proto /////////////// + +static int __Pyx_ImportFunction(PyObject *module, const char *funcname, void (**f)(void), const char *sig); /*proto*/ + +/////////////// FunctionImport /////////////// +//@substitute: naming + +#ifndef __PYX_HAVE_RT_ImportFunction +#define __PYX_HAVE_RT_ImportFunction +static int __Pyx_ImportFunction(PyObject *module, const char *funcname, void (**f)(void), const char *sig) { + PyObject *d = 0; + PyObject *cobj = 0; + union { + void (*fp)(void); + void *p; + } tmp; + + d = PyObject_GetAttrString(module, (char *)"$api_name"); + if (!d) + goto bad; + cobj = PyDict_GetItemString(d, funcname); + if (!cobj) { + PyErr_Format(PyExc_ImportError, + "%.200s does not export expected C function %.200s", + PyModule_GetName(module), funcname); + goto bad; + } +#if PY_VERSION_HEX >= 0x02070000 + if (!PyCapsule_IsValid(cobj, sig)) { + PyErr_Format(PyExc_TypeError, + "C function %.200s.%.200s has wrong signature (expected %.500s, got %.500s)", + PyModule_GetName(module), funcname, sig, PyCapsule_GetName(cobj)); + goto bad; + } + tmp.p = PyCapsule_GetPointer(cobj, sig); +#else + {const char *desc, *s1, *s2; + desc = (const char *)PyCObject_GetDesc(cobj); + if (!desc) + goto bad; + s1 = desc; s2 = sig; + while (*s1 != '\0' && *s1 == *s2) { s1++; s2++; } + if (*s1 != *s2) { + PyErr_Format(PyExc_TypeError, + "C function %.200s.%.200s has wrong signature (expected %.500s, got %.500s)", + PyModule_GetName(module), funcname, sig, desc); + goto bad; + } + tmp.p = PyCObject_AsVoidPtr(cobj);} +#endif + *f = tmp.fp; + if (!(*f)) + goto bad; + Py_DECREF(d); + return 0; +bad: + Py_XDECREF(d); + return -1; +} +#endif + +/////////////// FunctionExport.proto /////////////// + +static int __Pyx_ExportFunction(const char *name, void (*f)(void), const char *sig); /*proto*/ + +/////////////// FunctionExport /////////////// +//@substitute: naming + +static int __Pyx_ExportFunction(const char *name, void (*f)(void), const char *sig) { + PyObject *d = 0; + PyObject *cobj = 0; + union { + void (*fp)(void); + void *p; + } tmp; + + d = PyObject_GetAttrString($module_cname, (char *)"$api_name"); + if (!d) { + PyErr_Clear(); + d = PyDict_New(); + if (!d) + goto bad; + Py_INCREF(d); + if (PyModule_AddObject($module_cname, (char *)"$api_name", d) < 0) + goto bad; + } + tmp.fp = f; +#if PY_VERSION_HEX >= 0x02070000 + cobj = PyCapsule_New(tmp.p, sig, 0); +#else + cobj = PyCObject_FromVoidPtrAndDesc(tmp.p, (void *)sig, 0); +#endif + if (!cobj) + goto bad; + if (PyDict_SetItemString(d, name, cobj) < 0) + goto bad; + Py_DECREF(cobj); + Py_DECREF(d); + return 0; +bad: + Py_XDECREF(cobj); + Py_XDECREF(d); + return -1; +} + +/////////////// VoidPtrImport.proto /////////////// + +static int __Pyx_ImportVoidPtr(PyObject *module, const char *name, void **p, const char *sig); /*proto*/ + +/////////////// VoidPtrImport /////////////// +//@substitute: naming + +#ifndef __PYX_HAVE_RT_ImportVoidPtr +#define __PYX_HAVE_RT_ImportVoidPtr +static int __Pyx_ImportVoidPtr(PyObject *module, const char *name, void **p, const char *sig) { + PyObject *d = 0; + PyObject *cobj = 0; + + d = PyObject_GetAttrString(module, (char *)"$api_name"); + if (!d) + goto bad; + cobj = PyDict_GetItemString(d, name); + if (!cobj) { + PyErr_Format(PyExc_ImportError, + "%.200s does not export expected C variable %.200s", + PyModule_GetName(module), name); + goto bad; + } +#if PY_VERSION_HEX >= 0x02070000 + if (!PyCapsule_IsValid(cobj, sig)) { + PyErr_Format(PyExc_TypeError, + "C variable %.200s.%.200s has wrong signature (expected %.500s, got %.500s)", + PyModule_GetName(module), name, sig, PyCapsule_GetName(cobj)); + goto bad; + } + *p = PyCapsule_GetPointer(cobj, sig); +#else + {const char *desc, *s1, *s2; + desc = (const char *)PyCObject_GetDesc(cobj); + if (!desc) + goto bad; + s1 = desc; s2 = sig; + while (*s1 != '\0' && *s1 == *s2) { s1++; s2++; } + if (*s1 != *s2) { + PyErr_Format(PyExc_TypeError, + "C variable %.200s.%.200s has wrong signature (expected %.500s, got %.500s)", + PyModule_GetName(module), name, sig, desc); + goto bad; + } + *p = PyCObject_AsVoidPtr(cobj);} +#endif + if (!(*p)) + goto bad; + Py_DECREF(d); + return 0; +bad: + Py_XDECREF(d); + return -1; +} +#endif + +/////////////// VoidPtrExport.proto /////////////// + +static int __Pyx_ExportVoidPtr(PyObject *name, void *p, const char *sig); /*proto*/ + +/////////////// VoidPtrExport /////////////// +//@substitute: naming +//@requires: ObjectHandling.c::PyObjectSetAttrStr + +static int __Pyx_ExportVoidPtr(PyObject *name, void *p, const char *sig) { + PyObject *d; + PyObject *cobj = 0; + + d = PyDict_GetItem($moddict_cname, PYIDENT("$api_name")); + Py_XINCREF(d); + if (!d) { + d = PyDict_New(); + if (!d) + goto bad; + if (__Pyx_PyObject_SetAttrStr($module_cname, PYIDENT("$api_name"), d) < 0) + goto bad; + } +#if PY_VERSION_HEX >= 0x02070000 + cobj = PyCapsule_New(p, sig, 0); +#else + cobj = PyCObject_FromVoidPtrAndDesc(p, (void *)sig, 0); +#endif + if (!cobj) + goto bad; + if (PyDict_SetItem(d, name, cobj) < 0) + goto bad; + Py_DECREF(cobj); + Py_DECREF(d); + return 0; +bad: + Py_XDECREF(cobj); + Py_XDECREF(d); + return -1; +} + + +/////////////// SetVTable.proto /////////////// + +static int __Pyx_SetVtable(PyObject *dict, void *vtable); /*proto*/ + +/////////////// SetVTable /////////////// + +static int __Pyx_SetVtable(PyObject *dict, void *vtable) { +#if PY_VERSION_HEX >= 0x02070000 + PyObject *ob = PyCapsule_New(vtable, 0, 0); +#else + PyObject *ob = PyCObject_FromVoidPtr(vtable, 0); +#endif + if (!ob) + goto bad; + if (PyDict_SetItem(dict, PYIDENT("__pyx_vtable__"), ob) < 0) + goto bad; + Py_DECREF(ob); + return 0; +bad: + Py_XDECREF(ob); + return -1; +} + + +/////////////// GetVTable.proto /////////////// + +static void* __Pyx_GetVtable(PyObject *dict); /*proto*/ + +/////////////// GetVTable /////////////// + +static void* __Pyx_GetVtable(PyObject *dict) { + void* ptr; + PyObject *ob = PyObject_GetItem(dict, PYIDENT("__pyx_vtable__")); + if (!ob) + goto bad; +#if PY_VERSION_HEX >= 0x02070000 + ptr = PyCapsule_GetPointer(ob, 0); +#else + ptr = PyCObject_AsVoidPtr(ob); +#endif + if (!ptr && !PyErr_Occurred()) + PyErr_SetString(PyExc_RuntimeError, "invalid vtable found for imported type"); + Py_DECREF(ob); + return ptr; +bad: + Py_XDECREF(ob); + return NULL; +} /////////////// MergeVTables.proto /////////////// diff --git a/contrib/tools/cython/Cython/Utility/MemoryView.pyx b/contrib/tools/cython/Cython/Utility/MemoryView.pyx index 6ca5fab9ba..0b4386360d 100644 --- a/contrib/tools/cython/Cython/Utility/MemoryView.pyx +++ b/contrib/tools/cython/Cython/Utility/MemoryView.pyx @@ -1,313 +1,313 @@ -#################### View.MemoryView #################### - -# This utility provides cython.array and cython.view.memoryview - +#################### View.MemoryView #################### + +# This utility provides cython.array and cython.view.memoryview + from __future__ import absolute_import - + cimport cython -# from cpython cimport ... -cdef extern from "Python.h": - int PyIndex_Check(object) - object PyLong_FromVoidPtr(void *) - -cdef extern from "pythread.h": - ctypedef void *PyThread_type_lock - - PyThread_type_lock PyThread_allocate_lock() - void PyThread_free_lock(PyThread_type_lock) - int PyThread_acquire_lock(PyThread_type_lock, int mode) nogil - void PyThread_release_lock(PyThread_type_lock) nogil - +# from cpython cimport ... +cdef extern from "Python.h": + int PyIndex_Check(object) + object PyLong_FromVoidPtr(void *) + +cdef extern from "pythread.h": + ctypedef void *PyThread_type_lock + + PyThread_type_lock PyThread_allocate_lock() + void PyThread_free_lock(PyThread_type_lock) + int PyThread_acquire_lock(PyThread_type_lock, int mode) nogil + void PyThread_release_lock(PyThread_type_lock) nogil + cdef extern from "<string.h>": - void *memset(void *b, int c, size_t len) - -cdef extern from *: - int __Pyx_GetBuffer(object, Py_buffer *, int) except -1 - void __Pyx_ReleaseBuffer(Py_buffer *) - - ctypedef struct PyObject - ctypedef Py_ssize_t Py_intptr_t - void Py_INCREF(PyObject *) - void Py_DECREF(PyObject *) - - void* PyMem_Malloc(size_t n) - void PyMem_Free(void *p) + void *memset(void *b, int c, size_t len) + +cdef extern from *: + int __Pyx_GetBuffer(object, Py_buffer *, int) except -1 + void __Pyx_ReleaseBuffer(Py_buffer *) + + ctypedef struct PyObject + ctypedef Py_ssize_t Py_intptr_t + void Py_INCREF(PyObject *) + void Py_DECREF(PyObject *) + + void* PyMem_Malloc(size_t n) + void PyMem_Free(void *p) void* PyObject_Malloc(size_t n) void PyObject_Free(void *p) - - cdef struct __pyx_memoryview "__pyx_memoryview_obj": - Py_buffer view - PyObject *obj - __Pyx_TypeInfo *typeinfo - - ctypedef struct {{memviewslice_name}}: - __pyx_memoryview *memview - char *data - Py_ssize_t shape[{{max_dims}}] - Py_ssize_t strides[{{max_dims}}] - Py_ssize_t suboffsets[{{max_dims}}] - - void __PYX_INC_MEMVIEW({{memviewslice_name}} *memslice, int have_gil) - void __PYX_XDEC_MEMVIEW({{memviewslice_name}} *memslice, int have_gil) - - ctypedef struct __pyx_buffer "Py_buffer": - PyObject *obj - - PyObject *Py_None - - cdef enum: - PyBUF_C_CONTIGUOUS, - PyBUF_F_CONTIGUOUS, - PyBUF_ANY_CONTIGUOUS - PyBUF_FORMAT - PyBUF_WRITABLE - PyBUF_STRIDES - PyBUF_INDIRECT + + cdef struct __pyx_memoryview "__pyx_memoryview_obj": + Py_buffer view + PyObject *obj + __Pyx_TypeInfo *typeinfo + + ctypedef struct {{memviewslice_name}}: + __pyx_memoryview *memview + char *data + Py_ssize_t shape[{{max_dims}}] + Py_ssize_t strides[{{max_dims}}] + Py_ssize_t suboffsets[{{max_dims}}] + + void __PYX_INC_MEMVIEW({{memviewslice_name}} *memslice, int have_gil) + void __PYX_XDEC_MEMVIEW({{memviewslice_name}} *memslice, int have_gil) + + ctypedef struct __pyx_buffer "Py_buffer": + PyObject *obj + + PyObject *Py_None + + cdef enum: + PyBUF_C_CONTIGUOUS, + PyBUF_F_CONTIGUOUS, + PyBUF_ANY_CONTIGUOUS + PyBUF_FORMAT + PyBUF_WRITABLE + PyBUF_STRIDES + PyBUF_INDIRECT PyBUF_ND - PyBUF_RECORDS + PyBUF_RECORDS PyBUF_RECORDS_RO - - ctypedef struct __Pyx_TypeInfo: - pass - - cdef object capsule "__pyx_capsule_create" (void *p, char *sig) - cdef int __pyx_array_getbuffer(PyObject *obj, Py_buffer view, int flags) - cdef int __pyx_memoryview_getbuffer(PyObject *obj, Py_buffer view, int flags) - -cdef extern from *: - ctypedef int __pyx_atomic_int - {{memviewslice_name}} slice_copy_contig "__pyx_memoryview_copy_new_contig"( - __Pyx_memviewslice *from_mvs, - char *mode, int ndim, - size_t sizeof_dtype, int contig_flag, - bint dtype_is_object) nogil except * - bint slice_is_contig "__pyx_memviewslice_is_contig" ( + + ctypedef struct __Pyx_TypeInfo: + pass + + cdef object capsule "__pyx_capsule_create" (void *p, char *sig) + cdef int __pyx_array_getbuffer(PyObject *obj, Py_buffer view, int flags) + cdef int __pyx_memoryview_getbuffer(PyObject *obj, Py_buffer view, int flags) + +cdef extern from *: + ctypedef int __pyx_atomic_int + {{memviewslice_name}} slice_copy_contig "__pyx_memoryview_copy_new_contig"( + __Pyx_memviewslice *from_mvs, + char *mode, int ndim, + size_t sizeof_dtype, int contig_flag, + bint dtype_is_object) nogil except * + bint slice_is_contig "__pyx_memviewslice_is_contig" ( {{memviewslice_name}} mvs, char order, int ndim) nogil - bint slices_overlap "__pyx_slices_overlap" ({{memviewslice_name}} *slice1, - {{memviewslice_name}} *slice2, - int ndim, size_t itemsize) nogil - - + bint slices_overlap "__pyx_slices_overlap" ({{memviewslice_name}} *slice1, + {{memviewslice_name}} *slice2, + int ndim, size_t itemsize) nogil + + cdef extern from "<stdlib.h>": - void *malloc(size_t) nogil - void free(void *) nogil - void *memcpy(void *dest, void *src, size_t n) nogil - - - - -# -### cython.array class -# - -@cname("__pyx_array") -cdef class array: - - cdef: - char *data - Py_ssize_t len - char *format - int ndim - Py_ssize_t *_shape - Py_ssize_t *_strides - Py_ssize_t itemsize - unicode mode # FIXME: this should have been a simple 'char' - bytes _format - void (*callback_free_data)(void *data) - # cdef object _memview - cdef bint free_data - cdef bint dtype_is_object - - def __cinit__(array self, tuple shape, Py_ssize_t itemsize, format not None, - mode="c", bint allocate_buffer=True): - - cdef int idx - cdef Py_ssize_t i, dim - cdef PyObject **p - - self.ndim = <int> len(shape) - self.itemsize = itemsize - - if not self.ndim: - raise ValueError("Empty shape tuple for cython.array") - - if itemsize <= 0: - raise ValueError("itemsize <= 0 for cython.array") - + void *malloc(size_t) nogil + void free(void *) nogil + void *memcpy(void *dest, void *src, size_t n) nogil + + + + +# +### cython.array class +# + +@cname("__pyx_array") +cdef class array: + + cdef: + char *data + Py_ssize_t len + char *format + int ndim + Py_ssize_t *_shape + Py_ssize_t *_strides + Py_ssize_t itemsize + unicode mode # FIXME: this should have been a simple 'char' + bytes _format + void (*callback_free_data)(void *data) + # cdef object _memview + cdef bint free_data + cdef bint dtype_is_object + + def __cinit__(array self, tuple shape, Py_ssize_t itemsize, format not None, + mode="c", bint allocate_buffer=True): + + cdef int idx + cdef Py_ssize_t i, dim + cdef PyObject **p + + self.ndim = <int> len(shape) + self.itemsize = itemsize + + if not self.ndim: + raise ValueError("Empty shape tuple for cython.array") + + if itemsize <= 0: + raise ValueError("itemsize <= 0 for cython.array") + if not isinstance(format, bytes): format = format.encode('ASCII') - self._format = format # keep a reference to the byte string - self.format = self._format - - # use single malloc() for both shape and strides + self._format = format # keep a reference to the byte string + self.format = self._format + + # use single malloc() for both shape and strides self._shape = <Py_ssize_t *> PyObject_Malloc(sizeof(Py_ssize_t)*self.ndim*2) - self._strides = self._shape + self.ndim - - if not self._shape: - raise MemoryError("unable to allocate shape and strides.") - - # cdef Py_ssize_t dim, stride - for idx, dim in enumerate(shape): - if dim <= 0: - raise ValueError("Invalid shape in axis %d: %d." % (idx, dim)) - self._shape[idx] = dim - - cdef char order - if mode == 'fortran': - order = b'F' - self.mode = u'fortran' - elif mode == 'c': - order = b'C' - self.mode = u'c' - else: - raise ValueError("Invalid mode, expected 'c' or 'fortran', got %s" % mode) - - self.len = fill_contig_strides_array(self._shape, self._strides, - itemsize, self.ndim, order) - - self.free_data = allocate_buffer - self.dtype_is_object = format == b'O' - if allocate_buffer: - # use malloc() for backwards compatibility - # in case external code wants to change the data pointer - self.data = <char *>malloc(self.len) - if not self.data: - raise MemoryError("unable to allocate array data.") - - if self.dtype_is_object: - p = <PyObject **> self.data - for i in range(self.len / itemsize): - p[i] = Py_None - Py_INCREF(Py_None) - - @cname('getbuffer') - def __getbuffer__(self, Py_buffer *info, int flags): - cdef int bufmode = -1 - if self.mode == u"c": - bufmode = PyBUF_C_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS - elif self.mode == u"fortran": - bufmode = PyBUF_F_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS - if not (flags & bufmode): - raise ValueError("Can only create a buffer that is contiguous in memory.") - info.buf = self.data - info.len = self.len - info.ndim = self.ndim - info.shape = self._shape - info.strides = self._strides - info.suboffsets = NULL - info.itemsize = self.itemsize - info.readonly = 0 - - if flags & PyBUF_FORMAT: - info.format = self.format - else: - info.format = NULL - - info.obj = self - - __pyx_getbuffer = capsule(<void *> &__pyx_array_getbuffer, "getbuffer(obj, view, flags)") - - def __dealloc__(array self): - if self.callback_free_data != NULL: - self.callback_free_data(self.data) - elif self.free_data: - if self.dtype_is_object: - refcount_objects_in_slice(self.data, self._shape, - self._strides, self.ndim, False) - free(self.data) + self._strides = self._shape + self.ndim + + if not self._shape: + raise MemoryError("unable to allocate shape and strides.") + + # cdef Py_ssize_t dim, stride + for idx, dim in enumerate(shape): + if dim <= 0: + raise ValueError("Invalid shape in axis %d: %d." % (idx, dim)) + self._shape[idx] = dim + + cdef char order + if mode == 'fortran': + order = b'F' + self.mode = u'fortran' + elif mode == 'c': + order = b'C' + self.mode = u'c' + else: + raise ValueError("Invalid mode, expected 'c' or 'fortran', got %s" % mode) + + self.len = fill_contig_strides_array(self._shape, self._strides, + itemsize, self.ndim, order) + + self.free_data = allocate_buffer + self.dtype_is_object = format == b'O' + if allocate_buffer: + # use malloc() for backwards compatibility + # in case external code wants to change the data pointer + self.data = <char *>malloc(self.len) + if not self.data: + raise MemoryError("unable to allocate array data.") + + if self.dtype_is_object: + p = <PyObject **> self.data + for i in range(self.len / itemsize): + p[i] = Py_None + Py_INCREF(Py_None) + + @cname('getbuffer') + def __getbuffer__(self, Py_buffer *info, int flags): + cdef int bufmode = -1 + if self.mode == u"c": + bufmode = PyBUF_C_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS + elif self.mode == u"fortran": + bufmode = PyBUF_F_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS + if not (flags & bufmode): + raise ValueError("Can only create a buffer that is contiguous in memory.") + info.buf = self.data + info.len = self.len + info.ndim = self.ndim + info.shape = self._shape + info.strides = self._strides + info.suboffsets = NULL + info.itemsize = self.itemsize + info.readonly = 0 + + if flags & PyBUF_FORMAT: + info.format = self.format + else: + info.format = NULL + + info.obj = self + + __pyx_getbuffer = capsule(<void *> &__pyx_array_getbuffer, "getbuffer(obj, view, flags)") + + def __dealloc__(array self): + if self.callback_free_data != NULL: + self.callback_free_data(self.data) + elif self.free_data: + if self.dtype_is_object: + refcount_objects_in_slice(self.data, self._shape, + self._strides, self.ndim, False) + free(self.data) PyObject_Free(self._shape) - + @property def memview(self): return self.get_memview() - + @cname('get_memview') cdef get_memview(self): flags = PyBUF_ANY_CONTIGUOUS|PyBUF_FORMAT|PyBUF_WRITABLE return memoryview(self, flags, self.dtype_is_object) - + def __len__(self): return self._shape[0] - def __getattr__(self, attr): - return getattr(self.memview, attr) - - def __getitem__(self, item): - return self.memview[item] - - def __setitem__(self, item, value): - self.memview[item] = value - - -@cname("__pyx_array_new") -cdef array array_cwrapper(tuple shape, Py_ssize_t itemsize, char *format, - char *mode, char *buf): - cdef array result - - if buf == NULL: - result = array(shape, itemsize, format, mode.decode('ASCII')) - else: - result = array(shape, itemsize, format, mode.decode('ASCII'), - allocate_buffer=False) - result.data = buf - - return result - - -# -### Memoryview constants and cython.view.memoryview class -# - -# Disable generic_contiguous, as it makes trouble verifying contiguity: -# - 'contiguous' or '::1' means the dimension is contiguous with dtype -# - 'indirect_contiguous' means a contiguous list of pointers -# - dtype contiguous must be contiguous in the first or last dimension -# from the start, or from the dimension following the last indirect dimension -# -# e.g. -# int[::indirect_contiguous, ::contiguous, :] -# -# is valid (list of pointers to 2d fortran-contiguous array), but -# -# int[::generic_contiguous, ::contiguous, :] -# -# would mean you'd have assert dimension 0 to be indirect (and pointer contiguous) at runtime. -# So it doesn't bring any performance benefit, and it's only confusing. - -@cname('__pyx_MemviewEnum') -cdef class Enum(object): - cdef object name - def __init__(self, name): - self.name = name - def __repr__(self): - return self.name - -cdef generic = Enum("<strided and direct or indirect>") -cdef strided = Enum("<strided and direct>") # default -cdef indirect = Enum("<strided and indirect>") -# Disable generic_contiguous, as it is a troublemaker -#cdef generic_contiguous = Enum("<contiguous and direct or indirect>") -cdef contiguous = Enum("<contiguous and direct>") -cdef indirect_contiguous = Enum("<contiguous and indirect>") - -# 'follow' is implied when the first or last axis is ::1 - - -@cname('__pyx_align_pointer') -cdef void *align_pointer(void *memory, size_t alignment) nogil: - "Align pointer memory on a given boundary" - cdef Py_intptr_t aligned_p = <Py_intptr_t> memory - cdef size_t offset - - with cython.cdivision(True): - offset = aligned_p % alignment - - if offset > 0: - aligned_p += alignment - offset - - return <void *> aligned_p - + def __getattr__(self, attr): + return getattr(self.memview, attr) + + def __getitem__(self, item): + return self.memview[item] + + def __setitem__(self, item, value): + self.memview[item] = value + + +@cname("__pyx_array_new") +cdef array array_cwrapper(tuple shape, Py_ssize_t itemsize, char *format, + char *mode, char *buf): + cdef array result + + if buf == NULL: + result = array(shape, itemsize, format, mode.decode('ASCII')) + else: + result = array(shape, itemsize, format, mode.decode('ASCII'), + allocate_buffer=False) + result.data = buf + + return result + + +# +### Memoryview constants and cython.view.memoryview class +# + +# Disable generic_contiguous, as it makes trouble verifying contiguity: +# - 'contiguous' or '::1' means the dimension is contiguous with dtype +# - 'indirect_contiguous' means a contiguous list of pointers +# - dtype contiguous must be contiguous in the first or last dimension +# from the start, or from the dimension following the last indirect dimension +# +# e.g. +# int[::indirect_contiguous, ::contiguous, :] +# +# is valid (list of pointers to 2d fortran-contiguous array), but +# +# int[::generic_contiguous, ::contiguous, :] +# +# would mean you'd have assert dimension 0 to be indirect (and pointer contiguous) at runtime. +# So it doesn't bring any performance benefit, and it's only confusing. + +@cname('__pyx_MemviewEnum') +cdef class Enum(object): + cdef object name + def __init__(self, name): + self.name = name + def __repr__(self): + return self.name + +cdef generic = Enum("<strided and direct or indirect>") +cdef strided = Enum("<strided and direct>") # default +cdef indirect = Enum("<strided and indirect>") +# Disable generic_contiguous, as it is a troublemaker +#cdef generic_contiguous = Enum("<contiguous and direct or indirect>") +cdef contiguous = Enum("<contiguous and direct>") +cdef indirect_contiguous = Enum("<contiguous and indirect>") + +# 'follow' is implied when the first or last axis is ::1 + + +@cname('__pyx_align_pointer') +cdef void *align_pointer(void *memory, size_t alignment) nogil: + "Align pointer memory on a given boundary" + cdef Py_intptr_t aligned_p = <Py_intptr_t> memory + cdef size_t offset + + with cython.cdivision(True): + offset = aligned_p % alignment + + if offset > 0: + aligned_p += alignment - offset + + return <void *> aligned_p + # pre-allocate thread locks for reuse ## note that this could be implemented in a more beautiful way in "normal" Cython, @@ -326,31 +326,31 @@ cdef PyThread_type_lock[THREAD_LOCKS_PREALLOCATED] __pyx_memoryview_thread_locks ] -@cname('__pyx_memoryview') -cdef class memoryview(object): - - cdef object obj - cdef object _size - cdef object _array_interface - cdef PyThread_type_lock lock - # the following array will contain a single __pyx_atomic int with - # suitable alignment - cdef __pyx_atomic_int acquisition_count[2] - cdef __pyx_atomic_int *acquisition_count_aligned_p - cdef Py_buffer view - cdef int flags - cdef bint dtype_is_object - cdef __Pyx_TypeInfo *typeinfo - - def __cinit__(memoryview self, object obj, int flags, bint dtype_is_object=False): - self.obj = obj - self.flags = flags - if type(self) is memoryview or obj is not None: - __Pyx_GetBuffer(obj, &self.view, flags) - if <PyObject *> self.view.obj == NULL: - (<__pyx_buffer *> &self.view).obj = Py_None - Py_INCREF(Py_None) - +@cname('__pyx_memoryview') +cdef class memoryview(object): + + cdef object obj + cdef object _size + cdef object _array_interface + cdef PyThread_type_lock lock + # the following array will contain a single __pyx_atomic int with + # suitable alignment + cdef __pyx_atomic_int acquisition_count[2] + cdef __pyx_atomic_int *acquisition_count_aligned_p + cdef Py_buffer view + cdef int flags + cdef bint dtype_is_object + cdef __Pyx_TypeInfo *typeinfo + + def __cinit__(memoryview self, object obj, int flags, bint dtype_is_object=False): + self.obj = obj + self.flags = flags + if type(self) is memoryview or obj is not None: + __Pyx_GetBuffer(obj, &self.view, flags) + if <PyObject *> self.view.obj == NULL: + (<__pyx_buffer *> &self.view).obj = Py_None + Py_INCREF(Py_None) + global __pyx_memoryview_thread_locks_used if __pyx_memoryview_thread_locks_used < THREAD_LOCKS_PREALLOCATED: self.lock = __pyx_memoryview_thread_locks[__pyx_memoryview_thread_locks_used] @@ -359,27 +359,27 @@ cdef class memoryview(object): self.lock = PyThread_allocate_lock() if self.lock is NULL: raise MemoryError - - if flags & PyBUF_FORMAT: + + if flags & PyBUF_FORMAT: self.dtype_is_object = (self.view.format[0] == b'O' and self.view.format[1] == b'\0') - else: - self.dtype_is_object = dtype_is_object - - self.acquisition_count_aligned_p = <__pyx_atomic_int *> align_pointer( - <void *> &self.acquisition_count[0], sizeof(__pyx_atomic_int)) - self.typeinfo = NULL - - def __dealloc__(memoryview self): - if self.obj is not None: - __Pyx_ReleaseBuffer(&self.view) + else: + self.dtype_is_object = dtype_is_object + + self.acquisition_count_aligned_p = <__pyx_atomic_int *> align_pointer( + <void *> &self.acquisition_count[0], sizeof(__pyx_atomic_int)) + self.typeinfo = NULL + + def __dealloc__(memoryview self): + if self.obj is not None: + __Pyx_ReleaseBuffer(&self.view) elif (<__pyx_buffer *> &self.view).obj == Py_None: # Undo the incref in __cinit__() above. (<__pyx_buffer *> &self.view).obj = NULL Py_DECREF(Py_None) - + cdef int i global __pyx_memoryview_thread_locks_used - if self.lock != NULL: + if self.lock != NULL: for i in range(__pyx_memoryview_thread_locks_used): if __pyx_memoryview_thread_locks[i] is self.lock: __pyx_memoryview_thread_locks_used -= 1 @@ -389,649 +389,649 @@ cdef class memoryview(object): break else: PyThread_free_lock(self.lock) - - cdef char *get_item_pointer(memoryview self, object index) except NULL: - cdef Py_ssize_t dim - cdef char *itemp = <char *> self.view.buf - - for dim, idx in enumerate(index): - itemp = pybuffer_index(&self.view, itemp, idx, dim) - - return itemp - - #@cname('__pyx_memoryview_getitem') - def __getitem__(memoryview self, object index): - if index is Ellipsis: - return self - - have_slices, indices = _unellipsify(index, self.view.ndim) - - cdef char *itemp - if have_slices: - return memview_slice(self, indices) - else: - itemp = self.get_item_pointer(indices) - return self.convert_item_to_object(itemp) - - def __setitem__(memoryview self, object index, object value): + + cdef char *get_item_pointer(memoryview self, object index) except NULL: + cdef Py_ssize_t dim + cdef char *itemp = <char *> self.view.buf + + for dim, idx in enumerate(index): + itemp = pybuffer_index(&self.view, itemp, idx, dim) + + return itemp + + #@cname('__pyx_memoryview_getitem') + def __getitem__(memoryview self, object index): + if index is Ellipsis: + return self + + have_slices, indices = _unellipsify(index, self.view.ndim) + + cdef char *itemp + if have_slices: + return memview_slice(self, indices) + else: + itemp = self.get_item_pointer(indices) + return self.convert_item_to_object(itemp) + + def __setitem__(memoryview self, object index, object value): if self.view.readonly: raise TypeError("Cannot assign to read-only memoryview") - have_slices, index = _unellipsify(index, self.view.ndim) - - if have_slices: - obj = self.is_slice(value) - if obj: - self.setitem_slice_assignment(self[index], obj) - else: - self.setitem_slice_assign_scalar(self[index], value) - else: - self.setitem_indexed(index, value) - - cdef is_slice(self, obj): - if not isinstance(obj, memoryview): - try: + have_slices, index = _unellipsify(index, self.view.ndim) + + if have_slices: + obj = self.is_slice(value) + if obj: + self.setitem_slice_assignment(self[index], obj) + else: + self.setitem_slice_assign_scalar(self[index], value) + else: + self.setitem_indexed(index, value) + + cdef is_slice(self, obj): + if not isinstance(obj, memoryview): + try: obj = memoryview(obj, self.flags & ~PyBUF_WRITABLE | PyBUF_ANY_CONTIGUOUS, - self.dtype_is_object) - except TypeError: - return None - - return obj - - cdef setitem_slice_assignment(self, dst, src): - cdef {{memviewslice_name}} dst_slice - cdef {{memviewslice_name}} src_slice - - memoryview_copy_contents(get_slice_from_memview(src, &src_slice)[0], - get_slice_from_memview(dst, &dst_slice)[0], - src.ndim, dst.ndim, self.dtype_is_object) - - cdef setitem_slice_assign_scalar(self, memoryview dst, value): - cdef int array[128] - cdef void *tmp = NULL - cdef void *item - - cdef {{memviewslice_name}} *dst_slice - cdef {{memviewslice_name}} tmp_slice - dst_slice = get_slice_from_memview(dst, &tmp_slice) - - if <size_t>self.view.itemsize > sizeof(array): - tmp = PyMem_Malloc(self.view.itemsize) - if tmp == NULL: - raise MemoryError - item = tmp - else: - item = <void *> array - - try: - if self.dtype_is_object: - (<PyObject **> item)[0] = <PyObject *> value - else: - self.assign_item_from_object(<char *> item, value) - - # It would be easy to support indirect dimensions, but it's easier - # to disallow :) - if self.view.suboffsets != NULL: - assert_direct_dimensions(self.view.suboffsets, self.view.ndim) - slice_assign_scalar(dst_slice, dst.view.ndim, self.view.itemsize, - item, self.dtype_is_object) - finally: - PyMem_Free(tmp) - - cdef setitem_indexed(self, index, value): - cdef char *itemp = self.get_item_pointer(index) - self.assign_item_from_object(itemp, value) - - cdef convert_item_to_object(self, char *itemp): - """Only used if instantiated manually by the user, or if Cython doesn't - know how to convert the type""" - import struct - cdef bytes bytesitem - # Do a manual and complete check here instead of this easy hack - bytesitem = itemp[:self.view.itemsize] - try: - result = struct.unpack(self.view.format, bytesitem) - except struct.error: - raise ValueError("Unable to convert item to object") - else: - if len(self.view.format) == 1: - return result[0] - return result - - cdef assign_item_from_object(self, char *itemp, object value): - """Only used if instantiated manually by the user, or if Cython doesn't - know how to convert the type""" - import struct - cdef char c - cdef bytes bytesvalue - cdef Py_ssize_t i - - if isinstance(value, tuple): - bytesvalue = struct.pack(self.view.format, *value) - else: - bytesvalue = struct.pack(self.view.format, value) - - for i, c in enumerate(bytesvalue): - itemp[i] = c - - @cname('getbuffer') - def __getbuffer__(self, Py_buffer *info, int flags): + self.dtype_is_object) + except TypeError: + return None + + return obj + + cdef setitem_slice_assignment(self, dst, src): + cdef {{memviewslice_name}} dst_slice + cdef {{memviewslice_name}} src_slice + + memoryview_copy_contents(get_slice_from_memview(src, &src_slice)[0], + get_slice_from_memview(dst, &dst_slice)[0], + src.ndim, dst.ndim, self.dtype_is_object) + + cdef setitem_slice_assign_scalar(self, memoryview dst, value): + cdef int array[128] + cdef void *tmp = NULL + cdef void *item + + cdef {{memviewslice_name}} *dst_slice + cdef {{memviewslice_name}} tmp_slice + dst_slice = get_slice_from_memview(dst, &tmp_slice) + + if <size_t>self.view.itemsize > sizeof(array): + tmp = PyMem_Malloc(self.view.itemsize) + if tmp == NULL: + raise MemoryError + item = tmp + else: + item = <void *> array + + try: + if self.dtype_is_object: + (<PyObject **> item)[0] = <PyObject *> value + else: + self.assign_item_from_object(<char *> item, value) + + # It would be easy to support indirect dimensions, but it's easier + # to disallow :) + if self.view.suboffsets != NULL: + assert_direct_dimensions(self.view.suboffsets, self.view.ndim) + slice_assign_scalar(dst_slice, dst.view.ndim, self.view.itemsize, + item, self.dtype_is_object) + finally: + PyMem_Free(tmp) + + cdef setitem_indexed(self, index, value): + cdef char *itemp = self.get_item_pointer(index) + self.assign_item_from_object(itemp, value) + + cdef convert_item_to_object(self, char *itemp): + """Only used if instantiated manually by the user, or if Cython doesn't + know how to convert the type""" + import struct + cdef bytes bytesitem + # Do a manual and complete check here instead of this easy hack + bytesitem = itemp[:self.view.itemsize] + try: + result = struct.unpack(self.view.format, bytesitem) + except struct.error: + raise ValueError("Unable to convert item to object") + else: + if len(self.view.format) == 1: + return result[0] + return result + + cdef assign_item_from_object(self, char *itemp, object value): + """Only used if instantiated manually by the user, or if Cython doesn't + know how to convert the type""" + import struct + cdef char c + cdef bytes bytesvalue + cdef Py_ssize_t i + + if isinstance(value, tuple): + bytesvalue = struct.pack(self.view.format, *value) + else: + bytesvalue = struct.pack(self.view.format, value) + + for i, c in enumerate(bytesvalue): + itemp[i] = c + + @cname('getbuffer') + def __getbuffer__(self, Py_buffer *info, int flags): if flags & PyBUF_WRITABLE and self.view.readonly: raise ValueError("Cannot create writable memory view from read-only memoryview") if flags & PyBUF_ND: - info.shape = self.view.shape - else: - info.shape = NULL - - if flags & PyBUF_STRIDES: - info.strides = self.view.strides - else: - info.strides = NULL - - if flags & PyBUF_INDIRECT: - info.suboffsets = self.view.suboffsets - else: - info.suboffsets = NULL - - if flags & PyBUF_FORMAT: - info.format = self.view.format - else: - info.format = NULL - - info.buf = self.view.buf - info.ndim = self.view.ndim - info.itemsize = self.view.itemsize - info.len = self.view.len + info.shape = self.view.shape + else: + info.shape = NULL + + if flags & PyBUF_STRIDES: + info.strides = self.view.strides + else: + info.strides = NULL + + if flags & PyBUF_INDIRECT: + info.suboffsets = self.view.suboffsets + else: + info.suboffsets = NULL + + if flags & PyBUF_FORMAT: + info.format = self.view.format + else: + info.format = NULL + + info.buf = self.view.buf + info.ndim = self.view.ndim + info.itemsize = self.view.itemsize + info.len = self.view.len info.readonly = self.view.readonly - info.obj = self - - __pyx_getbuffer = capsule(<void *> &__pyx_memoryview_getbuffer, "getbuffer(obj, view, flags)") - + info.obj = self + + __pyx_getbuffer = capsule(<void *> &__pyx_memoryview_getbuffer, "getbuffer(obj, view, flags)") + # Some properties that have the same semantics as in NumPy @property def T(self): cdef _memoryviewslice result = memoryview_copy(self) transpose_memslice(&result.from_slice) return result - + @property def base(self): return self.obj - + @property def shape(self): return tuple([length for length in self.view.shape[:self.view.ndim]]) - + @property def strides(self): if self.view.strides == NULL: # Note: we always ask for strides, so if this is not set it's a bug raise ValueError("Buffer view does not expose strides") - + return tuple([stride for stride in self.view.strides[:self.view.ndim]]) - + @property def suboffsets(self): if self.view.suboffsets == NULL: return (-1,) * self.view.ndim - + return tuple([suboffset for suboffset in self.view.suboffsets[:self.view.ndim]]) - + @property def ndim(self): return self.view.ndim - + @property def itemsize(self): return self.view.itemsize - + @property def nbytes(self): return self.size * self.view.itemsize - + @property def size(self): if self._size is None: result = 1 - + for length in self.view.shape[:self.view.ndim]: result *= length - + self._size = result - + return self._size - - def __len__(self): - if self.view.ndim >= 1: - return self.view.shape[0] - - return 0 - - def __repr__(self): - return "<MemoryView of %r at 0x%x>" % (self.base.__class__.__name__, - id(self)) - - def __str__(self): - return "<MemoryView of %r object>" % (self.base.__class__.__name__,) - - # Support the same attributes as memoryview slices - def is_c_contig(self): - cdef {{memviewslice_name}} *mslice - cdef {{memviewslice_name}} tmp - mslice = get_slice_from_memview(self, &tmp) + + def __len__(self): + if self.view.ndim >= 1: + return self.view.shape[0] + + return 0 + + def __repr__(self): + return "<MemoryView of %r at 0x%x>" % (self.base.__class__.__name__, + id(self)) + + def __str__(self): + return "<MemoryView of %r object>" % (self.base.__class__.__name__,) + + # Support the same attributes as memoryview slices + def is_c_contig(self): + cdef {{memviewslice_name}} *mslice + cdef {{memviewslice_name}} tmp + mslice = get_slice_from_memview(self, &tmp) return slice_is_contig(mslice[0], 'C', self.view.ndim) - - def is_f_contig(self): - cdef {{memviewslice_name}} *mslice - cdef {{memviewslice_name}} tmp - mslice = get_slice_from_memview(self, &tmp) + + def is_f_contig(self): + cdef {{memviewslice_name}} *mslice + cdef {{memviewslice_name}} tmp + mslice = get_slice_from_memview(self, &tmp) return slice_is_contig(mslice[0], 'F', self.view.ndim) - - def copy(self): - cdef {{memviewslice_name}} mslice - cdef int flags = self.flags & ~PyBUF_F_CONTIGUOUS - - slice_copy(self, &mslice) - mslice = slice_copy_contig(&mslice, "c", self.view.ndim, - self.view.itemsize, - flags|PyBUF_C_CONTIGUOUS, - self.dtype_is_object) - - return memoryview_copy_from_slice(self, &mslice) - - def copy_fortran(self): - cdef {{memviewslice_name}} src, dst - cdef int flags = self.flags & ~PyBUF_C_CONTIGUOUS - - slice_copy(self, &src) - dst = slice_copy_contig(&src, "fortran", self.view.ndim, - self.view.itemsize, - flags|PyBUF_F_CONTIGUOUS, - self.dtype_is_object) - - return memoryview_copy_from_slice(self, &dst) - - -@cname('__pyx_memoryview_new') -cdef memoryview_cwrapper(object o, int flags, bint dtype_is_object, __Pyx_TypeInfo *typeinfo): - cdef memoryview result = memoryview(o, flags, dtype_is_object) - result.typeinfo = typeinfo - return result - -@cname('__pyx_memoryview_check') -cdef inline bint memoryview_check(object o): - return isinstance(o, memoryview) - -cdef tuple _unellipsify(object index, int ndim): - """ - Replace all ellipses with full slices and fill incomplete indices with - full slices. - """ - if not isinstance(index, tuple): - tup = (index,) - else: - tup = index - - result = [] - have_slices = False - seen_ellipsis = False - for idx, item in enumerate(tup): - if item is Ellipsis: - if not seen_ellipsis: - result.extend([slice(None)] * (ndim - len(tup) + 1)) - seen_ellipsis = True - else: - result.append(slice(None)) - have_slices = True - else: - if not isinstance(item, slice) and not PyIndex_Check(item): - raise TypeError("Cannot index with type '%s'" % type(item)) - - have_slices = have_slices or isinstance(item, slice) - result.append(item) - - nslices = ndim - len(result) - if nslices: - result.extend([slice(None)] * nslices) - - return have_slices or nslices, tuple(result) - -cdef assert_direct_dimensions(Py_ssize_t *suboffsets, int ndim): + + def copy(self): + cdef {{memviewslice_name}} mslice + cdef int flags = self.flags & ~PyBUF_F_CONTIGUOUS + + slice_copy(self, &mslice) + mslice = slice_copy_contig(&mslice, "c", self.view.ndim, + self.view.itemsize, + flags|PyBUF_C_CONTIGUOUS, + self.dtype_is_object) + + return memoryview_copy_from_slice(self, &mslice) + + def copy_fortran(self): + cdef {{memviewslice_name}} src, dst + cdef int flags = self.flags & ~PyBUF_C_CONTIGUOUS + + slice_copy(self, &src) + dst = slice_copy_contig(&src, "fortran", self.view.ndim, + self.view.itemsize, + flags|PyBUF_F_CONTIGUOUS, + self.dtype_is_object) + + return memoryview_copy_from_slice(self, &dst) + + +@cname('__pyx_memoryview_new') +cdef memoryview_cwrapper(object o, int flags, bint dtype_is_object, __Pyx_TypeInfo *typeinfo): + cdef memoryview result = memoryview(o, flags, dtype_is_object) + result.typeinfo = typeinfo + return result + +@cname('__pyx_memoryview_check') +cdef inline bint memoryview_check(object o): + return isinstance(o, memoryview) + +cdef tuple _unellipsify(object index, int ndim): + """ + Replace all ellipses with full slices and fill incomplete indices with + full slices. + """ + if not isinstance(index, tuple): + tup = (index,) + else: + tup = index + + result = [] + have_slices = False + seen_ellipsis = False + for idx, item in enumerate(tup): + if item is Ellipsis: + if not seen_ellipsis: + result.extend([slice(None)] * (ndim - len(tup) + 1)) + seen_ellipsis = True + else: + result.append(slice(None)) + have_slices = True + else: + if not isinstance(item, slice) and not PyIndex_Check(item): + raise TypeError("Cannot index with type '%s'" % type(item)) + + have_slices = have_slices or isinstance(item, slice) + result.append(item) + + nslices = ndim - len(result) + if nslices: + result.extend([slice(None)] * nslices) + + return have_slices or nslices, tuple(result) + +cdef assert_direct_dimensions(Py_ssize_t *suboffsets, int ndim): for suboffset in suboffsets[:ndim]: if suboffset >= 0: - raise ValueError("Indirect dimensions not supported") - -# -### Slicing a memoryview -# - -@cname('__pyx_memview_slice') -cdef memoryview memview_slice(memoryview memview, object indices): - cdef int new_ndim = 0, suboffset_dim = -1, dim - cdef bint negative_step - cdef {{memviewslice_name}} src, dst - cdef {{memviewslice_name}} *p_src - - # dst is copied by value in memoryview_fromslice -- initialize it - # src is never copied - memset(&dst, 0, sizeof(dst)) - - cdef _memoryviewslice memviewsliceobj - - assert memview.view.ndim > 0 - - if isinstance(memview, _memoryviewslice): - memviewsliceobj = memview - p_src = &memviewsliceobj.from_slice - else: - slice_copy(memview, &src) - p_src = &src - - # Note: don't use variable src at this point - # SubNote: we should be able to declare variables in blocks... - - # memoryview_fromslice() will inc our dst slice - dst.memview = p_src.memview - dst.data = p_src.data - - # Put everything in temps to avoid this bloody warning: - # "Argument evaluation order in C function call is undefined and - # may not be as expected" - cdef {{memviewslice_name}} *p_dst = &dst - cdef int *p_suboffset_dim = &suboffset_dim - cdef Py_ssize_t start, stop, step - cdef bint have_start, have_stop, have_step - - for dim, index in enumerate(indices): - if PyIndex_Check(index): - slice_memviewslice( - p_dst, p_src.shape[dim], p_src.strides[dim], p_src.suboffsets[dim], - dim, new_ndim, p_suboffset_dim, - index, 0, 0, # start, stop, step - 0, 0, 0, # have_{start,stop,step} - False) - elif index is None: - p_dst.shape[new_ndim] = 1 - p_dst.strides[new_ndim] = 0 - p_dst.suboffsets[new_ndim] = -1 - new_ndim += 1 - else: - start = index.start or 0 - stop = index.stop or 0 - step = index.step or 0 - - have_start = index.start is not None - have_stop = index.stop is not None - have_step = index.step is not None - - slice_memviewslice( - p_dst, p_src.shape[dim], p_src.strides[dim], p_src.suboffsets[dim], - dim, new_ndim, p_suboffset_dim, - start, stop, step, - have_start, have_stop, have_step, - True) - new_ndim += 1 - - if isinstance(memview, _memoryviewslice): - return memoryview_fromslice(dst, new_ndim, - memviewsliceobj.to_object_func, - memviewsliceobj.to_dtype_func, - memview.dtype_is_object) - else: - return memoryview_fromslice(dst, new_ndim, NULL, NULL, - memview.dtype_is_object) - - -# -### Slicing in a single dimension of a memoryviewslice -# - + raise ValueError("Indirect dimensions not supported") + +# +### Slicing a memoryview +# + +@cname('__pyx_memview_slice') +cdef memoryview memview_slice(memoryview memview, object indices): + cdef int new_ndim = 0, suboffset_dim = -1, dim + cdef bint negative_step + cdef {{memviewslice_name}} src, dst + cdef {{memviewslice_name}} *p_src + + # dst is copied by value in memoryview_fromslice -- initialize it + # src is never copied + memset(&dst, 0, sizeof(dst)) + + cdef _memoryviewslice memviewsliceobj + + assert memview.view.ndim > 0 + + if isinstance(memview, _memoryviewslice): + memviewsliceobj = memview + p_src = &memviewsliceobj.from_slice + else: + slice_copy(memview, &src) + p_src = &src + + # Note: don't use variable src at this point + # SubNote: we should be able to declare variables in blocks... + + # memoryview_fromslice() will inc our dst slice + dst.memview = p_src.memview + dst.data = p_src.data + + # Put everything in temps to avoid this bloody warning: + # "Argument evaluation order in C function call is undefined and + # may not be as expected" + cdef {{memviewslice_name}} *p_dst = &dst + cdef int *p_suboffset_dim = &suboffset_dim + cdef Py_ssize_t start, stop, step + cdef bint have_start, have_stop, have_step + + for dim, index in enumerate(indices): + if PyIndex_Check(index): + slice_memviewslice( + p_dst, p_src.shape[dim], p_src.strides[dim], p_src.suboffsets[dim], + dim, new_ndim, p_suboffset_dim, + index, 0, 0, # start, stop, step + 0, 0, 0, # have_{start,stop,step} + False) + elif index is None: + p_dst.shape[new_ndim] = 1 + p_dst.strides[new_ndim] = 0 + p_dst.suboffsets[new_ndim] = -1 + new_ndim += 1 + else: + start = index.start or 0 + stop = index.stop or 0 + step = index.step or 0 + + have_start = index.start is not None + have_stop = index.stop is not None + have_step = index.step is not None + + slice_memviewslice( + p_dst, p_src.shape[dim], p_src.strides[dim], p_src.suboffsets[dim], + dim, new_ndim, p_suboffset_dim, + start, stop, step, + have_start, have_stop, have_step, + True) + new_ndim += 1 + + if isinstance(memview, _memoryviewslice): + return memoryview_fromslice(dst, new_ndim, + memviewsliceobj.to_object_func, + memviewsliceobj.to_dtype_func, + memview.dtype_is_object) + else: + return memoryview_fromslice(dst, new_ndim, NULL, NULL, + memview.dtype_is_object) + + +# +### Slicing in a single dimension of a memoryviewslice +# + cdef extern from "<stdlib.h>": - void abort() nogil - void printf(char *s, ...) nogil - + void abort() nogil + void printf(char *s, ...) nogil + cdef extern from "<stdio.h>": - ctypedef struct FILE - FILE *stderr - int fputs(char *s, FILE *stream) - -cdef extern from "pystate.h": - void PyThreadState_Get() nogil - - # These are not actually nogil, but we check for the GIL before calling them - void PyErr_SetString(PyObject *type, char *msg) nogil - PyObject *PyErr_Format(PyObject *exc, char *msg, ...) nogil - -@cname('__pyx_memoryview_slice_memviewslice') -cdef int slice_memviewslice( - {{memviewslice_name}} *dst, - Py_ssize_t shape, Py_ssize_t stride, Py_ssize_t suboffset, - int dim, int new_ndim, int *suboffset_dim, - Py_ssize_t start, Py_ssize_t stop, Py_ssize_t step, - int have_start, int have_stop, int have_step, - bint is_slice) nogil except -1: - """ - Create a new slice dst given slice src. - - dim - the current src dimension (indexing will make dimensions - disappear) - new_dim - the new dst dimension - suboffset_dim - pointer to a single int initialized to -1 to keep track of - where slicing offsets should be added - """ - - cdef Py_ssize_t new_shape - cdef bint negative_step - - if not is_slice: - # index is a normal integer-like index - if start < 0: - start += shape - if not 0 <= start < shape: - _err_dim(IndexError, "Index out of bounds (axis %d)", dim) - else: - # index is a slice - negative_step = have_step != 0 and step < 0 - - if have_step and step == 0: - _err_dim(ValueError, "Step may not be zero (axis %d)", dim) - - # check our bounds and set defaults - if have_start: - if start < 0: - start += shape - if start < 0: - start = 0 - elif start >= shape: - if negative_step: - start = shape - 1 - else: - start = shape - else: - if negative_step: - start = shape - 1 - else: - start = 0 - - if have_stop: - if stop < 0: - stop += shape - if stop < 0: - stop = 0 - elif stop > shape: - stop = shape - else: - if negative_step: - stop = -1 - else: - stop = shape - - if not have_step: - step = 1 - - # len = ceil( (stop - start) / step ) - with cython.cdivision(True): - new_shape = (stop - start) // step - - if (stop - start) - step * new_shape: - new_shape += 1 - - if new_shape < 0: - new_shape = 0 - - # shape/strides/suboffsets - dst.strides[new_ndim] = stride * step - dst.shape[new_ndim] = new_shape - dst.suboffsets[new_ndim] = suboffset - - # Add the slicing or idexing offsets to the right suboffset or base data * - if suboffset_dim[0] < 0: - dst.data += start * stride - else: - dst.suboffsets[suboffset_dim[0]] += start * stride - - if suboffset >= 0: - if not is_slice: - if new_ndim == 0: - dst.data = (<char **> dst.data)[0] + suboffset - else: - _err_dim(IndexError, "All dimensions preceding dimension %d " - "must be indexed and not sliced", dim) - else: - suboffset_dim[0] = new_ndim - - return 0 - -# -### Index a memoryview -# -@cname('__pyx_pybuffer_index') -cdef char *pybuffer_index(Py_buffer *view, char *bufp, Py_ssize_t index, - Py_ssize_t dim) except NULL: - cdef Py_ssize_t shape, stride, suboffset = -1 - cdef Py_ssize_t itemsize = view.itemsize - cdef char *resultp - - if view.ndim == 0: - shape = view.len / itemsize - stride = itemsize - else: - shape = view.shape[dim] - stride = view.strides[dim] - if view.suboffsets != NULL: - suboffset = view.suboffsets[dim] - - if index < 0: - index += view.shape[dim] - if index < 0: - raise IndexError("Out of bounds on buffer access (axis %d)" % dim) - - if index >= shape: - raise IndexError("Out of bounds on buffer access (axis %d)" % dim) - - resultp = bufp + index * stride - if suboffset >= 0: - resultp = (<char **> resultp)[0] + suboffset - - return resultp - -# -### Transposing a memoryviewslice -# -@cname('__pyx_memslice_transpose') -cdef int transpose_memslice({{memviewslice_name}} *memslice) nogil except 0: - cdef int ndim = memslice.memview.view.ndim - - cdef Py_ssize_t *shape = memslice.shape - cdef Py_ssize_t *strides = memslice.strides - - # reverse strides and shape - cdef int i, j - for i in range(ndim / 2): - j = ndim - 1 - i - strides[i], strides[j] = strides[j], strides[i] - shape[i], shape[j] = shape[j], shape[i] - - if memslice.suboffsets[i] >= 0 or memslice.suboffsets[j] >= 0: - _err(ValueError, "Cannot transpose memoryview with indirect dimensions") - - return 1 - -# -### Creating new memoryview objects from slices and memoryviews -# -@cname('__pyx_memoryviewslice') -cdef class _memoryviewslice(memoryview): - "Internal class for passing memoryview slices to Python" - - # We need this to keep our shape/strides/suboffset pointers valid - cdef {{memviewslice_name}} from_slice - # We need this only to print it's class' name - cdef object from_object - - cdef object (*to_object_func)(char *) - cdef int (*to_dtype_func)(char *, object) except 0 - - def __dealloc__(self): - __PYX_XDEC_MEMVIEW(&self.from_slice, 1) - - cdef convert_item_to_object(self, char *itemp): - if self.to_object_func != NULL: - return self.to_object_func(itemp) - else: - return memoryview.convert_item_to_object(self, itemp) - - cdef assign_item_from_object(self, char *itemp, object value): - if self.to_dtype_func != NULL: - self.to_dtype_func(itemp, value) - else: - memoryview.assign_item_from_object(self, itemp, value) - + ctypedef struct FILE + FILE *stderr + int fputs(char *s, FILE *stream) + +cdef extern from "pystate.h": + void PyThreadState_Get() nogil + + # These are not actually nogil, but we check for the GIL before calling them + void PyErr_SetString(PyObject *type, char *msg) nogil + PyObject *PyErr_Format(PyObject *exc, char *msg, ...) nogil + +@cname('__pyx_memoryview_slice_memviewslice') +cdef int slice_memviewslice( + {{memviewslice_name}} *dst, + Py_ssize_t shape, Py_ssize_t stride, Py_ssize_t suboffset, + int dim, int new_ndim, int *suboffset_dim, + Py_ssize_t start, Py_ssize_t stop, Py_ssize_t step, + int have_start, int have_stop, int have_step, + bint is_slice) nogil except -1: + """ + Create a new slice dst given slice src. + + dim - the current src dimension (indexing will make dimensions + disappear) + new_dim - the new dst dimension + suboffset_dim - pointer to a single int initialized to -1 to keep track of + where slicing offsets should be added + """ + + cdef Py_ssize_t new_shape + cdef bint negative_step + + if not is_slice: + # index is a normal integer-like index + if start < 0: + start += shape + if not 0 <= start < shape: + _err_dim(IndexError, "Index out of bounds (axis %d)", dim) + else: + # index is a slice + negative_step = have_step != 0 and step < 0 + + if have_step and step == 0: + _err_dim(ValueError, "Step may not be zero (axis %d)", dim) + + # check our bounds and set defaults + if have_start: + if start < 0: + start += shape + if start < 0: + start = 0 + elif start >= shape: + if negative_step: + start = shape - 1 + else: + start = shape + else: + if negative_step: + start = shape - 1 + else: + start = 0 + + if have_stop: + if stop < 0: + stop += shape + if stop < 0: + stop = 0 + elif stop > shape: + stop = shape + else: + if negative_step: + stop = -1 + else: + stop = shape + + if not have_step: + step = 1 + + # len = ceil( (stop - start) / step ) + with cython.cdivision(True): + new_shape = (stop - start) // step + + if (stop - start) - step * new_shape: + new_shape += 1 + + if new_shape < 0: + new_shape = 0 + + # shape/strides/suboffsets + dst.strides[new_ndim] = stride * step + dst.shape[new_ndim] = new_shape + dst.suboffsets[new_ndim] = suboffset + + # Add the slicing or idexing offsets to the right suboffset or base data * + if suboffset_dim[0] < 0: + dst.data += start * stride + else: + dst.suboffsets[suboffset_dim[0]] += start * stride + + if suboffset >= 0: + if not is_slice: + if new_ndim == 0: + dst.data = (<char **> dst.data)[0] + suboffset + else: + _err_dim(IndexError, "All dimensions preceding dimension %d " + "must be indexed and not sliced", dim) + else: + suboffset_dim[0] = new_ndim + + return 0 + +# +### Index a memoryview +# +@cname('__pyx_pybuffer_index') +cdef char *pybuffer_index(Py_buffer *view, char *bufp, Py_ssize_t index, + Py_ssize_t dim) except NULL: + cdef Py_ssize_t shape, stride, suboffset = -1 + cdef Py_ssize_t itemsize = view.itemsize + cdef char *resultp + + if view.ndim == 0: + shape = view.len / itemsize + stride = itemsize + else: + shape = view.shape[dim] + stride = view.strides[dim] + if view.suboffsets != NULL: + suboffset = view.suboffsets[dim] + + if index < 0: + index += view.shape[dim] + if index < 0: + raise IndexError("Out of bounds on buffer access (axis %d)" % dim) + + if index >= shape: + raise IndexError("Out of bounds on buffer access (axis %d)" % dim) + + resultp = bufp + index * stride + if suboffset >= 0: + resultp = (<char **> resultp)[0] + suboffset + + return resultp + +# +### Transposing a memoryviewslice +# +@cname('__pyx_memslice_transpose') +cdef int transpose_memslice({{memviewslice_name}} *memslice) nogil except 0: + cdef int ndim = memslice.memview.view.ndim + + cdef Py_ssize_t *shape = memslice.shape + cdef Py_ssize_t *strides = memslice.strides + + # reverse strides and shape + cdef int i, j + for i in range(ndim / 2): + j = ndim - 1 - i + strides[i], strides[j] = strides[j], strides[i] + shape[i], shape[j] = shape[j], shape[i] + + if memslice.suboffsets[i] >= 0 or memslice.suboffsets[j] >= 0: + _err(ValueError, "Cannot transpose memoryview with indirect dimensions") + + return 1 + +# +### Creating new memoryview objects from slices and memoryviews +# +@cname('__pyx_memoryviewslice') +cdef class _memoryviewslice(memoryview): + "Internal class for passing memoryview slices to Python" + + # We need this to keep our shape/strides/suboffset pointers valid + cdef {{memviewslice_name}} from_slice + # We need this only to print it's class' name + cdef object from_object + + cdef object (*to_object_func)(char *) + cdef int (*to_dtype_func)(char *, object) except 0 + + def __dealloc__(self): + __PYX_XDEC_MEMVIEW(&self.from_slice, 1) + + cdef convert_item_to_object(self, char *itemp): + if self.to_object_func != NULL: + return self.to_object_func(itemp) + else: + return memoryview.convert_item_to_object(self, itemp) + + cdef assign_item_from_object(self, char *itemp, object value): + if self.to_dtype_func != NULL: + self.to_dtype_func(itemp, value) + else: + memoryview.assign_item_from_object(self, itemp, value) + @property def base(self): return self.from_object - - __pyx_getbuffer = capsule(<void *> &__pyx_memoryview_getbuffer, "getbuffer(obj, view, flags)") - - -@cname('__pyx_memoryview_fromslice') -cdef memoryview_fromslice({{memviewslice_name}} memviewslice, - int ndim, - object (*to_object_func)(char *), - int (*to_dtype_func)(char *, object) except 0, - bint dtype_is_object): - - cdef _memoryviewslice result - - if <PyObject *> memviewslice.memview == Py_None: - return None - - # assert 0 < ndim <= memviewslice.memview.view.ndim, ( - # ndim, memviewslice.memview.view.ndim) - - result = _memoryviewslice(None, 0, dtype_is_object) - - result.from_slice = memviewslice - __PYX_INC_MEMVIEW(&memviewslice, 1) - - result.from_object = (<memoryview> memviewslice.memview).base - result.typeinfo = memviewslice.memview.typeinfo - - result.view = memviewslice.memview.view - result.view.buf = <void *> memviewslice.data - result.view.ndim = ndim - (<__pyx_buffer *> &result.view).obj = Py_None - Py_INCREF(Py_None) - + + __pyx_getbuffer = capsule(<void *> &__pyx_memoryview_getbuffer, "getbuffer(obj, view, flags)") + + +@cname('__pyx_memoryview_fromslice') +cdef memoryview_fromslice({{memviewslice_name}} memviewslice, + int ndim, + object (*to_object_func)(char *), + int (*to_dtype_func)(char *, object) except 0, + bint dtype_is_object): + + cdef _memoryviewslice result + + if <PyObject *> memviewslice.memview == Py_None: + return None + + # assert 0 < ndim <= memviewslice.memview.view.ndim, ( + # ndim, memviewslice.memview.view.ndim) + + result = _memoryviewslice(None, 0, dtype_is_object) + + result.from_slice = memviewslice + __PYX_INC_MEMVIEW(&memviewslice, 1) + + result.from_object = (<memoryview> memviewslice.memview).base + result.typeinfo = memviewslice.memview.typeinfo + + result.view = memviewslice.memview.view + result.view.buf = <void *> memviewslice.data + result.view.ndim = ndim + (<__pyx_buffer *> &result.view).obj = Py_None + Py_INCREF(Py_None) + if (<memoryview>memviewslice.memview).flags & PyBUF_WRITABLE: result.flags = PyBUF_RECORDS else: result.flags = PyBUF_RECORDS_RO - - result.view.shape = <Py_ssize_t *> result.from_slice.shape - result.view.strides = <Py_ssize_t *> result.from_slice.strides - + + result.view.shape = <Py_ssize_t *> result.from_slice.shape + result.view.strides = <Py_ssize_t *> result.from_slice.strides + # only set suboffsets if actually used, otherwise set to NULL to improve compatibility result.view.suboffsets = NULL for suboffset in result.from_slice.suboffsets[:ndim]: @@ -1039,456 +1039,456 @@ cdef memoryview_fromslice({{memviewslice_name}} memviewslice, result.view.suboffsets = <Py_ssize_t *> result.from_slice.suboffsets break - result.view.len = result.view.itemsize + result.view.len = result.view.itemsize for length in result.view.shape[:ndim]: result.view.len *= length - - result.to_object_func = to_object_func - result.to_dtype_func = to_dtype_func - - return result - -@cname('__pyx_memoryview_get_slice_from_memoryview') -cdef {{memviewslice_name}} *get_slice_from_memview(memoryview memview, + + result.to_object_func = to_object_func + result.to_dtype_func = to_dtype_func + + return result + +@cname('__pyx_memoryview_get_slice_from_memoryview') +cdef {{memviewslice_name}} *get_slice_from_memview(memoryview memview, {{memviewslice_name}} *mslice) except NULL: - cdef _memoryviewslice obj - if isinstance(memview, _memoryviewslice): - obj = memview - return &obj.from_slice - else: - slice_copy(memview, mslice) - return mslice - -@cname('__pyx_memoryview_slice_copy') -cdef void slice_copy(memoryview memview, {{memviewslice_name}} *dst): - cdef int dim - cdef (Py_ssize_t*) shape, strides, suboffsets - - shape = memview.view.shape - strides = memview.view.strides - suboffsets = memview.view.suboffsets - - dst.memview = <__pyx_memoryview *> memview - dst.data = <char *> memview.view.buf - - for dim in range(memview.view.ndim): - dst.shape[dim] = shape[dim] - dst.strides[dim] = strides[dim] + cdef _memoryviewslice obj + if isinstance(memview, _memoryviewslice): + obj = memview + return &obj.from_slice + else: + slice_copy(memview, mslice) + return mslice + +@cname('__pyx_memoryview_slice_copy') +cdef void slice_copy(memoryview memview, {{memviewslice_name}} *dst): + cdef int dim + cdef (Py_ssize_t*) shape, strides, suboffsets + + shape = memview.view.shape + strides = memview.view.strides + suboffsets = memview.view.suboffsets + + dst.memview = <__pyx_memoryview *> memview + dst.data = <char *> memview.view.buf + + for dim in range(memview.view.ndim): + dst.shape[dim] = shape[dim] + dst.strides[dim] = strides[dim] dst.suboffsets[dim] = suboffsets[dim] if suboffsets else -1 - -@cname('__pyx_memoryview_copy_object') -cdef memoryview_copy(memoryview memview): - "Create a new memoryview object" - cdef {{memviewslice_name}} memviewslice - slice_copy(memview, &memviewslice) - return memoryview_copy_from_slice(memview, &memviewslice) - -@cname('__pyx_memoryview_copy_object_from_slice') -cdef memoryview_copy_from_slice(memoryview memview, {{memviewslice_name}} *memviewslice): - """ - Create a new memoryview object from a given memoryview object and slice. - """ - cdef object (*to_object_func)(char *) - cdef int (*to_dtype_func)(char *, object) except 0 - - if isinstance(memview, _memoryviewslice): - to_object_func = (<_memoryviewslice> memview).to_object_func - to_dtype_func = (<_memoryviewslice> memview).to_dtype_func - else: - to_object_func = NULL - to_dtype_func = NULL - - return memoryview_fromslice(memviewslice[0], memview.view.ndim, - to_object_func, to_dtype_func, - memview.dtype_is_object) - - -# -### Copy the contents of a memoryview slices -# -cdef Py_ssize_t abs_py_ssize_t(Py_ssize_t arg) nogil: - if arg < 0: - return -arg - else: - return arg - -@cname('__pyx_get_best_slice_order') -cdef char get_best_order({{memviewslice_name}} *mslice, int ndim) nogil: - """ - Figure out the best memory access order for a given slice. - """ - cdef int i - cdef Py_ssize_t c_stride = 0 - cdef Py_ssize_t f_stride = 0 - - for i in range(ndim - 1, -1, -1): - if mslice.shape[i] > 1: - c_stride = mslice.strides[i] - break - - for i in range(ndim): - if mslice.shape[i] > 1: - f_stride = mslice.strides[i] - break - - if abs_py_ssize_t(c_stride) <= abs_py_ssize_t(f_stride): - return 'C' - else: - return 'F' - -@cython.cdivision(True) -cdef void _copy_strided_to_strided(char *src_data, Py_ssize_t *src_strides, - char *dst_data, Py_ssize_t *dst_strides, - Py_ssize_t *src_shape, Py_ssize_t *dst_shape, - int ndim, size_t itemsize) nogil: - # Note: src_extent is 1 if we're broadcasting - # dst_extent always >= src_extent as we don't do reductions - cdef Py_ssize_t i - cdef Py_ssize_t src_extent = src_shape[0] - cdef Py_ssize_t dst_extent = dst_shape[0] - cdef Py_ssize_t src_stride = src_strides[0] - cdef Py_ssize_t dst_stride = dst_strides[0] - - if ndim == 1: - if (src_stride > 0 and dst_stride > 0 and - <size_t> src_stride == itemsize == <size_t> dst_stride): - memcpy(dst_data, src_data, itemsize * dst_extent) - else: - for i in range(dst_extent): - memcpy(dst_data, src_data, itemsize) - src_data += src_stride - dst_data += dst_stride - else: - for i in range(dst_extent): - _copy_strided_to_strided(src_data, src_strides + 1, - dst_data, dst_strides + 1, - src_shape + 1, dst_shape + 1, - ndim - 1, itemsize) - src_data += src_stride - dst_data += dst_stride - -cdef void copy_strided_to_strided({{memviewslice_name}} *src, - {{memviewslice_name}} *dst, - int ndim, size_t itemsize) nogil: - _copy_strided_to_strided(src.data, src.strides, dst.data, dst.strides, - src.shape, dst.shape, ndim, itemsize) - -@cname('__pyx_memoryview_slice_get_size') -cdef Py_ssize_t slice_get_size({{memviewslice_name}} *src, int ndim) nogil: - "Return the size of the memory occupied by the slice in number of bytes" + +@cname('__pyx_memoryview_copy_object') +cdef memoryview_copy(memoryview memview): + "Create a new memoryview object" + cdef {{memviewslice_name}} memviewslice + slice_copy(memview, &memviewslice) + return memoryview_copy_from_slice(memview, &memviewslice) + +@cname('__pyx_memoryview_copy_object_from_slice') +cdef memoryview_copy_from_slice(memoryview memview, {{memviewslice_name}} *memviewslice): + """ + Create a new memoryview object from a given memoryview object and slice. + """ + cdef object (*to_object_func)(char *) + cdef int (*to_dtype_func)(char *, object) except 0 + + if isinstance(memview, _memoryviewslice): + to_object_func = (<_memoryviewslice> memview).to_object_func + to_dtype_func = (<_memoryviewslice> memview).to_dtype_func + else: + to_object_func = NULL + to_dtype_func = NULL + + return memoryview_fromslice(memviewslice[0], memview.view.ndim, + to_object_func, to_dtype_func, + memview.dtype_is_object) + + +# +### Copy the contents of a memoryview slices +# +cdef Py_ssize_t abs_py_ssize_t(Py_ssize_t arg) nogil: + if arg < 0: + return -arg + else: + return arg + +@cname('__pyx_get_best_slice_order') +cdef char get_best_order({{memviewslice_name}} *mslice, int ndim) nogil: + """ + Figure out the best memory access order for a given slice. + """ + cdef int i + cdef Py_ssize_t c_stride = 0 + cdef Py_ssize_t f_stride = 0 + + for i in range(ndim - 1, -1, -1): + if mslice.shape[i] > 1: + c_stride = mslice.strides[i] + break + + for i in range(ndim): + if mslice.shape[i] > 1: + f_stride = mslice.strides[i] + break + + if abs_py_ssize_t(c_stride) <= abs_py_ssize_t(f_stride): + return 'C' + else: + return 'F' + +@cython.cdivision(True) +cdef void _copy_strided_to_strided(char *src_data, Py_ssize_t *src_strides, + char *dst_data, Py_ssize_t *dst_strides, + Py_ssize_t *src_shape, Py_ssize_t *dst_shape, + int ndim, size_t itemsize) nogil: + # Note: src_extent is 1 if we're broadcasting + # dst_extent always >= src_extent as we don't do reductions + cdef Py_ssize_t i + cdef Py_ssize_t src_extent = src_shape[0] + cdef Py_ssize_t dst_extent = dst_shape[0] + cdef Py_ssize_t src_stride = src_strides[0] + cdef Py_ssize_t dst_stride = dst_strides[0] + + if ndim == 1: + if (src_stride > 0 and dst_stride > 0 and + <size_t> src_stride == itemsize == <size_t> dst_stride): + memcpy(dst_data, src_data, itemsize * dst_extent) + else: + for i in range(dst_extent): + memcpy(dst_data, src_data, itemsize) + src_data += src_stride + dst_data += dst_stride + else: + for i in range(dst_extent): + _copy_strided_to_strided(src_data, src_strides + 1, + dst_data, dst_strides + 1, + src_shape + 1, dst_shape + 1, + ndim - 1, itemsize) + src_data += src_stride + dst_data += dst_stride + +cdef void copy_strided_to_strided({{memviewslice_name}} *src, + {{memviewslice_name}} *dst, + int ndim, size_t itemsize) nogil: + _copy_strided_to_strided(src.data, src.strides, dst.data, dst.strides, + src.shape, dst.shape, ndim, itemsize) + +@cname('__pyx_memoryview_slice_get_size') +cdef Py_ssize_t slice_get_size({{memviewslice_name}} *src, int ndim) nogil: + "Return the size of the memory occupied by the slice in number of bytes" cdef Py_ssize_t shape, size = src.memview.view.itemsize - + for shape in src.shape[:ndim]: size *= shape - - return size - -@cname('__pyx_fill_contig_strides_array') -cdef Py_ssize_t fill_contig_strides_array( - Py_ssize_t *shape, Py_ssize_t *strides, Py_ssize_t stride, - int ndim, char order) nogil: - """ - Fill the strides array for a slice with C or F contiguous strides. - This is like PyBuffer_FillContiguousStrides, but compatible with py < 2.6 - """ - cdef int idx - - if order == 'F': - for idx in range(ndim): - strides[idx] = stride + + return size + +@cname('__pyx_fill_contig_strides_array') +cdef Py_ssize_t fill_contig_strides_array( + Py_ssize_t *shape, Py_ssize_t *strides, Py_ssize_t stride, + int ndim, char order) nogil: + """ + Fill the strides array for a slice with C or F contiguous strides. + This is like PyBuffer_FillContiguousStrides, but compatible with py < 2.6 + """ + cdef int idx + + if order == 'F': + for idx in range(ndim): + strides[idx] = stride stride *= shape[idx] - else: - for idx in range(ndim - 1, -1, -1): - strides[idx] = stride + else: + for idx in range(ndim - 1, -1, -1): + strides[idx] = stride stride *= shape[idx] - - return stride - -@cname('__pyx_memoryview_copy_data_to_temp') -cdef void *copy_data_to_temp({{memviewslice_name}} *src, - {{memviewslice_name}} *tmpslice, - char order, - int ndim) nogil except NULL: - """ - Copy a direct slice to temporary contiguous memory. The caller should free - the result when done. - """ - cdef int i - cdef void *result - - cdef size_t itemsize = src.memview.view.itemsize - cdef size_t size = slice_get_size(src, ndim) - - result = malloc(size) - if not result: - _err(MemoryError, NULL) - - # tmpslice[0] = src - tmpslice.data = <char *> result - tmpslice.memview = src.memview - for i in range(ndim): - tmpslice.shape[i] = src.shape[i] - tmpslice.suboffsets[i] = -1 - - fill_contig_strides_array(&tmpslice.shape[0], &tmpslice.strides[0], itemsize, - ndim, order) - - # We need to broadcast strides again - for i in range(ndim): - if tmpslice.shape[i] == 1: - tmpslice.strides[i] = 0 - + + return stride + +@cname('__pyx_memoryview_copy_data_to_temp') +cdef void *copy_data_to_temp({{memviewslice_name}} *src, + {{memviewslice_name}} *tmpslice, + char order, + int ndim) nogil except NULL: + """ + Copy a direct slice to temporary contiguous memory. The caller should free + the result when done. + """ + cdef int i + cdef void *result + + cdef size_t itemsize = src.memview.view.itemsize + cdef size_t size = slice_get_size(src, ndim) + + result = malloc(size) + if not result: + _err(MemoryError, NULL) + + # tmpslice[0] = src + tmpslice.data = <char *> result + tmpslice.memview = src.memview + for i in range(ndim): + tmpslice.shape[i] = src.shape[i] + tmpslice.suboffsets[i] = -1 + + fill_contig_strides_array(&tmpslice.shape[0], &tmpslice.strides[0], itemsize, + ndim, order) + + # We need to broadcast strides again + for i in range(ndim): + if tmpslice.shape[i] == 1: + tmpslice.strides[i] = 0 + if slice_is_contig(src[0], order, ndim): - memcpy(result, src.data, size) - else: - copy_strided_to_strided(src, tmpslice, ndim, itemsize) - - return result - -# Use 'with gil' functions and avoid 'with gil' blocks, as the code within the blocks -# has temporaries that need the GIL to clean up -@cname('__pyx_memoryview_err_extents') -cdef int _err_extents(int i, Py_ssize_t extent1, - Py_ssize_t extent2) except -1 with gil: - raise ValueError("got differing extents in dimension %d (got %d and %d)" % - (i, extent1, extent2)) - -@cname('__pyx_memoryview_err_dim') -cdef int _err_dim(object error, char *msg, int dim) except -1 with gil: - raise error(msg.decode('ascii') % dim) - -@cname('__pyx_memoryview_err') -cdef int _err(object error, char *msg) except -1 with gil: - if msg != NULL: - raise error(msg.decode('ascii')) - else: - raise error - -@cname('__pyx_memoryview_copy_contents') -cdef int memoryview_copy_contents({{memviewslice_name}} src, - {{memviewslice_name}} dst, - int src_ndim, int dst_ndim, - bint dtype_is_object) nogil except -1: - """ - Copy memory from slice src to slice dst. - Check for overlapping memory and verify the shapes. - """ - cdef void *tmpdata = NULL - cdef size_t itemsize = src.memview.view.itemsize - cdef int i - cdef char order = get_best_order(&src, src_ndim) - cdef bint broadcasting = False - cdef bint direct_copy = False - cdef {{memviewslice_name}} tmp - - if src_ndim < dst_ndim: - broadcast_leading(&src, src_ndim, dst_ndim) - elif dst_ndim < src_ndim: - broadcast_leading(&dst, dst_ndim, src_ndim) - - cdef int ndim = max(src_ndim, dst_ndim) - - for i in range(ndim): - if src.shape[i] != dst.shape[i]: - if src.shape[i] == 1: - broadcasting = True - src.strides[i] = 0 - else: - _err_extents(i, dst.shape[i], src.shape[i]) - - if src.suboffsets[i] >= 0: - _err_dim(ValueError, "Dimension %d is not direct", i) - - if slices_overlap(&src, &dst, ndim, itemsize): - # slices overlap, copy to temp, copy temp to dst + memcpy(result, src.data, size) + else: + copy_strided_to_strided(src, tmpslice, ndim, itemsize) + + return result + +# Use 'with gil' functions and avoid 'with gil' blocks, as the code within the blocks +# has temporaries that need the GIL to clean up +@cname('__pyx_memoryview_err_extents') +cdef int _err_extents(int i, Py_ssize_t extent1, + Py_ssize_t extent2) except -1 with gil: + raise ValueError("got differing extents in dimension %d (got %d and %d)" % + (i, extent1, extent2)) + +@cname('__pyx_memoryview_err_dim') +cdef int _err_dim(object error, char *msg, int dim) except -1 with gil: + raise error(msg.decode('ascii') % dim) + +@cname('__pyx_memoryview_err') +cdef int _err(object error, char *msg) except -1 with gil: + if msg != NULL: + raise error(msg.decode('ascii')) + else: + raise error + +@cname('__pyx_memoryview_copy_contents') +cdef int memoryview_copy_contents({{memviewslice_name}} src, + {{memviewslice_name}} dst, + int src_ndim, int dst_ndim, + bint dtype_is_object) nogil except -1: + """ + Copy memory from slice src to slice dst. + Check for overlapping memory and verify the shapes. + """ + cdef void *tmpdata = NULL + cdef size_t itemsize = src.memview.view.itemsize + cdef int i + cdef char order = get_best_order(&src, src_ndim) + cdef bint broadcasting = False + cdef bint direct_copy = False + cdef {{memviewslice_name}} tmp + + if src_ndim < dst_ndim: + broadcast_leading(&src, src_ndim, dst_ndim) + elif dst_ndim < src_ndim: + broadcast_leading(&dst, dst_ndim, src_ndim) + + cdef int ndim = max(src_ndim, dst_ndim) + + for i in range(ndim): + if src.shape[i] != dst.shape[i]: + if src.shape[i] == 1: + broadcasting = True + src.strides[i] = 0 + else: + _err_extents(i, dst.shape[i], src.shape[i]) + + if src.suboffsets[i] >= 0: + _err_dim(ValueError, "Dimension %d is not direct", i) + + if slices_overlap(&src, &dst, ndim, itemsize): + # slices overlap, copy to temp, copy temp to dst if not slice_is_contig(src, order, ndim): - order = get_best_order(&dst, ndim) - - tmpdata = copy_data_to_temp(&src, &tmp, order, ndim) - src = tmp - - if not broadcasting: - # See if both slices have equal contiguity, in that case perform a - # direct copy. This only works when we are not broadcasting. + order = get_best_order(&dst, ndim) + + tmpdata = copy_data_to_temp(&src, &tmp, order, ndim) + src = tmp + + if not broadcasting: + # See if both slices have equal contiguity, in that case perform a + # direct copy. This only works when we are not broadcasting. if slice_is_contig(src, 'C', ndim): direct_copy = slice_is_contig(dst, 'C', ndim) elif slice_is_contig(src, 'F', ndim): direct_copy = slice_is_contig(dst, 'F', ndim) - - if direct_copy: - # Contiguous slices with same order - refcount_copying(&dst, dtype_is_object, ndim, False) - memcpy(dst.data, src.data, slice_get_size(&src, ndim)) - refcount_copying(&dst, dtype_is_object, ndim, True) - free(tmpdata) - return 0 - - if order == 'F' == get_best_order(&dst, ndim): - # see if both slices have Fortran order, transpose them to match our - # C-style indexing order - transpose_memslice(&src) - transpose_memslice(&dst) - - refcount_copying(&dst, dtype_is_object, ndim, False) - copy_strided_to_strided(&src, &dst, ndim, itemsize) - refcount_copying(&dst, dtype_is_object, ndim, True) - - free(tmpdata) - return 0 - -@cname('__pyx_memoryview_broadcast_leading') + + if direct_copy: + # Contiguous slices with same order + refcount_copying(&dst, dtype_is_object, ndim, False) + memcpy(dst.data, src.data, slice_get_size(&src, ndim)) + refcount_copying(&dst, dtype_is_object, ndim, True) + free(tmpdata) + return 0 + + if order == 'F' == get_best_order(&dst, ndim): + # see if both slices have Fortran order, transpose them to match our + # C-style indexing order + transpose_memslice(&src) + transpose_memslice(&dst) + + refcount_copying(&dst, dtype_is_object, ndim, False) + copy_strided_to_strided(&src, &dst, ndim, itemsize) + refcount_copying(&dst, dtype_is_object, ndim, True) + + free(tmpdata) + return 0 + +@cname('__pyx_memoryview_broadcast_leading') cdef void broadcast_leading({{memviewslice_name}} *mslice, - int ndim, - int ndim_other) nogil: - cdef int i - cdef int offset = ndim_other - ndim - - for i in range(ndim - 1, -1, -1): + int ndim, + int ndim_other) nogil: + cdef int i + cdef int offset = ndim_other - ndim + + for i in range(ndim - 1, -1, -1): mslice.shape[i + offset] = mslice.shape[i] mslice.strides[i + offset] = mslice.strides[i] mslice.suboffsets[i + offset] = mslice.suboffsets[i] - - for i in range(offset): + + for i in range(offset): mslice.shape[i] = 1 mslice.strides[i] = mslice.strides[0] mslice.suboffsets[i] = -1 - -# + +# ### Take care of refcounting the objects in slices. Do this separately from any copying, -### to minimize acquiring the GIL -# - -@cname('__pyx_memoryview_refcount_copying') -cdef void refcount_copying({{memviewslice_name}} *dst, bint dtype_is_object, - int ndim, bint inc) nogil: - # incref or decref the objects in the destination slice if the dtype is - # object - if dtype_is_object: - refcount_objects_in_slice_with_gil(dst.data, dst.shape, - dst.strides, ndim, inc) - -@cname('__pyx_memoryview_refcount_objects_in_slice_with_gil') -cdef void refcount_objects_in_slice_with_gil(char *data, Py_ssize_t *shape, - Py_ssize_t *strides, int ndim, - bint inc) with gil: - refcount_objects_in_slice(data, shape, strides, ndim, inc) - -@cname('__pyx_memoryview_refcount_objects_in_slice') -cdef void refcount_objects_in_slice(char *data, Py_ssize_t *shape, - Py_ssize_t *strides, int ndim, bint inc): - cdef Py_ssize_t i - - for i in range(shape[0]): - if ndim == 1: - if inc: - Py_INCREF((<PyObject **> data)[0]) - else: - Py_DECREF((<PyObject **> data)[0]) - else: - refcount_objects_in_slice(data, shape + 1, strides + 1, - ndim - 1, inc) - - data += strides[0] - -# -### Scalar to slice assignment -# -@cname('__pyx_memoryview_slice_assign_scalar') -cdef void slice_assign_scalar({{memviewslice_name}} *dst, int ndim, - size_t itemsize, void *item, - bint dtype_is_object) nogil: - refcount_copying(dst, dtype_is_object, ndim, False) - _slice_assign_scalar(dst.data, dst.shape, dst.strides, ndim, - itemsize, item) - refcount_copying(dst, dtype_is_object, ndim, True) - - -@cname('__pyx_memoryview__slice_assign_scalar') -cdef void _slice_assign_scalar(char *data, Py_ssize_t *shape, - Py_ssize_t *strides, int ndim, - size_t itemsize, void *item) nogil: - cdef Py_ssize_t i - cdef Py_ssize_t stride = strides[0] - cdef Py_ssize_t extent = shape[0] - - if ndim == 1: - for i in range(extent): - memcpy(data, item, itemsize) - data += stride - else: - for i in range(extent): - _slice_assign_scalar(data, shape + 1, strides + 1, - ndim - 1, itemsize, item) - data += stride - - -############### BufferFormatFromTypeInfo ############### -cdef extern from *: - ctypedef struct __Pyx_StructField - - cdef enum: - __PYX_BUF_FLAGS_PACKED_STRUCT - __PYX_BUF_FLAGS_INTEGER_COMPLEX - - ctypedef struct __Pyx_TypeInfo: - char* name - __Pyx_StructField* fields - size_t size - size_t arraysize[8] - int ndim - char typegroup - char is_unsigned - int flags - - ctypedef struct __Pyx_StructField: - __Pyx_TypeInfo* type - char* name - size_t offset - - ctypedef struct __Pyx_BufFmt_StackElem: - __Pyx_StructField* field - size_t parent_offset - - #ctypedef struct __Pyx_BufFmt_Context: - # __Pyx_StructField root - __Pyx_BufFmt_StackElem* head - - struct __pyx_typeinfo_string: - char string[3] - - __pyx_typeinfo_string __Pyx_TypeInfoToFormat(__Pyx_TypeInfo *) - - -@cname('__pyx_format_from_typeinfo') -cdef bytes format_from_typeinfo(__Pyx_TypeInfo *type): - cdef __Pyx_StructField *field - cdef __pyx_typeinfo_string fmt - cdef bytes part, result - - if type.typegroup == 'S': +### to minimize acquiring the GIL +# + +@cname('__pyx_memoryview_refcount_copying') +cdef void refcount_copying({{memviewslice_name}} *dst, bint dtype_is_object, + int ndim, bint inc) nogil: + # incref or decref the objects in the destination slice if the dtype is + # object + if dtype_is_object: + refcount_objects_in_slice_with_gil(dst.data, dst.shape, + dst.strides, ndim, inc) + +@cname('__pyx_memoryview_refcount_objects_in_slice_with_gil') +cdef void refcount_objects_in_slice_with_gil(char *data, Py_ssize_t *shape, + Py_ssize_t *strides, int ndim, + bint inc) with gil: + refcount_objects_in_slice(data, shape, strides, ndim, inc) + +@cname('__pyx_memoryview_refcount_objects_in_slice') +cdef void refcount_objects_in_slice(char *data, Py_ssize_t *shape, + Py_ssize_t *strides, int ndim, bint inc): + cdef Py_ssize_t i + + for i in range(shape[0]): + if ndim == 1: + if inc: + Py_INCREF((<PyObject **> data)[0]) + else: + Py_DECREF((<PyObject **> data)[0]) + else: + refcount_objects_in_slice(data, shape + 1, strides + 1, + ndim - 1, inc) + + data += strides[0] + +# +### Scalar to slice assignment +# +@cname('__pyx_memoryview_slice_assign_scalar') +cdef void slice_assign_scalar({{memviewslice_name}} *dst, int ndim, + size_t itemsize, void *item, + bint dtype_is_object) nogil: + refcount_copying(dst, dtype_is_object, ndim, False) + _slice_assign_scalar(dst.data, dst.shape, dst.strides, ndim, + itemsize, item) + refcount_copying(dst, dtype_is_object, ndim, True) + + +@cname('__pyx_memoryview__slice_assign_scalar') +cdef void _slice_assign_scalar(char *data, Py_ssize_t *shape, + Py_ssize_t *strides, int ndim, + size_t itemsize, void *item) nogil: + cdef Py_ssize_t i + cdef Py_ssize_t stride = strides[0] + cdef Py_ssize_t extent = shape[0] + + if ndim == 1: + for i in range(extent): + memcpy(data, item, itemsize) + data += stride + else: + for i in range(extent): + _slice_assign_scalar(data, shape + 1, strides + 1, + ndim - 1, itemsize, item) + data += stride + + +############### BufferFormatFromTypeInfo ############### +cdef extern from *: + ctypedef struct __Pyx_StructField + + cdef enum: + __PYX_BUF_FLAGS_PACKED_STRUCT + __PYX_BUF_FLAGS_INTEGER_COMPLEX + + ctypedef struct __Pyx_TypeInfo: + char* name + __Pyx_StructField* fields + size_t size + size_t arraysize[8] + int ndim + char typegroup + char is_unsigned + int flags + + ctypedef struct __Pyx_StructField: + __Pyx_TypeInfo* type + char* name + size_t offset + + ctypedef struct __Pyx_BufFmt_StackElem: + __Pyx_StructField* field + size_t parent_offset + + #ctypedef struct __Pyx_BufFmt_Context: + # __Pyx_StructField root + __Pyx_BufFmt_StackElem* head + + struct __pyx_typeinfo_string: + char string[3] + + __pyx_typeinfo_string __Pyx_TypeInfoToFormat(__Pyx_TypeInfo *) + + +@cname('__pyx_format_from_typeinfo') +cdef bytes format_from_typeinfo(__Pyx_TypeInfo *type): + cdef __Pyx_StructField *field + cdef __pyx_typeinfo_string fmt + cdef bytes part, result + + if type.typegroup == 'S': assert type.fields != NULL assert type.fields.type != NULL - - if type.flags & __PYX_BUF_FLAGS_PACKED_STRUCT: - alignment = b'^' - else: - alignment = b'' - - parts = [b"T{"] - field = type.fields - - while field.type: - part = format_from_typeinfo(field.type) - parts.append(part + b':' + field.name + b':') - field += 1 - - result = alignment.join(parts) + b'}' - else: - fmt = __Pyx_TypeInfoToFormat(type) - if type.arraysize[0]: - extents = [unicode(type.arraysize[i]) for i in range(type.ndim)] - result = (u"(%s)" % u','.join(extents)).encode('ascii') + fmt.string - else: - result = fmt.string - - return result + + if type.flags & __PYX_BUF_FLAGS_PACKED_STRUCT: + alignment = b'^' + else: + alignment = b'' + + parts = [b"T{"] + field = type.fields + + while field.type: + part = format_from_typeinfo(field.type) + parts.append(part + b':' + field.name + b':') + field += 1 + + result = alignment.join(parts) + b'}' + else: + fmt = __Pyx_TypeInfoToFormat(type) + if type.arraysize[0]: + extents = [unicode(type.arraysize[i]) for i in range(type.ndim)] + result = (u"(%s)" % u','.join(extents)).encode('ascii') + fmt.string + else: + result = fmt.string + + return result diff --git a/contrib/tools/cython/Cython/Utility/MemoryView_C.c b/contrib/tools/cython/Cython/Utility/MemoryView_C.c index 0a5d8ee2c2..44e6fa9d88 100644 --- a/contrib/tools/cython/Cython/Utility/MemoryView_C.c +++ b/contrib/tools/cython/Cython/Utility/MemoryView_C.c @@ -1,352 +1,352 @@ -////////// MemviewSliceStruct.proto ////////// +////////// MemviewSliceStruct.proto ////////// //@proto_block: utility_code_proto_before_types - -/* memoryview slice struct */ -struct {{memview_struct_name}}; - -typedef struct { - struct {{memview_struct_name}} *memview; - char *data; - Py_ssize_t shape[{{max_dims}}]; - Py_ssize_t strides[{{max_dims}}]; - Py_ssize_t suboffsets[{{max_dims}}]; -} {{memviewslice_name}}; - + +/* memoryview slice struct */ +struct {{memview_struct_name}}; + +typedef struct { + struct {{memview_struct_name}} *memview; + char *data; + Py_ssize_t shape[{{max_dims}}]; + Py_ssize_t strides[{{max_dims}}]; + Py_ssize_t suboffsets[{{max_dims}}]; +} {{memviewslice_name}}; + // used for "len(memviewslice)" #define __Pyx_MemoryView_Len(m) (m.shape[0]) + - -/////////// Atomics.proto ///////////// +/////////// Atomics.proto ///////////// //@proto_block: utility_code_proto_before_types - -#include <pythread.h> - -#ifndef CYTHON_ATOMICS - #define CYTHON_ATOMICS 1 -#endif - -#define __pyx_atomic_int_type int -// todo: Portland pgcc, maybe OS X's OSAtomicIncrement32, -// libatomic + autotools-like distutils support? Such a pain... -#if CYTHON_ATOMICS && __GNUC__ >= 4 && (__GNUC_MINOR__ > 1 || \ - (__GNUC_MINOR__ == 1 && __GNUC_PATCHLEVEL >= 2)) && \ - !defined(__i386__) - /* gcc >= 4.1.2 */ - #define __pyx_atomic_incr_aligned(value, lock) __sync_fetch_and_add(value, 1) - #define __pyx_atomic_decr_aligned(value, lock) __sync_fetch_and_sub(value, 1) - - #ifdef __PYX_DEBUG_ATOMICS - #warning "Using GNU atomics" - #endif + +#include <pythread.h> + +#ifndef CYTHON_ATOMICS + #define CYTHON_ATOMICS 1 +#endif + +#define __pyx_atomic_int_type int +// todo: Portland pgcc, maybe OS X's OSAtomicIncrement32, +// libatomic + autotools-like distutils support? Such a pain... +#if CYTHON_ATOMICS && __GNUC__ >= 4 && (__GNUC_MINOR__ > 1 || \ + (__GNUC_MINOR__ == 1 && __GNUC_PATCHLEVEL >= 2)) && \ + !defined(__i386__) + /* gcc >= 4.1.2 */ + #define __pyx_atomic_incr_aligned(value, lock) __sync_fetch_and_add(value, 1) + #define __pyx_atomic_decr_aligned(value, lock) __sync_fetch_and_sub(value, 1) + + #ifdef __PYX_DEBUG_ATOMICS + #warning "Using GNU atomics" + #endif #elif CYTHON_ATOMICS && defined(_MSC_VER) && 0 - /* msvc */ - #include <Windows.h> + /* msvc */ + #include <Windows.h> #undef __pyx_atomic_int_type - #define __pyx_atomic_int_type LONG - #define __pyx_atomic_incr_aligned(value, lock) InterlockedIncrement(value) - #define __pyx_atomic_decr_aligned(value, lock) InterlockedDecrement(value) - - #ifdef __PYX_DEBUG_ATOMICS + #define __pyx_atomic_int_type LONG + #define __pyx_atomic_incr_aligned(value, lock) InterlockedIncrement(value) + #define __pyx_atomic_decr_aligned(value, lock) InterlockedDecrement(value) + + #ifdef __PYX_DEBUG_ATOMICS #pragma message ("Using MSVC atomics") - #endif -#elif CYTHON_ATOMICS && (defined(__ICC) || defined(__INTEL_COMPILER)) && 0 - #define __pyx_atomic_incr_aligned(value, lock) _InterlockedIncrement(value) - #define __pyx_atomic_decr_aligned(value, lock) _InterlockedDecrement(value) - - #ifdef __PYX_DEBUG_ATOMICS - #warning "Using Intel atomics" - #endif -#else - #undef CYTHON_ATOMICS - #define CYTHON_ATOMICS 0 - - #ifdef __PYX_DEBUG_ATOMICS - #warning "Not using atomics" - #endif -#endif - -typedef volatile __pyx_atomic_int_type __pyx_atomic_int; - -#if CYTHON_ATOMICS - #define __pyx_add_acquisition_count(memview) \ - __pyx_atomic_incr_aligned(__pyx_get_slice_count_pointer(memview), memview->lock) - #define __pyx_sub_acquisition_count(memview) \ - __pyx_atomic_decr_aligned(__pyx_get_slice_count_pointer(memview), memview->lock) -#else - #define __pyx_add_acquisition_count(memview) \ - __pyx_add_acquisition_count_locked(__pyx_get_slice_count_pointer(memview), memview->lock) - #define __pyx_sub_acquisition_count(memview) \ - __pyx_sub_acquisition_count_locked(__pyx_get_slice_count_pointer(memview), memview->lock) -#endif - - -/////////////// ObjectToMemviewSlice.proto /////////////// - + #endif +#elif CYTHON_ATOMICS && (defined(__ICC) || defined(__INTEL_COMPILER)) && 0 + #define __pyx_atomic_incr_aligned(value, lock) _InterlockedIncrement(value) + #define __pyx_atomic_decr_aligned(value, lock) _InterlockedDecrement(value) + + #ifdef __PYX_DEBUG_ATOMICS + #warning "Using Intel atomics" + #endif +#else + #undef CYTHON_ATOMICS + #define CYTHON_ATOMICS 0 + + #ifdef __PYX_DEBUG_ATOMICS + #warning "Not using atomics" + #endif +#endif + +typedef volatile __pyx_atomic_int_type __pyx_atomic_int; + +#if CYTHON_ATOMICS + #define __pyx_add_acquisition_count(memview) \ + __pyx_atomic_incr_aligned(__pyx_get_slice_count_pointer(memview), memview->lock) + #define __pyx_sub_acquisition_count(memview) \ + __pyx_atomic_decr_aligned(__pyx_get_slice_count_pointer(memview), memview->lock) +#else + #define __pyx_add_acquisition_count(memview) \ + __pyx_add_acquisition_count_locked(__pyx_get_slice_count_pointer(memview), memview->lock) + #define __pyx_sub_acquisition_count(memview) \ + __pyx_sub_acquisition_count_locked(__pyx_get_slice_count_pointer(memview), memview->lock) +#endif + + +/////////////// ObjectToMemviewSlice.proto /////////////// + static CYTHON_INLINE {{memviewslice_name}} {{funcname}}(PyObject *, int writable_flag); - - -////////// MemviewSliceInit.proto ////////// - -#define __Pyx_BUF_MAX_NDIMS %(BUF_MAX_NDIMS)d - -#define __Pyx_MEMVIEW_DIRECT 1 -#define __Pyx_MEMVIEW_PTR 2 -#define __Pyx_MEMVIEW_FULL 4 -#define __Pyx_MEMVIEW_CONTIG 8 -#define __Pyx_MEMVIEW_STRIDED 16 -#define __Pyx_MEMVIEW_FOLLOW 32 - -#define __Pyx_IS_C_CONTIG 1 -#define __Pyx_IS_F_CONTIG 2 - -static int __Pyx_init_memviewslice( - struct __pyx_memoryview_obj *memview, - int ndim, - __Pyx_memviewslice *memviewslice, - int memview_is_new_reference); - -static CYTHON_INLINE int __pyx_add_acquisition_count_locked( - __pyx_atomic_int *acquisition_count, PyThread_type_lock lock); -static CYTHON_INLINE int __pyx_sub_acquisition_count_locked( - __pyx_atomic_int *acquisition_count, PyThread_type_lock lock); - -#define __pyx_get_slice_count_pointer(memview) (memview->acquisition_count_aligned_p) -#define __pyx_get_slice_count(memview) (*__pyx_get_slice_count_pointer(memview)) -#define __PYX_INC_MEMVIEW(slice, have_gil) __Pyx_INC_MEMVIEW(slice, have_gil, __LINE__) -#define __PYX_XDEC_MEMVIEW(slice, have_gil) __Pyx_XDEC_MEMVIEW(slice, have_gil, __LINE__) -static CYTHON_INLINE void __Pyx_INC_MEMVIEW({{memviewslice_name}} *, int, int); -static CYTHON_INLINE void __Pyx_XDEC_MEMVIEW({{memviewslice_name}} *, int, int); - - -/////////////// MemviewSliceIndex.proto /////////////// - -static CYTHON_INLINE char *__pyx_memviewslice_index_full( - const char *bufp, Py_ssize_t idx, Py_ssize_t stride, Py_ssize_t suboffset); - - -/////////////// ObjectToMemviewSlice /////////////// -//@requires: MemviewSliceValidateAndInit - + + +////////// MemviewSliceInit.proto ////////// + +#define __Pyx_BUF_MAX_NDIMS %(BUF_MAX_NDIMS)d + +#define __Pyx_MEMVIEW_DIRECT 1 +#define __Pyx_MEMVIEW_PTR 2 +#define __Pyx_MEMVIEW_FULL 4 +#define __Pyx_MEMVIEW_CONTIG 8 +#define __Pyx_MEMVIEW_STRIDED 16 +#define __Pyx_MEMVIEW_FOLLOW 32 + +#define __Pyx_IS_C_CONTIG 1 +#define __Pyx_IS_F_CONTIG 2 + +static int __Pyx_init_memviewslice( + struct __pyx_memoryview_obj *memview, + int ndim, + __Pyx_memviewslice *memviewslice, + int memview_is_new_reference); + +static CYTHON_INLINE int __pyx_add_acquisition_count_locked( + __pyx_atomic_int *acquisition_count, PyThread_type_lock lock); +static CYTHON_INLINE int __pyx_sub_acquisition_count_locked( + __pyx_atomic_int *acquisition_count, PyThread_type_lock lock); + +#define __pyx_get_slice_count_pointer(memview) (memview->acquisition_count_aligned_p) +#define __pyx_get_slice_count(memview) (*__pyx_get_slice_count_pointer(memview)) +#define __PYX_INC_MEMVIEW(slice, have_gil) __Pyx_INC_MEMVIEW(slice, have_gil, __LINE__) +#define __PYX_XDEC_MEMVIEW(slice, have_gil) __Pyx_XDEC_MEMVIEW(slice, have_gil, __LINE__) +static CYTHON_INLINE void __Pyx_INC_MEMVIEW({{memviewslice_name}} *, int, int); +static CYTHON_INLINE void __Pyx_XDEC_MEMVIEW({{memviewslice_name}} *, int, int); + + +/////////////// MemviewSliceIndex.proto /////////////// + +static CYTHON_INLINE char *__pyx_memviewslice_index_full( + const char *bufp, Py_ssize_t idx, Py_ssize_t stride, Py_ssize_t suboffset); + + +/////////////// ObjectToMemviewSlice /////////////// +//@requires: MemviewSliceValidateAndInit + static CYTHON_INLINE {{memviewslice_name}} {{funcname}}(PyObject *obj, int writable_flag) { - {{memviewslice_name}} result = {{memslice_init}}; - __Pyx_BufFmt_StackElem stack[{{struct_nesting_depth}}]; - int axes_specs[] = { {{axes_specs}} }; - int retcode; - - if (obj == Py_None) { - /* We don't bother to refcount None */ - result.memview = (struct __pyx_memoryview_obj *) Py_None; - return result; - } - - retcode = __Pyx_ValidateAndInit_memviewslice(axes_specs, {{c_or_f_flag}}, + {{memviewslice_name}} result = {{memslice_init}}; + __Pyx_BufFmt_StackElem stack[{{struct_nesting_depth}}]; + int axes_specs[] = { {{axes_specs}} }; + int retcode; + + if (obj == Py_None) { + /* We don't bother to refcount None */ + result.memview = (struct __pyx_memoryview_obj *) Py_None; + return result; + } + + retcode = __Pyx_ValidateAndInit_memviewslice(axes_specs, {{c_or_f_flag}}, {{buf_flag}} | writable_flag, {{ndim}}, - &{{dtype_typeinfo}}, stack, - &result, obj); - - if (unlikely(retcode == -1)) - goto __pyx_fail; - - return result; -__pyx_fail: - result.memview = NULL; - result.data = NULL; - return result; -} - - -/////////////// MemviewSliceValidateAndInit.proto /////////////// - -static int __Pyx_ValidateAndInit_memviewslice( - int *axes_specs, - int c_or_f_flag, - int buf_flags, - int ndim, - __Pyx_TypeInfo *dtype, - __Pyx_BufFmt_StackElem stack[], - __Pyx_memviewslice *memviewslice, - PyObject *original_obj); - -/////////////// MemviewSliceValidateAndInit /////////////// -//@requires: Buffer.c::TypeInfoCompare + &{{dtype_typeinfo}}, stack, + &result, obj); + + if (unlikely(retcode == -1)) + goto __pyx_fail; + + return result; +__pyx_fail: + result.memview = NULL; + result.data = NULL; + return result; +} + + +/////////////// MemviewSliceValidateAndInit.proto /////////////// + +static int __Pyx_ValidateAndInit_memviewslice( + int *axes_specs, + int c_or_f_flag, + int buf_flags, + int ndim, + __Pyx_TypeInfo *dtype, + __Pyx_BufFmt_StackElem stack[], + __Pyx_memviewslice *memviewslice, + PyObject *original_obj); + +/////////////// MemviewSliceValidateAndInit /////////////// +//@requires: Buffer.c::TypeInfoCompare //@requires: Buffer.c::BufferFormatStructs //@requires: Buffer.c::BufferFormatCheck - -static int -__pyx_check_strides(Py_buffer *buf, int dim, int ndim, int spec) -{ - if (buf->shape[dim] <= 1) - return 1; - - if (buf->strides) { - if (spec & __Pyx_MEMVIEW_CONTIG) { - if (spec & (__Pyx_MEMVIEW_PTR|__Pyx_MEMVIEW_FULL)) { + +static int +__pyx_check_strides(Py_buffer *buf, int dim, int ndim, int spec) +{ + if (buf->shape[dim] <= 1) + return 1; + + if (buf->strides) { + if (spec & __Pyx_MEMVIEW_CONTIG) { + if (spec & (__Pyx_MEMVIEW_PTR|__Pyx_MEMVIEW_FULL)) { if (unlikely(buf->strides[dim] != sizeof(void *))) { - PyErr_Format(PyExc_ValueError, - "Buffer is not indirectly contiguous " - "in dimension %d.", dim); - goto fail; - } + PyErr_Format(PyExc_ValueError, + "Buffer is not indirectly contiguous " + "in dimension %d.", dim); + goto fail; + } } else if (unlikely(buf->strides[dim] != buf->itemsize)) { - PyErr_SetString(PyExc_ValueError, - "Buffer and memoryview are not contiguous " - "in the same dimension."); - goto fail; - } - } - - if (spec & __Pyx_MEMVIEW_FOLLOW) { - Py_ssize_t stride = buf->strides[dim]; - if (stride < 0) - stride = -stride; + PyErr_SetString(PyExc_ValueError, + "Buffer and memoryview are not contiguous " + "in the same dimension."); + goto fail; + } + } + + if (spec & __Pyx_MEMVIEW_FOLLOW) { + Py_ssize_t stride = buf->strides[dim]; + if (stride < 0) + stride = -stride; if (unlikely(stride < buf->itemsize)) { - PyErr_SetString(PyExc_ValueError, - "Buffer and memoryview are not contiguous " - "in the same dimension."); - goto fail; - } - } - } else { + PyErr_SetString(PyExc_ValueError, + "Buffer and memoryview are not contiguous " + "in the same dimension."); + goto fail; + } + } + } else { if (unlikely(spec & __Pyx_MEMVIEW_CONTIG && dim != ndim - 1)) { - PyErr_Format(PyExc_ValueError, - "C-contiguous buffer is not contiguous in " - "dimension %d", dim); - goto fail; + PyErr_Format(PyExc_ValueError, + "C-contiguous buffer is not contiguous in " + "dimension %d", dim); + goto fail; } else if (unlikely(spec & (__Pyx_MEMVIEW_PTR))) { - PyErr_Format(PyExc_ValueError, - "C-contiguous buffer is not indirect in " - "dimension %d", dim); - goto fail; + PyErr_Format(PyExc_ValueError, + "C-contiguous buffer is not indirect in " + "dimension %d", dim); + goto fail; } else if (unlikely(buf->suboffsets)) { - PyErr_SetString(PyExc_ValueError, - "Buffer exposes suboffsets but no strides"); - goto fail; - } - } - - return 1; -fail: - return 0; -} - -static int -__pyx_check_suboffsets(Py_buffer *buf, int dim, CYTHON_UNUSED int ndim, int spec) -{ - // Todo: without PyBUF_INDIRECT we may not have suboffset information, i.e., the - // ptr may not be set to NULL but may be uninitialized? - if (spec & __Pyx_MEMVIEW_DIRECT) { + PyErr_SetString(PyExc_ValueError, + "Buffer exposes suboffsets but no strides"); + goto fail; + } + } + + return 1; +fail: + return 0; +} + +static int +__pyx_check_suboffsets(Py_buffer *buf, int dim, CYTHON_UNUSED int ndim, int spec) +{ + // Todo: without PyBUF_INDIRECT we may not have suboffset information, i.e., the + // ptr may not be set to NULL but may be uninitialized? + if (spec & __Pyx_MEMVIEW_DIRECT) { if (unlikely(buf->suboffsets && buf->suboffsets[dim] >= 0)) { - PyErr_Format(PyExc_ValueError, - "Buffer not compatible with direct access " - "in dimension %d.", dim); - goto fail; - } - } - - if (spec & __Pyx_MEMVIEW_PTR) { + PyErr_Format(PyExc_ValueError, + "Buffer not compatible with direct access " + "in dimension %d.", dim); + goto fail; + } + } + + if (spec & __Pyx_MEMVIEW_PTR) { if (unlikely(!buf->suboffsets || (buf->suboffsets[dim] < 0))) { - PyErr_Format(PyExc_ValueError, - "Buffer is not indirectly accessible " - "in dimension %d.", dim); - goto fail; - } - } - - return 1; -fail: - return 0; -} - -static int -__pyx_verify_contig(Py_buffer *buf, int ndim, int c_or_f_flag) -{ - int i; - - if (c_or_f_flag & __Pyx_IS_F_CONTIG) { - Py_ssize_t stride = 1; - for (i = 0; i < ndim; i++) { + PyErr_Format(PyExc_ValueError, + "Buffer is not indirectly accessible " + "in dimension %d.", dim); + goto fail; + } + } + + return 1; +fail: + return 0; +} + +static int +__pyx_verify_contig(Py_buffer *buf, int ndim, int c_or_f_flag) +{ + int i; + + if (c_or_f_flag & __Pyx_IS_F_CONTIG) { + Py_ssize_t stride = 1; + for (i = 0; i < ndim; i++) { if (unlikely(stride * buf->itemsize != buf->strides[i] && buf->shape[i] > 1)) { - PyErr_SetString(PyExc_ValueError, - "Buffer not fortran contiguous."); - goto fail; - } - stride = stride * buf->shape[i]; - } - } else if (c_or_f_flag & __Pyx_IS_C_CONTIG) { - Py_ssize_t stride = 1; - for (i = ndim - 1; i >- 1; i--) { + PyErr_SetString(PyExc_ValueError, + "Buffer not fortran contiguous."); + goto fail; + } + stride = stride * buf->shape[i]; + } + } else if (c_or_f_flag & __Pyx_IS_C_CONTIG) { + Py_ssize_t stride = 1; + for (i = ndim - 1; i >- 1; i--) { if (unlikely(stride * buf->itemsize != buf->strides[i] && buf->shape[i] > 1)) { - PyErr_SetString(PyExc_ValueError, - "Buffer not C contiguous."); - goto fail; - } - stride = stride * buf->shape[i]; - } - } - - return 1; -fail: - return 0; -} - -static int __Pyx_ValidateAndInit_memviewslice( - int *axes_specs, - int c_or_f_flag, - int buf_flags, - int ndim, - __Pyx_TypeInfo *dtype, - __Pyx_BufFmt_StackElem stack[], - __Pyx_memviewslice *memviewslice, - PyObject *original_obj) -{ - struct __pyx_memoryview_obj *memview, *new_memview; - __Pyx_RefNannyDeclarations - Py_buffer *buf; - int i, spec = 0, retval = -1; - __Pyx_BufFmt_Context ctx; - int from_memoryview = __pyx_memoryview_check(original_obj); - - __Pyx_RefNannySetupContext("ValidateAndInit_memviewslice", 0); - - if (from_memoryview && __pyx_typeinfo_cmp(dtype, ((struct __pyx_memoryview_obj *) - original_obj)->typeinfo)) { - /* We have a matching dtype, skip format parsing */ - memview = (struct __pyx_memoryview_obj *) original_obj; - new_memview = NULL; - } else { - memview = (struct __pyx_memoryview_obj *) __pyx_memoryview_new( - original_obj, buf_flags, 0, dtype); - new_memview = memview; - if (unlikely(!memview)) - goto fail; - } - - buf = &memview->view; + PyErr_SetString(PyExc_ValueError, + "Buffer not C contiguous."); + goto fail; + } + stride = stride * buf->shape[i]; + } + } + + return 1; +fail: + return 0; +} + +static int __Pyx_ValidateAndInit_memviewslice( + int *axes_specs, + int c_or_f_flag, + int buf_flags, + int ndim, + __Pyx_TypeInfo *dtype, + __Pyx_BufFmt_StackElem stack[], + __Pyx_memviewslice *memviewslice, + PyObject *original_obj) +{ + struct __pyx_memoryview_obj *memview, *new_memview; + __Pyx_RefNannyDeclarations + Py_buffer *buf; + int i, spec = 0, retval = -1; + __Pyx_BufFmt_Context ctx; + int from_memoryview = __pyx_memoryview_check(original_obj); + + __Pyx_RefNannySetupContext("ValidateAndInit_memviewslice", 0); + + if (from_memoryview && __pyx_typeinfo_cmp(dtype, ((struct __pyx_memoryview_obj *) + original_obj)->typeinfo)) { + /* We have a matching dtype, skip format parsing */ + memview = (struct __pyx_memoryview_obj *) original_obj; + new_memview = NULL; + } else { + memview = (struct __pyx_memoryview_obj *) __pyx_memoryview_new( + original_obj, buf_flags, 0, dtype); + new_memview = memview; + if (unlikely(!memview)) + goto fail; + } + + buf = &memview->view; if (unlikely(buf->ndim != ndim)) { - PyErr_Format(PyExc_ValueError, - "Buffer has wrong number of dimensions (expected %d, got %d)", - ndim, buf->ndim); - goto fail; - } - - if (new_memview) { - __Pyx_BufFmt_Init(&ctx, stack, dtype); + PyErr_Format(PyExc_ValueError, + "Buffer has wrong number of dimensions (expected %d, got %d)", + ndim, buf->ndim); + goto fail; + } + + if (new_memview) { + __Pyx_BufFmt_Init(&ctx, stack, dtype); if (unlikely(!__Pyx_BufFmt_CheckString(&ctx, buf->format))) goto fail; - } - + } + if (unlikely((unsigned) buf->itemsize != dtype->size)) { - PyErr_Format(PyExc_ValueError, - "Item size of buffer (%" CYTHON_FORMAT_SSIZE_T "u byte%s) " - "does not match size of '%s' (%" CYTHON_FORMAT_SSIZE_T "u byte%s)", - buf->itemsize, - (buf->itemsize > 1) ? "s" : "", - dtype->name, - dtype->size, - (dtype->size > 1) ? "s" : ""); - goto fail; - } - - /* Check axes */ + PyErr_Format(PyExc_ValueError, + "Item size of buffer (%" CYTHON_FORMAT_SSIZE_T "u byte%s) " + "does not match size of '%s' (%" CYTHON_FORMAT_SSIZE_T "u byte%s)", + buf->itemsize, + (buf->itemsize > 1) ? "s" : "", + dtype->name, + dtype->size, + (dtype->size > 1) ? "s" : ""); + goto fail; + } + + /* Check axes */ if (buf->len > 0) { // 0-sized arrays do not undergo these checks since their strides are // irrelevant and they are always both C- and F-contiguous. @@ -360,506 +360,506 @@ static int __Pyx_ValidateAndInit_memviewslice( /* Check contiguity */ if (unlikely(buf->strides && !__pyx_verify_contig(buf, ndim, c_or_f_flag))) - goto fail; - } - - /* Initialize */ - if (unlikely(__Pyx_init_memviewslice(memview, ndim, memviewslice, - new_memview != NULL) == -1)) { - goto fail; - } - - retval = 0; - goto no_fail; - -fail: - Py_XDECREF(new_memview); - retval = -1; - -no_fail: - __Pyx_RefNannyFinishContext(); - return retval; -} - - -////////// MemviewSliceInit ////////// - -static int -__Pyx_init_memviewslice(struct __pyx_memoryview_obj *memview, - int ndim, - {{memviewslice_name}} *memviewslice, - int memview_is_new_reference) -{ - __Pyx_RefNannyDeclarations - int i, retval=-1; - Py_buffer *buf = &memview->view; - __Pyx_RefNannySetupContext("init_memviewslice", 0); - + goto fail; + } + + /* Initialize */ + if (unlikely(__Pyx_init_memviewslice(memview, ndim, memviewslice, + new_memview != NULL) == -1)) { + goto fail; + } + + retval = 0; + goto no_fail; + +fail: + Py_XDECREF(new_memview); + retval = -1; + +no_fail: + __Pyx_RefNannyFinishContext(); + return retval; +} + + +////////// MemviewSliceInit ////////// + +static int +__Pyx_init_memviewslice(struct __pyx_memoryview_obj *memview, + int ndim, + {{memviewslice_name}} *memviewslice, + int memview_is_new_reference) +{ + __Pyx_RefNannyDeclarations + int i, retval=-1; + Py_buffer *buf = &memview->view; + __Pyx_RefNannySetupContext("init_memviewslice", 0); + if (unlikely(memviewslice->memview || memviewslice->data)) { - PyErr_SetString(PyExc_ValueError, - "memviewslice is already initialized!"); - goto fail; - } - - if (buf->strides) { - for (i = 0; i < ndim; i++) { - memviewslice->strides[i] = buf->strides[i]; - } - } else { - Py_ssize_t stride = buf->itemsize; - for (i = ndim - 1; i >= 0; i--) { - memviewslice->strides[i] = stride; - stride *= buf->shape[i]; - } - } - - for (i = 0; i < ndim; i++) { - memviewslice->shape[i] = buf->shape[i]; - if (buf->suboffsets) { - memviewslice->suboffsets[i] = buf->suboffsets[i]; - } else { - memviewslice->suboffsets[i] = -1; - } - } - - memviewslice->memview = memview; - memviewslice->data = (char *)buf->buf; - if (__pyx_add_acquisition_count(memview) == 0 && !memview_is_new_reference) { - Py_INCREF(memview); - } - retval = 0; - goto no_fail; - -fail: - /* Don't decref, the memoryview may be borrowed. Let the caller do the cleanup */ - /* __Pyx_XDECREF(memviewslice->memview); */ - memviewslice->memview = 0; - memviewslice->data = 0; - retval = -1; -no_fail: - __Pyx_RefNannyFinishContext(); - return retval; -} - + PyErr_SetString(PyExc_ValueError, + "memviewslice is already initialized!"); + goto fail; + } + + if (buf->strides) { + for (i = 0; i < ndim; i++) { + memviewslice->strides[i] = buf->strides[i]; + } + } else { + Py_ssize_t stride = buf->itemsize; + for (i = ndim - 1; i >= 0; i--) { + memviewslice->strides[i] = stride; + stride *= buf->shape[i]; + } + } + + for (i = 0; i < ndim; i++) { + memviewslice->shape[i] = buf->shape[i]; + if (buf->suboffsets) { + memviewslice->suboffsets[i] = buf->suboffsets[i]; + } else { + memviewslice->suboffsets[i] = -1; + } + } + + memviewslice->memview = memview; + memviewslice->data = (char *)buf->buf; + if (__pyx_add_acquisition_count(memview) == 0 && !memview_is_new_reference) { + Py_INCREF(memview); + } + retval = 0; + goto no_fail; + +fail: + /* Don't decref, the memoryview may be borrowed. Let the caller do the cleanup */ + /* __Pyx_XDECREF(memviewslice->memview); */ + memviewslice->memview = 0; + memviewslice->data = 0; + retval = -1; +no_fail: + __Pyx_RefNannyFinishContext(); + return retval; +} + #ifndef Py_NO_RETURN // available since Py3.3 #define Py_NO_RETURN #endif - + static void __pyx_fatalerror(const char *fmt, ...) Py_NO_RETURN { - va_list vargs; - char msg[200]; - -#ifdef HAVE_STDARG_PROTOTYPES - va_start(vargs, fmt); -#else - va_start(vargs); -#endif + va_list vargs; + char msg[200]; + +#ifdef HAVE_STDARG_PROTOTYPES + va_start(vargs, fmt); +#else + va_start(vargs); +#endif vsnprintf(msg, 200, fmt, vargs); va_end(vargs); - - Py_FatalError(msg); -} - -static CYTHON_INLINE int -__pyx_add_acquisition_count_locked(__pyx_atomic_int *acquisition_count, - PyThread_type_lock lock) -{ - int result; - PyThread_acquire_lock(lock, 1); - result = (*acquisition_count)++; - PyThread_release_lock(lock); - return result; -} - -static CYTHON_INLINE int -__pyx_sub_acquisition_count_locked(__pyx_atomic_int *acquisition_count, - PyThread_type_lock lock) -{ - int result; - PyThread_acquire_lock(lock, 1); - result = (*acquisition_count)--; - PyThread_release_lock(lock); - return result; -} - - -static CYTHON_INLINE void -__Pyx_INC_MEMVIEW({{memviewslice_name}} *memslice, int have_gil, int lineno) -{ - int first_time; - struct {{memview_struct_name}} *memview = memslice->memview; + + Py_FatalError(msg); +} + +static CYTHON_INLINE int +__pyx_add_acquisition_count_locked(__pyx_atomic_int *acquisition_count, + PyThread_type_lock lock) +{ + int result; + PyThread_acquire_lock(lock, 1); + result = (*acquisition_count)++; + PyThread_release_lock(lock); + return result; +} + +static CYTHON_INLINE int +__pyx_sub_acquisition_count_locked(__pyx_atomic_int *acquisition_count, + PyThread_type_lock lock) +{ + int result; + PyThread_acquire_lock(lock, 1); + result = (*acquisition_count)--; + PyThread_release_lock(lock); + return result; +} + + +static CYTHON_INLINE void +__Pyx_INC_MEMVIEW({{memviewslice_name}} *memslice, int have_gil, int lineno) +{ + int first_time; + struct {{memview_struct_name}} *memview = memslice->memview; if (unlikely(!memview || (PyObject *) memview == Py_None)) - return; /* allow uninitialized memoryview assignment */ - + return; /* allow uninitialized memoryview assignment */ + if (unlikely(__pyx_get_slice_count(memview) < 0)) - __pyx_fatalerror("Acquisition count is %d (line %d)", - __pyx_get_slice_count(memview), lineno); - - first_time = __pyx_add_acquisition_count(memview) == 0; - + __pyx_fatalerror("Acquisition count is %d (line %d)", + __pyx_get_slice_count(memview), lineno); + + first_time = __pyx_add_acquisition_count(memview) == 0; + if (unlikely(first_time)) { - if (have_gil) { - Py_INCREF((PyObject *) memview); - } else { - PyGILState_STATE _gilstate = PyGILState_Ensure(); - Py_INCREF((PyObject *) memview); - PyGILState_Release(_gilstate); - } - } -} - -static CYTHON_INLINE void __Pyx_XDEC_MEMVIEW({{memviewslice_name}} *memslice, - int have_gil, int lineno) { - int last_time; - struct {{memview_struct_name}} *memview = memslice->memview; - + if (have_gil) { + Py_INCREF((PyObject *) memview); + } else { + PyGILState_STATE _gilstate = PyGILState_Ensure(); + Py_INCREF((PyObject *) memview); + PyGILState_Release(_gilstate); + } + } +} + +static CYTHON_INLINE void __Pyx_XDEC_MEMVIEW({{memviewslice_name}} *memslice, + int have_gil, int lineno) { + int last_time; + struct {{memview_struct_name}} *memview = memslice->memview; + if (unlikely(!memview || (PyObject *) memview == Py_None)) { // we do not ref-count None - memslice->memview = NULL; - return; - } - + memslice->memview = NULL; + return; + } + if (unlikely(__pyx_get_slice_count(memview) <= 0)) - __pyx_fatalerror("Acquisition count is %d (line %d)", - __pyx_get_slice_count(memview), lineno); - - last_time = __pyx_sub_acquisition_count(memview) == 1; - memslice->data = NULL; + __pyx_fatalerror("Acquisition count is %d (line %d)", + __pyx_get_slice_count(memview), lineno); + + last_time = __pyx_sub_acquisition_count(memview) == 1; + memslice->data = NULL; if (unlikely(last_time)) { - if (have_gil) { - Py_CLEAR(memslice->memview); - } else { - PyGILState_STATE _gilstate = PyGILState_Ensure(); - Py_CLEAR(memslice->memview); - PyGILState_Release(_gilstate); - } - } else { - memslice->memview = NULL; - } -} - - -////////// MemviewSliceCopyTemplate.proto ////////// - -static {{memviewslice_name}} -__pyx_memoryview_copy_new_contig(const __Pyx_memviewslice *from_mvs, - const char *mode, int ndim, - size_t sizeof_dtype, int contig_flag, - int dtype_is_object); - - -////////// MemviewSliceCopyTemplate ////////// - -static {{memviewslice_name}} -__pyx_memoryview_copy_new_contig(const __Pyx_memviewslice *from_mvs, - const char *mode, int ndim, - size_t sizeof_dtype, int contig_flag, - int dtype_is_object) -{ - __Pyx_RefNannyDeclarations - int i; - __Pyx_memviewslice new_mvs = {{memslice_init}}; - struct __pyx_memoryview_obj *from_memview = from_mvs->memview; - Py_buffer *buf = &from_memview->view; - PyObject *shape_tuple = NULL; - PyObject *temp_int = NULL; - struct __pyx_array_obj *array_obj = NULL; - struct __pyx_memoryview_obj *memview_obj = NULL; - - __Pyx_RefNannySetupContext("__pyx_memoryview_copy_new_contig", 0); - - for (i = 0; i < ndim; i++) { + if (have_gil) { + Py_CLEAR(memslice->memview); + } else { + PyGILState_STATE _gilstate = PyGILState_Ensure(); + Py_CLEAR(memslice->memview); + PyGILState_Release(_gilstate); + } + } else { + memslice->memview = NULL; + } +} + + +////////// MemviewSliceCopyTemplate.proto ////////// + +static {{memviewslice_name}} +__pyx_memoryview_copy_new_contig(const __Pyx_memviewslice *from_mvs, + const char *mode, int ndim, + size_t sizeof_dtype, int contig_flag, + int dtype_is_object); + + +////////// MemviewSliceCopyTemplate ////////// + +static {{memviewslice_name}} +__pyx_memoryview_copy_new_contig(const __Pyx_memviewslice *from_mvs, + const char *mode, int ndim, + size_t sizeof_dtype, int contig_flag, + int dtype_is_object) +{ + __Pyx_RefNannyDeclarations + int i; + __Pyx_memviewslice new_mvs = {{memslice_init}}; + struct __pyx_memoryview_obj *from_memview = from_mvs->memview; + Py_buffer *buf = &from_memview->view; + PyObject *shape_tuple = NULL; + PyObject *temp_int = NULL; + struct __pyx_array_obj *array_obj = NULL; + struct __pyx_memoryview_obj *memview_obj = NULL; + + __Pyx_RefNannySetupContext("__pyx_memoryview_copy_new_contig", 0); + + for (i = 0; i < ndim; i++) { if (unlikely(from_mvs->suboffsets[i] >= 0)) { - PyErr_Format(PyExc_ValueError, "Cannot copy memoryview slice with " - "indirect dimensions (axis %d)", i); - goto fail; - } - } - - shape_tuple = PyTuple_New(ndim); - if (unlikely(!shape_tuple)) { - goto fail; - } - __Pyx_GOTREF(shape_tuple); - - - for(i = 0; i < ndim; i++) { - temp_int = PyInt_FromSsize_t(from_mvs->shape[i]); - if(unlikely(!temp_int)) { - goto fail; - } else { - PyTuple_SET_ITEM(shape_tuple, i, temp_int); - temp_int = NULL; - } - } - - array_obj = __pyx_array_new(shape_tuple, sizeof_dtype, buf->format, (char *) mode, NULL); - if (unlikely(!array_obj)) { - goto fail; - } - __Pyx_GOTREF(array_obj); - - memview_obj = (struct __pyx_memoryview_obj *) __pyx_memoryview_new( - (PyObject *) array_obj, contig_flag, - dtype_is_object, - from_mvs->memview->typeinfo); - if (unlikely(!memview_obj)) - goto fail; - - /* initialize new_mvs */ - if (unlikely(__Pyx_init_memviewslice(memview_obj, ndim, &new_mvs, 1) < 0)) - goto fail; - - if (unlikely(__pyx_memoryview_copy_contents(*from_mvs, new_mvs, ndim, ndim, - dtype_is_object) < 0)) - goto fail; - - goto no_fail; - -fail: - __Pyx_XDECREF(new_mvs.memview); - new_mvs.memview = NULL; - new_mvs.data = NULL; -no_fail: - __Pyx_XDECREF(shape_tuple); - __Pyx_XDECREF(temp_int); - __Pyx_XDECREF(array_obj); - __Pyx_RefNannyFinishContext(); - return new_mvs; -} - - -////////// CopyContentsUtility.proto ///////// - -#define {{func_cname}}(slice) \ - __pyx_memoryview_copy_new_contig(&slice, "{{mode}}", {{ndim}}, \ - sizeof({{dtype_decl}}), {{contig_flag}}, \ - {{dtype_is_object}}) - - -////////// OverlappingSlices.proto ////////// - -static int __pyx_slices_overlap({{memviewslice_name}} *slice1, - {{memviewslice_name}} *slice2, - int ndim, size_t itemsize); - - -////////// OverlappingSlices ////////// - -/* Based on numpy's core/src/multiarray/array_assign.c */ - -/* Gets a half-open range [start, end) which contains the array data */ -static void -__pyx_get_array_memory_extents({{memviewslice_name}} *slice, - void **out_start, void **out_end, - int ndim, size_t itemsize) -{ - char *start, *end; - int i; - - start = end = slice->data; - - for (i = 0; i < ndim; i++) { - Py_ssize_t stride = slice->strides[i]; - Py_ssize_t extent = slice->shape[i]; - - if (extent == 0) { - *out_start = *out_end = start; - return; - } else { - if (stride > 0) - end += stride * (extent - 1); - else - start += stride * (extent - 1); - } - } - - /* Return a half-open range */ - *out_start = start; - *out_end = end + itemsize; -} - -/* Returns 1 if the arrays have overlapping data, 0 otherwise */ -static int -__pyx_slices_overlap({{memviewslice_name}} *slice1, - {{memviewslice_name}} *slice2, - int ndim, size_t itemsize) -{ - void *start1, *end1, *start2, *end2; - - __pyx_get_array_memory_extents(slice1, &start1, &end1, ndim, itemsize); - __pyx_get_array_memory_extents(slice2, &start2, &end2, ndim, itemsize); - - return (start1 < end2) && (start2 < end1); -} - - + PyErr_Format(PyExc_ValueError, "Cannot copy memoryview slice with " + "indirect dimensions (axis %d)", i); + goto fail; + } + } + + shape_tuple = PyTuple_New(ndim); + if (unlikely(!shape_tuple)) { + goto fail; + } + __Pyx_GOTREF(shape_tuple); + + + for(i = 0; i < ndim; i++) { + temp_int = PyInt_FromSsize_t(from_mvs->shape[i]); + if(unlikely(!temp_int)) { + goto fail; + } else { + PyTuple_SET_ITEM(shape_tuple, i, temp_int); + temp_int = NULL; + } + } + + array_obj = __pyx_array_new(shape_tuple, sizeof_dtype, buf->format, (char *) mode, NULL); + if (unlikely(!array_obj)) { + goto fail; + } + __Pyx_GOTREF(array_obj); + + memview_obj = (struct __pyx_memoryview_obj *) __pyx_memoryview_new( + (PyObject *) array_obj, contig_flag, + dtype_is_object, + from_mvs->memview->typeinfo); + if (unlikely(!memview_obj)) + goto fail; + + /* initialize new_mvs */ + if (unlikely(__Pyx_init_memviewslice(memview_obj, ndim, &new_mvs, 1) < 0)) + goto fail; + + if (unlikely(__pyx_memoryview_copy_contents(*from_mvs, new_mvs, ndim, ndim, + dtype_is_object) < 0)) + goto fail; + + goto no_fail; + +fail: + __Pyx_XDECREF(new_mvs.memview); + new_mvs.memview = NULL; + new_mvs.data = NULL; +no_fail: + __Pyx_XDECREF(shape_tuple); + __Pyx_XDECREF(temp_int); + __Pyx_XDECREF(array_obj); + __Pyx_RefNannyFinishContext(); + return new_mvs; +} + + +////////// CopyContentsUtility.proto ///////// + +#define {{func_cname}}(slice) \ + __pyx_memoryview_copy_new_contig(&slice, "{{mode}}", {{ndim}}, \ + sizeof({{dtype_decl}}), {{contig_flag}}, \ + {{dtype_is_object}}) + + +////////// OverlappingSlices.proto ////////// + +static int __pyx_slices_overlap({{memviewslice_name}} *slice1, + {{memviewslice_name}} *slice2, + int ndim, size_t itemsize); + + +////////// OverlappingSlices ////////// + +/* Based on numpy's core/src/multiarray/array_assign.c */ + +/* Gets a half-open range [start, end) which contains the array data */ +static void +__pyx_get_array_memory_extents({{memviewslice_name}} *slice, + void **out_start, void **out_end, + int ndim, size_t itemsize) +{ + char *start, *end; + int i; + + start = end = slice->data; + + for (i = 0; i < ndim; i++) { + Py_ssize_t stride = slice->strides[i]; + Py_ssize_t extent = slice->shape[i]; + + if (extent == 0) { + *out_start = *out_end = start; + return; + } else { + if (stride > 0) + end += stride * (extent - 1); + else + start += stride * (extent - 1); + } + } + + /* Return a half-open range */ + *out_start = start; + *out_end = end + itemsize; +} + +/* Returns 1 if the arrays have overlapping data, 0 otherwise */ +static int +__pyx_slices_overlap({{memviewslice_name}} *slice1, + {{memviewslice_name}} *slice2, + int ndim, size_t itemsize) +{ + void *start1, *end1, *start2, *end2; + + __pyx_get_array_memory_extents(slice1, &start1, &end1, ndim, itemsize); + __pyx_get_array_memory_extents(slice2, &start2, &end2, ndim, itemsize); + + return (start1 < end2) && (start2 < end1); +} + + ////////// MemviewSliceCheckContig.proto ////////// - + #define __pyx_memviewslice_is_contig_{{contig_type}}{{ndim}}(slice) \ __pyx_memviewslice_is_contig(slice, '{{contig_type}}', {{ndim}}) - - -////////// MemviewSliceIsContig.proto ////////// - + + +////////// MemviewSliceIsContig.proto ////////// + static int __pyx_memviewslice_is_contig(const {{memviewslice_name}} mvs, char order, int ndim);/*proto*/ - - -////////// MemviewSliceIsContig ////////// - -static int + + +////////// MemviewSliceIsContig ////////// + +static int __pyx_memviewslice_is_contig(const {{memviewslice_name}} mvs, char order, int ndim) -{ - int i, index, step, start; +{ + int i, index, step, start; Py_ssize_t itemsize = mvs.memview->view.itemsize; - - if (order == 'F') { - step = 1; - start = 0; - } else { - step = -1; - start = ndim - 1; - } - - for (i = 0; i < ndim; i++) { - index = start + step * i; + + if (order == 'F') { + step = 1; + start = 0; + } else { + step = -1; + start = ndim - 1; + } + + for (i = 0; i < ndim; i++) { + index = start + step * i; if (mvs.suboffsets[index] >= 0 || mvs.strides[index] != itemsize) - return 0; - + return 0; + itemsize *= mvs.shape[index]; - } - - return 1; -} - - -/////////////// MemviewSliceIndex /////////////// - -static CYTHON_INLINE char * -__pyx_memviewslice_index_full(const char *bufp, Py_ssize_t idx, - Py_ssize_t stride, Py_ssize_t suboffset) -{ - bufp = bufp + idx * stride; - if (suboffset >= 0) { - bufp = *((char **) bufp) + suboffset; - } - return (char *) bufp; -} - - -/////////////// MemviewDtypeToObject.proto /////////////// - -{{if to_py_function}} + } + + return 1; +} + + +/////////////// MemviewSliceIndex /////////////// + +static CYTHON_INLINE char * +__pyx_memviewslice_index_full(const char *bufp, Py_ssize_t idx, + Py_ssize_t stride, Py_ssize_t suboffset) +{ + bufp = bufp + idx * stride; + if (suboffset >= 0) { + bufp = *((char **) bufp) + suboffset; + } + return (char *) bufp; +} + + +/////////////// MemviewDtypeToObject.proto /////////////// + +{{if to_py_function}} static CYTHON_INLINE PyObject *{{get_function}}(const char *itemp); /* proto */ -{{endif}} - -{{if from_py_function}} +{{endif}} + +{{if from_py_function}} static CYTHON_INLINE int {{set_function}}(const char *itemp, PyObject *obj); /* proto */ -{{endif}} - -/////////////// MemviewDtypeToObject /////////////// - -{{#__pyx_memview_<dtype_name>_to_object}} - -/* Convert a dtype to or from a Python object */ - -{{if to_py_function}} +{{endif}} + +/////////////// MemviewDtypeToObject /////////////// + +{{#__pyx_memview_<dtype_name>_to_object}} + +/* Convert a dtype to or from a Python object */ + +{{if to_py_function}} static CYTHON_INLINE PyObject *{{get_function}}(const char *itemp) { - return (PyObject *) {{to_py_function}}(*({{dtype}} *) itemp); -} -{{endif}} - -{{if from_py_function}} + return (PyObject *) {{to_py_function}}(*({{dtype}} *) itemp); +} +{{endif}} + +{{if from_py_function}} static CYTHON_INLINE int {{set_function}}(const char *itemp, PyObject *obj) { - {{dtype}} value = {{from_py_function}}(obj); - if ({{error_condition}}) - return 0; - *({{dtype}} *) itemp = value; - return 1; -} -{{endif}} - - -/////////////// MemviewObjectToObject.proto /////////////// - -/* Function callbacks (for memoryview object) for dtype object */ -static PyObject *{{get_function}}(const char *itemp); /* proto */ -static int {{set_function}}(const char *itemp, PyObject *obj); /* proto */ - - -/////////////// MemviewObjectToObject /////////////// - -static PyObject *{{get_function}}(const char *itemp) { - PyObject *result = *(PyObject **) itemp; - Py_INCREF(result); - return result; -} - -static int {{set_function}}(const char *itemp, PyObject *obj) { - Py_INCREF(obj); - Py_DECREF(*(PyObject **) itemp); - *(PyObject **) itemp = obj; - return 1; -} - -/////////// ToughSlice ////////// - -/* Dimension is indexed with 'start:stop:step' */ - -if (unlikely(__pyx_memoryview_slice_memviewslice( - &{{dst}}, - {{src}}.shape[{{dim}}], {{src}}.strides[{{dim}}], {{src}}.suboffsets[{{dim}}], - {{dim}}, - {{new_ndim}}, + {{dtype}} value = {{from_py_function}}(obj); + if ({{error_condition}}) + return 0; + *({{dtype}} *) itemp = value; + return 1; +} +{{endif}} + + +/////////////// MemviewObjectToObject.proto /////////////// + +/* Function callbacks (for memoryview object) for dtype object */ +static PyObject *{{get_function}}(const char *itemp); /* proto */ +static int {{set_function}}(const char *itemp, PyObject *obj); /* proto */ + + +/////////////// MemviewObjectToObject /////////////// + +static PyObject *{{get_function}}(const char *itemp) { + PyObject *result = *(PyObject **) itemp; + Py_INCREF(result); + return result; +} + +static int {{set_function}}(const char *itemp, PyObject *obj) { + Py_INCREF(obj); + Py_DECREF(*(PyObject **) itemp); + *(PyObject **) itemp = obj; + return 1; +} + +/////////// ToughSlice ////////// + +/* Dimension is indexed with 'start:stop:step' */ + +if (unlikely(__pyx_memoryview_slice_memviewslice( + &{{dst}}, + {{src}}.shape[{{dim}}], {{src}}.strides[{{dim}}], {{src}}.suboffsets[{{dim}}], + {{dim}}, + {{new_ndim}}, &{{get_suboffset_dim()}}, - {{start}}, - {{stop}}, - {{step}}, - {{int(have_start)}}, - {{int(have_stop)}}, - {{int(have_step)}}, - 1) < 0)) -{ - {{error_goto}} -} - - -////////// SimpleSlice ////////// - -/* Dimension is indexed with ':' only */ - -{{dst}}.shape[{{new_ndim}}] = {{src}}.shape[{{dim}}]; -{{dst}}.strides[{{new_ndim}}] = {{src}}.strides[{{dim}}]; - -{{if access == 'direct'}} - {{dst}}.suboffsets[{{new_ndim}}] = -1; -{{else}} - {{dst}}.suboffsets[{{new_ndim}}] = {{src}}.suboffsets[{{dim}}]; - if ({{src}}.suboffsets[{{dim}}] >= 0) + {{start}}, + {{stop}}, + {{step}}, + {{int(have_start)}}, + {{int(have_stop)}}, + {{int(have_step)}}, + 1) < 0)) +{ + {{error_goto}} +} + + +////////// SimpleSlice ////////// + +/* Dimension is indexed with ':' only */ + +{{dst}}.shape[{{new_ndim}}] = {{src}}.shape[{{dim}}]; +{{dst}}.strides[{{new_ndim}}] = {{src}}.strides[{{dim}}]; + +{{if access == 'direct'}} + {{dst}}.suboffsets[{{new_ndim}}] = -1; +{{else}} + {{dst}}.suboffsets[{{new_ndim}}] = {{src}}.suboffsets[{{dim}}]; + if ({{src}}.suboffsets[{{dim}}] >= 0) {{get_suboffset_dim()}} = {{new_ndim}}; -{{endif}} - - -////////// SliceIndex ////////// - -// Dimension is indexed with an integer, we could use the ToughSlice -// approach, but this is faster - -{ - Py_ssize_t __pyx_tmp_idx = {{idx}}; +{{endif}} + + +////////// SliceIndex ////////// + +// Dimension is indexed with an integer, we could use the ToughSlice +// approach, but this is faster + +{ + Py_ssize_t __pyx_tmp_idx = {{idx}}; {{if wraparound or boundscheck}} Py_ssize_t __pyx_tmp_shape = {{src}}.shape[{{dim}}]; {{endif}} - Py_ssize_t __pyx_tmp_stride = {{src}}.strides[{{dim}}]; + Py_ssize_t __pyx_tmp_stride = {{src}}.strides[{{dim}}]; {{if wraparound}} if (__pyx_tmp_idx < 0) __pyx_tmp_idx += __pyx_tmp_shape; {{endif}} - + {{if boundscheck}} if (unlikely(!__Pyx_is_valid_index(__pyx_tmp_idx, __pyx_tmp_shape))) { {{if not have_gil}} @@ -867,79 +867,79 @@ if (unlikely(__pyx_memoryview_slice_memviewslice( PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure(); #endif {{endif}} - + PyErr_SetString(PyExc_IndexError, "Index out of bounds (axis {{dim}})"); - + {{if not have_gil}} #ifdef WITH_THREAD PyGILState_Release(__pyx_gilstate_save); #endif {{endif}} - + {{error_goto}} } {{endif}} - - {{if all_dimensions_direct}} - {{dst}}.data += __pyx_tmp_idx * __pyx_tmp_stride; - {{else}} + + {{if all_dimensions_direct}} + {{dst}}.data += __pyx_tmp_idx * __pyx_tmp_stride; + {{else}} if ({{get_suboffset_dim()}} < 0) { - {{dst}}.data += __pyx_tmp_idx * __pyx_tmp_stride; - - /* This dimension is the first dimension, or is preceded by */ - /* direct or indirect dimensions that are indexed away. */ - /* Hence suboffset_dim must be less than zero, and we can have */ - /* our data pointer refer to another block by dereferencing. */ - /* slice.data -> B -> C becomes slice.data -> C */ - - {{if indirect}} - { - Py_ssize_t __pyx_tmp_suboffset = {{src}}.suboffsets[{{dim}}]; - - {{if generic}} - if (__pyx_tmp_suboffset >= 0) - {{endif}} - - {{dst}}.data = *((char **) {{dst}}.data) + __pyx_tmp_suboffset; - } - {{endif}} - - } else { + {{dst}}.data += __pyx_tmp_idx * __pyx_tmp_stride; + + /* This dimension is the first dimension, or is preceded by */ + /* direct or indirect dimensions that are indexed away. */ + /* Hence suboffset_dim must be less than zero, and we can have */ + /* our data pointer refer to another block by dereferencing. */ + /* slice.data -> B -> C becomes slice.data -> C */ + + {{if indirect}} + { + Py_ssize_t __pyx_tmp_suboffset = {{src}}.suboffsets[{{dim}}]; + + {{if generic}} + if (__pyx_tmp_suboffset >= 0) + {{endif}} + + {{dst}}.data = *((char **) {{dst}}.data) + __pyx_tmp_suboffset; + } + {{endif}} + + } else { {{dst}}.suboffsets[{{get_suboffset_dim()}}] += __pyx_tmp_idx * __pyx_tmp_stride; - - /* Note: dimension can not be indirect, the compiler will have */ - /* issued an error */ - } - - {{endif}} -} - - -////////// FillStrided1DScalar.proto ////////// - -static void -__pyx_fill_slice_{{dtype_name}}({{type_decl}} *p, Py_ssize_t extent, Py_ssize_t stride, - size_t itemsize, void *itemp); - -////////// FillStrided1DScalar ////////// - -/* Fill a slice with a scalar value. The dimension is direct and strided or contiguous */ -/* This can be used as a callback for the memoryview object to efficienty assign a scalar */ -/* Currently unused */ -static void -__pyx_fill_slice_{{dtype_name}}({{type_decl}} *p, Py_ssize_t extent, Py_ssize_t stride, - size_t itemsize, void *itemp) -{ - Py_ssize_t i; - {{type_decl}} item = *(({{type_decl}} *) itemp); - {{type_decl}} *endp; - - stride /= sizeof({{type_decl}}); - endp = p + stride * extent; - - while (p < endp) { - *p = item; - p += stride; - } -} + + /* Note: dimension can not be indirect, the compiler will have */ + /* issued an error */ + } + + {{endif}} +} + + +////////// FillStrided1DScalar.proto ////////// + +static void +__pyx_fill_slice_{{dtype_name}}({{type_decl}} *p, Py_ssize_t extent, Py_ssize_t stride, + size_t itemsize, void *itemp); + +////////// FillStrided1DScalar ////////// + +/* Fill a slice with a scalar value. The dimension is direct and strided or contiguous */ +/* This can be used as a callback for the memoryview object to efficienty assign a scalar */ +/* Currently unused */ +static void +__pyx_fill_slice_{{dtype_name}}({{type_decl}} *p, Py_ssize_t extent, Py_ssize_t stride, + size_t itemsize, void *itemp) +{ + Py_ssize_t i; + {{type_decl}} item = *(({{type_decl}} *) itemp); + {{type_decl}} *endp; + + stride /= sizeof({{type_decl}}); + endp = p + stride * extent; + + while (p < endp) { + *p = item; + p += stride; + } +} diff --git a/contrib/tools/cython/Cython/Utility/ModuleSetupCode.c b/contrib/tools/cython/Cython/Utility/ModuleSetupCode.c index 0c7059b354..b246058bd3 100644 --- a/contrib/tools/cython/Cython/Utility/ModuleSetupCode.c +++ b/contrib/tools/cython/Cython/Utility/ModuleSetupCode.c @@ -1,5 +1,5 @@ -/////////////// CModulePreamble /////////////// - +/////////////// CModulePreamble /////////////// + #if defined(__GNUC__) || defined(__clang__) #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wshadow" @@ -7,33 +7,33 @@ #if PY_VERSION_HEX >= 0x030800b4 && PY_VERSION_HEX < 0x03090000 // Ignore tp_print initializer. Need for ya make -DUSE_SYSTEM_PYTHON=3.8 #pragma GCC diagnostic ignored "-Wdeprecated-declarations" +#endif #endif -#endif - -#include <stddef.h> /* For offsetof */ -#ifndef offsetof + +#include <stddef.h> /* For offsetof */ +#ifndef offsetof #define offsetof(type, member) ( (size_t) & ((type*)0) -> member ) -#endif - -#if !defined(WIN32) && !defined(MS_WINDOWS) - #ifndef __stdcall - #define __stdcall - #endif - #ifndef __cdecl - #define __cdecl - #endif - #ifndef __fastcall - #define __fastcall - #endif -#endif - -#ifndef DL_IMPORT - #define DL_IMPORT(t) t -#endif -#ifndef DL_EXPORT - #define DL_EXPORT(t) t -#endif - +#endif + +#if !defined(WIN32) && !defined(MS_WINDOWS) + #ifndef __stdcall + #define __stdcall + #endif + #ifndef __cdecl + #define __cdecl + #endif + #ifndef __fastcall + #define __fastcall + #endif +#endif + +#ifndef DL_IMPORT + #define DL_IMPORT(t) t +#endif +#ifndef DL_EXPORT + #define DL_EXPORT(t) t +#endif + // For use in DL_IMPORT/DL_EXPORT macros. #define __PYX_COMMA , @@ -44,15 +44,15 @@ #endif #endif -#ifndef PY_LONG_LONG - #define PY_LONG_LONG LONG_LONG -#endif - -#ifndef Py_HUGE_VAL - #define Py_HUGE_VAL HUGE_VAL -#endif - -#ifdef PYPY_VERSION +#ifndef PY_LONG_LONG + #define PY_LONG_LONG LONG_LONG +#endif + +#ifndef Py_HUGE_VAL + #define Py_HUGE_VAL HUGE_VAL +#endif + +#ifdef PYPY_VERSION #define CYTHON_COMPILING_IN_PYPY 1 #define CYTHON_COMPILING_IN_PYSTON 0 #define CYTHON_COMPILING_IN_CPYTHON 0 @@ -137,7 +137,7 @@ #undef CYTHON_USE_EXC_INFO_STACK #define CYTHON_USE_EXC_INFO_STACK 0 -#else +#else #define CYTHON_COMPILING_IN_PYPY 0 #define CYTHON_COMPILING_IN_PYSTON 0 #define CYTHON_COMPILING_IN_CPYTHON 1 @@ -207,8 +207,8 @@ #ifndef CYTHON_USE_EXC_INFO_STACK #define CYTHON_USE_EXC_INFO_STACK (PY_VERSION_HEX >= 0x030700A3) #endif -#endif - +#endif + #if !defined(CYTHON_FAST_PYCCALL) #define CYTHON_FAST_PYCCALL (CYTHON_FAST_PYCALL && PY_VERSION_HEX >= 0x030600B1) #endif @@ -385,18 +385,18 @@ class __Pyx_FakeReference { #if CYTHON_COMPILING_IN_PYPY && PY_VERSION_HEX < 0x02070600 && !defined(Py_OptimizeFlag) #define Py_OptimizeFlag 0 -#endif - -#define __PYX_BUILD_PY_SSIZE_T "n" -#define CYTHON_FORMAT_SSIZE_T "z" - -#if PY_MAJOR_VERSION < 3 - #define __Pyx_BUILTIN_MODULE_NAME "__builtin__" - #define __Pyx_PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) \ - PyCode_New(a+k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) - #define __Pyx_DefaultClassType PyClass_Type -#else - #define __Pyx_BUILTIN_MODULE_NAME "builtins" +#endif + +#define __PYX_BUILD_PY_SSIZE_T "n" +#define CYTHON_FORMAT_SSIZE_T "z" + +#if PY_MAJOR_VERSION < 3 + #define __Pyx_BUILTIN_MODULE_NAME "__builtin__" + #define __Pyx_PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) \ + PyCode_New(a+k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) + #define __Pyx_DefaultClassType PyClass_Type +#else + #define __Pyx_BUILTIN_MODULE_NAME "builtins" #define __Pyx_DefaultClassType PyType_Type #if PY_VERSION_HEX >= 0x030B00A1 static CYTHON_INLINE PyCodeObject* __Pyx_PyCode_New(int a, int k, int l, int s, int f, @@ -470,24 +470,24 @@ class __Pyx_FakeReference { } #else #define __Pyx_PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) \ - PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) -#endif - #define __Pyx_DefaultClassType PyType_Type + PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) #endif - + #define __Pyx_DefaultClassType PyType_Type +#endif + #ifndef Py_TPFLAGS_CHECKTYPES - #define Py_TPFLAGS_CHECKTYPES 0 + #define Py_TPFLAGS_CHECKTYPES 0 #endif #ifndef Py_TPFLAGS_HAVE_INDEX - #define Py_TPFLAGS_HAVE_INDEX 0 -#endif + #define Py_TPFLAGS_HAVE_INDEX 0 +#endif #ifndef Py_TPFLAGS_HAVE_NEWBUFFER - #define Py_TPFLAGS_HAVE_NEWBUFFER 0 -#endif + #define Py_TPFLAGS_HAVE_NEWBUFFER 0 +#endif #ifndef Py_TPFLAGS_HAVE_FINALIZE - #define Py_TPFLAGS_HAVE_FINALIZE 0 -#endif - + #define Py_TPFLAGS_HAVE_FINALIZE 0 +#endif + #ifndef METH_STACKLESS // already defined for Stackless Python (all versions) and C-Python >= 3.7 // value if defined: Stackless Python < 3.6: 0x80 else 0x100 @@ -604,24 +604,24 @@ static CYTHON_INLINE void * PyThread_tss_get(Py_tss_t *key) { #define __Pyx_PyDict_GetItemStr(dict, name) PyDict_GetItem(dict, name) #endif -/* new Py3.3 unicode type (PEP 393) */ -#if PY_VERSION_HEX > 0x03030000 && defined(PyUnicode_KIND) - #define CYTHON_PEP393_ENABLED 1 +/* new Py3.3 unicode type (PEP 393) */ +#if PY_VERSION_HEX > 0x03030000 && defined(PyUnicode_KIND) + #define CYTHON_PEP393_ENABLED 1 #if defined(PyUnicode_IS_READY) - #define __Pyx_PyUnicode_READY(op) (likely(PyUnicode_IS_READY(op)) ? \ - 0 : _PyUnicode_Ready((PyObject *)(op))) + #define __Pyx_PyUnicode_READY(op) (likely(PyUnicode_IS_READY(op)) ? \ + 0 : _PyUnicode_Ready((PyObject *)(op))) #else // Py3.12 / PEP-623 will remove wstr type unicode strings and all of the PyUnicode_READY() machinery. #define __Pyx_PyUnicode_READY(op) (0) #endif - #define __Pyx_PyUnicode_GET_LENGTH(u) PyUnicode_GET_LENGTH(u) - #define __Pyx_PyUnicode_READ_CHAR(u, i) PyUnicode_READ_CHAR(u, i) + #define __Pyx_PyUnicode_GET_LENGTH(u) PyUnicode_GET_LENGTH(u) + #define __Pyx_PyUnicode_READ_CHAR(u, i) PyUnicode_READ_CHAR(u, i) #define __Pyx_PyUnicode_MAX_CHAR_VALUE(u) PyUnicode_MAX_CHAR_VALUE(u) - #define __Pyx_PyUnicode_KIND(u) PyUnicode_KIND(u) - #define __Pyx_PyUnicode_DATA(u) PyUnicode_DATA(u) - #define __Pyx_PyUnicode_READ(k, d, i) PyUnicode_READ(k, d, i) + #define __Pyx_PyUnicode_KIND(u) PyUnicode_KIND(u) + #define __Pyx_PyUnicode_DATA(u) PyUnicode_DATA(u) + #define __Pyx_PyUnicode_READ(k, d, i) PyUnicode_READ(k, d, i) #define __Pyx_PyUnicode_WRITE(k, d, i, ch) PyUnicode_WRITE(k, d, i, ch) #if defined(PyUnicode_IS_READY) && defined(PyUnicode_GET_SIZE) #if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x03090000 @@ -634,32 +634,32 @@ static CYTHON_INLINE void * PyThread_tss_get(Py_tss_t *key) { #else #define __Pyx_PyUnicode_IS_TRUE(u) (0 != PyUnicode_GET_LENGTH(u)) #endif -#else - #define CYTHON_PEP393_ENABLED 0 +#else + #define CYTHON_PEP393_ENABLED 0 #define PyUnicode_1BYTE_KIND 1 #define PyUnicode_2BYTE_KIND 2 #define PyUnicode_4BYTE_KIND 4 - #define __Pyx_PyUnicode_READY(op) (0) - #define __Pyx_PyUnicode_GET_LENGTH(u) PyUnicode_GET_SIZE(u) - #define __Pyx_PyUnicode_READ_CHAR(u, i) ((Py_UCS4)(PyUnicode_AS_UNICODE(u)[i])) + #define __Pyx_PyUnicode_READY(op) (0) + #define __Pyx_PyUnicode_GET_LENGTH(u) PyUnicode_GET_SIZE(u) + #define __Pyx_PyUnicode_READ_CHAR(u, i) ((Py_UCS4)(PyUnicode_AS_UNICODE(u)[i])) #define __Pyx_PyUnicode_MAX_CHAR_VALUE(u) ((sizeof(Py_UNICODE) == 2) ? 65535 : 1114111) - #define __Pyx_PyUnicode_KIND(u) (sizeof(Py_UNICODE)) - #define __Pyx_PyUnicode_DATA(u) ((void*)PyUnicode_AS_UNICODE(u)) - /* (void)(k) => avoid unused variable warning due to macro: */ - #define __Pyx_PyUnicode_READ(k, d, i) ((void)(k), (Py_UCS4)(((Py_UNICODE*)d)[i])) + #define __Pyx_PyUnicode_KIND(u) (sizeof(Py_UNICODE)) + #define __Pyx_PyUnicode_DATA(u) ((void*)PyUnicode_AS_UNICODE(u)) + /* (void)(k) => avoid unused variable warning due to macro: */ + #define __Pyx_PyUnicode_READ(k, d, i) ((void)(k), (Py_UCS4)(((Py_UNICODE*)d)[i])) #define __Pyx_PyUnicode_WRITE(k, d, i, ch) (((void)(k)), ((Py_UNICODE*)d)[i] = ch) #define __Pyx_PyUnicode_IS_TRUE(u) (0 != PyUnicode_GET_SIZE(u)) -#endif - -#if CYTHON_COMPILING_IN_PYPY - #define __Pyx_PyUnicode_Concat(a, b) PyNumber_Add(a, b) - #define __Pyx_PyUnicode_ConcatSafe(a, b) PyNumber_Add(a, b) -#else - #define __Pyx_PyUnicode_Concat(a, b) PyUnicode_Concat(a, b) - #define __Pyx_PyUnicode_ConcatSafe(a, b) ((unlikely((a) == Py_None) || unlikely((b) == Py_None)) ? \ - PyNumber_Add(a, b) : __Pyx_PyUnicode_Concat(a, b)) -#endif - +#endif + +#if CYTHON_COMPILING_IN_PYPY + #define __Pyx_PyUnicode_Concat(a, b) PyNumber_Add(a, b) + #define __Pyx_PyUnicode_ConcatSafe(a, b) PyNumber_Add(a, b) +#else + #define __Pyx_PyUnicode_Concat(a, b) PyUnicode_Concat(a, b) + #define __Pyx_PyUnicode_ConcatSafe(a, b) ((unlikely((a) == Py_None) || unlikely((b) == Py_None)) ? \ + PyNumber_Add(a, b) : __Pyx_PyUnicode_Concat(a, b)) +#endif + #if CYTHON_COMPILING_IN_PYPY && !defined(PyUnicode_Contains) #define PyUnicode_Contains(u, s) PySequence_Contains(u, s) #endif @@ -675,41 +675,41 @@ static CYTHON_INLINE void * PyThread_tss_get(Py_tss_t *key) { // ("..." % x) must call PyNumber_Remainder() if x is a string subclass that implements "__rmod__()". #define __Pyx_PyString_FormatSafe(a, b) ((unlikely((a) == Py_None || (PyString_Check(b) && !PyString_CheckExact(b)))) ? PyNumber_Remainder(a, b) : __Pyx_PyString_Format(a, b)) #define __Pyx_PyUnicode_FormatSafe(a, b) ((unlikely((a) == Py_None || (PyUnicode_Check(b) && !PyUnicode_CheckExact(b)))) ? PyNumber_Remainder(a, b) : PyUnicode_Format(a, b)) - -#if PY_MAJOR_VERSION >= 3 - #define __Pyx_PyString_Format(a, b) PyUnicode_Format(a, b) -#else - #define __Pyx_PyString_Format(a, b) PyString_Format(a, b) -#endif - + +#if PY_MAJOR_VERSION >= 3 + #define __Pyx_PyString_Format(a, b) PyUnicode_Format(a, b) +#else + #define __Pyx_PyString_Format(a, b) PyString_Format(a, b) +#endif + #if PY_MAJOR_VERSION < 3 && !defined(PyObject_ASCII) #define PyObject_ASCII(o) PyObject_Repr(o) #endif -#if PY_MAJOR_VERSION >= 3 - #define PyBaseString_Type PyUnicode_Type - #define PyStringObject PyUnicodeObject - #define PyString_Type PyUnicode_Type - #define PyString_Check PyUnicode_Check - #define PyString_CheckExact PyUnicode_CheckExact +#if PY_MAJOR_VERSION >= 3 + #define PyBaseString_Type PyUnicode_Type + #define PyStringObject PyUnicodeObject + #define PyString_Type PyUnicode_Type + #define PyString_Check PyUnicode_Check + #define PyString_CheckExact PyUnicode_CheckExact // PyPy3 used to define "PyObject_Unicode" #ifndef PyObject_Unicode #define PyObject_Unicode PyObject_Str -#endif -#endif - -#if PY_MAJOR_VERSION >= 3 - #define __Pyx_PyBaseString_Check(obj) PyUnicode_Check(obj) - #define __Pyx_PyBaseString_CheckExact(obj) PyUnicode_CheckExact(obj) -#else - #define __Pyx_PyBaseString_Check(obj) (PyString_Check(obj) || PyUnicode_Check(obj)) - #define __Pyx_PyBaseString_CheckExact(obj) (PyString_CheckExact(obj) || PyUnicode_CheckExact(obj)) -#endif - -#ifndef PySet_CheckExact - #define PySet_CheckExact(obj) (Py_TYPE(obj) == &PySet_Type) -#endif - +#endif +#endif + +#if PY_MAJOR_VERSION >= 3 + #define __Pyx_PyBaseString_Check(obj) PyUnicode_Check(obj) + #define __Pyx_PyBaseString_CheckExact(obj) PyUnicode_CheckExact(obj) +#else + #define __Pyx_PyBaseString_Check(obj) (PyString_Check(obj) || PyUnicode_Check(obj)) + #define __Pyx_PyBaseString_CheckExact(obj) (PyString_CheckExact(obj) || PyUnicode_CheckExact(obj)) +#endif + +#ifndef PySet_CheckExact + #define PySet_CheckExact(obj) (Py_TYPE(obj) == &PySet_Type) +#endif + #if PY_VERSION_HEX >= 0x030900A4 #define __Pyx_SET_REFCNT(obj, refcnt) Py_SET_REFCNT(obj, refcnt) @@ -725,50 +725,50 @@ static CYTHON_INLINE void * PyThread_tss_get(Py_tss_t *key) { // NOTE: might fail with exception => check for -1 #define __Pyx_PySequence_SIZE(seq) PySequence_Size(seq) #endif - -#if PY_MAJOR_VERSION >= 3 - #define PyIntObject PyLongObject - #define PyInt_Type PyLong_Type - #define PyInt_Check(op) PyLong_Check(op) - #define PyInt_CheckExact(op) PyLong_CheckExact(op) - #define PyInt_FromString PyLong_FromString - #define PyInt_FromUnicode PyLong_FromUnicode - #define PyInt_FromLong PyLong_FromLong - #define PyInt_FromSize_t PyLong_FromSize_t - #define PyInt_FromSsize_t PyLong_FromSsize_t - #define PyInt_AsLong PyLong_AsLong - #define PyInt_AS_LONG PyLong_AS_LONG - #define PyInt_AsSsize_t PyLong_AsSsize_t - #define PyInt_AsUnsignedLongMask PyLong_AsUnsignedLongMask - #define PyInt_AsUnsignedLongLongMask PyLong_AsUnsignedLongLongMask - #define PyNumber_Int PyNumber_Long -#endif - -#if PY_MAJOR_VERSION >= 3 - #define PyBoolObject PyLongObject -#endif - + +#if PY_MAJOR_VERSION >= 3 + #define PyIntObject PyLongObject + #define PyInt_Type PyLong_Type + #define PyInt_Check(op) PyLong_Check(op) + #define PyInt_CheckExact(op) PyLong_CheckExact(op) + #define PyInt_FromString PyLong_FromString + #define PyInt_FromUnicode PyLong_FromUnicode + #define PyInt_FromLong PyLong_FromLong + #define PyInt_FromSize_t PyLong_FromSize_t + #define PyInt_FromSsize_t PyLong_FromSsize_t + #define PyInt_AsLong PyLong_AsLong + #define PyInt_AS_LONG PyLong_AS_LONG + #define PyInt_AsSsize_t PyLong_AsSsize_t + #define PyInt_AsUnsignedLongMask PyLong_AsUnsignedLongMask + #define PyInt_AsUnsignedLongLongMask PyLong_AsUnsignedLongLongMask + #define PyNumber_Int PyNumber_Long +#endif + +#if PY_MAJOR_VERSION >= 3 + #define PyBoolObject PyLongObject +#endif + #if PY_MAJOR_VERSION >= 3 && CYTHON_COMPILING_IN_PYPY #ifndef PyUnicode_InternFromString #define PyUnicode_InternFromString(s) PyUnicode_FromString(s) #endif #endif -#if PY_VERSION_HEX < 0x030200A4 - typedef long Py_hash_t; - #define __Pyx_PyInt_FromHash_t PyInt_FromLong +#if PY_VERSION_HEX < 0x030200A4 + typedef long Py_hash_t; + #define __Pyx_PyInt_FromHash_t PyInt_FromLong #define __Pyx_PyInt_AsHash_t __Pyx_PyIndex_AsHash_t -#else - #define __Pyx_PyInt_FromHash_t PyInt_FromSsize_t +#else + #define __Pyx_PyInt_FromHash_t PyInt_FromSsize_t #define __Pyx_PyInt_AsHash_t __Pyx_PyIndex_AsSsize_t -#endif - -#if PY_MAJOR_VERSION >= 3 +#endif + +#if PY_MAJOR_VERSION >= 3 #define __Pyx_PyMethod_New(func, self, klass) ((self) ? ((void)(klass), PyMethod_New(func, self)) : __Pyx_NewRef(func)) #else #define __Pyx_PyMethod_New(func, self, klass) PyMethod_New(func, self, klass) -#endif - +#endif + // backport of PyAsyncMethods from Py3.5 to older Py3.x versions // (mis-)using the "tp_reserved" type slot which is re-activated as "tp_as_async" in Py3.5 #if CYTHON_USE_ASYNC_SLOTS @@ -787,9 +787,9 @@ static CYTHON_INLINE void * PyThread_tss_get(Py_tss_t *key) { unaryfunc am_aiter; unaryfunc am_anext; } __Pyx_PyAsyncMethodsStruct; -#endif - - +#endif + + /////////////// SmallCodeConfig.proto /////////////// #ifndef CYTHON_SMALL_CODE @@ -972,44 +972,44 @@ static CYTHON_INLINE int __Pyx_PyErr_GivenExceptionMatches2(PyObject *err, PyObj #endif #include <math.h> -#ifdef NAN -#define __PYX_NAN() ((float) NAN) -#else -static CYTHON_INLINE float __PYX_NAN() { +#ifdef NAN +#define __PYX_NAN() ((float) NAN) +#else +static CYTHON_INLINE float __PYX_NAN() { // Initialize NaN. The sign is irrelevant, an exponent with all bits 1 and // a nonzero mantissa means NaN. If the first bit in the mantissa is 1, it is // a quiet NaN. - float value; - memset(&value, 0xFF, sizeof(value)); - return value; -} -#endif - + float value; + memset(&value, 0xFF, sizeof(value)); + return value; +} +#endif + #if defined(__CYGWIN__) && defined(_LDBL_EQ_DBL) #define __Pyx_truncl trunc #else #define __Pyx_truncl truncl #endif + - -/////////////// UtilityFunctionPredeclarations.proto /////////////// - +/////////////// UtilityFunctionPredeclarations.proto /////////////// + typedef struct {PyObject **p; const char *s; const Py_ssize_t n; const char* encoding; - const char is_unicode; const char is_str; const char intern; } __Pyx_StringTabEntry; /*proto*/ - -/////////////// ForceInitThreads.proto /////////////// + const char is_unicode; const char is_str; const char intern; } __Pyx_StringTabEntry; /*proto*/ + +/////////////// ForceInitThreads.proto /////////////// //@proto_block: utility_code_proto_before_types - -#ifndef __PYX_FORCE_INIT_THREADS - #define __PYX_FORCE_INIT_THREADS 0 -#endif - -/////////////// InitThreads.init /////////////// - + +#ifndef __PYX_FORCE_INIT_THREADS + #define __PYX_FORCE_INIT_THREADS 0 +#endif + +/////////////// InitThreads.init /////////////// + #if defined(WITH_THREAD) && PY_VERSION_HEX < 0x030700F0 -PyEval_InitThreads(); -#endif - +PyEval_InitThreads(); +#endif + /////////////// ModuleCreationPEP489 /////////////// //@substitute: naming @@ -1090,145 +1090,145 @@ bad: //#endif -/////////////// CodeObjectCache.proto /////////////// - -typedef struct { +/////////////// CodeObjectCache.proto /////////////// + +typedef struct { PyCodeObject* code_object; - int code_line; -} __Pyx_CodeObjectCacheEntry; - -struct __Pyx_CodeObjectCache { - int count; - int max_count; - __Pyx_CodeObjectCacheEntry* entries; -}; - -static struct __Pyx_CodeObjectCache __pyx_code_cache = {0,0,NULL}; - -static int __pyx_bisect_code_objects(__Pyx_CodeObjectCacheEntry* entries, int count, int code_line); -static PyCodeObject *__pyx_find_code_object(int code_line); -static void __pyx_insert_code_object(int code_line, PyCodeObject* code_object); - -/////////////// CodeObjectCache /////////////// -// Note that errors are simply ignored in the code below. -// This is just a cache, if a lookup or insertion fails - so what? - -static int __pyx_bisect_code_objects(__Pyx_CodeObjectCacheEntry* entries, int count, int code_line) { - int start = 0, mid = 0, end = count - 1; - if (end >= 0 && code_line > entries[end].code_line) { - return count; - } - while (start < end) { + int code_line; +} __Pyx_CodeObjectCacheEntry; + +struct __Pyx_CodeObjectCache { + int count; + int max_count; + __Pyx_CodeObjectCacheEntry* entries; +}; + +static struct __Pyx_CodeObjectCache __pyx_code_cache = {0,0,NULL}; + +static int __pyx_bisect_code_objects(__Pyx_CodeObjectCacheEntry* entries, int count, int code_line); +static PyCodeObject *__pyx_find_code_object(int code_line); +static void __pyx_insert_code_object(int code_line, PyCodeObject* code_object); + +/////////////// CodeObjectCache /////////////// +// Note that errors are simply ignored in the code below. +// This is just a cache, if a lookup or insertion fails - so what? + +static int __pyx_bisect_code_objects(__Pyx_CodeObjectCacheEntry* entries, int count, int code_line) { + int start = 0, mid = 0, end = count - 1; + if (end >= 0 && code_line > entries[end].code_line) { + return count; + } + while (start < end) { mid = start + (end - start) / 2; - if (code_line < entries[mid].code_line) { - end = mid; - } else if (code_line > entries[mid].code_line) { - start = mid + 1; - } else { - return mid; - } - } - if (code_line <= entries[mid].code_line) { - return mid; - } else { - return mid + 1; - } -} - -static PyCodeObject *__pyx_find_code_object(int code_line) { - PyCodeObject* code_object; - int pos; - if (unlikely(!code_line) || unlikely(!__pyx_code_cache.entries)) { - return NULL; - } - pos = __pyx_bisect_code_objects(__pyx_code_cache.entries, __pyx_code_cache.count, code_line); - if (unlikely(pos >= __pyx_code_cache.count) || unlikely(__pyx_code_cache.entries[pos].code_line != code_line)) { - return NULL; - } - code_object = __pyx_code_cache.entries[pos].code_object; - Py_INCREF(code_object); - return code_object; -} - -static void __pyx_insert_code_object(int code_line, PyCodeObject* code_object) { - int pos, i; - __Pyx_CodeObjectCacheEntry* entries = __pyx_code_cache.entries; - if (unlikely(!code_line)) { - return; - } - if (unlikely(!entries)) { - entries = (__Pyx_CodeObjectCacheEntry*)PyMem_Malloc(64*sizeof(__Pyx_CodeObjectCacheEntry)); - if (likely(entries)) { - __pyx_code_cache.entries = entries; - __pyx_code_cache.max_count = 64; - __pyx_code_cache.count = 1; - entries[0].code_line = code_line; - entries[0].code_object = code_object; - Py_INCREF(code_object); - } - return; - } - pos = __pyx_bisect_code_objects(__pyx_code_cache.entries, __pyx_code_cache.count, code_line); - if ((pos < __pyx_code_cache.count) && unlikely(__pyx_code_cache.entries[pos].code_line == code_line)) { - PyCodeObject* tmp = entries[pos].code_object; - entries[pos].code_object = code_object; - Py_DECREF(tmp); - return; - } - if (__pyx_code_cache.count == __pyx_code_cache.max_count) { - int new_max = __pyx_code_cache.max_count + 64; - entries = (__Pyx_CodeObjectCacheEntry*)PyMem_Realloc( + if (code_line < entries[mid].code_line) { + end = mid; + } else if (code_line > entries[mid].code_line) { + start = mid + 1; + } else { + return mid; + } + } + if (code_line <= entries[mid].code_line) { + return mid; + } else { + return mid + 1; + } +} + +static PyCodeObject *__pyx_find_code_object(int code_line) { + PyCodeObject* code_object; + int pos; + if (unlikely(!code_line) || unlikely(!__pyx_code_cache.entries)) { + return NULL; + } + pos = __pyx_bisect_code_objects(__pyx_code_cache.entries, __pyx_code_cache.count, code_line); + if (unlikely(pos >= __pyx_code_cache.count) || unlikely(__pyx_code_cache.entries[pos].code_line != code_line)) { + return NULL; + } + code_object = __pyx_code_cache.entries[pos].code_object; + Py_INCREF(code_object); + return code_object; +} + +static void __pyx_insert_code_object(int code_line, PyCodeObject* code_object) { + int pos, i; + __Pyx_CodeObjectCacheEntry* entries = __pyx_code_cache.entries; + if (unlikely(!code_line)) { + return; + } + if (unlikely(!entries)) { + entries = (__Pyx_CodeObjectCacheEntry*)PyMem_Malloc(64*sizeof(__Pyx_CodeObjectCacheEntry)); + if (likely(entries)) { + __pyx_code_cache.entries = entries; + __pyx_code_cache.max_count = 64; + __pyx_code_cache.count = 1; + entries[0].code_line = code_line; + entries[0].code_object = code_object; + Py_INCREF(code_object); + } + return; + } + pos = __pyx_bisect_code_objects(__pyx_code_cache.entries, __pyx_code_cache.count, code_line); + if ((pos < __pyx_code_cache.count) && unlikely(__pyx_code_cache.entries[pos].code_line == code_line)) { + PyCodeObject* tmp = entries[pos].code_object; + entries[pos].code_object = code_object; + Py_DECREF(tmp); + return; + } + if (__pyx_code_cache.count == __pyx_code_cache.max_count) { + int new_max = __pyx_code_cache.max_count + 64; + entries = (__Pyx_CodeObjectCacheEntry*)PyMem_Realloc( __pyx_code_cache.entries, ((size_t)new_max) * sizeof(__Pyx_CodeObjectCacheEntry)); - if (unlikely(!entries)) { - return; - } - __pyx_code_cache.entries = entries; - __pyx_code_cache.max_count = new_max; - } - for (i=__pyx_code_cache.count; i>pos; i--) { - entries[i] = entries[i-1]; - } - entries[pos].code_line = code_line; - entries[pos].code_object = code_object; - __pyx_code_cache.count++; - Py_INCREF(code_object); -} - -/////////////// CodeObjectCache.cleanup /////////////// - - if (__pyx_code_cache.entries) { - __Pyx_CodeObjectCacheEntry* entries = __pyx_code_cache.entries; - int i, count = __pyx_code_cache.count; - __pyx_code_cache.count = 0; - __pyx_code_cache.max_count = 0; - __pyx_code_cache.entries = NULL; - for (i=0; i<count; i++) { - Py_DECREF(entries[i].code_object); - } - PyMem_Free(entries); - } - -/////////////// CheckBinaryVersion.proto /////////////// - -static int __Pyx_check_binary_version(void); - -/////////////// CheckBinaryVersion /////////////// - -static int __Pyx_check_binary_version(void) { - char ctversion[4], rtversion[4]; - PyOS_snprintf(ctversion, 4, "%d.%d", PY_MAJOR_VERSION, PY_MINOR_VERSION); - PyOS_snprintf(rtversion, 4, "%s", Py_GetVersion()); - if (ctversion[0] != rtversion[0] || ctversion[2] != rtversion[2]) { - char message[200]; - PyOS_snprintf(message, sizeof(message), - "compiletime version %s of module '%.100s' " - "does not match runtime version %s", - ctversion, __Pyx_MODULE_NAME, rtversion); - return PyErr_WarnEx(NULL, message, 1); - } - return 0; -} - + if (unlikely(!entries)) { + return; + } + __pyx_code_cache.entries = entries; + __pyx_code_cache.max_count = new_max; + } + for (i=__pyx_code_cache.count; i>pos; i--) { + entries[i] = entries[i-1]; + } + entries[pos].code_line = code_line; + entries[pos].code_object = code_object; + __pyx_code_cache.count++; + Py_INCREF(code_object); +} + +/////////////// CodeObjectCache.cleanup /////////////// + + if (__pyx_code_cache.entries) { + __Pyx_CodeObjectCacheEntry* entries = __pyx_code_cache.entries; + int i, count = __pyx_code_cache.count; + __pyx_code_cache.count = 0; + __pyx_code_cache.max_count = 0; + __pyx_code_cache.entries = NULL; + for (i=0; i<count; i++) { + Py_DECREF(entries[i].code_object); + } + PyMem_Free(entries); + } + +/////////////// CheckBinaryVersion.proto /////////////// + +static int __Pyx_check_binary_version(void); + +/////////////// CheckBinaryVersion /////////////// + +static int __Pyx_check_binary_version(void) { + char ctversion[4], rtversion[4]; + PyOS_snprintf(ctversion, 4, "%d.%d", PY_MAJOR_VERSION, PY_MINOR_VERSION); + PyOS_snprintf(rtversion, 4, "%s", Py_GetVersion()); + if (ctversion[0] != rtversion[0] || ctversion[2] != rtversion[2]) { + char message[200]; + PyOS_snprintf(message, sizeof(message), + "compiletime version %s of module '%.100s' " + "does not match runtime version %s", + ctversion, __Pyx_MODULE_NAME, rtversion); + return PyErr_WarnEx(NULL, message, 1); + } + return 0; +} + /////////////// IsLittleEndian.proto /////////////// static CYTHON_INLINE int __Pyx_Is_Little_Endian(void); @@ -1245,91 +1245,91 @@ static CYTHON_INLINE int __Pyx_Is_Little_Endian(void) return S.u8[0] == 4; } -/////////////// Refnanny.proto /////////////// - -#ifndef CYTHON_REFNANNY - #define CYTHON_REFNANNY 0 -#endif - -#if CYTHON_REFNANNY - typedef struct { - void (*INCREF)(void*, PyObject*, int); - void (*DECREF)(void*, PyObject*, int); - void (*GOTREF)(void*, PyObject*, int); - void (*GIVEREF)(void*, PyObject*, int); - void* (*SetupContext)(const char*, int, const char*); - void (*FinishContext)(void**); - } __Pyx_RefNannyAPIStruct; - static __Pyx_RefNannyAPIStruct *__Pyx_RefNanny = NULL; - static __Pyx_RefNannyAPIStruct *__Pyx_RefNannyImportAPI(const char *modname); /*proto*/ - #define __Pyx_RefNannyDeclarations void *__pyx_refnanny = NULL; -#ifdef WITH_THREAD - #define __Pyx_RefNannySetupContext(name, acquire_gil) \ - if (acquire_gil) { \ - PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure(); \ - __pyx_refnanny = __Pyx_RefNanny->SetupContext((name), __LINE__, __FILE__); \ - PyGILState_Release(__pyx_gilstate_save); \ - } else { \ - __pyx_refnanny = __Pyx_RefNanny->SetupContext((name), __LINE__, __FILE__); \ - } -#else - #define __Pyx_RefNannySetupContext(name, acquire_gil) \ - __pyx_refnanny = __Pyx_RefNanny->SetupContext((name), __LINE__, __FILE__) -#endif - #define __Pyx_RefNannyFinishContext() \ - __Pyx_RefNanny->FinishContext(&__pyx_refnanny) - #define __Pyx_INCREF(r) __Pyx_RefNanny->INCREF(__pyx_refnanny, (PyObject *)(r), __LINE__) - #define __Pyx_DECREF(r) __Pyx_RefNanny->DECREF(__pyx_refnanny, (PyObject *)(r), __LINE__) - #define __Pyx_GOTREF(r) __Pyx_RefNanny->GOTREF(__pyx_refnanny, (PyObject *)(r), __LINE__) - #define __Pyx_GIVEREF(r) __Pyx_RefNanny->GIVEREF(__pyx_refnanny, (PyObject *)(r), __LINE__) - #define __Pyx_XINCREF(r) do { if((r) != NULL) {__Pyx_INCREF(r); }} while(0) - #define __Pyx_XDECREF(r) do { if((r) != NULL) {__Pyx_DECREF(r); }} while(0) - #define __Pyx_XGOTREF(r) do { if((r) != NULL) {__Pyx_GOTREF(r); }} while(0) - #define __Pyx_XGIVEREF(r) do { if((r) != NULL) {__Pyx_GIVEREF(r);}} while(0) -#else - #define __Pyx_RefNannyDeclarations - #define __Pyx_RefNannySetupContext(name, acquire_gil) - #define __Pyx_RefNannyFinishContext() - #define __Pyx_INCREF(r) Py_INCREF(r) - #define __Pyx_DECREF(r) Py_DECREF(r) - #define __Pyx_GOTREF(r) - #define __Pyx_GIVEREF(r) - #define __Pyx_XINCREF(r) Py_XINCREF(r) - #define __Pyx_XDECREF(r) Py_XDECREF(r) - #define __Pyx_XGOTREF(r) - #define __Pyx_XGIVEREF(r) -#endif /* CYTHON_REFNANNY */ - -#define __Pyx_XDECREF_SET(r, v) do { \ - PyObject *tmp = (PyObject *) r; \ - r = v; __Pyx_XDECREF(tmp); \ - } while (0) -#define __Pyx_DECREF_SET(r, v) do { \ - PyObject *tmp = (PyObject *) r; \ - r = v; __Pyx_DECREF(tmp); \ - } while (0) - -#define __Pyx_CLEAR(r) do { PyObject* tmp = ((PyObject*)(r)); r = NULL; __Pyx_DECREF(tmp);} while(0) -#define __Pyx_XCLEAR(r) do { if((r) != NULL) {PyObject* tmp = ((PyObject*)(r)); r = NULL; __Pyx_DECREF(tmp);}} while(0) - -/////////////// Refnanny /////////////// - -#if CYTHON_REFNANNY -static __Pyx_RefNannyAPIStruct *__Pyx_RefNannyImportAPI(const char *modname) { - PyObject *m = NULL, *p = NULL; - void *r = NULL; +/////////////// Refnanny.proto /////////////// + +#ifndef CYTHON_REFNANNY + #define CYTHON_REFNANNY 0 +#endif + +#if CYTHON_REFNANNY + typedef struct { + void (*INCREF)(void*, PyObject*, int); + void (*DECREF)(void*, PyObject*, int); + void (*GOTREF)(void*, PyObject*, int); + void (*GIVEREF)(void*, PyObject*, int); + void* (*SetupContext)(const char*, int, const char*); + void (*FinishContext)(void**); + } __Pyx_RefNannyAPIStruct; + static __Pyx_RefNannyAPIStruct *__Pyx_RefNanny = NULL; + static __Pyx_RefNannyAPIStruct *__Pyx_RefNannyImportAPI(const char *modname); /*proto*/ + #define __Pyx_RefNannyDeclarations void *__pyx_refnanny = NULL; +#ifdef WITH_THREAD + #define __Pyx_RefNannySetupContext(name, acquire_gil) \ + if (acquire_gil) { \ + PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure(); \ + __pyx_refnanny = __Pyx_RefNanny->SetupContext((name), __LINE__, __FILE__); \ + PyGILState_Release(__pyx_gilstate_save); \ + } else { \ + __pyx_refnanny = __Pyx_RefNanny->SetupContext((name), __LINE__, __FILE__); \ + } +#else + #define __Pyx_RefNannySetupContext(name, acquire_gil) \ + __pyx_refnanny = __Pyx_RefNanny->SetupContext((name), __LINE__, __FILE__) +#endif + #define __Pyx_RefNannyFinishContext() \ + __Pyx_RefNanny->FinishContext(&__pyx_refnanny) + #define __Pyx_INCREF(r) __Pyx_RefNanny->INCREF(__pyx_refnanny, (PyObject *)(r), __LINE__) + #define __Pyx_DECREF(r) __Pyx_RefNanny->DECREF(__pyx_refnanny, (PyObject *)(r), __LINE__) + #define __Pyx_GOTREF(r) __Pyx_RefNanny->GOTREF(__pyx_refnanny, (PyObject *)(r), __LINE__) + #define __Pyx_GIVEREF(r) __Pyx_RefNanny->GIVEREF(__pyx_refnanny, (PyObject *)(r), __LINE__) + #define __Pyx_XINCREF(r) do { if((r) != NULL) {__Pyx_INCREF(r); }} while(0) + #define __Pyx_XDECREF(r) do { if((r) != NULL) {__Pyx_DECREF(r); }} while(0) + #define __Pyx_XGOTREF(r) do { if((r) != NULL) {__Pyx_GOTREF(r); }} while(0) + #define __Pyx_XGIVEREF(r) do { if((r) != NULL) {__Pyx_GIVEREF(r);}} while(0) +#else + #define __Pyx_RefNannyDeclarations + #define __Pyx_RefNannySetupContext(name, acquire_gil) + #define __Pyx_RefNannyFinishContext() + #define __Pyx_INCREF(r) Py_INCREF(r) + #define __Pyx_DECREF(r) Py_DECREF(r) + #define __Pyx_GOTREF(r) + #define __Pyx_GIVEREF(r) + #define __Pyx_XINCREF(r) Py_XINCREF(r) + #define __Pyx_XDECREF(r) Py_XDECREF(r) + #define __Pyx_XGOTREF(r) + #define __Pyx_XGIVEREF(r) +#endif /* CYTHON_REFNANNY */ + +#define __Pyx_XDECREF_SET(r, v) do { \ + PyObject *tmp = (PyObject *) r; \ + r = v; __Pyx_XDECREF(tmp); \ + } while (0) +#define __Pyx_DECREF_SET(r, v) do { \ + PyObject *tmp = (PyObject *) r; \ + r = v; __Pyx_DECREF(tmp); \ + } while (0) + +#define __Pyx_CLEAR(r) do { PyObject* tmp = ((PyObject*)(r)); r = NULL; __Pyx_DECREF(tmp);} while(0) +#define __Pyx_XCLEAR(r) do { if((r) != NULL) {PyObject* tmp = ((PyObject*)(r)); r = NULL; __Pyx_DECREF(tmp);}} while(0) + +/////////////// Refnanny /////////////// + +#if CYTHON_REFNANNY +static __Pyx_RefNannyAPIStruct *__Pyx_RefNannyImportAPI(const char *modname) { + PyObject *m = NULL, *p = NULL; + void *r = NULL; m = PyImport_ImportModule(modname); - if (!m) goto end; + if (!m) goto end; p = PyObject_GetAttrString(m, "RefNannyAPI"); - if (!p) goto end; - r = PyLong_AsVoidPtr(p); -end: - Py_XDECREF(p); - Py_XDECREF(m); - return (__Pyx_RefNannyAPIStruct *)r; -} -#endif /* CYTHON_REFNANNY */ - + if (!p) goto end; + r = PyLong_AsVoidPtr(p); +end: + Py_XDECREF(p); + Py_XDECREF(m); + return (__Pyx_RefNannyAPIStruct *)r; +} +#endif /* CYTHON_REFNANNY */ + /////////////// ImportRefnannyAPI /////////////// @@ -1344,91 +1344,91 @@ if (!__Pyx_RefNanny) { #endif -/////////////// RegisterModuleCleanup.proto /////////////// -//@substitute: naming - -static void ${cleanup_cname}(PyObject *self); /*proto*/ +/////////////// RegisterModuleCleanup.proto /////////////// +//@substitute: naming + +static void ${cleanup_cname}(PyObject *self); /*proto*/ #if PY_MAJOR_VERSION < 3 || CYTHON_COMPILING_IN_PYPY -static int __Pyx_RegisterCleanup(void); /*proto*/ +static int __Pyx_RegisterCleanup(void); /*proto*/ #else #define __Pyx_RegisterCleanup() (0) #endif - -/////////////// RegisterModuleCleanup /////////////// -//@substitute: naming - + +/////////////// RegisterModuleCleanup /////////////// +//@substitute: naming + #if PY_MAJOR_VERSION < 3 || CYTHON_COMPILING_IN_PYPY -static PyObject* ${cleanup_cname}_atexit(PyObject *module, CYTHON_UNUSED PyObject *unused) { - ${cleanup_cname}(module); - Py_INCREF(Py_None); return Py_None; -} - -static int __Pyx_RegisterCleanup(void) { - // Don't use Py_AtExit because that has a 32-call limit and is called - // after python finalization. - // Also, we try to prepend the cleanup function to "atexit._exithandlers" - // in Py2 because CPython runs them last-to-first. Being run last allows - // user exit code to run before us that may depend on the globals - // and cached objects that we are about to clean up. - - static PyMethodDef cleanup_def = { - "__cleanup", (PyCFunction)${cleanup_cname}_atexit, METH_NOARGS, 0}; - - PyObject *cleanup_func = 0; - PyObject *atexit = 0; - PyObject *reg = 0; - PyObject *args = 0; - PyObject *res = 0; - int ret = -1; - - cleanup_func = PyCFunction_New(&cleanup_def, 0); - if (!cleanup_func) - goto bad; - +static PyObject* ${cleanup_cname}_atexit(PyObject *module, CYTHON_UNUSED PyObject *unused) { + ${cleanup_cname}(module); + Py_INCREF(Py_None); return Py_None; +} + +static int __Pyx_RegisterCleanup(void) { + // Don't use Py_AtExit because that has a 32-call limit and is called + // after python finalization. + // Also, we try to prepend the cleanup function to "atexit._exithandlers" + // in Py2 because CPython runs them last-to-first. Being run last allows + // user exit code to run before us that may depend on the globals + // and cached objects that we are about to clean up. + + static PyMethodDef cleanup_def = { + "__cleanup", (PyCFunction)${cleanup_cname}_atexit, METH_NOARGS, 0}; + + PyObject *cleanup_func = 0; + PyObject *atexit = 0; + PyObject *reg = 0; + PyObject *args = 0; + PyObject *res = 0; + int ret = -1; + + cleanup_func = PyCFunction_New(&cleanup_def, 0); + if (!cleanup_func) + goto bad; + atexit = PyImport_ImportModule("atexit"); - if (!atexit) - goto bad; - reg = PyObject_GetAttrString(atexit, "_exithandlers"); - if (reg && PyList_Check(reg)) { - PyObject *a, *kw; - a = PyTuple_New(0); - kw = PyDict_New(); - if (!a || !kw) { - Py_XDECREF(a); - Py_XDECREF(kw); - goto bad; - } - args = PyTuple_Pack(3, cleanup_func, a, kw); - Py_DECREF(a); - Py_DECREF(kw); - if (!args) - goto bad; - ret = PyList_Insert(reg, 0, args); - } else { - if (!reg) - PyErr_Clear(); - Py_XDECREF(reg); - reg = PyObject_GetAttrString(atexit, "register"); - if (!reg) - goto bad; - args = PyTuple_Pack(1, cleanup_func); - if (!args) - goto bad; - res = PyObject_CallObject(reg, args); - if (!res) - goto bad; - ret = 0; - } -bad: - Py_XDECREF(cleanup_func); - Py_XDECREF(atexit); - Py_XDECREF(reg); - Py_XDECREF(args); - Py_XDECREF(res); - return ret; -} -#endif + if (!atexit) + goto bad; + reg = PyObject_GetAttrString(atexit, "_exithandlers"); + if (reg && PyList_Check(reg)) { + PyObject *a, *kw; + a = PyTuple_New(0); + kw = PyDict_New(); + if (!a || !kw) { + Py_XDECREF(a); + Py_XDECREF(kw); + goto bad; + } + args = PyTuple_Pack(3, cleanup_func, a, kw); + Py_DECREF(a); + Py_DECREF(kw); + if (!args) + goto bad; + ret = PyList_Insert(reg, 0, args); + } else { + if (!reg) + PyErr_Clear(); + Py_XDECREF(reg); + reg = PyObject_GetAttrString(atexit, "register"); + if (!reg) + goto bad; + args = PyTuple_Pack(1, cleanup_func); + if (!args) + goto bad; + res = PyObject_CallObject(reg, args); + if (!res) + goto bad; + ret = 0; + } +bad: + Py_XDECREF(cleanup_func); + Py_XDECREF(atexit); + Py_XDECREF(reg); + Py_XDECREF(args); + Py_XDECREF(res); + return ret; +} +#endif /////////////// FastGil.init /////////////// #ifdef WITH_THREAD diff --git a/contrib/tools/cython/Cython/Utility/ObjectHandling.c b/contrib/tools/cython/Cython/Utility/ObjectHandling.c index c1b1c60bda..2f9b3868d8 100644 --- a/contrib/tools/cython/Cython/Utility/ObjectHandling.c +++ b/contrib/tools/cython/Cython/Utility/ObjectHandling.c @@ -1,119 +1,119 @@ -/* - * General object operations and protocol implementations, - * including their specialisations for certain builtins. - * - * Optional optimisations for builtins are in Optimize.c. - * - * Required replacements of builtins are in Builtins.c. - */ - -/////////////// RaiseNoneIterError.proto /////////////// - -static CYTHON_INLINE void __Pyx_RaiseNoneNotIterableError(void); - -/////////////// RaiseNoneIterError /////////////// - -static CYTHON_INLINE void __Pyx_RaiseNoneNotIterableError(void) { - PyErr_SetString(PyExc_TypeError, "'NoneType' object is not iterable"); -} - -/////////////// RaiseTooManyValuesToUnpack.proto /////////////// - -static CYTHON_INLINE void __Pyx_RaiseTooManyValuesError(Py_ssize_t expected); - -/////////////// RaiseTooManyValuesToUnpack /////////////// - -static CYTHON_INLINE void __Pyx_RaiseTooManyValuesError(Py_ssize_t expected) { - PyErr_Format(PyExc_ValueError, - "too many values to unpack (expected %" CYTHON_FORMAT_SSIZE_T "d)", expected); -} - -/////////////// RaiseNeedMoreValuesToUnpack.proto /////////////// - -static CYTHON_INLINE void __Pyx_RaiseNeedMoreValuesError(Py_ssize_t index); - -/////////////// RaiseNeedMoreValuesToUnpack /////////////// - -static CYTHON_INLINE void __Pyx_RaiseNeedMoreValuesError(Py_ssize_t index) { - PyErr_Format(PyExc_ValueError, - "need more than %" CYTHON_FORMAT_SSIZE_T "d value%.1s to unpack", - index, (index == 1) ? "" : "s"); -} - -/////////////// UnpackTupleError.proto /////////////// - -static void __Pyx_UnpackTupleError(PyObject *, Py_ssize_t index); /*proto*/ - -/////////////// UnpackTupleError /////////////// -//@requires: RaiseNoneIterError -//@requires: RaiseNeedMoreValuesToUnpack -//@requires: RaiseTooManyValuesToUnpack - -static void __Pyx_UnpackTupleError(PyObject *t, Py_ssize_t index) { - if (t == Py_None) { - __Pyx_RaiseNoneNotIterableError(); - } else if (PyTuple_GET_SIZE(t) < index) { - __Pyx_RaiseNeedMoreValuesError(PyTuple_GET_SIZE(t)); - } else { - __Pyx_RaiseTooManyValuesError(index); - } -} - -/////////////// UnpackItemEndCheck.proto /////////////// - -static int __Pyx_IternextUnpackEndCheck(PyObject *retval, Py_ssize_t expected); /*proto*/ - -/////////////// UnpackItemEndCheck /////////////// -//@requires: RaiseTooManyValuesToUnpack -//@requires: IterFinish - -static int __Pyx_IternextUnpackEndCheck(PyObject *retval, Py_ssize_t expected) { - if (unlikely(retval)) { - Py_DECREF(retval); - __Pyx_RaiseTooManyValuesError(expected); - return -1; - } else { - return __Pyx_IterFinish(); - } - return 0; -} - -/////////////// UnpackTuple2.proto /////////////// - +/* + * General object operations and protocol implementations, + * including their specialisations for certain builtins. + * + * Optional optimisations for builtins are in Optimize.c. + * + * Required replacements of builtins are in Builtins.c. + */ + +/////////////// RaiseNoneIterError.proto /////////////// + +static CYTHON_INLINE void __Pyx_RaiseNoneNotIterableError(void); + +/////////////// RaiseNoneIterError /////////////// + +static CYTHON_INLINE void __Pyx_RaiseNoneNotIterableError(void) { + PyErr_SetString(PyExc_TypeError, "'NoneType' object is not iterable"); +} + +/////////////// RaiseTooManyValuesToUnpack.proto /////////////// + +static CYTHON_INLINE void __Pyx_RaiseTooManyValuesError(Py_ssize_t expected); + +/////////////// RaiseTooManyValuesToUnpack /////////////// + +static CYTHON_INLINE void __Pyx_RaiseTooManyValuesError(Py_ssize_t expected) { + PyErr_Format(PyExc_ValueError, + "too many values to unpack (expected %" CYTHON_FORMAT_SSIZE_T "d)", expected); +} + +/////////////// RaiseNeedMoreValuesToUnpack.proto /////////////// + +static CYTHON_INLINE void __Pyx_RaiseNeedMoreValuesError(Py_ssize_t index); + +/////////////// RaiseNeedMoreValuesToUnpack /////////////// + +static CYTHON_INLINE void __Pyx_RaiseNeedMoreValuesError(Py_ssize_t index) { + PyErr_Format(PyExc_ValueError, + "need more than %" CYTHON_FORMAT_SSIZE_T "d value%.1s to unpack", + index, (index == 1) ? "" : "s"); +} + +/////////////// UnpackTupleError.proto /////////////// + +static void __Pyx_UnpackTupleError(PyObject *, Py_ssize_t index); /*proto*/ + +/////////////// UnpackTupleError /////////////// +//@requires: RaiseNoneIterError +//@requires: RaiseNeedMoreValuesToUnpack +//@requires: RaiseTooManyValuesToUnpack + +static void __Pyx_UnpackTupleError(PyObject *t, Py_ssize_t index) { + if (t == Py_None) { + __Pyx_RaiseNoneNotIterableError(); + } else if (PyTuple_GET_SIZE(t) < index) { + __Pyx_RaiseNeedMoreValuesError(PyTuple_GET_SIZE(t)); + } else { + __Pyx_RaiseTooManyValuesError(index); + } +} + +/////////////// UnpackItemEndCheck.proto /////////////// + +static int __Pyx_IternextUnpackEndCheck(PyObject *retval, Py_ssize_t expected); /*proto*/ + +/////////////// UnpackItemEndCheck /////////////// +//@requires: RaiseTooManyValuesToUnpack +//@requires: IterFinish + +static int __Pyx_IternextUnpackEndCheck(PyObject *retval, Py_ssize_t expected) { + if (unlikely(retval)) { + Py_DECREF(retval); + __Pyx_RaiseTooManyValuesError(expected); + return -1; + } else { + return __Pyx_IterFinish(); + } + return 0; +} + +/////////////// UnpackTuple2.proto /////////////// + #define __Pyx_unpack_tuple2(tuple, value1, value2, is_tuple, has_known_size, decref_tuple) \ (likely(is_tuple || PyTuple_Check(tuple)) ? \ (likely(has_known_size || PyTuple_GET_SIZE(tuple) == 2) ? \ __Pyx_unpack_tuple2_exact(tuple, value1, value2, decref_tuple) : \ (__Pyx_UnpackTupleError(tuple, 2), -1)) : \ __Pyx_unpack_tuple2_generic(tuple, value1, value2, has_known_size, decref_tuple)) - + static CYTHON_INLINE int __Pyx_unpack_tuple2_exact( PyObject* tuple, PyObject** value1, PyObject** value2, int decref_tuple); static int __Pyx_unpack_tuple2_generic( PyObject* tuple, PyObject** value1, PyObject** value2, int has_known_size, int decref_tuple); -/////////////// UnpackTuple2 /////////////// -//@requires: UnpackItemEndCheck -//@requires: UnpackTupleError -//@requires: RaiseNeedMoreValuesToUnpack - +/////////////// UnpackTuple2 /////////////// +//@requires: UnpackItemEndCheck +//@requires: UnpackTupleError +//@requires: RaiseNeedMoreValuesToUnpack + static CYTHON_INLINE int __Pyx_unpack_tuple2_exact( PyObject* tuple, PyObject** pvalue1, PyObject** pvalue2, int decref_tuple) { PyObject *value1 = NULL, *value2 = NULL; -#if CYTHON_COMPILING_IN_PYPY +#if CYTHON_COMPILING_IN_PYPY value1 = PySequence_ITEM(tuple, 0); if (unlikely(!value1)) goto bad; value2 = PySequence_ITEM(tuple, 1); if (unlikely(!value2)) goto bad; -#else +#else value1 = PyTuple_GET_ITEM(tuple, 0); Py_INCREF(value1); value2 = PyTuple_GET_ITEM(tuple, 1); Py_INCREF(value2); -#endif +#endif if (decref_tuple) { Py_DECREF(tuple); - } + } - *pvalue1 = value1; - *pvalue2 = value2; - return 0; + *pvalue1 = value1; + *pvalue2 = value2; + return 0; #if CYTHON_COMPILING_IN_PYPY bad: Py_XDECREF(value1); @@ -143,27 +143,27 @@ static int __Pyx_unpack_tuple2_generic(PyObject* tuple, PyObject** pvalue1, PyOb *pvalue2 = value2; return 0; -unpacking_failed: - if (!has_known_size && __Pyx_IterFinish() == 0) - __Pyx_RaiseNeedMoreValuesError(index); -bad: - Py_XDECREF(iter); - Py_XDECREF(value1); - Py_XDECREF(value2); - if (decref_tuple) { Py_XDECREF(tuple); } - return -1; -} - - -/////////////// IterNext.proto /////////////// - -#define __Pyx_PyIter_Next(obj) __Pyx_PyIter_Next2(obj, NULL) -static CYTHON_INLINE PyObject *__Pyx_PyIter_Next2(PyObject *, PyObject *); /*proto*/ - -/////////////// IterNext /////////////// +unpacking_failed: + if (!has_known_size && __Pyx_IterFinish() == 0) + __Pyx_RaiseNeedMoreValuesError(index); +bad: + Py_XDECREF(iter); + Py_XDECREF(value1); + Py_XDECREF(value2); + if (decref_tuple) { Py_XDECREF(tuple); } + return -1; +} + + +/////////////// IterNext.proto /////////////// + +#define __Pyx_PyIter_Next(obj) __Pyx_PyIter_Next2(obj, NULL) +static CYTHON_INLINE PyObject *__Pyx_PyIter_Next2(PyObject *, PyObject *); /*proto*/ + +/////////////// IterNext /////////////// //@requires: Exceptions.c::PyThreadStateGet //@requires: Exceptions.c::PyErrFetchRestore - + static PyObject *__Pyx_PyIter_Next2Default(PyObject* defval) { PyObject* exc_type; __Pyx_PyThreadState_declare @@ -189,11 +189,11 @@ static void __Pyx_PyIter_Next_ErrorNoIterator(PyObject *iterator) { "%.200s object is not an iterator", Py_TYPE(iterator)->tp_name); } -// originally copied from Py3's builtin_next() -static CYTHON_INLINE PyObject *__Pyx_PyIter_Next2(PyObject* iterator, PyObject* defval) { - PyObject* next; +// originally copied from Py3's builtin_next() +static CYTHON_INLINE PyObject *__Pyx_PyIter_Next2(PyObject* iterator, PyObject* defval) { + PyObject* next; // We always do a quick slot check because calling PyIter_Check() is so wasteful. - iternextfunc iternext = Py_TYPE(iterator)->tp_iternext; + iternextfunc iternext = Py_TYPE(iterator)->tp_iternext; if (likely(iternext)) { #if CYTHON_USE_TYPE_SLOTS next = iternext(iterator); @@ -203,19 +203,19 @@ static CYTHON_INLINE PyObject *__Pyx_PyIter_Next2(PyObject* iterator, PyObject* if (unlikely(iternext == &_PyObject_NextNotImplemented)) return NULL; #endif -#else +#else // Since the slot was set, assume that PyIter_Next() will likely succeed, and properly fail otherwise. // Note: PyIter_Next() crashes in CPython if "tp_iternext" is NULL. next = PyIter_Next(iterator); if (likely(next)) return next; -#endif +#endif } else if (CYTHON_USE_TYPE_SLOTS || unlikely(!PyIter_Check(iterator))) { // If CYTHON_USE_TYPE_SLOTS, then the slot was not set and we don't have an iterable. // Otherwise, don't trust "tp_iternext" and rely on PyIter_Check(). __Pyx_PyIter_Next_ErrorNoIterator(iterator); - return NULL; - } + return NULL; + } #if !CYTHON_USE_TYPE_SLOTS else { // We have an iterator with an empty "tp_iternext", but didn't call next() on it yet. @@ -225,52 +225,52 @@ static CYTHON_INLINE PyObject *__Pyx_PyIter_Next2(PyObject* iterator, PyObject* } #endif return __Pyx_PyIter_Next2Default(defval); -} - -/////////////// IterFinish.proto /////////////// - -static CYTHON_INLINE int __Pyx_IterFinish(void); /*proto*/ - -/////////////// IterFinish /////////////// - -// When PyIter_Next(iter) has returned NULL in order to signal termination, -// this function does the right cleanup and returns 0 on success. If it -// detects an error that occurred in the iterator, it returns -1. - -static CYTHON_INLINE int __Pyx_IterFinish(void) { +} + +/////////////// IterFinish.proto /////////////// + +static CYTHON_INLINE int __Pyx_IterFinish(void); /*proto*/ + +/////////////// IterFinish /////////////// + +// When PyIter_Next(iter) has returned NULL in order to signal termination, +// this function does the right cleanup and returns 0 on success. If it +// detects an error that occurred in the iterator, it returns -1. + +static CYTHON_INLINE int __Pyx_IterFinish(void) { #if CYTHON_FAST_THREAD_STATE PyThreadState *tstate = __Pyx_PyThreadState_Current; - PyObject* exc_type = tstate->curexc_type; - if (unlikely(exc_type)) { + PyObject* exc_type = tstate->curexc_type; + if (unlikely(exc_type)) { if (likely(__Pyx_PyErr_GivenExceptionMatches(exc_type, PyExc_StopIteration))) { - PyObject *exc_value, *exc_tb; - exc_value = tstate->curexc_value; - exc_tb = tstate->curexc_traceback; - tstate->curexc_type = 0; - tstate->curexc_value = 0; - tstate->curexc_traceback = 0; - Py_DECREF(exc_type); - Py_XDECREF(exc_value); - Py_XDECREF(exc_tb); - return 0; - } else { - return -1; - } - } - return 0; -#else - if (unlikely(PyErr_Occurred())) { - if (likely(PyErr_ExceptionMatches(PyExc_StopIteration))) { - PyErr_Clear(); - return 0; - } else { - return -1; - } - } - return 0; -#endif -} - + PyObject *exc_value, *exc_tb; + exc_value = tstate->curexc_value; + exc_tb = tstate->curexc_traceback; + tstate->curexc_type = 0; + tstate->curexc_value = 0; + tstate->curexc_traceback = 0; + Py_DECREF(exc_type); + Py_XDECREF(exc_value); + Py_XDECREF(exc_tb); + return 0; + } else { + return -1; + } + } + return 0; +#else + if (unlikely(PyErr_Occurred())) { + if (likely(PyErr_ExceptionMatches(PyExc_StopIteration))) { + PyErr_Clear(); + return 0; + } else { + return -1; + } + } + return 0; +#endif +} + /////////////// ObjectGetItem.proto /////////////// @@ -316,8 +316,8 @@ static PyObject *__Pyx_PyObject_GetItem(PyObject *obj, PyObject* key) { #endif -/////////////// DictGetItem.proto /////////////// - +/////////////// DictGetItem.proto /////////////// + #if PY_MAJOR_VERSION >= 3 && !CYTHON_COMPILING_IN_PYPY static PyObject *__Pyx_PyDict_GetItem(PyObject *d, PyObject* key);/*proto*/ @@ -333,11 +333,11 @@ static PyObject *__Pyx_PyDict_GetItem(PyObject *d, PyObject* key);/*proto*/ /////////////// DictGetItem /////////////// #if PY_MAJOR_VERSION >= 3 && !CYTHON_COMPILING_IN_PYPY -static PyObject *__Pyx_PyDict_GetItem(PyObject *d, PyObject* key) { - PyObject *value; - value = PyDict_GetItemWithError(d, key); - if (unlikely(!value)) { - if (!PyErr_Occurred()) { +static PyObject *__Pyx_PyDict_GetItem(PyObject *d, PyObject* key) { + PyObject *value; + value = PyDict_GetItemWithError(d, key); + if (unlikely(!value)) { + if (!PyErr_Occurred()) { if (unlikely(PyTuple_Check(key))) { // CPython interprets tuples as separate arguments => must wrap them in another tuple. PyObject* args = PyTuple_Pack(1, key); @@ -349,48 +349,48 @@ static PyObject *__Pyx_PyDict_GetItem(PyObject *d, PyObject* key) { // Avoid tuple packing if possible. PyErr_SetObject(PyExc_KeyError, key); } - } - return NULL; - } - Py_INCREF(value); - return value; -} -#endif - -/////////////// GetItemInt.proto /////////////// - -#define __Pyx_GetItemInt(o, i, type, is_signed, to_py_func, is_list, wraparound, boundscheck) \ - (__Pyx_fits_Py_ssize_t(i, type, is_signed) ? \ - __Pyx_GetItemInt_Fast(o, (Py_ssize_t)i, is_list, wraparound, boundscheck) : \ - (is_list ? (PyErr_SetString(PyExc_IndexError, "list index out of range"), (PyObject*)NULL) : \ - __Pyx_GetItemInt_Generic(o, to_py_func(i)))) - -{{for type in ['List', 'Tuple']}} -#define __Pyx_GetItemInt_{{type}}(o, i, type, is_signed, to_py_func, is_list, wraparound, boundscheck) \ - (__Pyx_fits_Py_ssize_t(i, type, is_signed) ? \ - __Pyx_GetItemInt_{{type}}_Fast(o, (Py_ssize_t)i, wraparound, boundscheck) : \ - (PyErr_SetString(PyExc_IndexError, "{{ type.lower() }} index out of range"), (PyObject*)NULL)) - -static CYTHON_INLINE PyObject *__Pyx_GetItemInt_{{type}}_Fast(PyObject *o, Py_ssize_t i, - int wraparound, int boundscheck); -{{endfor}} - + } + return NULL; + } + Py_INCREF(value); + return value; +} +#endif + +/////////////// GetItemInt.proto /////////////// + +#define __Pyx_GetItemInt(o, i, type, is_signed, to_py_func, is_list, wraparound, boundscheck) \ + (__Pyx_fits_Py_ssize_t(i, type, is_signed) ? \ + __Pyx_GetItemInt_Fast(o, (Py_ssize_t)i, is_list, wraparound, boundscheck) : \ + (is_list ? (PyErr_SetString(PyExc_IndexError, "list index out of range"), (PyObject*)NULL) : \ + __Pyx_GetItemInt_Generic(o, to_py_func(i)))) + +{{for type in ['List', 'Tuple']}} +#define __Pyx_GetItemInt_{{type}}(o, i, type, is_signed, to_py_func, is_list, wraparound, boundscheck) \ + (__Pyx_fits_Py_ssize_t(i, type, is_signed) ? \ + __Pyx_GetItemInt_{{type}}_Fast(o, (Py_ssize_t)i, wraparound, boundscheck) : \ + (PyErr_SetString(PyExc_IndexError, "{{ type.lower() }} index out of range"), (PyObject*)NULL)) + +static CYTHON_INLINE PyObject *__Pyx_GetItemInt_{{type}}_Fast(PyObject *o, Py_ssize_t i, + int wraparound, int boundscheck); +{{endfor}} + static PyObject *__Pyx_GetItemInt_Generic(PyObject *o, PyObject* j); -static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Fast(PyObject *o, Py_ssize_t i, - int is_list, int wraparound, int boundscheck); - -/////////////// GetItemInt /////////////// - +static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Fast(PyObject *o, Py_ssize_t i, + int is_list, int wraparound, int boundscheck); + +/////////////// GetItemInt /////////////// + static PyObject *__Pyx_GetItemInt_Generic(PyObject *o, PyObject* j) { - PyObject *r; - if (!j) return NULL; - r = PyObject_GetItem(o, j); - Py_DECREF(j); - return r; -} - -{{for type in ['List', 'Tuple']}} -static CYTHON_INLINE PyObject *__Pyx_GetItemInt_{{type}}_Fast(PyObject *o, Py_ssize_t i, + PyObject *r; + if (!j) return NULL; + r = PyObject_GetItem(o, j); + Py_DECREF(j); + return r; +} + +{{for type in ['List', 'Tuple']}} +static CYTHON_INLINE PyObject *__Pyx_GetItemInt_{{type}}_Fast(PyObject *o, Py_ssize_t i, CYTHON_NCP_UNUSED int wraparound, CYTHON_NCP_UNUSED int boundscheck) { #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS @@ -400,658 +400,658 @@ static CYTHON_INLINE PyObject *__Pyx_GetItemInt_{{type}}_Fast(PyObject *o, Py_ss } if ((!boundscheck) || likely(__Pyx_is_valid_index(wrapped_i, Py{{type}}_GET_SIZE(o)))) { PyObject *r = Py{{type}}_GET_ITEM(o, wrapped_i); - Py_INCREF(r); - return r; - } - return __Pyx_GetItemInt_Generic(o, PyInt_FromSsize_t(i)); -#else - return PySequence_GetItem(o, i); -#endif -} -{{endfor}} - + Py_INCREF(r); + return r; + } + return __Pyx_GetItemInt_Generic(o, PyInt_FromSsize_t(i)); +#else + return PySequence_GetItem(o, i); +#endif +} +{{endfor}} + static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Fast(PyObject *o, Py_ssize_t i, int is_list, CYTHON_NCP_UNUSED int wraparound, CYTHON_NCP_UNUSED int boundscheck) { #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS && CYTHON_USE_TYPE_SLOTS - if (is_list || PyList_CheckExact(o)) { - Py_ssize_t n = ((!wraparound) | likely(i >= 0)) ? i : i + PyList_GET_SIZE(o); + if (is_list || PyList_CheckExact(o)) { + Py_ssize_t n = ((!wraparound) | likely(i >= 0)) ? i : i + PyList_GET_SIZE(o); if ((!boundscheck) || (likely(__Pyx_is_valid_index(n, PyList_GET_SIZE(o))))) { - PyObject *r = PyList_GET_ITEM(o, n); - Py_INCREF(r); - return r; - } - } - else if (PyTuple_CheckExact(o)) { - Py_ssize_t n = ((!wraparound) | likely(i >= 0)) ? i : i + PyTuple_GET_SIZE(o); + PyObject *r = PyList_GET_ITEM(o, n); + Py_INCREF(r); + return r; + } + } + else if (PyTuple_CheckExact(o)) { + Py_ssize_t n = ((!wraparound) | likely(i >= 0)) ? i : i + PyTuple_GET_SIZE(o); if ((!boundscheck) || likely(__Pyx_is_valid_index(n, PyTuple_GET_SIZE(o)))) { - PyObject *r = PyTuple_GET_ITEM(o, n); - Py_INCREF(r); - return r; - } - } else { - // inlined PySequence_GetItem() + special cased length overflow - PySequenceMethods *m = Py_TYPE(o)->tp_as_sequence; - if (likely(m && m->sq_item)) { - if (wraparound && unlikely(i < 0) && likely(m->sq_length)) { - Py_ssize_t l = m->sq_length(o); - if (likely(l >= 0)) { - i += l; - } else { - // if length > max(Py_ssize_t), maybe the object can wrap around itself? + PyObject *r = PyTuple_GET_ITEM(o, n); + Py_INCREF(r); + return r; + } + } else { + // inlined PySequence_GetItem() + special cased length overflow + PySequenceMethods *m = Py_TYPE(o)->tp_as_sequence; + if (likely(m && m->sq_item)) { + if (wraparound && unlikely(i < 0) && likely(m->sq_length)) { + Py_ssize_t l = m->sq_length(o); + if (likely(l >= 0)) { + i += l; + } else { + // if length > max(Py_ssize_t), maybe the object can wrap around itself? if (!PyErr_ExceptionMatches(PyExc_OverflowError)) - return NULL; + return NULL; PyErr_Clear(); - } - } - return m->sq_item(o, i); - } - } -#else - if (is_list || PySequence_Check(o)) { - return PySequence_GetItem(o, i); - } -#endif - return __Pyx_GetItemInt_Generic(o, PyInt_FromSsize_t(i)); -} - -/////////////// SetItemInt.proto /////////////// - -#define __Pyx_SetItemInt(o, i, v, type, is_signed, to_py_func, is_list, wraparound, boundscheck) \ - (__Pyx_fits_Py_ssize_t(i, type, is_signed) ? \ - __Pyx_SetItemInt_Fast(o, (Py_ssize_t)i, v, is_list, wraparound, boundscheck) : \ - (is_list ? (PyErr_SetString(PyExc_IndexError, "list assignment index out of range"), -1) : \ - __Pyx_SetItemInt_Generic(o, to_py_func(i), v))) - + } + } + return m->sq_item(o, i); + } + } +#else + if (is_list || PySequence_Check(o)) { + return PySequence_GetItem(o, i); + } +#endif + return __Pyx_GetItemInt_Generic(o, PyInt_FromSsize_t(i)); +} + +/////////////// SetItemInt.proto /////////////// + +#define __Pyx_SetItemInt(o, i, v, type, is_signed, to_py_func, is_list, wraparound, boundscheck) \ + (__Pyx_fits_Py_ssize_t(i, type, is_signed) ? \ + __Pyx_SetItemInt_Fast(o, (Py_ssize_t)i, v, is_list, wraparound, boundscheck) : \ + (is_list ? (PyErr_SetString(PyExc_IndexError, "list assignment index out of range"), -1) : \ + __Pyx_SetItemInt_Generic(o, to_py_func(i), v))) + static int __Pyx_SetItemInt_Generic(PyObject *o, PyObject *j, PyObject *v); -static CYTHON_INLINE int __Pyx_SetItemInt_Fast(PyObject *o, Py_ssize_t i, PyObject *v, - int is_list, int wraparound, int boundscheck); - -/////////////// SetItemInt /////////////// - +static CYTHON_INLINE int __Pyx_SetItemInt_Fast(PyObject *o, Py_ssize_t i, PyObject *v, + int is_list, int wraparound, int boundscheck); + +/////////////// SetItemInt /////////////// + static int __Pyx_SetItemInt_Generic(PyObject *o, PyObject *j, PyObject *v) { - int r; - if (!j) return -1; - r = PyObject_SetItem(o, j, v); - Py_DECREF(j); - return r; -} - + int r; + if (!j) return -1; + r = PyObject_SetItem(o, j, v); + Py_DECREF(j); + return r; +} + static CYTHON_INLINE int __Pyx_SetItemInt_Fast(PyObject *o, Py_ssize_t i, PyObject *v, int is_list, CYTHON_NCP_UNUSED int wraparound, CYTHON_NCP_UNUSED int boundscheck) { #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS && CYTHON_USE_TYPE_SLOTS - if (is_list || PyList_CheckExact(o)) { - Py_ssize_t n = (!wraparound) ? i : ((likely(i >= 0)) ? i : i + PyList_GET_SIZE(o)); + if (is_list || PyList_CheckExact(o)) { + Py_ssize_t n = (!wraparound) ? i : ((likely(i >= 0)) ? i : i + PyList_GET_SIZE(o)); if ((!boundscheck) || likely(__Pyx_is_valid_index(n, PyList_GET_SIZE(o)))) { - PyObject* old = PyList_GET_ITEM(o, n); - Py_INCREF(v); - PyList_SET_ITEM(o, n, v); - Py_DECREF(old); - return 1; - } - } else { - // inlined PySequence_SetItem() + special cased length overflow - PySequenceMethods *m = Py_TYPE(o)->tp_as_sequence; - if (likely(m && m->sq_ass_item)) { - if (wraparound && unlikely(i < 0) && likely(m->sq_length)) { - Py_ssize_t l = m->sq_length(o); - if (likely(l >= 0)) { - i += l; - } else { - // if length > max(Py_ssize_t), maybe the object can wrap around itself? + PyObject* old = PyList_GET_ITEM(o, n); + Py_INCREF(v); + PyList_SET_ITEM(o, n, v); + Py_DECREF(old); + return 1; + } + } else { + // inlined PySequence_SetItem() + special cased length overflow + PySequenceMethods *m = Py_TYPE(o)->tp_as_sequence; + if (likely(m && m->sq_ass_item)) { + if (wraparound && unlikely(i < 0) && likely(m->sq_length)) { + Py_ssize_t l = m->sq_length(o); + if (likely(l >= 0)) { + i += l; + } else { + // if length > max(Py_ssize_t), maybe the object can wrap around itself? if (!PyErr_ExceptionMatches(PyExc_OverflowError)) - return -1; + return -1; PyErr_Clear(); - } - } - return m->sq_ass_item(o, i, v); - } - } -#else -#if CYTHON_COMPILING_IN_PYPY + } + } + return m->sq_ass_item(o, i, v); + } + } +#else +#if CYTHON_COMPILING_IN_PYPY if (is_list || (PySequence_Check(o) && !PyDict_Check(o))) -#else +#else if (is_list || PySequence_Check(o)) -#endif +#endif { - return PySequence_SetItem(o, i, v); - } -#endif - return __Pyx_SetItemInt_Generic(o, PyInt_FromSsize_t(i), v); -} - - -/////////////// DelItemInt.proto /////////////// - -#define __Pyx_DelItemInt(o, i, type, is_signed, to_py_func, is_list, wraparound, boundscheck) \ - (__Pyx_fits_Py_ssize_t(i, type, is_signed) ? \ - __Pyx_DelItemInt_Fast(o, (Py_ssize_t)i, is_list, wraparound) : \ - (is_list ? (PyErr_SetString(PyExc_IndexError, "list assignment index out of range"), -1) : \ - __Pyx_DelItem_Generic(o, to_py_func(i)))) - + return PySequence_SetItem(o, i, v); + } +#endif + return __Pyx_SetItemInt_Generic(o, PyInt_FromSsize_t(i), v); +} + + +/////////////// DelItemInt.proto /////////////// + +#define __Pyx_DelItemInt(o, i, type, is_signed, to_py_func, is_list, wraparound, boundscheck) \ + (__Pyx_fits_Py_ssize_t(i, type, is_signed) ? \ + __Pyx_DelItemInt_Fast(o, (Py_ssize_t)i, is_list, wraparound) : \ + (is_list ? (PyErr_SetString(PyExc_IndexError, "list assignment index out of range"), -1) : \ + __Pyx_DelItem_Generic(o, to_py_func(i)))) + static int __Pyx_DelItem_Generic(PyObject *o, PyObject *j); -static CYTHON_INLINE int __Pyx_DelItemInt_Fast(PyObject *o, Py_ssize_t i, +static CYTHON_INLINE int __Pyx_DelItemInt_Fast(PyObject *o, Py_ssize_t i, int is_list, int wraparound); - -/////////////// DelItemInt /////////////// - + +/////////////// DelItemInt /////////////// + static int __Pyx_DelItem_Generic(PyObject *o, PyObject *j) { - int r; - if (!j) return -1; - r = PyObject_DelItem(o, j); - Py_DECREF(j); - return r; -} - -static CYTHON_INLINE int __Pyx_DelItemInt_Fast(PyObject *o, Py_ssize_t i, + int r; + if (!j) return -1; + r = PyObject_DelItem(o, j); + Py_DECREF(j); + return r; +} + +static CYTHON_INLINE int __Pyx_DelItemInt_Fast(PyObject *o, Py_ssize_t i, CYTHON_UNUSED int is_list, CYTHON_NCP_UNUSED int wraparound) { #if !CYTHON_USE_TYPE_SLOTS - if (is_list || PySequence_Check(o)) { - return PySequence_DelItem(o, i); - } -#else - // inlined PySequence_DelItem() + special cased length overflow - PySequenceMethods *m = Py_TYPE(o)->tp_as_sequence; - if (likely(m && m->sq_ass_item)) { - if (wraparound && unlikely(i < 0) && likely(m->sq_length)) { - Py_ssize_t l = m->sq_length(o); - if (likely(l >= 0)) { - i += l; - } else { - // if length > max(Py_ssize_t), maybe the object can wrap around itself? + if (is_list || PySequence_Check(o)) { + return PySequence_DelItem(o, i); + } +#else + // inlined PySequence_DelItem() + special cased length overflow + PySequenceMethods *m = Py_TYPE(o)->tp_as_sequence; + if (likely(m && m->sq_ass_item)) { + if (wraparound && unlikely(i < 0) && likely(m->sq_length)) { + Py_ssize_t l = m->sq_length(o); + if (likely(l >= 0)) { + i += l; + } else { + // if length > max(Py_ssize_t), maybe the object can wrap around itself? if (!PyErr_ExceptionMatches(PyExc_OverflowError)) - return -1; + return -1; PyErr_Clear(); - } - } - return m->sq_ass_item(o, i, (PyObject *)NULL); - } -#endif - return __Pyx_DelItem_Generic(o, PyInt_FromSsize_t(i)); -} - - -/////////////// SliceObject.proto /////////////// - -// we pass pointer addresses to show the C compiler what is NULL and what isn't -{{if access == 'Get'}} -static CYTHON_INLINE PyObject* __Pyx_PyObject_GetSlice( - PyObject* obj, Py_ssize_t cstart, Py_ssize_t cstop, - PyObject** py_start, PyObject** py_stop, PyObject** py_slice, - int has_cstart, int has_cstop, int wraparound); -{{else}} -#define __Pyx_PyObject_DelSlice(obj, cstart, cstop, py_start, py_stop, py_slice, has_cstart, has_cstop, wraparound) \ - __Pyx_PyObject_SetSlice(obj, (PyObject*)NULL, cstart, cstop, py_start, py_stop, py_slice, has_cstart, has_cstop, wraparound) - -// we pass pointer addresses to show the C compiler what is NULL and what isn't -static CYTHON_INLINE int __Pyx_PyObject_SetSlice( - PyObject* obj, PyObject* value, Py_ssize_t cstart, Py_ssize_t cstop, - PyObject** py_start, PyObject** py_stop, PyObject** py_slice, - int has_cstart, int has_cstop, int wraparound); -{{endif}} - -/////////////// SliceObject /////////////// - -{{if access == 'Get'}} + } + } + return m->sq_ass_item(o, i, (PyObject *)NULL); + } +#endif + return __Pyx_DelItem_Generic(o, PyInt_FromSsize_t(i)); +} + + +/////////////// SliceObject.proto /////////////// + +// we pass pointer addresses to show the C compiler what is NULL and what isn't +{{if access == 'Get'}} +static CYTHON_INLINE PyObject* __Pyx_PyObject_GetSlice( + PyObject* obj, Py_ssize_t cstart, Py_ssize_t cstop, + PyObject** py_start, PyObject** py_stop, PyObject** py_slice, + int has_cstart, int has_cstop, int wraparound); +{{else}} +#define __Pyx_PyObject_DelSlice(obj, cstart, cstop, py_start, py_stop, py_slice, has_cstart, has_cstop, wraparound) \ + __Pyx_PyObject_SetSlice(obj, (PyObject*)NULL, cstart, cstop, py_start, py_stop, py_slice, has_cstart, has_cstop, wraparound) + +// we pass pointer addresses to show the C compiler what is NULL and what isn't +static CYTHON_INLINE int __Pyx_PyObject_SetSlice( + PyObject* obj, PyObject* value, Py_ssize_t cstart, Py_ssize_t cstop, + PyObject** py_start, PyObject** py_stop, PyObject** py_slice, + int has_cstart, int has_cstop, int wraparound); +{{endif}} + +/////////////// SliceObject /////////////// + +{{if access == 'Get'}} static CYTHON_INLINE PyObject* __Pyx_PyObject_GetSlice(PyObject* obj, -{{else}} +{{else}} static CYTHON_INLINE int __Pyx_PyObject_SetSlice(PyObject* obj, PyObject* value, -{{endif}} +{{endif}} Py_ssize_t cstart, Py_ssize_t cstop, - PyObject** _py_start, PyObject** _py_stop, PyObject** _py_slice, - int has_cstart, int has_cstop, CYTHON_UNUSED int wraparound) { + PyObject** _py_start, PyObject** _py_stop, PyObject** _py_slice, + int has_cstart, int has_cstop, CYTHON_UNUSED int wraparound) { #if CYTHON_USE_TYPE_SLOTS - PyMappingMethods* mp; -#if PY_MAJOR_VERSION < 3 - PySequenceMethods* ms = Py_TYPE(obj)->tp_as_sequence; - if (likely(ms && ms->sq_{{if access == 'Set'}}ass_{{endif}}slice)) { - if (!has_cstart) { - if (_py_start && (*_py_start != Py_None)) { - cstart = __Pyx_PyIndex_AsSsize_t(*_py_start); - if ((cstart == (Py_ssize_t)-1) && PyErr_Occurred()) goto bad; - } else - cstart = 0; - } - if (!has_cstop) { - if (_py_stop && (*_py_stop != Py_None)) { - cstop = __Pyx_PyIndex_AsSsize_t(*_py_stop); - if ((cstop == (Py_ssize_t)-1) && PyErr_Occurred()) goto bad; - } else - cstop = PY_SSIZE_T_MAX; - } - if (wraparound && unlikely((cstart < 0) | (cstop < 0)) && likely(ms->sq_length)) { - Py_ssize_t l = ms->sq_length(obj); - if (likely(l >= 0)) { - if (cstop < 0) { - cstop += l; - if (cstop < 0) cstop = 0; - } - if (cstart < 0) { - cstart += l; - if (cstart < 0) cstart = 0; - } - } else { - // if length > max(Py_ssize_t), maybe the object can wrap around itself? + PyMappingMethods* mp; +#if PY_MAJOR_VERSION < 3 + PySequenceMethods* ms = Py_TYPE(obj)->tp_as_sequence; + if (likely(ms && ms->sq_{{if access == 'Set'}}ass_{{endif}}slice)) { + if (!has_cstart) { + if (_py_start && (*_py_start != Py_None)) { + cstart = __Pyx_PyIndex_AsSsize_t(*_py_start); + if ((cstart == (Py_ssize_t)-1) && PyErr_Occurred()) goto bad; + } else + cstart = 0; + } + if (!has_cstop) { + if (_py_stop && (*_py_stop != Py_None)) { + cstop = __Pyx_PyIndex_AsSsize_t(*_py_stop); + if ((cstop == (Py_ssize_t)-1) && PyErr_Occurred()) goto bad; + } else + cstop = PY_SSIZE_T_MAX; + } + if (wraparound && unlikely((cstart < 0) | (cstop < 0)) && likely(ms->sq_length)) { + Py_ssize_t l = ms->sq_length(obj); + if (likely(l >= 0)) { + if (cstop < 0) { + cstop += l; + if (cstop < 0) cstop = 0; + } + if (cstart < 0) { + cstart += l; + if (cstart < 0) cstart = 0; + } + } else { + // if length > max(Py_ssize_t), maybe the object can wrap around itself? if (!PyErr_ExceptionMatches(PyExc_OverflowError)) - goto bad; + goto bad; PyErr_Clear(); - } - } -{{if access == 'Get'}} - return ms->sq_slice(obj, cstart, cstop); -{{else}} - return ms->sq_ass_slice(obj, cstart, cstop, value); -{{endif}} - } -#endif - - mp = Py_TYPE(obj)->tp_as_mapping; -{{if access == 'Get'}} - if (likely(mp && mp->mp_subscript)) -{{else}} - if (likely(mp && mp->mp_ass_subscript)) -{{endif}} -#endif - { - {{if access == 'Get'}}PyObject*{{else}}int{{endif}} result; - PyObject *py_slice, *py_start, *py_stop; - if (_py_slice) { - py_slice = *_py_slice; - } else { - PyObject* owned_start = NULL; - PyObject* owned_stop = NULL; - if (_py_start) { - py_start = *_py_start; - } else { - if (has_cstart) { - owned_start = py_start = PyInt_FromSsize_t(cstart); - if (unlikely(!py_start)) goto bad; - } else - py_start = Py_None; - } - if (_py_stop) { - py_stop = *_py_stop; - } else { - if (has_cstop) { - owned_stop = py_stop = PyInt_FromSsize_t(cstop); - if (unlikely(!py_stop)) { - Py_XDECREF(owned_start); - goto bad; - } - } else - py_stop = Py_None; - } - py_slice = PySlice_New(py_start, py_stop, Py_None); - Py_XDECREF(owned_start); - Py_XDECREF(owned_stop); - if (unlikely(!py_slice)) goto bad; - } + } + } +{{if access == 'Get'}} + return ms->sq_slice(obj, cstart, cstop); +{{else}} + return ms->sq_ass_slice(obj, cstart, cstop, value); +{{endif}} + } +#endif + + mp = Py_TYPE(obj)->tp_as_mapping; +{{if access == 'Get'}} + if (likely(mp && mp->mp_subscript)) +{{else}} + if (likely(mp && mp->mp_ass_subscript)) +{{endif}} +#endif + { + {{if access == 'Get'}}PyObject*{{else}}int{{endif}} result; + PyObject *py_slice, *py_start, *py_stop; + if (_py_slice) { + py_slice = *_py_slice; + } else { + PyObject* owned_start = NULL; + PyObject* owned_stop = NULL; + if (_py_start) { + py_start = *_py_start; + } else { + if (has_cstart) { + owned_start = py_start = PyInt_FromSsize_t(cstart); + if (unlikely(!py_start)) goto bad; + } else + py_start = Py_None; + } + if (_py_stop) { + py_stop = *_py_stop; + } else { + if (has_cstop) { + owned_stop = py_stop = PyInt_FromSsize_t(cstop); + if (unlikely(!py_stop)) { + Py_XDECREF(owned_start); + goto bad; + } + } else + py_stop = Py_None; + } + py_slice = PySlice_New(py_start, py_stop, Py_None); + Py_XDECREF(owned_start); + Py_XDECREF(owned_stop); + if (unlikely(!py_slice)) goto bad; + } #if CYTHON_USE_TYPE_SLOTS -{{if access == 'Get'}} - result = mp->mp_subscript(obj, py_slice); -#else - result = PyObject_GetItem(obj, py_slice); -{{else}} - result = mp->mp_ass_subscript(obj, py_slice, value); -#else - result = value ? PyObject_SetItem(obj, py_slice, value) : PyObject_DelItem(obj, py_slice); -{{endif}} -#endif - if (!_py_slice) { - Py_DECREF(py_slice); - } - return result; - } - PyErr_Format(PyExc_TypeError, -{{if access == 'Get'}} - "'%.200s' object is unsliceable", Py_TYPE(obj)->tp_name); -{{else}} - "'%.200s' object does not support slice %.10s", - Py_TYPE(obj)->tp_name, value ? "assignment" : "deletion"); -{{endif}} - -bad: - return {{if access == 'Get'}}NULL{{else}}-1{{endif}}; -} - - -/////////////// SliceTupleAndList.proto /////////////// - -#if CYTHON_COMPILING_IN_CPYTHON -static CYTHON_INLINE PyObject* __Pyx_PyList_GetSlice(PyObject* src, Py_ssize_t start, Py_ssize_t stop); -static CYTHON_INLINE PyObject* __Pyx_PyTuple_GetSlice(PyObject* src, Py_ssize_t start, Py_ssize_t stop); -#else -#define __Pyx_PyList_GetSlice(seq, start, stop) PySequence_GetSlice(seq, start, stop) -#define __Pyx_PyTuple_GetSlice(seq, start, stop) PySequence_GetSlice(seq, start, stop) -#endif - -/////////////// SliceTupleAndList /////////////// - -#if CYTHON_COMPILING_IN_CPYTHON -static CYTHON_INLINE void __Pyx_crop_slice(Py_ssize_t* _start, Py_ssize_t* _stop, Py_ssize_t* _length) { - Py_ssize_t start = *_start, stop = *_stop, length = *_length; - if (start < 0) { - start += length; - if (start < 0) - start = 0; - } - - if (stop < 0) - stop += length; - else if (stop > length) - stop = length; - - *_length = stop - start; - *_start = start; - *_stop = stop; -} - -static CYTHON_INLINE void __Pyx_copy_object_array(PyObject** CYTHON_RESTRICT src, PyObject** CYTHON_RESTRICT dest, Py_ssize_t length) { - PyObject *v; - Py_ssize_t i; - for (i = 0; i < length; i++) { - v = dest[i] = src[i]; - Py_INCREF(v); - } -} - -{{for type in ['List', 'Tuple']}} -static CYTHON_INLINE PyObject* __Pyx_Py{{type}}_GetSlice( - PyObject* src, Py_ssize_t start, Py_ssize_t stop) { - PyObject* dest; - Py_ssize_t length = Py{{type}}_GET_SIZE(src); - __Pyx_crop_slice(&start, &stop, &length); - if (unlikely(length <= 0)) - return Py{{type}}_New(0); - - dest = Py{{type}}_New(length); - if (unlikely(!dest)) - return NULL; - __Pyx_copy_object_array( - ((Py{{type}}Object*)src)->ob_item + start, - ((Py{{type}}Object*)dest)->ob_item, - length); - return dest; -} -{{endfor}} -#endif - - -/////////////// CalculateMetaclass.proto /////////////// - -static PyObject *__Pyx_CalculateMetaclass(PyTypeObject *metaclass, PyObject *bases); - -/////////////// CalculateMetaclass /////////////// - -static PyObject *__Pyx_CalculateMetaclass(PyTypeObject *metaclass, PyObject *bases) { - Py_ssize_t i, nbases = PyTuple_GET_SIZE(bases); - for (i=0; i < nbases; i++) { - PyTypeObject *tmptype; - PyObject *tmp = PyTuple_GET_ITEM(bases, i); - tmptype = Py_TYPE(tmp); -#if PY_MAJOR_VERSION < 3 - if (tmptype == &PyClass_Type) - continue; -#endif - if (!metaclass) { - metaclass = tmptype; - continue; - } - if (PyType_IsSubtype(metaclass, tmptype)) - continue; - if (PyType_IsSubtype(tmptype, metaclass)) { - metaclass = tmptype; - continue; - } - // else: - PyErr_SetString(PyExc_TypeError, - "metaclass conflict: " - "the metaclass of a derived class " - "must be a (non-strict) subclass " - "of the metaclasses of all its bases"); - return NULL; - } - if (!metaclass) { -#if PY_MAJOR_VERSION < 3 - metaclass = &PyClass_Type; -#else - metaclass = &PyType_Type; -#endif - } - // make owned reference - Py_INCREF((PyObject*) metaclass); - return (PyObject*) metaclass; -} - - -/////////////// FindInheritedMetaclass.proto /////////////// - -static PyObject *__Pyx_FindInheritedMetaclass(PyObject *bases); /*proto*/ - -/////////////// FindInheritedMetaclass /////////////// -//@requires: PyObjectGetAttrStr -//@requires: CalculateMetaclass - -static PyObject *__Pyx_FindInheritedMetaclass(PyObject *bases) { - PyObject *metaclass; - if (PyTuple_Check(bases) && PyTuple_GET_SIZE(bases) > 0) { - PyTypeObject *metatype; +{{if access == 'Get'}} + result = mp->mp_subscript(obj, py_slice); +#else + result = PyObject_GetItem(obj, py_slice); +{{else}} + result = mp->mp_ass_subscript(obj, py_slice, value); +#else + result = value ? PyObject_SetItem(obj, py_slice, value) : PyObject_DelItem(obj, py_slice); +{{endif}} +#endif + if (!_py_slice) { + Py_DECREF(py_slice); + } + return result; + } + PyErr_Format(PyExc_TypeError, +{{if access == 'Get'}} + "'%.200s' object is unsliceable", Py_TYPE(obj)->tp_name); +{{else}} + "'%.200s' object does not support slice %.10s", + Py_TYPE(obj)->tp_name, value ? "assignment" : "deletion"); +{{endif}} + +bad: + return {{if access == 'Get'}}NULL{{else}}-1{{endif}}; +} + + +/////////////// SliceTupleAndList.proto /////////////// + +#if CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE PyObject* __Pyx_PyList_GetSlice(PyObject* src, Py_ssize_t start, Py_ssize_t stop); +static CYTHON_INLINE PyObject* __Pyx_PyTuple_GetSlice(PyObject* src, Py_ssize_t start, Py_ssize_t stop); +#else +#define __Pyx_PyList_GetSlice(seq, start, stop) PySequence_GetSlice(seq, start, stop) +#define __Pyx_PyTuple_GetSlice(seq, start, stop) PySequence_GetSlice(seq, start, stop) +#endif + +/////////////// SliceTupleAndList /////////////// + +#if CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE void __Pyx_crop_slice(Py_ssize_t* _start, Py_ssize_t* _stop, Py_ssize_t* _length) { + Py_ssize_t start = *_start, stop = *_stop, length = *_length; + if (start < 0) { + start += length; + if (start < 0) + start = 0; + } + + if (stop < 0) + stop += length; + else if (stop > length) + stop = length; + + *_length = stop - start; + *_start = start; + *_stop = stop; +} + +static CYTHON_INLINE void __Pyx_copy_object_array(PyObject** CYTHON_RESTRICT src, PyObject** CYTHON_RESTRICT dest, Py_ssize_t length) { + PyObject *v; + Py_ssize_t i; + for (i = 0; i < length; i++) { + v = dest[i] = src[i]; + Py_INCREF(v); + } +} + +{{for type in ['List', 'Tuple']}} +static CYTHON_INLINE PyObject* __Pyx_Py{{type}}_GetSlice( + PyObject* src, Py_ssize_t start, Py_ssize_t stop) { + PyObject* dest; + Py_ssize_t length = Py{{type}}_GET_SIZE(src); + __Pyx_crop_slice(&start, &stop, &length); + if (unlikely(length <= 0)) + return Py{{type}}_New(0); + + dest = Py{{type}}_New(length); + if (unlikely(!dest)) + return NULL; + __Pyx_copy_object_array( + ((Py{{type}}Object*)src)->ob_item + start, + ((Py{{type}}Object*)dest)->ob_item, + length); + return dest; +} +{{endfor}} +#endif + + +/////////////// CalculateMetaclass.proto /////////////// + +static PyObject *__Pyx_CalculateMetaclass(PyTypeObject *metaclass, PyObject *bases); + +/////////////// CalculateMetaclass /////////////// + +static PyObject *__Pyx_CalculateMetaclass(PyTypeObject *metaclass, PyObject *bases) { + Py_ssize_t i, nbases = PyTuple_GET_SIZE(bases); + for (i=0; i < nbases; i++) { + PyTypeObject *tmptype; + PyObject *tmp = PyTuple_GET_ITEM(bases, i); + tmptype = Py_TYPE(tmp); +#if PY_MAJOR_VERSION < 3 + if (tmptype == &PyClass_Type) + continue; +#endif + if (!metaclass) { + metaclass = tmptype; + continue; + } + if (PyType_IsSubtype(metaclass, tmptype)) + continue; + if (PyType_IsSubtype(tmptype, metaclass)) { + metaclass = tmptype; + continue; + } + // else: + PyErr_SetString(PyExc_TypeError, + "metaclass conflict: " + "the metaclass of a derived class " + "must be a (non-strict) subclass " + "of the metaclasses of all its bases"); + return NULL; + } + if (!metaclass) { +#if PY_MAJOR_VERSION < 3 + metaclass = &PyClass_Type; +#else + metaclass = &PyType_Type; +#endif + } + // make owned reference + Py_INCREF((PyObject*) metaclass); + return (PyObject*) metaclass; +} + + +/////////////// FindInheritedMetaclass.proto /////////////// + +static PyObject *__Pyx_FindInheritedMetaclass(PyObject *bases); /*proto*/ + +/////////////// FindInheritedMetaclass /////////////// +//@requires: PyObjectGetAttrStr +//@requires: CalculateMetaclass + +static PyObject *__Pyx_FindInheritedMetaclass(PyObject *bases) { + PyObject *metaclass; + if (PyTuple_Check(bases) && PyTuple_GET_SIZE(bases) > 0) { + PyTypeObject *metatype; #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS - PyObject *base = PyTuple_GET_ITEM(bases, 0); + PyObject *base = PyTuple_GET_ITEM(bases, 0); #else PyObject *base = PySequence_ITEM(bases, 0); #endif -#if PY_MAJOR_VERSION < 3 - PyObject* basetype = __Pyx_PyObject_GetAttrStr(base, PYIDENT("__class__")); - if (basetype) { - metatype = (PyType_Check(basetype)) ? ((PyTypeObject*) basetype) : NULL; - } else { - PyErr_Clear(); - metatype = Py_TYPE(base); - basetype = (PyObject*) metatype; - Py_INCREF(basetype); - } -#else - metatype = Py_TYPE(base); -#endif - metaclass = __Pyx_CalculateMetaclass(metatype, bases); +#if PY_MAJOR_VERSION < 3 + PyObject* basetype = __Pyx_PyObject_GetAttrStr(base, PYIDENT("__class__")); + if (basetype) { + metatype = (PyType_Check(basetype)) ? ((PyTypeObject*) basetype) : NULL; + } else { + PyErr_Clear(); + metatype = Py_TYPE(base); + basetype = (PyObject*) metatype; + Py_INCREF(basetype); + } +#else + metatype = Py_TYPE(base); +#endif + metaclass = __Pyx_CalculateMetaclass(metatype, bases); #if !(CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS) Py_DECREF(base); #endif -#if PY_MAJOR_VERSION < 3 - Py_DECREF(basetype); -#endif - } else { - // no bases => use default metaclass -#if PY_MAJOR_VERSION < 3 - metaclass = (PyObject *) &PyClass_Type; -#else - metaclass = (PyObject *) &PyType_Type; -#endif - Py_INCREF(metaclass); - } - return metaclass; -} - -/////////////// Py3MetaclassGet.proto /////////////// - -static PyObject *__Pyx_Py3MetaclassGet(PyObject *bases, PyObject *mkw); /*proto*/ - -/////////////// Py3MetaclassGet /////////////// -//@requires: FindInheritedMetaclass -//@requires: CalculateMetaclass - -static PyObject *__Pyx_Py3MetaclassGet(PyObject *bases, PyObject *mkw) { +#if PY_MAJOR_VERSION < 3 + Py_DECREF(basetype); +#endif + } else { + // no bases => use default metaclass +#if PY_MAJOR_VERSION < 3 + metaclass = (PyObject *) &PyClass_Type; +#else + metaclass = (PyObject *) &PyType_Type; +#endif + Py_INCREF(metaclass); + } + return metaclass; +} + +/////////////// Py3MetaclassGet.proto /////////////// + +static PyObject *__Pyx_Py3MetaclassGet(PyObject *bases, PyObject *mkw); /*proto*/ + +/////////////// Py3MetaclassGet /////////////// +//@requires: FindInheritedMetaclass +//@requires: CalculateMetaclass + +static PyObject *__Pyx_Py3MetaclassGet(PyObject *bases, PyObject *mkw) { PyObject *metaclass = mkw ? __Pyx_PyDict_GetItemStr(mkw, PYIDENT("metaclass")) : NULL; - if (metaclass) { - Py_INCREF(metaclass); - if (PyDict_DelItem(mkw, PYIDENT("metaclass")) < 0) { - Py_DECREF(metaclass); - return NULL; - } - if (PyType_Check(metaclass)) { - PyObject* orig = metaclass; - metaclass = __Pyx_CalculateMetaclass((PyTypeObject*) metaclass, bases); - Py_DECREF(orig); - } - return metaclass; - } - return __Pyx_FindInheritedMetaclass(bases); -} - -/////////////// CreateClass.proto /////////////// - -static PyObject *__Pyx_CreateClass(PyObject *bases, PyObject *dict, PyObject *name, - PyObject *qualname, PyObject *modname); /*proto*/ - -/////////////// CreateClass /////////////// -//@requires: FindInheritedMetaclass -//@requires: CalculateMetaclass - -static PyObject *__Pyx_CreateClass(PyObject *bases, PyObject *dict, PyObject *name, - PyObject *qualname, PyObject *modname) { - PyObject *result; - PyObject *metaclass; - - if (PyDict_SetItem(dict, PYIDENT("__module__"), modname) < 0) - return NULL; - if (PyDict_SetItem(dict, PYIDENT("__qualname__"), qualname) < 0) - return NULL; - - /* Python2 __metaclass__ */ + if (metaclass) { + Py_INCREF(metaclass); + if (PyDict_DelItem(mkw, PYIDENT("metaclass")) < 0) { + Py_DECREF(metaclass); + return NULL; + } + if (PyType_Check(metaclass)) { + PyObject* orig = metaclass; + metaclass = __Pyx_CalculateMetaclass((PyTypeObject*) metaclass, bases); + Py_DECREF(orig); + } + return metaclass; + } + return __Pyx_FindInheritedMetaclass(bases); +} + +/////////////// CreateClass.proto /////////////// + +static PyObject *__Pyx_CreateClass(PyObject *bases, PyObject *dict, PyObject *name, + PyObject *qualname, PyObject *modname); /*proto*/ + +/////////////// CreateClass /////////////// +//@requires: FindInheritedMetaclass +//@requires: CalculateMetaclass + +static PyObject *__Pyx_CreateClass(PyObject *bases, PyObject *dict, PyObject *name, + PyObject *qualname, PyObject *modname) { + PyObject *result; + PyObject *metaclass; + + if (PyDict_SetItem(dict, PYIDENT("__module__"), modname) < 0) + return NULL; + if (PyDict_SetItem(dict, PYIDENT("__qualname__"), qualname) < 0) + return NULL; + + /* Python2 __metaclass__ */ metaclass = __Pyx_PyDict_GetItemStr(dict, PYIDENT("__metaclass__")); - if (metaclass) { - Py_INCREF(metaclass); - if (PyType_Check(metaclass)) { - PyObject* orig = metaclass; - metaclass = __Pyx_CalculateMetaclass((PyTypeObject*) metaclass, bases); - Py_DECREF(orig); - } - } else { - metaclass = __Pyx_FindInheritedMetaclass(bases); - } - if (unlikely(!metaclass)) - return NULL; - result = PyObject_CallFunctionObjArgs(metaclass, name, bases, dict, NULL); - Py_DECREF(metaclass); - return result; -} - -/////////////// Py3ClassCreate.proto /////////////// - -static PyObject *__Pyx_Py3MetaclassPrepare(PyObject *metaclass, PyObject *bases, PyObject *name, PyObject *qualname, - PyObject *mkw, PyObject *modname, PyObject *doc); /*proto*/ -static PyObject *__Pyx_Py3ClassCreate(PyObject *metaclass, PyObject *name, PyObject *bases, PyObject *dict, - PyObject *mkw, int calculate_metaclass, int allow_py2_metaclass); /*proto*/ - -/////////////// Py3ClassCreate /////////////// -//@requires: PyObjectGetAttrStr -//@requires: CalculateMetaclass - -static PyObject *__Pyx_Py3MetaclassPrepare(PyObject *metaclass, PyObject *bases, PyObject *name, - PyObject *qualname, PyObject *mkw, PyObject *modname, PyObject *doc) { - PyObject *ns; - if (metaclass) { - PyObject *prep = __Pyx_PyObject_GetAttrStr(metaclass, PYIDENT("__prepare__")); - if (prep) { - PyObject *pargs = PyTuple_Pack(2, name, bases); - if (unlikely(!pargs)) { - Py_DECREF(prep); - return NULL; - } - ns = PyObject_Call(prep, pargs, mkw); - Py_DECREF(prep); - Py_DECREF(pargs); - } else { - if (unlikely(!PyErr_ExceptionMatches(PyExc_AttributeError))) - return NULL; - PyErr_Clear(); - ns = PyDict_New(); - } - } else { - ns = PyDict_New(); - } - - if (unlikely(!ns)) - return NULL; - - /* Required here to emulate assignment order */ - if (unlikely(PyObject_SetItem(ns, PYIDENT("__module__"), modname) < 0)) goto bad; - if (unlikely(PyObject_SetItem(ns, PYIDENT("__qualname__"), qualname) < 0)) goto bad; - if (unlikely(doc && PyObject_SetItem(ns, PYIDENT("__doc__"), doc) < 0)) goto bad; - return ns; -bad: - Py_DECREF(ns); - return NULL; -} - -static PyObject *__Pyx_Py3ClassCreate(PyObject *metaclass, PyObject *name, PyObject *bases, - PyObject *dict, PyObject *mkw, - int calculate_metaclass, int allow_py2_metaclass) { - PyObject *result, *margs; - PyObject *owned_metaclass = NULL; - if (allow_py2_metaclass) { - /* honour Python2 __metaclass__ for backward compatibility */ - owned_metaclass = PyObject_GetItem(dict, PYIDENT("__metaclass__")); - if (owned_metaclass) { - metaclass = owned_metaclass; - } else if (likely(PyErr_ExceptionMatches(PyExc_KeyError))) { - PyErr_Clear(); - } else { - return NULL; - } - } - if (calculate_metaclass && (!metaclass || PyType_Check(metaclass))) { - metaclass = __Pyx_CalculateMetaclass((PyTypeObject*) metaclass, bases); - Py_XDECREF(owned_metaclass); - if (unlikely(!metaclass)) - return NULL; - owned_metaclass = metaclass; - } - margs = PyTuple_Pack(3, name, bases, dict); - if (unlikely(!margs)) { - result = NULL; - } else { - result = PyObject_Call(metaclass, margs, mkw); - Py_DECREF(margs); - } - Py_XDECREF(owned_metaclass); - return result; -} - -/////////////// ExtTypeTest.proto /////////////// - -static CYTHON_INLINE int __Pyx_TypeTest(PyObject *obj, PyTypeObject *type); /*proto*/ - -/////////////// ExtTypeTest /////////////// - -static CYTHON_INLINE int __Pyx_TypeTest(PyObject *obj, PyTypeObject *type) { - if (unlikely(!type)) { - PyErr_SetString(PyExc_SystemError, "Missing type object"); - return 0; - } + if (metaclass) { + Py_INCREF(metaclass); + if (PyType_Check(metaclass)) { + PyObject* orig = metaclass; + metaclass = __Pyx_CalculateMetaclass((PyTypeObject*) metaclass, bases); + Py_DECREF(orig); + } + } else { + metaclass = __Pyx_FindInheritedMetaclass(bases); + } + if (unlikely(!metaclass)) + return NULL; + result = PyObject_CallFunctionObjArgs(metaclass, name, bases, dict, NULL); + Py_DECREF(metaclass); + return result; +} + +/////////////// Py3ClassCreate.proto /////////////// + +static PyObject *__Pyx_Py3MetaclassPrepare(PyObject *metaclass, PyObject *bases, PyObject *name, PyObject *qualname, + PyObject *mkw, PyObject *modname, PyObject *doc); /*proto*/ +static PyObject *__Pyx_Py3ClassCreate(PyObject *metaclass, PyObject *name, PyObject *bases, PyObject *dict, + PyObject *mkw, int calculate_metaclass, int allow_py2_metaclass); /*proto*/ + +/////////////// Py3ClassCreate /////////////// +//@requires: PyObjectGetAttrStr +//@requires: CalculateMetaclass + +static PyObject *__Pyx_Py3MetaclassPrepare(PyObject *metaclass, PyObject *bases, PyObject *name, + PyObject *qualname, PyObject *mkw, PyObject *modname, PyObject *doc) { + PyObject *ns; + if (metaclass) { + PyObject *prep = __Pyx_PyObject_GetAttrStr(metaclass, PYIDENT("__prepare__")); + if (prep) { + PyObject *pargs = PyTuple_Pack(2, name, bases); + if (unlikely(!pargs)) { + Py_DECREF(prep); + return NULL; + } + ns = PyObject_Call(prep, pargs, mkw); + Py_DECREF(prep); + Py_DECREF(pargs); + } else { + if (unlikely(!PyErr_ExceptionMatches(PyExc_AttributeError))) + return NULL; + PyErr_Clear(); + ns = PyDict_New(); + } + } else { + ns = PyDict_New(); + } + + if (unlikely(!ns)) + return NULL; + + /* Required here to emulate assignment order */ + if (unlikely(PyObject_SetItem(ns, PYIDENT("__module__"), modname) < 0)) goto bad; + if (unlikely(PyObject_SetItem(ns, PYIDENT("__qualname__"), qualname) < 0)) goto bad; + if (unlikely(doc && PyObject_SetItem(ns, PYIDENT("__doc__"), doc) < 0)) goto bad; + return ns; +bad: + Py_DECREF(ns); + return NULL; +} + +static PyObject *__Pyx_Py3ClassCreate(PyObject *metaclass, PyObject *name, PyObject *bases, + PyObject *dict, PyObject *mkw, + int calculate_metaclass, int allow_py2_metaclass) { + PyObject *result, *margs; + PyObject *owned_metaclass = NULL; + if (allow_py2_metaclass) { + /* honour Python2 __metaclass__ for backward compatibility */ + owned_metaclass = PyObject_GetItem(dict, PYIDENT("__metaclass__")); + if (owned_metaclass) { + metaclass = owned_metaclass; + } else if (likely(PyErr_ExceptionMatches(PyExc_KeyError))) { + PyErr_Clear(); + } else { + return NULL; + } + } + if (calculate_metaclass && (!metaclass || PyType_Check(metaclass))) { + metaclass = __Pyx_CalculateMetaclass((PyTypeObject*) metaclass, bases); + Py_XDECREF(owned_metaclass); + if (unlikely(!metaclass)) + return NULL; + owned_metaclass = metaclass; + } + margs = PyTuple_Pack(3, name, bases, dict); + if (unlikely(!margs)) { + result = NULL; + } else { + result = PyObject_Call(metaclass, margs, mkw); + Py_DECREF(margs); + } + Py_XDECREF(owned_metaclass); + return result; +} + +/////////////// ExtTypeTest.proto /////////////// + +static CYTHON_INLINE int __Pyx_TypeTest(PyObject *obj, PyTypeObject *type); /*proto*/ + +/////////////// ExtTypeTest /////////////// + +static CYTHON_INLINE int __Pyx_TypeTest(PyObject *obj, PyTypeObject *type) { + if (unlikely(!type)) { + PyErr_SetString(PyExc_SystemError, "Missing type object"); + return 0; + } if (likely(__Pyx_TypeCheck(obj, type))) - return 1; - PyErr_Format(PyExc_TypeError, "Cannot convert %.200s to %.200s", - Py_TYPE(obj)->tp_name, type->tp_name); - return 0; -} - -/////////////// CallableCheck.proto /////////////// - + return 1; + PyErr_Format(PyExc_TypeError, "Cannot convert %.200s to %.200s", + Py_TYPE(obj)->tp_name, type->tp_name); + return 0; +} + +/////////////// CallableCheck.proto /////////////// + #if CYTHON_USE_TYPE_SLOTS && PY_MAJOR_VERSION >= 3 #define __Pyx_PyCallable_Check(obj) (Py_TYPE(obj)->tp_call != NULL) -#else -#define __Pyx_PyCallable_Check(obj) PyCallable_Check(obj) -#endif - -/////////////// PyDictContains.proto /////////////// - +#else +#define __Pyx_PyCallable_Check(obj) PyCallable_Check(obj) +#endif + +/////////////// PyDictContains.proto /////////////// + static CYTHON_INLINE int __Pyx_PyDict_ContainsTF(PyObject* item, PyObject* dict, int eq) { - int result = PyDict_Contains(dict, item); - return unlikely(result < 0) ? result : (result == (eq == Py_EQ)); -} - + int result = PyDict_Contains(dict, item); + return unlikely(result < 0) ? result : (result == (eq == Py_EQ)); +} + /////////////// PySetContains.proto /////////////// static CYTHON_INLINE int __Pyx_PySet_ContainsTF(PyObject* key, PyObject* set, int eq); /* proto */ @@ -1083,52 +1083,52 @@ static CYTHON_INLINE int __Pyx_PySet_ContainsTF(PyObject* key, PyObject* set, in return unlikely(result < 0) ? result : (result == (eq == Py_EQ)); } -/////////////// PySequenceContains.proto /////////////// - +/////////////// PySequenceContains.proto /////////////// + static CYTHON_INLINE int __Pyx_PySequence_ContainsTF(PyObject* item, PyObject* seq, int eq) { - int result = PySequence_Contains(seq, item); - return unlikely(result < 0) ? result : (result == (eq == Py_EQ)); -} - -/////////////// PyBoolOrNullFromLong.proto /////////////// - -static CYTHON_INLINE PyObject* __Pyx_PyBoolOrNull_FromLong(long b) { - return unlikely(b < 0) ? NULL : __Pyx_PyBool_FromLong(b); -} - -/////////////// GetBuiltinName.proto /////////////// - -static PyObject *__Pyx_GetBuiltinName(PyObject *name); /*proto*/ - -/////////////// GetBuiltinName /////////////// -//@requires: PyObjectGetAttrStr -//@substitute: naming - -static PyObject *__Pyx_GetBuiltinName(PyObject *name) { - PyObject* result = __Pyx_PyObject_GetAttrStr($builtins_cname, name); - if (unlikely(!result)) { - PyErr_Format(PyExc_NameError, -#if PY_MAJOR_VERSION >= 3 - "name '%U' is not defined", name); -#else - "name '%.200s' is not defined", PyString_AS_STRING(name)); -#endif - } - return result; -} - -/////////////// GetNameInClass.proto /////////////// - + int result = PySequence_Contains(seq, item); + return unlikely(result < 0) ? result : (result == (eq == Py_EQ)); +} + +/////////////// PyBoolOrNullFromLong.proto /////////////// + +static CYTHON_INLINE PyObject* __Pyx_PyBoolOrNull_FromLong(long b) { + return unlikely(b < 0) ? NULL : __Pyx_PyBool_FromLong(b); +} + +/////////////// GetBuiltinName.proto /////////////// + +static PyObject *__Pyx_GetBuiltinName(PyObject *name); /*proto*/ + +/////////////// GetBuiltinName /////////////// +//@requires: PyObjectGetAttrStr +//@substitute: naming + +static PyObject *__Pyx_GetBuiltinName(PyObject *name) { + PyObject* result = __Pyx_PyObject_GetAttrStr($builtins_cname, name); + if (unlikely(!result)) { + PyErr_Format(PyExc_NameError, +#if PY_MAJOR_VERSION >= 3 + "name '%U' is not defined", name); +#else + "name '%.200s' is not defined", PyString_AS_STRING(name)); +#endif + } + return result; +} + +/////////////// GetNameInClass.proto /////////////// + #define __Pyx_GetNameInClass(var, nmspace, name) (var) = __Pyx__GetNameInClass(nmspace, name) static PyObject *__Pyx__GetNameInClass(PyObject *nmspace, PyObject *name); /*proto*/ - -/////////////// GetNameInClass /////////////// -//@requires: PyObjectGetAttrStr -//@requires: GetModuleGlobalName + +/////////////// GetNameInClass /////////////// +//@requires: PyObjectGetAttrStr +//@requires: GetModuleGlobalName //@requires: Exceptions.c::PyThreadStateGet //@requires: Exceptions.c::PyErrFetchRestore //@requires: Exceptions.c::PyErrExceptionMatches - + static PyObject *__Pyx_GetGlobalNameAfterAttributeLookup(PyObject *name) { PyObject *result; __Pyx_PyThreadState_declare @@ -1141,14 +1141,14 @@ static PyObject *__Pyx_GetGlobalNameAfterAttributeLookup(PyObject *name) { } static PyObject *__Pyx__GetNameInClass(PyObject *nmspace, PyObject *name) { - PyObject *result; - result = __Pyx_PyObject_GetAttrStr(nmspace, name); + PyObject *result; + result = __Pyx_PyObject_GetAttrStr(nmspace, name); if (!result) { result = __Pyx_GetGlobalNameAfterAttributeLookup(name); } - return result; -} - + return result; +} + /////////////// SetNameInClass.proto /////////////// @@ -1164,10 +1164,10 @@ static PyObject *__Pyx__GetNameInClass(PyObject *nmspace, PyObject *name) { #endif -/////////////// GetModuleGlobalName.proto /////////////// +/////////////// GetModuleGlobalName.proto /////////////// //@requires: PyDictVersioning //@substitute: naming - + #if CYTHON_USE_DICT_VERSIONS #define __Pyx_GetModuleGlobalName(var, name) { \ static PY_UINT64_T __pyx_dict_version = 0; \ @@ -1187,19 +1187,19 @@ static PyObject *__Pyx__GetModuleGlobalName(PyObject *name, PY_UINT64_T *dict_ve #define __Pyx_GetModuleGlobalNameUncached(var, name) (var) = __Pyx__GetModuleGlobalName(name) static CYTHON_INLINE PyObject *__Pyx__GetModuleGlobalName(PyObject *name); /*proto*/ #endif + - -/////////////// GetModuleGlobalName /////////////// -//@requires: GetBuiltinName -//@substitute: naming - +/////////////// GetModuleGlobalName /////////////// +//@requires: GetBuiltinName +//@substitute: naming + #if CYTHON_USE_DICT_VERSIONS static PyObject *__Pyx__GetModuleGlobalName(PyObject *name, PY_UINT64_T *dict_version, PyObject **dict_cached_value) #else static CYTHON_INLINE PyObject *__Pyx__GetModuleGlobalName(PyObject *name) #endif { - PyObject *result; + PyObject *result; #if !CYTHON_AVOID_BORROWED_REFS #if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x030500A1 // Identifier names are always interned and have a pre-calculated hash value. @@ -1211,14 +1211,14 @@ static CYTHON_INLINE PyObject *__Pyx__GetModuleGlobalName(PyObject *name) return NULL; } #else - result = PyDict_GetItem($moddict_cname, name); + result = PyDict_GetItem($moddict_cname, name); __PYX_UPDATE_DICT_CACHE($moddict_cname, result, *dict_cached_value, *dict_version) - if (likely(result)) { + if (likely(result)) { return __Pyx_NewRef(result); } #endif -#else - result = PyObject_GetItem($moddict_cname, name); +#else + result = PyObject_GetItem($moddict_cname, name); __PYX_UPDATE_DICT_CACHE($moddict_cname, result, *dict_cached_value, *dict_version) if (likely(result)) { return __Pyx_NewRef(result); @@ -1226,56 +1226,56 @@ static CYTHON_INLINE PyObject *__Pyx__GetModuleGlobalName(PyObject *name) PyErr_Clear(); #endif return __Pyx_GetBuiltinName(name); -} - -//////////////////// GetAttr.proto //////////////////// - -static CYTHON_INLINE PyObject *__Pyx_GetAttr(PyObject *, PyObject *); /*proto*/ - -//////////////////// GetAttr //////////////////// -//@requires: PyObjectGetAttrStr - -static CYTHON_INLINE PyObject *__Pyx_GetAttr(PyObject *o, PyObject *n) { +} + +//////////////////// GetAttr.proto //////////////////// + +static CYTHON_INLINE PyObject *__Pyx_GetAttr(PyObject *, PyObject *); /*proto*/ + +//////////////////// GetAttr //////////////////// +//@requires: PyObjectGetAttrStr + +static CYTHON_INLINE PyObject *__Pyx_GetAttr(PyObject *o, PyObject *n) { #if CYTHON_USE_TYPE_SLOTS -#if PY_MAJOR_VERSION >= 3 - if (likely(PyUnicode_Check(n))) -#else - if (likely(PyString_Check(n))) -#endif - return __Pyx_PyObject_GetAttrStr(o, n); -#endif - return PyObject_GetAttr(o, n); -} - -/////////////// PyObjectLookupSpecial.proto /////////////// -//@requires: PyObjectGetAttrStr - +#if PY_MAJOR_VERSION >= 3 + if (likely(PyUnicode_Check(n))) +#else + if (likely(PyString_Check(n))) +#endif + return __Pyx_PyObject_GetAttrStr(o, n); +#endif + return PyObject_GetAttr(o, n); +} + +/////////////// PyObjectLookupSpecial.proto /////////////// +//@requires: PyObjectGetAttrStr + #if CYTHON_USE_PYTYPE_LOOKUP && CYTHON_USE_TYPE_SLOTS -static CYTHON_INLINE PyObject* __Pyx_PyObject_LookupSpecial(PyObject* obj, PyObject* attr_name) { - PyObject *res; - PyTypeObject *tp = Py_TYPE(obj); -#if PY_MAJOR_VERSION < 3 - if (unlikely(PyInstance_Check(obj))) - return __Pyx_PyObject_GetAttrStr(obj, attr_name); -#endif - // adapted from CPython's special_lookup() in ceval.c - res = _PyType_Lookup(tp, attr_name); - if (likely(res)) { - descrgetfunc f = Py_TYPE(res)->tp_descr_get; - if (!f) { - Py_INCREF(res); - } else { - res = f(res, obj, (PyObject *)tp); - } - } else { - PyErr_SetObject(PyExc_AttributeError, attr_name); - } - return res; -} -#else -#define __Pyx_PyObject_LookupSpecial(o,n) __Pyx_PyObject_GetAttrStr(o,n) -#endif - +static CYTHON_INLINE PyObject* __Pyx_PyObject_LookupSpecial(PyObject* obj, PyObject* attr_name) { + PyObject *res; + PyTypeObject *tp = Py_TYPE(obj); +#if PY_MAJOR_VERSION < 3 + if (unlikely(PyInstance_Check(obj))) + return __Pyx_PyObject_GetAttrStr(obj, attr_name); +#endif + // adapted from CPython's special_lookup() in ceval.c + res = _PyType_Lookup(tp, attr_name); + if (likely(res)) { + descrgetfunc f = Py_TYPE(res)->tp_descr_get; + if (!f) { + Py_INCREF(res); + } else { + res = f(res, obj, (PyObject *)tp); + } + } else { + PyErr_SetObject(PyExc_AttributeError, attr_name); + } + return res; +} +#else +#define __Pyx_PyObject_LookupSpecial(o,n) __Pyx_PyObject_GetAttrStr(o,n) +#endif + /////////////// PyObject_GenericGetAttrNoDict.proto /////////////// @@ -1396,8 +1396,8 @@ static CYTHON_INLINE PyObject* __Pyx_PyObject_GetAttrStrNoError(PyObject* obj, P } -/////////////// PyObjectGetAttrStr.proto /////////////// - +/////////////// PyObjectGetAttrStr.proto /////////////// + #if CYTHON_USE_TYPE_SLOTS static CYTHON_INLINE PyObject* __Pyx_PyObject_GetAttrStr(PyObject* obj, PyObject* attr_name);/*proto*/ #else @@ -1407,21 +1407,21 @@ static CYTHON_INLINE PyObject* __Pyx_PyObject_GetAttrStr(PyObject* obj, PyObject /////////////// PyObjectGetAttrStr /////////////// #if CYTHON_USE_TYPE_SLOTS -static CYTHON_INLINE PyObject* __Pyx_PyObject_GetAttrStr(PyObject* obj, PyObject* attr_name) { - PyTypeObject* tp = Py_TYPE(obj); - if (likely(tp->tp_getattro)) - return tp->tp_getattro(obj, attr_name); -#if PY_MAJOR_VERSION < 3 - if (likely(tp->tp_getattr)) - return tp->tp_getattr(obj, PyString_AS_STRING(attr_name)); -#endif - return PyObject_GetAttr(obj, attr_name); -} -#endif - - -/////////////// PyObjectSetAttrStr.proto /////////////// - +static CYTHON_INLINE PyObject* __Pyx_PyObject_GetAttrStr(PyObject* obj, PyObject* attr_name) { + PyTypeObject* tp = Py_TYPE(obj); + if (likely(tp->tp_getattro)) + return tp->tp_getattro(obj, attr_name); +#if PY_MAJOR_VERSION < 3 + if (likely(tp->tp_getattr)) + return tp->tp_getattr(obj, PyString_AS_STRING(attr_name)); +#endif + return PyObject_GetAttr(obj, attr_name); +} +#endif + + +/////////////// PyObjectSetAttrStr.proto /////////////// + #if CYTHON_USE_TYPE_SLOTS #define __Pyx_PyObject_DelAttrStr(o,n) __Pyx_PyObject_SetAttrStr(o, n, NULL) static CYTHON_INLINE int __Pyx_PyObject_SetAttrStr(PyObject* obj, PyObject* attr_name, PyObject* value);/*proto*/ @@ -1433,19 +1433,19 @@ static CYTHON_INLINE int __Pyx_PyObject_SetAttrStr(PyObject* obj, PyObject* attr /////////////// PyObjectSetAttrStr /////////////// #if CYTHON_USE_TYPE_SLOTS -static CYTHON_INLINE int __Pyx_PyObject_SetAttrStr(PyObject* obj, PyObject* attr_name, PyObject* value) { - PyTypeObject* tp = Py_TYPE(obj); - if (likely(tp->tp_setattro)) - return tp->tp_setattro(obj, attr_name, value); -#if PY_MAJOR_VERSION < 3 - if (likely(tp->tp_setattr)) - return tp->tp_setattr(obj, PyString_AS_STRING(attr_name), value); -#endif - return PyObject_SetAttr(obj, attr_name, value); -} -#endif - - +static CYTHON_INLINE int __Pyx_PyObject_SetAttrStr(PyObject* obj, PyObject* attr_name, PyObject* value) { + PyTypeObject* tp = Py_TYPE(obj); + if (likely(tp->tp_setattro)) + return tp->tp_setattro(obj, attr_name, value); +#if PY_MAJOR_VERSION < 3 + if (likely(tp->tp_setattr)) + return tp->tp_setattr(obj, PyString_AS_STRING(attr_name), value); +#endif + return PyObject_SetAttr(obj, attr_name, value); +} +#endif + + /////////////// PyObjectGetMethod.proto /////////////// static int __Pyx_PyObject_GetMethod(PyObject *obj, PyObject *name, PyObject **method);/*proto*/ @@ -1785,16 +1785,16 @@ bad: } -/////////////// PyObjectCallMethod0.proto /////////////// - -static PyObject* __Pyx_PyObject_CallMethod0(PyObject* obj, PyObject* method_name); /*proto*/ - -/////////////// PyObjectCallMethod0 /////////////// +/////////////// PyObjectCallMethod0.proto /////////////// + +static PyObject* __Pyx_PyObject_CallMethod0(PyObject* obj, PyObject* method_name); /*proto*/ + +/////////////// PyObjectCallMethod0 /////////////// //@requires: PyObjectGetMethod -//@requires: PyObjectCallOneArg -//@requires: PyObjectCallNoArg - -static PyObject* __Pyx_PyObject_CallMethod0(PyObject* obj, PyObject* method_name) { +//@requires: PyObjectCallOneArg +//@requires: PyObjectCallNoArg + +static PyObject* __Pyx_PyObject_CallMethod0(PyObject* obj, PyObject* method_name) { PyObject *method = NULL, *result = NULL; int is_method = __Pyx_PyObject_GetMethod(obj, method_name, &method); if (likely(is_method)) { @@ -1803,22 +1803,22 @@ static PyObject* __Pyx_PyObject_CallMethod0(PyObject* obj, PyObject* method_name return result; } if (unlikely(!method)) goto bad; - result = __Pyx_PyObject_CallNoArg(method); - Py_DECREF(method); -bad: - return result; -} - - -/////////////// PyObjectCallMethod1.proto /////////////// - -static PyObject* __Pyx_PyObject_CallMethod1(PyObject* obj, PyObject* method_name, PyObject* arg); /*proto*/ - -/////////////// PyObjectCallMethod1 /////////////// + result = __Pyx_PyObject_CallNoArg(method); + Py_DECREF(method); +bad: + return result; +} + + +/////////////// PyObjectCallMethod1.proto /////////////// + +static PyObject* __Pyx_PyObject_CallMethod1(PyObject* obj, PyObject* method_name, PyObject* arg); /*proto*/ + +/////////////// PyObjectCallMethod1 /////////////// //@requires: PyObjectGetMethod -//@requires: PyObjectCallOneArg +//@requires: PyObjectCallOneArg //@requires: PyObjectCall2Args - + static PyObject* __Pyx__PyObject_CallMethod1(PyObject* method, PyObject* arg) { // Separate function to avoid excessive inlining. PyObject *result = __Pyx_PyObject_CallOneArg(method, arg); @@ -1836,19 +1836,19 @@ static PyObject* __Pyx_PyObject_CallMethod1(PyObject* obj, PyObject* method_name } if (unlikely(!method)) return NULL; return __Pyx__PyObject_CallMethod1(method, arg); -} - - -/////////////// PyObjectCallMethod2.proto /////////////// - -static PyObject* __Pyx_PyObject_CallMethod2(PyObject* obj, PyObject* method_name, PyObject* arg1, PyObject* arg2); /*proto*/ - -/////////////// PyObjectCallMethod2 /////////////// -//@requires: PyObjectCall +} + + +/////////////// PyObjectCallMethod2.proto /////////////// + +static PyObject* __Pyx_PyObject_CallMethod2(PyObject* obj, PyObject* method_name, PyObject* arg1, PyObject* arg2); /*proto*/ + +/////////////// PyObjectCallMethod2 /////////////// +//@requires: PyObjectCall //@requires: PyFunctionFastCall //@requires: PyCFunctionFastCall //@requires: PyObjectCall2Args - + static PyObject* __Pyx_PyObject_Call3Args(PyObject* function, PyObject* arg1, PyObject* arg2, PyObject* arg3) { #if CYTHON_FAST_PYCALL if (PyFunction_Check(function)) { @@ -1877,89 +1877,89 @@ static PyObject* __Pyx_PyObject_Call3Args(PyObject* function, PyObject* arg1, Py return result; } -static PyObject* __Pyx_PyObject_CallMethod2(PyObject* obj, PyObject* method_name, PyObject* arg1, PyObject* arg2) { +static PyObject* __Pyx_PyObject_CallMethod2(PyObject* obj, PyObject* method_name, PyObject* arg1, PyObject* arg2) { PyObject *args, *method = NULL, *result = NULL; int is_method = __Pyx_PyObject_GetMethod(obj, method_name, &method); if (likely(is_method)) { result = __Pyx_PyObject_Call3Args(method, obj, arg1, arg2); - Py_DECREF(method); + Py_DECREF(method); return result; - } + } if (unlikely(!method)) return NULL; result = __Pyx_PyObject_Call2Args(method, arg1, arg2); - Py_DECREF(method); - return result; -} - - -/////////////// tp_new.proto /////////////// - -#define __Pyx_tp_new(type_obj, args) __Pyx_tp_new_kwargs(type_obj, args, NULL) -static CYTHON_INLINE PyObject* __Pyx_tp_new_kwargs(PyObject* type_obj, PyObject* args, PyObject* kwargs) { - return (PyObject*) (((PyTypeObject*)type_obj)->tp_new((PyTypeObject*)type_obj, args, kwargs)); -} - - -/////////////// PyObjectCall.proto /////////////// - -#if CYTHON_COMPILING_IN_CPYTHON -static CYTHON_INLINE PyObject* __Pyx_PyObject_Call(PyObject *func, PyObject *arg, PyObject *kw); /*proto*/ -#else -#define __Pyx_PyObject_Call(func, arg, kw) PyObject_Call(func, arg, kw) -#endif - -/////////////// PyObjectCall /////////////// - -#if CYTHON_COMPILING_IN_CPYTHON -static CYTHON_INLINE PyObject* __Pyx_PyObject_Call(PyObject *func, PyObject *arg, PyObject *kw) { - PyObject *result; + Py_DECREF(method); + return result; +} + + +/////////////// tp_new.proto /////////////// + +#define __Pyx_tp_new(type_obj, args) __Pyx_tp_new_kwargs(type_obj, args, NULL) +static CYTHON_INLINE PyObject* __Pyx_tp_new_kwargs(PyObject* type_obj, PyObject* args, PyObject* kwargs) { + return (PyObject*) (((PyTypeObject*)type_obj)->tp_new((PyTypeObject*)type_obj, args, kwargs)); +} + + +/////////////// PyObjectCall.proto /////////////// + +#if CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE PyObject* __Pyx_PyObject_Call(PyObject *func, PyObject *arg, PyObject *kw); /*proto*/ +#else +#define __Pyx_PyObject_Call(func, arg, kw) PyObject_Call(func, arg, kw) +#endif + +/////////////// PyObjectCall /////////////// + +#if CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE PyObject* __Pyx_PyObject_Call(PyObject *func, PyObject *arg, PyObject *kw) { + PyObject *result; ternaryfunc call = Py_TYPE(func)->tp_call; - - if (unlikely(!call)) - return PyObject_Call(func, arg, kw); - if (unlikely(Py_EnterRecursiveCall((char*)" while calling a Python object"))) - return NULL; - result = (*call)(func, arg, kw); - Py_LeaveRecursiveCall(); - if (unlikely(!result) && unlikely(!PyErr_Occurred())) { - PyErr_SetString( - PyExc_SystemError, - "NULL result without error in PyObject_Call"); - } - return result; -} -#endif - - -/////////////// PyObjectCallMethO.proto /////////////// - -#if CYTHON_COMPILING_IN_CPYTHON -static CYTHON_INLINE PyObject* __Pyx_PyObject_CallMethO(PyObject *func, PyObject *arg); /*proto*/ -#endif - -/////////////// PyObjectCallMethO /////////////// - -#if CYTHON_COMPILING_IN_CPYTHON -static CYTHON_INLINE PyObject* __Pyx_PyObject_CallMethO(PyObject *func, PyObject *arg) { - PyObject *self, *result; - PyCFunction cfunc; - cfunc = PyCFunction_GET_FUNCTION(func); - self = PyCFunction_GET_SELF(func); - - if (unlikely(Py_EnterRecursiveCall((char*)" while calling a Python object"))) - return NULL; - result = cfunc(self, arg); - Py_LeaveRecursiveCall(); - if (unlikely(!result) && unlikely(!PyErr_Occurred())) { - PyErr_SetString( - PyExc_SystemError, - "NULL result without error in PyObject_Call"); - } - return result; -} -#endif - - + + if (unlikely(!call)) + return PyObject_Call(func, arg, kw); + if (unlikely(Py_EnterRecursiveCall((char*)" while calling a Python object"))) + return NULL; + result = (*call)(func, arg, kw); + Py_LeaveRecursiveCall(); + if (unlikely(!result) && unlikely(!PyErr_Occurred())) { + PyErr_SetString( + PyExc_SystemError, + "NULL result without error in PyObject_Call"); + } + return result; +} +#endif + + +/////////////// PyObjectCallMethO.proto /////////////// + +#if CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE PyObject* __Pyx_PyObject_CallMethO(PyObject *func, PyObject *arg); /*proto*/ +#endif + +/////////////// PyObjectCallMethO /////////////// + +#if CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE PyObject* __Pyx_PyObject_CallMethO(PyObject *func, PyObject *arg) { + PyObject *self, *result; + PyCFunction cfunc; + cfunc = PyCFunction_GET_FUNCTION(func); + self = PyCFunction_GET_SELF(func); + + if (unlikely(Py_EnterRecursiveCall((char*)" while calling a Python object"))) + return NULL; + result = cfunc(self, arg); + Py_LeaveRecursiveCall(); + if (unlikely(!result) && unlikely(!PyErr_Occurred())) { + PyErr_SetString( + PyExc_SystemError, + "NULL result without error in PyObject_Call"); + } + return result; +} +#endif + + /////////////// PyFunctionFastCall.proto /////////////// #if CYTHON_FAST_PYCALL @@ -2240,124 +2240,124 @@ done: } -/////////////// PyObjectCallOneArg.proto /////////////// - -static CYTHON_INLINE PyObject* __Pyx_PyObject_CallOneArg(PyObject *func, PyObject *arg); /*proto*/ - -/////////////// PyObjectCallOneArg /////////////// -//@requires: PyObjectCallMethO -//@requires: PyObjectCall +/////////////// PyObjectCallOneArg.proto /////////////// + +static CYTHON_INLINE PyObject* __Pyx_PyObject_CallOneArg(PyObject *func, PyObject *arg); /*proto*/ + +/////////////// PyObjectCallOneArg /////////////// +//@requires: PyObjectCallMethO +//@requires: PyObjectCall //@requires: PyFunctionFastCall //@requires: PyCFunctionFastCall - -#if CYTHON_COMPILING_IN_CPYTHON -static PyObject* __Pyx__PyObject_CallOneArg(PyObject *func, PyObject *arg) { - PyObject *result; - PyObject *args = PyTuple_New(1); - if (unlikely(!args)) return NULL; - Py_INCREF(arg); - PyTuple_SET_ITEM(args, 0, arg); - result = __Pyx_PyObject_Call(func, args, NULL); - Py_DECREF(args); - return result; -} - -static CYTHON_INLINE PyObject* __Pyx_PyObject_CallOneArg(PyObject *func, PyObject *arg) { + +#if CYTHON_COMPILING_IN_CPYTHON +static PyObject* __Pyx__PyObject_CallOneArg(PyObject *func, PyObject *arg) { + PyObject *result; + PyObject *args = PyTuple_New(1); + if (unlikely(!args)) return NULL; + Py_INCREF(arg); + PyTuple_SET_ITEM(args, 0, arg); + result = __Pyx_PyObject_Call(func, args, NULL); + Py_DECREF(args); + return result; +} + +static CYTHON_INLINE PyObject* __Pyx_PyObject_CallOneArg(PyObject *func, PyObject *arg) { #if CYTHON_FAST_PYCALL if (PyFunction_Check(func)) { return __Pyx_PyFunction_FastCall(func, &arg, 1); } #endif - if (likely(PyCFunction_Check(func))) { - if (likely(PyCFunction_GET_FLAGS(func) & METH_O)) { - // fast and simple case that we are optimising for - return __Pyx_PyObject_CallMethO(func, arg); + if (likely(PyCFunction_Check(func))) { + if (likely(PyCFunction_GET_FLAGS(func) & METH_O)) { + // fast and simple case that we are optimising for + return __Pyx_PyObject_CallMethO(func, arg); #if CYTHON_FAST_PYCCALL } else if (__Pyx_PyFastCFunction_Check(func)) { return __Pyx_PyCFunction_FastCall(func, &arg, 1); #endif - } - } - return __Pyx__PyObject_CallOneArg(func, arg); -} -#else -static CYTHON_INLINE PyObject* __Pyx_PyObject_CallOneArg(PyObject *func, PyObject *arg) { + } + } + return __Pyx__PyObject_CallOneArg(func, arg); +} +#else +static CYTHON_INLINE PyObject* __Pyx_PyObject_CallOneArg(PyObject *func, PyObject *arg) { PyObject *result; PyObject *args = PyTuple_Pack(1, arg); if (unlikely(!args)) return NULL; result = __Pyx_PyObject_Call(func, args, NULL); Py_DECREF(args); return result; -} -#endif - - -/////////////// PyObjectCallNoArg.proto /////////////// -//@requires: PyObjectCall -//@substitute: naming - -#if CYTHON_COMPILING_IN_CPYTHON -static CYTHON_INLINE PyObject* __Pyx_PyObject_CallNoArg(PyObject *func); /*proto*/ -#else -#define __Pyx_PyObject_CallNoArg(func) __Pyx_PyObject_Call(func, $empty_tuple, NULL) -#endif - -/////////////// PyObjectCallNoArg /////////////// -//@requires: PyObjectCallMethO -//@requires: PyObjectCall +} +#endif + + +/////////////// PyObjectCallNoArg.proto /////////////// +//@requires: PyObjectCall +//@substitute: naming + +#if CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE PyObject* __Pyx_PyObject_CallNoArg(PyObject *func); /*proto*/ +#else +#define __Pyx_PyObject_CallNoArg(func) __Pyx_PyObject_Call(func, $empty_tuple, NULL) +#endif + +/////////////// PyObjectCallNoArg /////////////// +//@requires: PyObjectCallMethO +//@requires: PyObjectCall //@requires: PyFunctionFastCall -//@substitute: naming - -#if CYTHON_COMPILING_IN_CPYTHON -static CYTHON_INLINE PyObject* __Pyx_PyObject_CallNoArg(PyObject *func) { +//@substitute: naming + +#if CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE PyObject* __Pyx_PyObject_CallNoArg(PyObject *func) { #if CYTHON_FAST_PYCALL if (PyFunction_Check(func)) { return __Pyx_PyFunction_FastCall(func, NULL, 0); } #endif -#ifdef __Pyx_CyFunction_USED +#ifdef __Pyx_CyFunction_USED if (likely(PyCFunction_Check(func) || __Pyx_CyFunction_Check(func))) -#else +#else if (likely(PyCFunction_Check(func))) -#endif +#endif { - if (likely(PyCFunction_GET_FLAGS(func) & METH_NOARGS)) { - // fast and simple case that we are optimising for - return __Pyx_PyObject_CallMethO(func, NULL); - } - } - return __Pyx_PyObject_Call(func, $empty_tuple, NULL); -} -#endif - - -/////////////// MatrixMultiply.proto /////////////// - -#if PY_VERSION_HEX >= 0x03050000 - #define __Pyx_PyNumber_MatrixMultiply(x,y) PyNumber_MatrixMultiply(x,y) - #define __Pyx_PyNumber_InPlaceMatrixMultiply(x,y) PyNumber_InPlaceMatrixMultiply(x,y) -#else -#define __Pyx_PyNumber_MatrixMultiply(x,y) __Pyx__PyNumber_MatrixMultiply(x, y, "@") -static PyObject* __Pyx__PyNumber_MatrixMultiply(PyObject* x, PyObject* y, const char* op_name); -static PyObject* __Pyx_PyNumber_InPlaceMatrixMultiply(PyObject* x, PyObject* y); -#endif - -/////////////// MatrixMultiply /////////////// -//@requires: PyObjectGetAttrStr -//@requires: PyObjectCallOneArg + if (likely(PyCFunction_GET_FLAGS(func) & METH_NOARGS)) { + // fast and simple case that we are optimising for + return __Pyx_PyObject_CallMethO(func, NULL); + } + } + return __Pyx_PyObject_Call(func, $empty_tuple, NULL); +} +#endif + + +/////////////// MatrixMultiply.proto /////////////// + +#if PY_VERSION_HEX >= 0x03050000 + #define __Pyx_PyNumber_MatrixMultiply(x,y) PyNumber_MatrixMultiply(x,y) + #define __Pyx_PyNumber_InPlaceMatrixMultiply(x,y) PyNumber_InPlaceMatrixMultiply(x,y) +#else +#define __Pyx_PyNumber_MatrixMultiply(x,y) __Pyx__PyNumber_MatrixMultiply(x, y, "@") +static PyObject* __Pyx__PyNumber_MatrixMultiply(PyObject* x, PyObject* y, const char* op_name); +static PyObject* __Pyx_PyNumber_InPlaceMatrixMultiply(PyObject* x, PyObject* y); +#endif + +/////////////// MatrixMultiply /////////////// +//@requires: PyObjectGetAttrStr +//@requires: PyObjectCallOneArg //@requires: PyFunctionFastCall //@requires: PyCFunctionFastCall - -#if PY_VERSION_HEX < 0x03050000 -static PyObject* __Pyx_PyObject_CallMatrixMethod(PyObject* method, PyObject* arg) { - // NOTE: eats the method reference - PyObject *result = NULL; + +#if PY_VERSION_HEX < 0x03050000 +static PyObject* __Pyx_PyObject_CallMatrixMethod(PyObject* method, PyObject* arg) { + // NOTE: eats the method reference + PyObject *result = NULL; #if CYTHON_UNPACK_METHODS - if (likely(PyMethod_Check(method))) { - PyObject *self = PyMethod_GET_SELF(method); - if (likely(self)) { - PyObject *args; - PyObject *function = PyMethod_GET_FUNCTION(method); + if (likely(PyMethod_Check(method))) { + PyObject *self = PyMethod_GET_SELF(method); + if (likely(self)) { + PyObject *args; + PyObject *function = PyMethod_GET_FUNCTION(method); #if CYTHON_FAST_PYCALL if (PyFunction_Check(function)) { PyObject *args[2] = {self, arg}; @@ -2372,69 +2372,69 @@ static PyObject* __Pyx_PyObject_CallMatrixMethod(PyObject* method, PyObject* arg goto done; } #endif - args = PyTuple_New(2); + args = PyTuple_New(2); if (unlikely(!args)) goto done; - Py_INCREF(self); - PyTuple_SET_ITEM(args, 0, self); - Py_INCREF(arg); - PyTuple_SET_ITEM(args, 1, arg); - Py_INCREF(function); - Py_DECREF(method); method = NULL; - result = __Pyx_PyObject_Call(function, args, NULL); - Py_DECREF(args); - Py_DECREF(function); - return result; - } - } -#endif - result = __Pyx_PyObject_CallOneArg(method, arg); + Py_INCREF(self); + PyTuple_SET_ITEM(args, 0, self); + Py_INCREF(arg); + PyTuple_SET_ITEM(args, 1, arg); + Py_INCREF(function); + Py_DECREF(method); method = NULL; + result = __Pyx_PyObject_Call(function, args, NULL); + Py_DECREF(args); + Py_DECREF(function); + return result; + } + } +#endif + result = __Pyx_PyObject_CallOneArg(method, arg); done: - Py_DECREF(method); - return result; -} - -#define __Pyx_TryMatrixMethod(x, y, py_method_name) { \ - PyObject *func = __Pyx_PyObject_GetAttrStr(x, py_method_name); \ - if (func) { \ - PyObject *result = __Pyx_PyObject_CallMatrixMethod(func, y); \ - if (result != Py_NotImplemented) \ - return result; \ - Py_DECREF(result); \ - } else { \ - if (!PyErr_ExceptionMatches(PyExc_AttributeError)) \ - return NULL; \ - PyErr_Clear(); \ - } \ -} - -static PyObject* __Pyx__PyNumber_MatrixMultiply(PyObject* x, PyObject* y, const char* op_name) { - int right_is_subtype = PyObject_IsSubclass((PyObject*)Py_TYPE(y), (PyObject*)Py_TYPE(x)); + Py_DECREF(method); + return result; +} + +#define __Pyx_TryMatrixMethod(x, y, py_method_name) { \ + PyObject *func = __Pyx_PyObject_GetAttrStr(x, py_method_name); \ + if (func) { \ + PyObject *result = __Pyx_PyObject_CallMatrixMethod(func, y); \ + if (result != Py_NotImplemented) \ + return result; \ + Py_DECREF(result); \ + } else { \ + if (!PyErr_ExceptionMatches(PyExc_AttributeError)) \ + return NULL; \ + PyErr_Clear(); \ + } \ +} + +static PyObject* __Pyx__PyNumber_MatrixMultiply(PyObject* x, PyObject* y, const char* op_name) { + int right_is_subtype = PyObject_IsSubclass((PyObject*)Py_TYPE(y), (PyObject*)Py_TYPE(x)); if (unlikely(right_is_subtype == -1)) return NULL; - if (right_is_subtype) { - // to allow subtypes to override parent behaviour, try reversed operation first - // see note at https://docs.python.org/3/reference/datamodel.html#emulating-numeric-types - __Pyx_TryMatrixMethod(y, x, PYIDENT("__rmatmul__")) - } - __Pyx_TryMatrixMethod(x, y, PYIDENT("__matmul__")) - if (!right_is_subtype) { - __Pyx_TryMatrixMethod(y, x, PYIDENT("__rmatmul__")) - } - PyErr_Format(PyExc_TypeError, - "unsupported operand type(s) for %.2s: '%.100s' and '%.100s'", - op_name, - Py_TYPE(x)->tp_name, - Py_TYPE(y)->tp_name); - return NULL; -} - -static PyObject* __Pyx_PyNumber_InPlaceMatrixMultiply(PyObject* x, PyObject* y) { - __Pyx_TryMatrixMethod(x, y, PYIDENT("__imatmul__")) - return __Pyx__PyNumber_MatrixMultiply(x, y, "@="); -} - -#undef __Pyx_TryMatrixMethod -#endif + if (right_is_subtype) { + // to allow subtypes to override parent behaviour, try reversed operation first + // see note at https://docs.python.org/3/reference/datamodel.html#emulating-numeric-types + __Pyx_TryMatrixMethod(y, x, PYIDENT("__rmatmul__")) + } + __Pyx_TryMatrixMethod(x, y, PYIDENT("__matmul__")) + if (!right_is_subtype) { + __Pyx_TryMatrixMethod(y, x, PYIDENT("__rmatmul__")) + } + PyErr_Format(PyExc_TypeError, + "unsupported operand type(s) for %.2s: '%.100s' and '%.100s'", + op_name, + Py_TYPE(x)->tp_name, + Py_TYPE(y)->tp_name); + return NULL; +} + +static PyObject* __Pyx_PyNumber_InPlaceMatrixMultiply(PyObject* x, PyObject* y) { + __Pyx_TryMatrixMethod(x, y, PYIDENT("__imatmul__")) + return __Pyx__PyNumber_MatrixMultiply(x, y, "@="); +} + +#undef __Pyx_TryMatrixMethod +#endif /////////////// PyDictVersioning.proto /////////////// diff --git a/contrib/tools/cython/Cython/Utility/Optimize.c b/contrib/tools/cython/Cython/Utility/Optimize.c index d18c9b78ec..34b6438f33 100644 --- a/contrib/tools/cython/Cython/Utility/Optimize.c +++ b/contrib/tools/cython/Cython/Utility/Optimize.c @@ -1,122 +1,122 @@ -/* - * Optional optimisations of built-in functions and methods. - * - * Required replacements of builtins are in Builtins.c. - * - * General object operations and protocols are in ObjectHandling.c. - */ - -/////////////// append.proto /////////////// - -static CYTHON_INLINE int __Pyx_PyObject_Append(PyObject* L, PyObject* x); /*proto*/ - -/////////////// append /////////////// -//@requires: ListAppend -//@requires: ObjectHandling.c::PyObjectCallMethod1 - -static CYTHON_INLINE int __Pyx_PyObject_Append(PyObject* L, PyObject* x) { - if (likely(PyList_CheckExact(L))) { - if (unlikely(__Pyx_PyList_Append(L, x) < 0)) return -1; - } else { - PyObject* retval = __Pyx_PyObject_CallMethod1(L, PYIDENT("append"), x); - if (unlikely(!retval)) - return -1; - Py_DECREF(retval); - } - return 0; -} - -/////////////// ListAppend.proto /////////////// - +/* + * Optional optimisations of built-in functions and methods. + * + * Required replacements of builtins are in Builtins.c. + * + * General object operations and protocols are in ObjectHandling.c. + */ + +/////////////// append.proto /////////////// + +static CYTHON_INLINE int __Pyx_PyObject_Append(PyObject* L, PyObject* x); /*proto*/ + +/////////////// append /////////////// +//@requires: ListAppend +//@requires: ObjectHandling.c::PyObjectCallMethod1 + +static CYTHON_INLINE int __Pyx_PyObject_Append(PyObject* L, PyObject* x) { + if (likely(PyList_CheckExact(L))) { + if (unlikely(__Pyx_PyList_Append(L, x) < 0)) return -1; + } else { + PyObject* retval = __Pyx_PyObject_CallMethod1(L, PYIDENT("append"), x); + if (unlikely(!retval)) + return -1; + Py_DECREF(retval); + } + return 0; +} + +/////////////// ListAppend.proto /////////////// + #if CYTHON_USE_PYLIST_INTERNALS && CYTHON_ASSUME_SAFE_MACROS -static CYTHON_INLINE int __Pyx_PyList_Append(PyObject* list, PyObject* x) { - PyListObject* L = (PyListObject*) list; - Py_ssize_t len = Py_SIZE(list); - if (likely(L->allocated > len) & likely(len > (L->allocated >> 1))) { - Py_INCREF(x); - PyList_SET_ITEM(list, len, x); +static CYTHON_INLINE int __Pyx_PyList_Append(PyObject* list, PyObject* x) { + PyListObject* L = (PyListObject*) list; + Py_ssize_t len = Py_SIZE(list); + if (likely(L->allocated > len) & likely(len > (L->allocated >> 1))) { + Py_INCREF(x); + PyList_SET_ITEM(list, len, x); __Pyx_SET_SIZE(list, len + 1); - return 0; - } - return PyList_Append(list, x); -} -#else -#define __Pyx_PyList_Append(L,x) PyList_Append(L,x) -#endif - -/////////////// ListCompAppend.proto /////////////// - + return 0; + } + return PyList_Append(list, x); +} +#else +#define __Pyx_PyList_Append(L,x) PyList_Append(L,x) +#endif + +/////////////// ListCompAppend.proto /////////////// + #if CYTHON_USE_PYLIST_INTERNALS && CYTHON_ASSUME_SAFE_MACROS -static CYTHON_INLINE int __Pyx_ListComp_Append(PyObject* list, PyObject* x) { - PyListObject* L = (PyListObject*) list; - Py_ssize_t len = Py_SIZE(list); - if (likely(L->allocated > len)) { - Py_INCREF(x); - PyList_SET_ITEM(list, len, x); +static CYTHON_INLINE int __Pyx_ListComp_Append(PyObject* list, PyObject* x) { + PyListObject* L = (PyListObject*) list; + Py_ssize_t len = Py_SIZE(list); + if (likely(L->allocated > len)) { + Py_INCREF(x); + PyList_SET_ITEM(list, len, x); __Pyx_SET_SIZE(list, len + 1); - return 0; - } - return PyList_Append(list, x); -} -#else -#define __Pyx_ListComp_Append(L,x) PyList_Append(L,x) -#endif - -//////////////////// ListExtend.proto //////////////////// - -static CYTHON_INLINE int __Pyx_PyList_Extend(PyObject* L, PyObject* v) { -#if CYTHON_COMPILING_IN_CPYTHON - PyObject* none = _PyList_Extend((PyListObject*)L, v); - if (unlikely(!none)) - return -1; - Py_DECREF(none); - return 0; -#else - return PyList_SetSlice(L, PY_SSIZE_T_MAX, PY_SSIZE_T_MAX, v); -#endif -} - -/////////////// pop.proto /////////////// - + return 0; + } + return PyList_Append(list, x); +} +#else +#define __Pyx_ListComp_Append(L,x) PyList_Append(L,x) +#endif + +//////////////////// ListExtend.proto //////////////////// + +static CYTHON_INLINE int __Pyx_PyList_Extend(PyObject* L, PyObject* v) { +#if CYTHON_COMPILING_IN_CPYTHON + PyObject* none = _PyList_Extend((PyListObject*)L, v); + if (unlikely(!none)) + return -1; + Py_DECREF(none); + return 0; +#else + return PyList_SetSlice(L, PY_SSIZE_T_MAX, PY_SSIZE_T_MAX, v); +#endif +} + +/////////////// pop.proto /////////////// + static CYTHON_INLINE PyObject* __Pyx__PyObject_Pop(PyObject* L); /*proto*/ - + #if CYTHON_USE_PYLIST_INTERNALS && CYTHON_ASSUME_SAFE_MACROS -static CYTHON_INLINE PyObject* __Pyx_PyList_Pop(PyObject* L); /*proto*/ +static CYTHON_INLINE PyObject* __Pyx_PyList_Pop(PyObject* L); /*proto*/ #define __Pyx_PyObject_Pop(L) (likely(PyList_CheckExact(L)) ? \ __Pyx_PyList_Pop(L) : __Pyx__PyObject_Pop(L)) - + #else #define __Pyx_PyList_Pop(L) __Pyx__PyObject_Pop(L) #define __Pyx_PyObject_Pop(L) __Pyx__PyObject_Pop(L) #endif -/////////////// pop /////////////// -//@requires: ObjectHandling.c::PyObjectCallMethod0 - -static CYTHON_INLINE PyObject* __Pyx__PyObject_Pop(PyObject* L) { - if (Py_TYPE(L) == &PySet_Type) { - return PySet_Pop(L); - } - return __Pyx_PyObject_CallMethod0(L, PYIDENT("pop")); -} - +/////////////// pop /////////////// +//@requires: ObjectHandling.c::PyObjectCallMethod0 + +static CYTHON_INLINE PyObject* __Pyx__PyObject_Pop(PyObject* L) { + if (Py_TYPE(L) == &PySet_Type) { + return PySet_Pop(L); + } + return __Pyx_PyObject_CallMethod0(L, PYIDENT("pop")); +} + #if CYTHON_USE_PYLIST_INTERNALS && CYTHON_ASSUME_SAFE_MACROS -static CYTHON_INLINE PyObject* __Pyx_PyList_Pop(PyObject* L) { - /* Check that both the size is positive and no reallocation shrinking needs to be done. */ - if (likely(PyList_GET_SIZE(L) > (((PyListObject*)L)->allocated >> 1))) { +static CYTHON_INLINE PyObject* __Pyx_PyList_Pop(PyObject* L) { + /* Check that both the size is positive and no reallocation shrinking needs to be done. */ + if (likely(PyList_GET_SIZE(L) > (((PyListObject*)L)->allocated >> 1))) { __Pyx_SET_SIZE(L, Py_SIZE(L) - 1); - return PyList_GET_ITEM(L, PyList_GET_SIZE(L)); - } + return PyList_GET_ITEM(L, PyList_GET_SIZE(L)); + } return CALL_UNBOUND_METHOD(PyList_Type, "pop", L); } -#endif - - -/////////////// pop_index.proto /////////////// - +#endif + + +/////////////// pop_index.proto /////////////// + static PyObject* __Pyx__PyObject_PopNewIndex(PyObject* L, PyObject* py_ix); /*proto*/ static PyObject* __Pyx__PyObject_PopIndex(PyObject* L, PyObject* py_ix); /*proto*/ - + #if CYTHON_USE_PYLIST_INTERNALS && CYTHON_ASSUME_SAFE_MACROS static PyObject* __Pyx__PyList_PopIndex(PyObject* L, PyObject* py_ix, Py_ssize_t ix); /*proto*/ @@ -127,13 +127,13 @@ static PyObject* __Pyx__PyList_PopIndex(PyObject* L, PyObject* py_ix, Py_ssize_t __Pyx__PyObject_PopIndex(L, py_ix))) #define __Pyx_PyList_PopIndex(L, py_ix, ix, is_signed, type, to_py_func) ( \ - __Pyx_fits_Py_ssize_t(ix, type, is_signed) ? \ + __Pyx_fits_Py_ssize_t(ix, type, is_signed) ? \ __Pyx__PyList_PopIndex(L, py_ix, ix) : ( \ (unlikely((py_ix) == Py_None)) ? __Pyx__PyObject_PopNewIndex(L, to_py_func(ix)) : \ __Pyx__PyObject_PopIndex(L, py_ix))) - + #else - + #define __Pyx_PyList_PopIndex(L, py_ix, ix, is_signed, type, to_py_func) \ __Pyx_PyObject_PopIndex(L, py_ix, ix, is_signed, type, to_py_func) @@ -142,135 +142,135 @@ static PyObject* __Pyx__PyList_PopIndex(PyObject* L, PyObject* py_ix, Py_ssize_t __Pyx__PyObject_PopIndex(L, py_ix)) #endif -/////////////// pop_index /////////////// -//@requires: ObjectHandling.c::PyObjectCallMethod1 - +/////////////// pop_index /////////////// +//@requires: ObjectHandling.c::PyObjectCallMethod1 + static PyObject* __Pyx__PyObject_PopNewIndex(PyObject* L, PyObject* py_ix) { - PyObject *r; - if (unlikely(!py_ix)) return NULL; + PyObject *r; + if (unlikely(!py_ix)) return NULL; r = __Pyx__PyObject_PopIndex(L, py_ix); - Py_DECREF(py_ix); - return r; -} - + Py_DECREF(py_ix); + return r; +} + static PyObject* __Pyx__PyObject_PopIndex(PyObject* L, PyObject* py_ix) { return __Pyx_PyObject_CallMethod1(L, PYIDENT("pop"), py_ix); } #if CYTHON_USE_PYLIST_INTERNALS && CYTHON_ASSUME_SAFE_MACROS static PyObject* __Pyx__PyList_PopIndex(PyObject* L, PyObject* py_ix, Py_ssize_t ix) { - Py_ssize_t size = PyList_GET_SIZE(L); - if (likely(size > (((PyListObject*)L)->allocated >> 1))) { - Py_ssize_t cix = ix; - if (cix < 0) { - cix += size; - } + Py_ssize_t size = PyList_GET_SIZE(L); + if (likely(size > (((PyListObject*)L)->allocated >> 1))) { + Py_ssize_t cix = ix; + if (cix < 0) { + cix += size; + } if (likely(__Pyx_is_valid_index(cix, size))) { - PyObject* v = PyList_GET_ITEM(L, cix); + PyObject* v = PyList_GET_ITEM(L, cix); __Pyx_SET_SIZE(L, Py_SIZE(L) - 1); - size -= 1; - memmove(&PyList_GET_ITEM(L, cix), &PyList_GET_ITEM(L, cix+1), (size_t)(size-cix)*sizeof(PyObject*)); - return v; - } - } + size -= 1; + memmove(&PyList_GET_ITEM(L, cix), &PyList_GET_ITEM(L, cix+1), (size_t)(size-cix)*sizeof(PyObject*)); + return v; + } + } if (py_ix == Py_None) { return __Pyx__PyObject_PopNewIndex(L, PyInt_FromSsize_t(ix)); } else { return __Pyx__PyObject_PopIndex(L, py_ix); } } -#endif - - -/////////////// dict_getitem_default.proto /////////////// - -static PyObject* __Pyx_PyDict_GetItemDefault(PyObject* d, PyObject* key, PyObject* default_value); /*proto*/ - -/////////////// dict_getitem_default /////////////// - -static PyObject* __Pyx_PyDict_GetItemDefault(PyObject* d, PyObject* key, PyObject* default_value) { - PyObject* value; +#endif + + +/////////////// dict_getitem_default.proto /////////////// + +static PyObject* __Pyx_PyDict_GetItemDefault(PyObject* d, PyObject* key, PyObject* default_value); /*proto*/ + +/////////////// dict_getitem_default /////////////// + +static PyObject* __Pyx_PyDict_GetItemDefault(PyObject* d, PyObject* key, PyObject* default_value) { + PyObject* value; #if PY_MAJOR_VERSION >= 3 && !CYTHON_COMPILING_IN_PYPY - value = PyDict_GetItemWithError(d, key); - if (unlikely(!value)) { - if (unlikely(PyErr_Occurred())) - return NULL; - value = default_value; - } - Py_INCREF(value); + value = PyDict_GetItemWithError(d, key); + if (unlikely(!value)) { + if (unlikely(PyErr_Occurred())) + return NULL; + value = default_value; + } + Py_INCREF(value); // avoid C compiler warning about unused utility functions if ((1)); -#else - if (PyString_CheckExact(key) || PyUnicode_CheckExact(key) || PyInt_CheckExact(key)) { - /* these presumably have safe hash functions */ - value = PyDict_GetItem(d, key); - if (unlikely(!value)) { - value = default_value; - } - Py_INCREF(value); +#else + if (PyString_CheckExact(key) || PyUnicode_CheckExact(key) || PyInt_CheckExact(key)) { + /* these presumably have safe hash functions */ + value = PyDict_GetItem(d, key); + if (unlikely(!value)) { + value = default_value; + } + Py_INCREF(value); } #endif else { - if (default_value == Py_None) + if (default_value == Py_None) value = CALL_UNBOUND_METHOD(PyDict_Type, "get", d, key); else value = CALL_UNBOUND_METHOD(PyDict_Type, "get", d, key, default_value); - } - return value; -} - - -/////////////// dict_setdefault.proto /////////////// - -static CYTHON_INLINE PyObject *__Pyx_PyDict_SetDefault(PyObject *d, PyObject *key, PyObject *default_value, int is_safe_type); /*proto*/ - -/////////////// dict_setdefault /////////////// - -static CYTHON_INLINE PyObject *__Pyx_PyDict_SetDefault(PyObject *d, PyObject *key, PyObject *default_value, - CYTHON_UNUSED int is_safe_type) { - PyObject* value; -#if PY_VERSION_HEX >= 0x030400A0 - // we keep the method call at the end to avoid "unused" C compiler warnings + } + return value; +} + + +/////////////// dict_setdefault.proto /////////////// + +static CYTHON_INLINE PyObject *__Pyx_PyDict_SetDefault(PyObject *d, PyObject *key, PyObject *default_value, int is_safe_type); /*proto*/ + +/////////////// dict_setdefault /////////////// + +static CYTHON_INLINE PyObject *__Pyx_PyDict_SetDefault(PyObject *d, PyObject *key, PyObject *default_value, + CYTHON_UNUSED int is_safe_type) { + PyObject* value; +#if PY_VERSION_HEX >= 0x030400A0 + // we keep the method call at the end to avoid "unused" C compiler warnings if ((1)) { - value = PyDict_SetDefault(d, key, default_value); - if (unlikely(!value)) return NULL; - Py_INCREF(value); -#else - if (is_safe_type == 1 || (is_safe_type == -1 && - /* the following builtins presumably have repeatably safe and fast hash functions */ + value = PyDict_SetDefault(d, key, default_value); + if (unlikely(!value)) return NULL; + Py_INCREF(value); +#else + if (is_safe_type == 1 || (is_safe_type == -1 && + /* the following builtins presumably have repeatably safe and fast hash functions */ #if PY_MAJOR_VERSION >= 3 && !CYTHON_COMPILING_IN_PYPY - (PyUnicode_CheckExact(key) || PyString_CheckExact(key) || PyLong_CheckExact(key)))) { - value = PyDict_GetItemWithError(d, key); - if (unlikely(!value)) { - if (unlikely(PyErr_Occurred())) - return NULL; - if (unlikely(PyDict_SetItem(d, key, default_value) == -1)) - return NULL; - value = default_value; - } - Py_INCREF(value); -#else - (PyString_CheckExact(key) || PyUnicode_CheckExact(key) || PyInt_CheckExact(key) || PyLong_CheckExact(key)))) { - value = PyDict_GetItem(d, key); - if (unlikely(!value)) { - if (unlikely(PyDict_SetItem(d, key, default_value) == -1)) - return NULL; - value = default_value; - } - Py_INCREF(value); -#endif -#endif - } else { + (PyUnicode_CheckExact(key) || PyString_CheckExact(key) || PyLong_CheckExact(key)))) { + value = PyDict_GetItemWithError(d, key); + if (unlikely(!value)) { + if (unlikely(PyErr_Occurred())) + return NULL; + if (unlikely(PyDict_SetItem(d, key, default_value) == -1)) + return NULL; + value = default_value; + } + Py_INCREF(value); +#else + (PyString_CheckExact(key) || PyUnicode_CheckExact(key) || PyInt_CheckExact(key) || PyLong_CheckExact(key)))) { + value = PyDict_GetItem(d, key); + if (unlikely(!value)) { + if (unlikely(PyDict_SetItem(d, key, default_value) == -1)) + return NULL; + value = default_value; + } + Py_INCREF(value); +#endif +#endif + } else { value = CALL_UNBOUND_METHOD(PyDict_Type, "setdefault", d, key, default_value); - } - return value; -} - - -/////////////// py_dict_clear.proto /////////////// - -#define __Pyx_PyDict_Clear(d) (PyDict_Clear(d), 0) - + } + return value; +} + + +/////////////// py_dict_clear.proto /////////////// + +#define __Pyx_PyDict_Clear(d) (PyDict_Clear(d), 0) + /////////////// py_dict_pop.proto /////////////// @@ -293,27 +293,27 @@ static CYTHON_INLINE PyObject *__Pyx_PyDict_Pop(PyObject *d, PyObject *key, PyOb } -/////////////// dict_iter.proto /////////////// - -static CYTHON_INLINE PyObject* __Pyx_dict_iterator(PyObject* dict, int is_dict, PyObject* method_name, - Py_ssize_t* p_orig_length, int* p_is_dict); -static CYTHON_INLINE int __Pyx_dict_iter_next(PyObject* dict_or_iter, Py_ssize_t orig_length, Py_ssize_t* ppos, - PyObject** pkey, PyObject** pvalue, PyObject** pitem, int is_dict); - -/////////////// dict_iter /////////////// -//@requires: ObjectHandling.c::UnpackTuple2 -//@requires: ObjectHandling.c::IterFinish -//@requires: ObjectHandling.c::PyObjectCallMethod0 - -static CYTHON_INLINE PyObject* __Pyx_dict_iterator(PyObject* iterable, int is_dict, PyObject* method_name, - Py_ssize_t* p_orig_length, int* p_source_is_dict) { - is_dict = is_dict || likely(PyDict_CheckExact(iterable)); - *p_source_is_dict = is_dict; +/////////////// dict_iter.proto /////////////// + +static CYTHON_INLINE PyObject* __Pyx_dict_iterator(PyObject* dict, int is_dict, PyObject* method_name, + Py_ssize_t* p_orig_length, int* p_is_dict); +static CYTHON_INLINE int __Pyx_dict_iter_next(PyObject* dict_or_iter, Py_ssize_t orig_length, Py_ssize_t* ppos, + PyObject** pkey, PyObject** pvalue, PyObject** pitem, int is_dict); + +/////////////// dict_iter /////////////// +//@requires: ObjectHandling.c::UnpackTuple2 +//@requires: ObjectHandling.c::IterFinish +//@requires: ObjectHandling.c::PyObjectCallMethod0 + +static CYTHON_INLINE PyObject* __Pyx_dict_iterator(PyObject* iterable, int is_dict, PyObject* method_name, + Py_ssize_t* p_orig_length, int* p_source_is_dict) { + is_dict = is_dict || likely(PyDict_CheckExact(iterable)); + *p_source_is_dict = is_dict; if (is_dict) { -#if !CYTHON_COMPILING_IN_PYPY - *p_orig_length = PyDict_Size(iterable); - Py_INCREF(iterable); - return iterable; +#if !CYTHON_COMPILING_IN_PYPY + *p_orig_length = PyDict_Size(iterable); + Py_INCREF(iterable); + return iterable; #elif PY_MAJOR_VERSION >= 3 // On PyPy3, we need to translate manually a few method names. // This logic is not needed on CPython thanks to the fast case above. @@ -334,93 +334,93 @@ static CYTHON_INLINE PyObject* __Pyx_dict_iterator(PyObject* iterable, int is_di } } #endif - } - *p_orig_length = 0; - if (method_name) { - PyObject* iter; - iterable = __Pyx_PyObject_CallMethod0(iterable, method_name); - if (!iterable) - return NULL; -#if !CYTHON_COMPILING_IN_PYPY - if (PyTuple_CheckExact(iterable) || PyList_CheckExact(iterable)) - return iterable; -#endif - iter = PyObject_GetIter(iterable); - Py_DECREF(iterable); - return iter; - } - return PyObject_GetIter(iterable); -} - + } + *p_orig_length = 0; + if (method_name) { + PyObject* iter; + iterable = __Pyx_PyObject_CallMethod0(iterable, method_name); + if (!iterable) + return NULL; +#if !CYTHON_COMPILING_IN_PYPY + if (PyTuple_CheckExact(iterable) || PyList_CheckExact(iterable)) + return iterable; +#endif + iter = PyObject_GetIter(iterable); + Py_DECREF(iterable); + return iter; + } + return PyObject_GetIter(iterable); +} + static CYTHON_INLINE int __Pyx_dict_iter_next( PyObject* iter_obj, CYTHON_NCP_UNUSED Py_ssize_t orig_length, CYTHON_NCP_UNUSED Py_ssize_t* ppos, PyObject** pkey, PyObject** pvalue, PyObject** pitem, int source_is_dict) { - PyObject* next_item; -#if !CYTHON_COMPILING_IN_PYPY - if (source_is_dict) { - PyObject *key, *value; - if (unlikely(orig_length != PyDict_Size(iter_obj))) { - PyErr_SetString(PyExc_RuntimeError, "dictionary changed size during iteration"); - return -1; - } - if (unlikely(!PyDict_Next(iter_obj, ppos, &key, &value))) { - return 0; - } - if (pitem) { - PyObject* tuple = PyTuple_New(2); - if (unlikely(!tuple)) { - return -1; - } - Py_INCREF(key); - Py_INCREF(value); - PyTuple_SET_ITEM(tuple, 0, key); - PyTuple_SET_ITEM(tuple, 1, value); - *pitem = tuple; - } else { - if (pkey) { - Py_INCREF(key); - *pkey = key; - } - if (pvalue) { - Py_INCREF(value); - *pvalue = value; - } - } - return 1; - } else if (PyTuple_CheckExact(iter_obj)) { - Py_ssize_t pos = *ppos; - if (unlikely(pos >= PyTuple_GET_SIZE(iter_obj))) return 0; - *ppos = pos + 1; - next_item = PyTuple_GET_ITEM(iter_obj, pos); - Py_INCREF(next_item); - } else if (PyList_CheckExact(iter_obj)) { - Py_ssize_t pos = *ppos; - if (unlikely(pos >= PyList_GET_SIZE(iter_obj))) return 0; - *ppos = pos + 1; - next_item = PyList_GET_ITEM(iter_obj, pos); - Py_INCREF(next_item); - } else -#endif - { - next_item = PyIter_Next(iter_obj); - if (unlikely(!next_item)) { - return __Pyx_IterFinish(); - } - } - if (pitem) { - *pitem = next_item; - } else if (pkey && pvalue) { - if (__Pyx_unpack_tuple2(next_item, pkey, pvalue, source_is_dict, source_is_dict, 1)) - return -1; - } else if (pkey) { - *pkey = next_item; - } else { - *pvalue = next_item; - } - return 1; -} - - + PyObject* next_item; +#if !CYTHON_COMPILING_IN_PYPY + if (source_is_dict) { + PyObject *key, *value; + if (unlikely(orig_length != PyDict_Size(iter_obj))) { + PyErr_SetString(PyExc_RuntimeError, "dictionary changed size during iteration"); + return -1; + } + if (unlikely(!PyDict_Next(iter_obj, ppos, &key, &value))) { + return 0; + } + if (pitem) { + PyObject* tuple = PyTuple_New(2); + if (unlikely(!tuple)) { + return -1; + } + Py_INCREF(key); + Py_INCREF(value); + PyTuple_SET_ITEM(tuple, 0, key); + PyTuple_SET_ITEM(tuple, 1, value); + *pitem = tuple; + } else { + if (pkey) { + Py_INCREF(key); + *pkey = key; + } + if (pvalue) { + Py_INCREF(value); + *pvalue = value; + } + } + return 1; + } else if (PyTuple_CheckExact(iter_obj)) { + Py_ssize_t pos = *ppos; + if (unlikely(pos >= PyTuple_GET_SIZE(iter_obj))) return 0; + *ppos = pos + 1; + next_item = PyTuple_GET_ITEM(iter_obj, pos); + Py_INCREF(next_item); + } else if (PyList_CheckExact(iter_obj)) { + Py_ssize_t pos = *ppos; + if (unlikely(pos >= PyList_GET_SIZE(iter_obj))) return 0; + *ppos = pos + 1; + next_item = PyList_GET_ITEM(iter_obj, pos); + Py_INCREF(next_item); + } else +#endif + { + next_item = PyIter_Next(iter_obj); + if (unlikely(!next_item)) { + return __Pyx_IterFinish(); + } + } + if (pitem) { + *pitem = next_item; + } else if (pkey && pvalue) { + if (__Pyx_unpack_tuple2(next_item, pkey, pvalue, source_is_dict, source_is_dict, 1)) + return -1; + } else if (pkey) { + *pkey = next_item; + } else { + *pvalue = next_item; + } + return 1; +} + + /////////////// set_iter.proto /////////////// static CYTHON_INLINE PyObject* __Pyx_set_iterator(PyObject* iterable, int is_set, @@ -558,105 +558,105 @@ static CYTHON_INLINE int __Pyx_PySet_Remove(PyObject *set, PyObject *key) { } -/////////////// unicode_iter.proto /////////////// - -static CYTHON_INLINE int __Pyx_init_unicode_iteration( - PyObject* ustring, Py_ssize_t *length, void** data, int *kind); /* proto */ - -/////////////// unicode_iter /////////////// - -static CYTHON_INLINE int __Pyx_init_unicode_iteration( - PyObject* ustring, Py_ssize_t *length, void** data, int *kind) { -#if CYTHON_PEP393_ENABLED - if (unlikely(__Pyx_PyUnicode_READY(ustring) < 0)) return -1; - *kind = PyUnicode_KIND(ustring); - *length = PyUnicode_GET_LENGTH(ustring); - *data = PyUnicode_DATA(ustring); -#else - *kind = 0; - *length = PyUnicode_GET_SIZE(ustring); - *data = (void*)PyUnicode_AS_UNICODE(ustring); -#endif - return 0; -} - -/////////////// pyobject_as_double.proto /////////////// - -static double __Pyx__PyObject_AsDouble(PyObject* obj); /* proto */ - -#if CYTHON_COMPILING_IN_PYPY -#define __Pyx_PyObject_AsDouble(obj) \ -(likely(PyFloat_CheckExact(obj)) ? PyFloat_AS_DOUBLE(obj) : \ - likely(PyInt_CheckExact(obj)) ? \ - PyFloat_AsDouble(obj) : __Pyx__PyObject_AsDouble(obj)) -#else -#define __Pyx_PyObject_AsDouble(obj) \ -((likely(PyFloat_CheckExact(obj))) ? \ - PyFloat_AS_DOUBLE(obj) : __Pyx__PyObject_AsDouble(obj)) -#endif - -/////////////// pyobject_as_double /////////////// - -static double __Pyx__PyObject_AsDouble(PyObject* obj) { - PyObject* float_value; +/////////////// unicode_iter.proto /////////////// + +static CYTHON_INLINE int __Pyx_init_unicode_iteration( + PyObject* ustring, Py_ssize_t *length, void** data, int *kind); /* proto */ + +/////////////// unicode_iter /////////////// + +static CYTHON_INLINE int __Pyx_init_unicode_iteration( + PyObject* ustring, Py_ssize_t *length, void** data, int *kind) { +#if CYTHON_PEP393_ENABLED + if (unlikely(__Pyx_PyUnicode_READY(ustring) < 0)) return -1; + *kind = PyUnicode_KIND(ustring); + *length = PyUnicode_GET_LENGTH(ustring); + *data = PyUnicode_DATA(ustring); +#else + *kind = 0; + *length = PyUnicode_GET_SIZE(ustring); + *data = (void*)PyUnicode_AS_UNICODE(ustring); +#endif + return 0; +} + +/////////////// pyobject_as_double.proto /////////////// + +static double __Pyx__PyObject_AsDouble(PyObject* obj); /* proto */ + +#if CYTHON_COMPILING_IN_PYPY +#define __Pyx_PyObject_AsDouble(obj) \ +(likely(PyFloat_CheckExact(obj)) ? PyFloat_AS_DOUBLE(obj) : \ + likely(PyInt_CheckExact(obj)) ? \ + PyFloat_AsDouble(obj) : __Pyx__PyObject_AsDouble(obj)) +#else +#define __Pyx_PyObject_AsDouble(obj) \ +((likely(PyFloat_CheckExact(obj))) ? \ + PyFloat_AS_DOUBLE(obj) : __Pyx__PyObject_AsDouble(obj)) +#endif + +/////////////// pyobject_as_double /////////////// + +static double __Pyx__PyObject_AsDouble(PyObject* obj) { + PyObject* float_value; #if !CYTHON_USE_TYPE_SLOTS float_value = PyNumber_Float(obj); if ((0)) goto bad; -#else - PyNumberMethods *nb = Py_TYPE(obj)->tp_as_number; - if (likely(nb) && likely(nb->nb_float)) { - float_value = nb->nb_float(obj); - if (likely(float_value) && unlikely(!PyFloat_Check(float_value))) { - PyErr_Format(PyExc_TypeError, - "__float__ returned non-float (type %.200s)", - Py_TYPE(float_value)->tp_name); - Py_DECREF(float_value); - goto bad; - } - } else if (PyUnicode_CheckExact(obj) || PyBytes_CheckExact(obj)) { -#if PY_MAJOR_VERSION >= 3 - float_value = PyFloat_FromString(obj); -#else - float_value = PyFloat_FromString(obj, 0); -#endif - } else { - PyObject* args = PyTuple_New(1); - if (unlikely(!args)) goto bad; - PyTuple_SET_ITEM(args, 0, obj); - float_value = PyObject_Call((PyObject*)&PyFloat_Type, args, 0); - PyTuple_SET_ITEM(args, 0, 0); - Py_DECREF(args); - } -#endif - if (likely(float_value)) { - double value = PyFloat_AS_DOUBLE(float_value); - Py_DECREF(float_value); - return value; - } -bad: - return (double)-1; -} - - -/////////////// PyNumberPow2.proto /////////////// - -#define __Pyx_PyNumber_InPlacePowerOf2(a, b, c) __Pyx__PyNumber_PowerOf2(a, b, c, 1) -#define __Pyx_PyNumber_PowerOf2(a, b, c) __Pyx__PyNumber_PowerOf2(a, b, c, 0) - -static PyObject* __Pyx__PyNumber_PowerOf2(PyObject *two, PyObject *exp, PyObject *none, int inplace); /*proto*/ - -/////////////// PyNumberPow2 /////////////// - -static PyObject* __Pyx__PyNumber_PowerOf2(PyObject *two, PyObject *exp, PyObject *none, int inplace) { -// in CPython, 1<<N is substantially faster than 2**N -// see http://bugs.python.org/issue21420 +#else + PyNumberMethods *nb = Py_TYPE(obj)->tp_as_number; + if (likely(nb) && likely(nb->nb_float)) { + float_value = nb->nb_float(obj); + if (likely(float_value) && unlikely(!PyFloat_Check(float_value))) { + PyErr_Format(PyExc_TypeError, + "__float__ returned non-float (type %.200s)", + Py_TYPE(float_value)->tp_name); + Py_DECREF(float_value); + goto bad; + } + } else if (PyUnicode_CheckExact(obj) || PyBytes_CheckExact(obj)) { +#if PY_MAJOR_VERSION >= 3 + float_value = PyFloat_FromString(obj); +#else + float_value = PyFloat_FromString(obj, 0); +#endif + } else { + PyObject* args = PyTuple_New(1); + if (unlikely(!args)) goto bad; + PyTuple_SET_ITEM(args, 0, obj); + float_value = PyObject_Call((PyObject*)&PyFloat_Type, args, 0); + PyTuple_SET_ITEM(args, 0, 0); + Py_DECREF(args); + } +#endif + if (likely(float_value)) { + double value = PyFloat_AS_DOUBLE(float_value); + Py_DECREF(float_value); + return value; + } +bad: + return (double)-1; +} + + +/////////////// PyNumberPow2.proto /////////////// + +#define __Pyx_PyNumber_InPlacePowerOf2(a, b, c) __Pyx__PyNumber_PowerOf2(a, b, c, 1) +#define __Pyx_PyNumber_PowerOf2(a, b, c) __Pyx__PyNumber_PowerOf2(a, b, c, 0) + +static PyObject* __Pyx__PyNumber_PowerOf2(PyObject *two, PyObject *exp, PyObject *none, int inplace); /*proto*/ + +/////////////// PyNumberPow2 /////////////// + +static PyObject* __Pyx__PyNumber_PowerOf2(PyObject *two, PyObject *exp, PyObject *none, int inplace) { +// in CPython, 1<<N is substantially faster than 2**N +// see http://bugs.python.org/issue21420 #if !CYTHON_COMPILING_IN_PYPY - Py_ssize_t shiftby; + Py_ssize_t shiftby; #if PY_MAJOR_VERSION < 3 if (likely(PyInt_CheckExact(exp))) { shiftby = PyInt_AS_LONG(exp); } else #endif - if (likely(PyLong_CheckExact(exp))) { + if (likely(PyLong_CheckExact(exp))) { #if CYTHON_USE_PYLONG_INTERNALS const Py_ssize_t size = Py_SIZE(exp); // tuned to optimise branch prediction @@ -668,36 +668,36 @@ static PyObject* __Pyx__PyNumber_PowerOf2(PyObject *two, PyObject *exp, PyObject goto fallback; } else { shiftby = PyLong_AsSsize_t(exp); - } - #else - shiftby = PyLong_AsSsize_t(exp); - #endif - } else { - goto fallback; - } - if (likely(shiftby >= 0)) { - if ((size_t)shiftby <= sizeof(long) * 8 - 2) { - long value = 1L << shiftby; - return PyInt_FromLong(value); + } + #else + shiftby = PyLong_AsSsize_t(exp); + #endif + } else { + goto fallback; + } + if (likely(shiftby >= 0)) { + if ((size_t)shiftby <= sizeof(long) * 8 - 2) { + long value = 1L << shiftby; + return PyInt_FromLong(value); #ifdef HAVE_LONG_LONG } else if ((size_t)shiftby <= sizeof(unsigned PY_LONG_LONG) * 8 - 1) { unsigned PY_LONG_LONG value = ((unsigned PY_LONG_LONG)1) << shiftby; return PyLong_FromUnsignedLongLong(value); #endif - } else { + } else { PyObject *result, *one = PyInt_FromLong(1L); - if (unlikely(!one)) return NULL; + if (unlikely(!one)) return NULL; result = PyNumber_Lshift(one, exp); Py_DECREF(one); return result; - } - } else if (shiftby == -1 && PyErr_Occurred()) { - PyErr_Clear(); - } -fallback: -#endif - return (inplace ? PyNumber_InPlacePower : PyNumber_Power)(two, exp, none); -} + } + } else if (shiftby == -1 && PyErr_Occurred()) { + PyErr_Clear(); + } +fallback: +#endif + return (inplace ? PyNumber_InPlacePower : PyNumber_Power)(two, exp, none); +} /////////////// PyIntCompare.proto /////////////// diff --git a/contrib/tools/cython/Cython/Utility/Overflow.c b/contrib/tools/cython/Cython/Utility/Overflow.c index 0259c58f01..5fd3aa55da 100644 --- a/contrib/tools/cython/Cython/Utility/Overflow.c +++ b/contrib/tools/cython/Cython/Utility/Overflow.c @@ -1,269 +1,269 @@ -/* -These functions provide integer arithmetic with integer checking. They do not -actually raise an exception when an overflow is detected, but rather set a bit +/* +These functions provide integer arithmetic with integer checking. They do not +actually raise an exception when an overflow is detected, but rather set a bit in the overflow parameter. (This parameter may be re-used across several -arithmetic operations, so should be or-ed rather than assigned to.) - -The implementation is divided into two parts, the signed and unsigned basecases, -which is where the magic happens, and a generic template matching a specific -type to an implementation based on its (c-compile-time) size and signedness. - -When possible, branching is avoided, and preference is given to speed over -accuracy (a low rate of falsely "detected" overflows are acceptable, -undetected overflows are not). - - -TODO: Hook up checking. -TODO: Conditionally support 128-bit with intmax_t? -*/ - -/////////////// Common.proto /////////////// - -static int __Pyx_check_twos_complement(void) { +arithmetic operations, so should be or-ed rather than assigned to.) + +The implementation is divided into two parts, the signed and unsigned basecases, +which is where the magic happens, and a generic template matching a specific +type to an implementation based on its (c-compile-time) size and signedness. + +When possible, branching is avoided, and preference is given to speed over +accuracy (a low rate of falsely "detected" overflows are acceptable, +undetected overflows are not). + + +TODO: Hook up checking. +TODO: Conditionally support 128-bit with intmax_t? +*/ + +/////////////// Common.proto /////////////// + +static int __Pyx_check_twos_complement(void) { if ((-1 != ~0)) { - PyErr_SetString(PyExc_RuntimeError, "Two's complement required for overflow checks."); - return 1; + PyErr_SetString(PyExc_RuntimeError, "Two's complement required for overflow checks."); + return 1; } else if ((sizeof(short) == sizeof(int))) { - PyErr_SetString(PyExc_RuntimeError, "sizeof(short) < sizeof(int) required for overflow checks."); - return 1; - } else { - return 0; - } -} - + PyErr_SetString(PyExc_RuntimeError, "sizeof(short) < sizeof(int) required for overflow checks."); + return 1; + } else { + return 0; + } +} + #define __PYX_IS_UNSIGNED(type) ((((type) -1) > 0)) #define __PYX_SIGN_BIT(type) ((((unsigned type) 1) << (sizeof(type) * 8 - 1))) #define __PYX_HALF_MAX(type) ((((type) 1) << (sizeof(type) * 8 - 2))) #define __PYX_MIN(type) ((__PYX_IS_UNSIGNED(type) ? (type) 0 : 0 - __PYX_HALF_MAX(type) - __PYX_HALF_MAX(type))) #define __PYX_MAX(type) ((~__PYX_MIN(type))) - -#define __Pyx_add_no_overflow(a, b, overflow) ((a) + (b)) -#define __Pyx_add_const_no_overflow(a, b, overflow) ((a) + (b)) -#define __Pyx_sub_no_overflow(a, b, overflow) ((a) - (b)) -#define __Pyx_sub_const_no_overflow(a, b, overflow) ((a) - (b)) -#define __Pyx_mul_no_overflow(a, b, overflow) ((a) * (b)) -#define __Pyx_mul_const_no_overflow(a, b, overflow) ((a) * (b)) -#define __Pyx_div_no_overflow(a, b, overflow) ((a) / (b)) -#define __Pyx_div_const_no_overflow(a, b, overflow) ((a) / (b)) - -/////////////// Common.init /////////////// + +#define __Pyx_add_no_overflow(a, b, overflow) ((a) + (b)) +#define __Pyx_add_const_no_overflow(a, b, overflow) ((a) + (b)) +#define __Pyx_sub_no_overflow(a, b, overflow) ((a) - (b)) +#define __Pyx_sub_const_no_overflow(a, b, overflow) ((a) - (b)) +#define __Pyx_mul_no_overflow(a, b, overflow) ((a) * (b)) +#define __Pyx_mul_const_no_overflow(a, b, overflow) ((a) * (b)) +#define __Pyx_div_no_overflow(a, b, overflow) ((a) / (b)) +#define __Pyx_div_const_no_overflow(a, b, overflow) ((a) / (b)) + +/////////////// Common.init /////////////// //@substitute: naming - + // FIXME: Propagate the error here instead of just printing it. if (unlikely(__Pyx_check_twos_complement())) { PyErr_WriteUnraisable($module_cname); } - -/////////////// BaseCaseUnsigned.proto /////////////// - -static CYTHON_INLINE {{UINT}} __Pyx_add_{{NAME}}_checking_overflow({{UINT}} a, {{UINT}} b, int *overflow); -static CYTHON_INLINE {{UINT}} __Pyx_sub_{{NAME}}_checking_overflow({{UINT}} a, {{UINT}} b, int *overflow); -static CYTHON_INLINE {{UINT}} __Pyx_mul_{{NAME}}_checking_overflow({{UINT}} a, {{UINT}} b, int *overflow); -static CYTHON_INLINE {{UINT}} __Pyx_div_{{NAME}}_checking_overflow({{UINT}} a, {{UINT}} b, int *overflow); - -// Use these when b is known at compile time. -#define __Pyx_add_const_{{NAME}}_checking_overflow __Pyx_add_{{NAME}}_checking_overflow -#define __Pyx_sub_const_{{NAME}}_checking_overflow __Pyx_sub_{{NAME}}_checking_overflow -static CYTHON_INLINE {{UINT}} __Pyx_mul_const_{{NAME}}_checking_overflow({{UINT}} a, {{UINT}} constant, int *overflow); -#define __Pyx_div_const_{{NAME}}_checking_overflow __Pyx_div_{{NAME}}_checking_overflow - -/////////////// BaseCaseUnsigned /////////////// - -static CYTHON_INLINE {{UINT}} __Pyx_add_{{NAME}}_checking_overflow({{UINT}} a, {{UINT}} b, int *overflow) { - {{UINT}} r = a + b; - *overflow |= r < a; - return r; -} - -static CYTHON_INLINE {{UINT}} __Pyx_sub_{{NAME}}_checking_overflow({{UINT}} a, {{UINT}} b, int *overflow) { - {{UINT}} r = a - b; - *overflow |= r > a; - return r; -} - -static CYTHON_INLINE {{UINT}} __Pyx_mul_{{NAME}}_checking_overflow({{UINT}} a, {{UINT}} b, int *overflow) { + +/////////////// BaseCaseUnsigned.proto /////////////// + +static CYTHON_INLINE {{UINT}} __Pyx_add_{{NAME}}_checking_overflow({{UINT}} a, {{UINT}} b, int *overflow); +static CYTHON_INLINE {{UINT}} __Pyx_sub_{{NAME}}_checking_overflow({{UINT}} a, {{UINT}} b, int *overflow); +static CYTHON_INLINE {{UINT}} __Pyx_mul_{{NAME}}_checking_overflow({{UINT}} a, {{UINT}} b, int *overflow); +static CYTHON_INLINE {{UINT}} __Pyx_div_{{NAME}}_checking_overflow({{UINT}} a, {{UINT}} b, int *overflow); + +// Use these when b is known at compile time. +#define __Pyx_add_const_{{NAME}}_checking_overflow __Pyx_add_{{NAME}}_checking_overflow +#define __Pyx_sub_const_{{NAME}}_checking_overflow __Pyx_sub_{{NAME}}_checking_overflow +static CYTHON_INLINE {{UINT}} __Pyx_mul_const_{{NAME}}_checking_overflow({{UINT}} a, {{UINT}} constant, int *overflow); +#define __Pyx_div_const_{{NAME}}_checking_overflow __Pyx_div_{{NAME}}_checking_overflow + +/////////////// BaseCaseUnsigned /////////////// + +static CYTHON_INLINE {{UINT}} __Pyx_add_{{NAME}}_checking_overflow({{UINT}} a, {{UINT}} b, int *overflow) { + {{UINT}} r = a + b; + *overflow |= r < a; + return r; +} + +static CYTHON_INLINE {{UINT}} __Pyx_sub_{{NAME}}_checking_overflow({{UINT}} a, {{UINT}} b, int *overflow) { + {{UINT}} r = a - b; + *overflow |= r > a; + return r; +} + +static CYTHON_INLINE {{UINT}} __Pyx_mul_{{NAME}}_checking_overflow({{UINT}} a, {{UINT}} b, int *overflow) { if ((sizeof({{UINT}}) < sizeof(unsigned long))) { - unsigned long big_r = ((unsigned long) a) * ((unsigned long) b); - {{UINT}} r = ({{UINT}}) big_r; - *overflow |= big_r != r; - return r; + unsigned long big_r = ((unsigned long) a) * ((unsigned long) b); + {{UINT}} r = ({{UINT}}) big_r; + *overflow |= big_r != r; + return r; #ifdef HAVE_LONG_LONG } else if ((sizeof({{UINT}}) < sizeof(unsigned PY_LONG_LONG))) { unsigned PY_LONG_LONG big_r = ((unsigned PY_LONG_LONG) a) * ((unsigned PY_LONG_LONG) b); - {{UINT}} r = ({{UINT}}) big_r; - *overflow |= big_r != r; - return r; + {{UINT}} r = ({{UINT}}) big_r; + *overflow |= big_r != r; + return r; #endif - } else { - {{UINT}} prod = a * b; - double dprod = ((double) a) * ((double) b); - // Overflow results in an error of at least 2^sizeof(UINT), - // whereas rounding represents an error on the order of 2^(sizeof(UINT)-53). - *overflow |= fabs(dprod - prod) > (__PYX_MAX({{UINT}}) / 2); - return prod; - } -} - -static CYTHON_INLINE {{UINT}} __Pyx_mul_const_{{NAME}}_checking_overflow({{UINT}} a, {{UINT}} b, int *overflow) { - if (b > 1) { - *overflow |= a > __PYX_MAX({{UINT}}) / b; - } - return a * b; -} - - -static CYTHON_INLINE {{UINT}} __Pyx_div_{{NAME}}_checking_overflow({{UINT}} a, {{UINT}} b, int *overflow) { - if (b == 0) { - *overflow |= 1; - return 0; - } - return a / b; -} - - -/////////////// BaseCaseSigned.proto /////////////// - -static CYTHON_INLINE {{INT}} __Pyx_add_{{NAME}}_checking_overflow({{INT}} a, {{INT}} b, int *overflow); -static CYTHON_INLINE {{INT}} __Pyx_sub_{{NAME}}_checking_overflow({{INT}} a, {{INT}} b, int *overflow); -static CYTHON_INLINE {{INT}} __Pyx_mul_{{NAME}}_checking_overflow({{INT}} a, {{INT}} b, int *overflow); -static CYTHON_INLINE {{INT}} __Pyx_div_{{NAME}}_checking_overflow({{INT}} a, {{INT}} b, int *overflow); - - -// Use when b is known at compile time. -static CYTHON_INLINE {{INT}} __Pyx_add_const_{{NAME}}_checking_overflow({{INT}} a, {{INT}} b, int *overflow); -static CYTHON_INLINE {{INT}} __Pyx_sub_const_{{NAME}}_checking_overflow({{INT}} a, {{INT}} b, int *overflow); -static CYTHON_INLINE {{INT}} __Pyx_mul_const_{{NAME}}_checking_overflow({{INT}} a, {{INT}} constant, int *overflow); -#define __Pyx_div_const_{{NAME}}_checking_overflow __Pyx_div_{{NAME}}_checking_overflow - -/////////////// BaseCaseSigned /////////////// - -static CYTHON_INLINE {{INT}} __Pyx_add_{{NAME}}_checking_overflow({{INT}} a, {{INT}} b, int *overflow) { + } else { + {{UINT}} prod = a * b; + double dprod = ((double) a) * ((double) b); + // Overflow results in an error of at least 2^sizeof(UINT), + // whereas rounding represents an error on the order of 2^(sizeof(UINT)-53). + *overflow |= fabs(dprod - prod) > (__PYX_MAX({{UINT}}) / 2); + return prod; + } +} + +static CYTHON_INLINE {{UINT}} __Pyx_mul_const_{{NAME}}_checking_overflow({{UINT}} a, {{UINT}} b, int *overflow) { + if (b > 1) { + *overflow |= a > __PYX_MAX({{UINT}}) / b; + } + return a * b; +} + + +static CYTHON_INLINE {{UINT}} __Pyx_div_{{NAME}}_checking_overflow({{UINT}} a, {{UINT}} b, int *overflow) { + if (b == 0) { + *overflow |= 1; + return 0; + } + return a / b; +} + + +/////////////// BaseCaseSigned.proto /////////////// + +static CYTHON_INLINE {{INT}} __Pyx_add_{{NAME}}_checking_overflow({{INT}} a, {{INT}} b, int *overflow); +static CYTHON_INLINE {{INT}} __Pyx_sub_{{NAME}}_checking_overflow({{INT}} a, {{INT}} b, int *overflow); +static CYTHON_INLINE {{INT}} __Pyx_mul_{{NAME}}_checking_overflow({{INT}} a, {{INT}} b, int *overflow); +static CYTHON_INLINE {{INT}} __Pyx_div_{{NAME}}_checking_overflow({{INT}} a, {{INT}} b, int *overflow); + + +// Use when b is known at compile time. +static CYTHON_INLINE {{INT}} __Pyx_add_const_{{NAME}}_checking_overflow({{INT}} a, {{INT}} b, int *overflow); +static CYTHON_INLINE {{INT}} __Pyx_sub_const_{{NAME}}_checking_overflow({{INT}} a, {{INT}} b, int *overflow); +static CYTHON_INLINE {{INT}} __Pyx_mul_const_{{NAME}}_checking_overflow({{INT}} a, {{INT}} constant, int *overflow); +#define __Pyx_div_const_{{NAME}}_checking_overflow __Pyx_div_{{NAME}}_checking_overflow + +/////////////// BaseCaseSigned /////////////// + +static CYTHON_INLINE {{INT}} __Pyx_add_{{NAME}}_checking_overflow({{INT}} a, {{INT}} b, int *overflow) { if ((sizeof({{INT}}) < sizeof(long))) { - long big_r = ((long) a) + ((long) b); - {{INT}} r = ({{INT}}) big_r; - *overflow |= big_r != r; - return r; + long big_r = ((long) a) + ((long) b); + {{INT}} r = ({{INT}}) big_r; + *overflow |= big_r != r; + return r; #ifdef HAVE_LONG_LONG } else if ((sizeof({{INT}}) < sizeof(PY_LONG_LONG))) { PY_LONG_LONG big_r = ((PY_LONG_LONG) a) + ((PY_LONG_LONG) b); - {{INT}} r = ({{INT}}) big_r; - *overflow |= big_r != r; - return r; + {{INT}} r = ({{INT}}) big_r; + *overflow |= big_r != r; + return r; #endif - } else { - // Signed overflow undefined, but unsigned overflow is well defined. - {{INT}} r = ({{INT}}) ((unsigned {{INT}}) a + (unsigned {{INT}}) b); - // Overflow happened if the operands have the same sign, but the result - // has opposite sign. - // sign(a) == sign(b) != sign(r) - {{INT}} sign_a = __PYX_SIGN_BIT({{INT}}) & a; - {{INT}} sign_b = __PYX_SIGN_BIT({{INT}}) & b; - {{INT}} sign_r = __PYX_SIGN_BIT({{INT}}) & r; - *overflow |= (sign_a == sign_b) & (sign_a != sign_r); - return r; - } -} - -static CYTHON_INLINE {{INT}} __Pyx_add_const_{{NAME}}_checking_overflow({{INT}} a, {{INT}} b, int *overflow) { - if (b > 0) { - *overflow |= a > __PYX_MAX({{INT}}) - b; - } else if (b < 0) { - *overflow |= a < __PYX_MIN({{INT}}) - b; - } - return a + b; -} - -static CYTHON_INLINE {{INT}} __Pyx_sub_{{NAME}}_checking_overflow({{INT}} a, {{INT}} b, int *overflow) { - *overflow |= b == __PYX_MIN({{INT}}); - return __Pyx_add_{{NAME}}_checking_overflow(a, -b, overflow); -} - -static CYTHON_INLINE {{INT}} __Pyx_sub_const_{{NAME}}_checking_overflow({{INT}} a, {{INT}} b, int *overflow) { - *overflow |= b == __PYX_MIN({{INT}}); - return __Pyx_add_const_{{NAME}}_checking_overflow(a, -b, overflow); -} - -static CYTHON_INLINE {{INT}} __Pyx_mul_{{NAME}}_checking_overflow({{INT}} a, {{INT}} b, int *overflow) { + } else { + // Signed overflow undefined, but unsigned overflow is well defined. + {{INT}} r = ({{INT}}) ((unsigned {{INT}}) a + (unsigned {{INT}}) b); + // Overflow happened if the operands have the same sign, but the result + // has opposite sign. + // sign(a) == sign(b) != sign(r) + {{INT}} sign_a = __PYX_SIGN_BIT({{INT}}) & a; + {{INT}} sign_b = __PYX_SIGN_BIT({{INT}}) & b; + {{INT}} sign_r = __PYX_SIGN_BIT({{INT}}) & r; + *overflow |= (sign_a == sign_b) & (sign_a != sign_r); + return r; + } +} + +static CYTHON_INLINE {{INT}} __Pyx_add_const_{{NAME}}_checking_overflow({{INT}} a, {{INT}} b, int *overflow) { + if (b > 0) { + *overflow |= a > __PYX_MAX({{INT}}) - b; + } else if (b < 0) { + *overflow |= a < __PYX_MIN({{INT}}) - b; + } + return a + b; +} + +static CYTHON_INLINE {{INT}} __Pyx_sub_{{NAME}}_checking_overflow({{INT}} a, {{INT}} b, int *overflow) { + *overflow |= b == __PYX_MIN({{INT}}); + return __Pyx_add_{{NAME}}_checking_overflow(a, -b, overflow); +} + +static CYTHON_INLINE {{INT}} __Pyx_sub_const_{{NAME}}_checking_overflow({{INT}} a, {{INT}} b, int *overflow) { + *overflow |= b == __PYX_MIN({{INT}}); + return __Pyx_add_const_{{NAME}}_checking_overflow(a, -b, overflow); +} + +static CYTHON_INLINE {{INT}} __Pyx_mul_{{NAME}}_checking_overflow({{INT}} a, {{INT}} b, int *overflow) { if ((sizeof({{INT}}) < sizeof(long))) { - long big_r = ((long) a) * ((long) b); - {{INT}} r = ({{INT}}) big_r; - *overflow |= big_r != r; - return ({{INT}}) r; + long big_r = ((long) a) * ((long) b); + {{INT}} r = ({{INT}}) big_r; + *overflow |= big_r != r; + return ({{INT}}) r; #ifdef HAVE_LONG_LONG } else if ((sizeof({{INT}}) < sizeof(PY_LONG_LONG))) { PY_LONG_LONG big_r = ((PY_LONG_LONG) a) * ((PY_LONG_LONG) b); - {{INT}} r = ({{INT}}) big_r; - *overflow |= big_r != r; - return ({{INT}}) r; + {{INT}} r = ({{INT}}) big_r; + *overflow |= big_r != r; + return ({{INT}}) r; #endif - } else { - {{INT}} prod = a * b; - double dprod = ((double) a) * ((double) b); - // Overflow results in an error of at least 2^sizeof(INT), - // whereas rounding represents an error on the order of 2^(sizeof(INT)-53). - *overflow |= fabs(dprod - prod) > (__PYX_MAX({{INT}}) / 2); - return prod; - } -} - -static CYTHON_INLINE {{INT}} __Pyx_mul_const_{{NAME}}_checking_overflow({{INT}} a, {{INT}} b, int *overflow) { - if (b > 1) { - *overflow |= a > __PYX_MAX({{INT}}) / b; - *overflow |= a < __PYX_MIN({{INT}}) / b; - } else if (b == -1) { - *overflow |= a == __PYX_MIN({{INT}}); - } else if (b < -1) { - *overflow |= a > __PYX_MIN({{INT}}) / b; - *overflow |= a < __PYX_MAX({{INT}}) / b; - } - return a * b; -} - -static CYTHON_INLINE {{INT}} __Pyx_div_{{NAME}}_checking_overflow({{INT}} a, {{INT}} b, int *overflow) { - if (b == 0) { - *overflow |= 1; - return 0; - } - *overflow |= (a == __PYX_MIN({{INT}})) & (b == -1); - return a / b; -} - - -/////////////// SizeCheck.init /////////////// + } else { + {{INT}} prod = a * b; + double dprod = ((double) a) * ((double) b); + // Overflow results in an error of at least 2^sizeof(INT), + // whereas rounding represents an error on the order of 2^(sizeof(INT)-53). + *overflow |= fabs(dprod - prod) > (__PYX_MAX({{INT}}) / 2); + return prod; + } +} + +static CYTHON_INLINE {{INT}} __Pyx_mul_const_{{NAME}}_checking_overflow({{INT}} a, {{INT}} b, int *overflow) { + if (b > 1) { + *overflow |= a > __PYX_MAX({{INT}}) / b; + *overflow |= a < __PYX_MIN({{INT}}) / b; + } else if (b == -1) { + *overflow |= a == __PYX_MIN({{INT}}); + } else if (b < -1) { + *overflow |= a > __PYX_MIN({{INT}}) / b; + *overflow |= a < __PYX_MAX({{INT}}) / b; + } + return a * b; +} + +static CYTHON_INLINE {{INT}} __Pyx_div_{{NAME}}_checking_overflow({{INT}} a, {{INT}} b, int *overflow) { + if (b == 0) { + *overflow |= 1; + return 0; + } + *overflow |= (a == __PYX_MIN({{INT}})) & (b == -1); + return a / b; +} + + +/////////////// SizeCheck.init /////////////// //@substitute: naming - + // FIXME: Propagate the error here instead of just printing it. if (unlikely(__Pyx_check_sane_{{NAME}}())) { PyErr_WriteUnraisable($module_cname); } - -/////////////// SizeCheck.proto /////////////// - -static int __Pyx_check_sane_{{NAME}}(void) { + +/////////////// SizeCheck.proto /////////////// + +static int __Pyx_check_sane_{{NAME}}(void) { if (((sizeof({{TYPE}}) <= sizeof(int)) || #ifdef HAVE_LONG_LONG (sizeof({{TYPE}}) == sizeof(PY_LONG_LONG)) || #endif (sizeof({{TYPE}}) == sizeof(long)))) { - return 0; - } else { - PyErr_Format(PyExc_RuntimeError, \ - "Bad size for int type %.{{max(60, len(TYPE))}}s: %d", "{{TYPE}}", (int) sizeof({{TYPE}})); - return 1; - } -} - - -/////////////// Binop.proto /////////////// - -static CYTHON_INLINE {{TYPE}} __Pyx_{{BINOP}}_{{NAME}}_checking_overflow({{TYPE}} a, {{TYPE}} b, int *overflow); - -/////////////// Binop /////////////// - -static CYTHON_INLINE {{TYPE}} __Pyx_{{BINOP}}_{{NAME}}_checking_overflow({{TYPE}} a, {{TYPE}} b, int *overflow) { + return 0; + } else { + PyErr_Format(PyExc_RuntimeError, \ + "Bad size for int type %.{{max(60, len(TYPE))}}s: %d", "{{TYPE}}", (int) sizeof({{TYPE}})); + return 1; + } +} + + +/////////////// Binop.proto /////////////// + +static CYTHON_INLINE {{TYPE}} __Pyx_{{BINOP}}_{{NAME}}_checking_overflow({{TYPE}} a, {{TYPE}} b, int *overflow); + +/////////////// Binop /////////////// + +static CYTHON_INLINE {{TYPE}} __Pyx_{{BINOP}}_{{NAME}}_checking_overflow({{TYPE}} a, {{TYPE}} b, int *overflow) { if ((sizeof({{TYPE}}) < sizeof(int))) { - return __Pyx_{{BINOP}}_no_overflow(a, b, overflow); - } else if (__PYX_IS_UNSIGNED({{TYPE}})) { + return __Pyx_{{BINOP}}_no_overflow(a, b, overflow); + } else if (__PYX_IS_UNSIGNED({{TYPE}})) { if ((sizeof({{TYPE}}) == sizeof(unsigned int))) { return ({{TYPE}}) __Pyx_{{BINOP}}_unsigned_int_checking_overflow(a, b, overflow); } else if ((sizeof({{TYPE}}) == sizeof(unsigned long))) { @@ -272,10 +272,10 @@ static CYTHON_INLINE {{TYPE}} __Pyx_{{BINOP}}_{{NAME}}_checking_overflow({{TYPE} } else if ((sizeof({{TYPE}}) == sizeof(unsigned PY_LONG_LONG))) { return ({{TYPE}}) __Pyx_{{BINOP}}_unsigned_long_long_checking_overflow(a, b, overflow); #endif - } else { + } else { abort(); return 0; /* handled elsewhere */ - } - } else { + } + } else { if ((sizeof({{TYPE}}) == sizeof(int))) { return ({{TYPE}}) __Pyx_{{BINOP}}_int_checking_overflow(a, b, overflow); } else if ((sizeof({{TYPE}}) == sizeof(long))) { @@ -284,24 +284,24 @@ static CYTHON_INLINE {{TYPE}} __Pyx_{{BINOP}}_{{NAME}}_checking_overflow({{TYPE} } else if ((sizeof({{TYPE}}) == sizeof(PY_LONG_LONG))) { return ({{TYPE}}) __Pyx_{{BINOP}}_long_long_checking_overflow(a, b, overflow); #endif - } else { + } else { abort(); return 0; /* handled elsewhere */ - } - } -} - -/////////////// LeftShift.proto /////////////// - -static CYTHON_INLINE {{TYPE}} __Pyx_lshift_{{NAME}}_checking_overflow({{TYPE}} a, {{TYPE}} b, int *overflow) { - *overflow |= -#if {{SIGNED}} - (b < 0) | -#endif - (b > ({{TYPE}}) (8 * sizeof({{TYPE}}))) | (a > (__PYX_MAX({{TYPE}}) >> b)); - return a << b; -} -#define __Pyx_lshift_const_{{NAME}}_checking_overflow __Pyx_lshift_{{NAME}}_checking_overflow - + } + } +} + +/////////////// LeftShift.proto /////////////// + +static CYTHON_INLINE {{TYPE}} __Pyx_lshift_{{NAME}}_checking_overflow({{TYPE}} a, {{TYPE}} b, int *overflow) { + *overflow |= +#if {{SIGNED}} + (b < 0) | +#endif + (b > ({{TYPE}}) (8 * sizeof({{TYPE}}))) | (a > (__PYX_MAX({{TYPE}}) >> b)); + return a << b; +} +#define __Pyx_lshift_const_{{NAME}}_checking_overflow __Pyx_lshift_{{NAME}}_checking_overflow + /////////////// UnaryNegOverflows.proto /////////////// diff --git a/contrib/tools/cython/Cython/Utility/Printing.c b/contrib/tools/cython/Cython/Utility/Printing.c index 71aa7eafe9..40768e6aff 100644 --- a/contrib/tools/cython/Cython/Utility/Printing.c +++ b/contrib/tools/cython/Cython/Utility/Printing.c @@ -1,176 +1,176 @@ -////////////////////// Print.proto ////////////////////// -//@substitute: naming - -static int __Pyx_Print(PyObject*, PyObject *, int); /*proto*/ -#if CYTHON_COMPILING_IN_PYPY || PY_MAJOR_VERSION >= 3 -static PyObject* $print_function = 0; -static PyObject* $print_function_kwargs = 0; -#endif - -////////////////////// Print.cleanup ////////////////////// -//@substitute: naming - -#if CYTHON_COMPILING_IN_PYPY || PY_MAJOR_VERSION >= 3 -Py_CLEAR($print_function); -Py_CLEAR($print_function_kwargs); -#endif - -////////////////////// Print ////////////////////// -//@substitute: naming - -#if !CYTHON_COMPILING_IN_PYPY && PY_MAJOR_VERSION < 3 -static PyObject *__Pyx_GetStdout(void) { - PyObject *f = PySys_GetObject((char *)"stdout"); - if (!f) { - PyErr_SetString(PyExc_RuntimeError, "lost sys.stdout"); - } - return f; -} - -static int __Pyx_Print(PyObject* f, PyObject *arg_tuple, int newline) { - int i; - - if (!f) { - if (!(f = __Pyx_GetStdout())) - return -1; - } - Py_INCREF(f); - for (i=0; i < PyTuple_GET_SIZE(arg_tuple); i++) { - PyObject* v; - if (PyFile_SoftSpace(f, 1)) { - if (PyFile_WriteString(" ", f) < 0) - goto error; - } - v = PyTuple_GET_ITEM(arg_tuple, i); - if (PyFile_WriteObject(v, f, Py_PRINT_RAW) < 0) - goto error; - if (PyString_Check(v)) { - char *s = PyString_AsString(v); - Py_ssize_t len = PyString_Size(v); - if (len > 0) { - // append soft-space if necessary (not using isspace() due to C/C++ problem on MacOS-X) - switch (s[len-1]) { - case ' ': break; - case '\f': case '\r': case '\n': case '\t': case '\v': - PyFile_SoftSpace(f, 0); - break; - default: break; - } - } - } - } - if (newline) { - if (PyFile_WriteString("\n", f) < 0) - goto error; - PyFile_SoftSpace(f, 0); - } - Py_DECREF(f); - return 0; -error: - Py_DECREF(f); - return -1; -} - -#else /* Python 3 has a print function */ - -static int __Pyx_Print(PyObject* stream, PyObject *arg_tuple, int newline) { - PyObject* kwargs = 0; - PyObject* result = 0; - PyObject* end_string; - if (unlikely(!$print_function)) { - $print_function = PyObject_GetAttr($builtins_cname, PYIDENT("print")); - if (!$print_function) - return -1; - } - if (stream) { - kwargs = PyDict_New(); - if (unlikely(!kwargs)) - return -1; - if (unlikely(PyDict_SetItem(kwargs, PYIDENT("file"), stream) < 0)) - goto bad; - if (!newline) { - end_string = PyUnicode_FromStringAndSize(" ", 1); - if (unlikely(!end_string)) - goto bad; - if (PyDict_SetItem(kwargs, PYIDENT("end"), end_string) < 0) { - Py_DECREF(end_string); - goto bad; - } - Py_DECREF(end_string); - } - } else if (!newline) { - if (unlikely(!$print_function_kwargs)) { - $print_function_kwargs = PyDict_New(); - if (unlikely(!$print_function_kwargs)) - return -1; - end_string = PyUnicode_FromStringAndSize(" ", 1); - if (unlikely(!end_string)) - return -1; - if (PyDict_SetItem($print_function_kwargs, PYIDENT("end"), end_string) < 0) { - Py_DECREF(end_string); - return -1; - } - Py_DECREF(end_string); - } - kwargs = $print_function_kwargs; - } - result = PyObject_Call($print_function, arg_tuple, kwargs); - if (unlikely(kwargs) && (kwargs != $print_function_kwargs)) - Py_DECREF(kwargs); - if (!result) - return -1; - Py_DECREF(result); - return 0; -bad: - if (kwargs != $print_function_kwargs) - Py_XDECREF(kwargs); - return -1; -} -#endif - -////////////////////// PrintOne.proto ////////////////////// -//@requires: Print - -static int __Pyx_PrintOne(PyObject* stream, PyObject *o); /*proto*/ - -////////////////////// PrintOne ////////////////////// - -#if !CYTHON_COMPILING_IN_PYPY && PY_MAJOR_VERSION < 3 - -static int __Pyx_PrintOne(PyObject* f, PyObject *o) { - if (!f) { - if (!(f = __Pyx_GetStdout())) - return -1; - } - Py_INCREF(f); - if (PyFile_SoftSpace(f, 0)) { - if (PyFile_WriteString(" ", f) < 0) - goto error; - } - if (PyFile_WriteObject(o, f, Py_PRINT_RAW) < 0) - goto error; - if (PyFile_WriteString("\n", f) < 0) - goto error; - Py_DECREF(f); - return 0; -error: - Py_DECREF(f); - return -1; - /* the line below is just to avoid C compiler - * warnings about unused functions */ - return __Pyx_Print(f, NULL, 0); -} - -#else /* Python 3 has a print function */ - -static int __Pyx_PrintOne(PyObject* stream, PyObject *o) { - int res; - PyObject* arg_tuple = PyTuple_Pack(1, o); - if (unlikely(!arg_tuple)) - return -1; - res = __Pyx_Print(stream, arg_tuple, 1); - Py_DECREF(arg_tuple); - return res; -} - -#endif +////////////////////// Print.proto ////////////////////// +//@substitute: naming + +static int __Pyx_Print(PyObject*, PyObject *, int); /*proto*/ +#if CYTHON_COMPILING_IN_PYPY || PY_MAJOR_VERSION >= 3 +static PyObject* $print_function = 0; +static PyObject* $print_function_kwargs = 0; +#endif + +////////////////////// Print.cleanup ////////////////////// +//@substitute: naming + +#if CYTHON_COMPILING_IN_PYPY || PY_MAJOR_VERSION >= 3 +Py_CLEAR($print_function); +Py_CLEAR($print_function_kwargs); +#endif + +////////////////////// Print ////////////////////// +//@substitute: naming + +#if !CYTHON_COMPILING_IN_PYPY && PY_MAJOR_VERSION < 3 +static PyObject *__Pyx_GetStdout(void) { + PyObject *f = PySys_GetObject((char *)"stdout"); + if (!f) { + PyErr_SetString(PyExc_RuntimeError, "lost sys.stdout"); + } + return f; +} + +static int __Pyx_Print(PyObject* f, PyObject *arg_tuple, int newline) { + int i; + + if (!f) { + if (!(f = __Pyx_GetStdout())) + return -1; + } + Py_INCREF(f); + for (i=0; i < PyTuple_GET_SIZE(arg_tuple); i++) { + PyObject* v; + if (PyFile_SoftSpace(f, 1)) { + if (PyFile_WriteString(" ", f) < 0) + goto error; + } + v = PyTuple_GET_ITEM(arg_tuple, i); + if (PyFile_WriteObject(v, f, Py_PRINT_RAW) < 0) + goto error; + if (PyString_Check(v)) { + char *s = PyString_AsString(v); + Py_ssize_t len = PyString_Size(v); + if (len > 0) { + // append soft-space if necessary (not using isspace() due to C/C++ problem on MacOS-X) + switch (s[len-1]) { + case ' ': break; + case '\f': case '\r': case '\n': case '\t': case '\v': + PyFile_SoftSpace(f, 0); + break; + default: break; + } + } + } + } + if (newline) { + if (PyFile_WriteString("\n", f) < 0) + goto error; + PyFile_SoftSpace(f, 0); + } + Py_DECREF(f); + return 0; +error: + Py_DECREF(f); + return -1; +} + +#else /* Python 3 has a print function */ + +static int __Pyx_Print(PyObject* stream, PyObject *arg_tuple, int newline) { + PyObject* kwargs = 0; + PyObject* result = 0; + PyObject* end_string; + if (unlikely(!$print_function)) { + $print_function = PyObject_GetAttr($builtins_cname, PYIDENT("print")); + if (!$print_function) + return -1; + } + if (stream) { + kwargs = PyDict_New(); + if (unlikely(!kwargs)) + return -1; + if (unlikely(PyDict_SetItem(kwargs, PYIDENT("file"), stream) < 0)) + goto bad; + if (!newline) { + end_string = PyUnicode_FromStringAndSize(" ", 1); + if (unlikely(!end_string)) + goto bad; + if (PyDict_SetItem(kwargs, PYIDENT("end"), end_string) < 0) { + Py_DECREF(end_string); + goto bad; + } + Py_DECREF(end_string); + } + } else if (!newline) { + if (unlikely(!$print_function_kwargs)) { + $print_function_kwargs = PyDict_New(); + if (unlikely(!$print_function_kwargs)) + return -1; + end_string = PyUnicode_FromStringAndSize(" ", 1); + if (unlikely(!end_string)) + return -1; + if (PyDict_SetItem($print_function_kwargs, PYIDENT("end"), end_string) < 0) { + Py_DECREF(end_string); + return -1; + } + Py_DECREF(end_string); + } + kwargs = $print_function_kwargs; + } + result = PyObject_Call($print_function, arg_tuple, kwargs); + if (unlikely(kwargs) && (kwargs != $print_function_kwargs)) + Py_DECREF(kwargs); + if (!result) + return -1; + Py_DECREF(result); + return 0; +bad: + if (kwargs != $print_function_kwargs) + Py_XDECREF(kwargs); + return -1; +} +#endif + +////////////////////// PrintOne.proto ////////////////////// +//@requires: Print + +static int __Pyx_PrintOne(PyObject* stream, PyObject *o); /*proto*/ + +////////////////////// PrintOne ////////////////////// + +#if !CYTHON_COMPILING_IN_PYPY && PY_MAJOR_VERSION < 3 + +static int __Pyx_PrintOne(PyObject* f, PyObject *o) { + if (!f) { + if (!(f = __Pyx_GetStdout())) + return -1; + } + Py_INCREF(f); + if (PyFile_SoftSpace(f, 0)) { + if (PyFile_WriteString(" ", f) < 0) + goto error; + } + if (PyFile_WriteObject(o, f, Py_PRINT_RAW) < 0) + goto error; + if (PyFile_WriteString("\n", f) < 0) + goto error; + Py_DECREF(f); + return 0; +error: + Py_DECREF(f); + return -1; + /* the line below is just to avoid C compiler + * warnings about unused functions */ + return __Pyx_Print(f, NULL, 0); +} + +#else /* Python 3 has a print function */ + +static int __Pyx_PrintOne(PyObject* stream, PyObject *o) { + int res; + PyObject* arg_tuple = PyTuple_Pack(1, o); + if (unlikely(!arg_tuple)) + return -1; + res = __Pyx_Print(stream, arg_tuple, 1); + Py_DECREF(arg_tuple); + return res; +} + +#endif diff --git a/contrib/tools/cython/Cython/Utility/Profile.c b/contrib/tools/cython/Cython/Utility/Profile.c index 921eb67529..56c5a08e1f 100644 --- a/contrib/tools/cython/Cython/Utility/Profile.c +++ b/contrib/tools/cython/Cython/Utility/Profile.c @@ -1,18 +1,18 @@ -/////////////// Profile.proto /////////////// +/////////////// Profile.proto /////////////// //@requires: Exceptions.c::PyErrFetchRestore -//@substitute: naming - -// Note that cPython ignores PyTrace_EXCEPTION, -// but maybe some other profilers don't. - -#ifndef CYTHON_PROFILE +//@substitute: naming + +// Note that cPython ignores PyTrace_EXCEPTION, +// but maybe some other profilers don't. + +#ifndef CYTHON_PROFILE #if CYTHON_COMPILING_IN_PYPY || CYTHON_COMPILING_IN_PYSTON #define CYTHON_PROFILE 0 #else - #define CYTHON_PROFILE 1 -#endif + #define CYTHON_PROFILE 1 +#endif #endif - + #ifndef CYTHON_TRACE_NOGIL #define CYTHON_TRACE_NOGIL 0 #else @@ -21,37 +21,37 @@ #endif #endif -#ifndef CYTHON_TRACE - #define CYTHON_TRACE 0 -#endif - -#if CYTHON_TRACE - #undef CYTHON_PROFILE_REUSE_FRAME -#endif - -#ifndef CYTHON_PROFILE_REUSE_FRAME - #define CYTHON_PROFILE_REUSE_FRAME 0 -#endif - -#if CYTHON_PROFILE || CYTHON_TRACE - - #include "compile.h" - #include "frameobject.h" - #include "traceback.h" - - #if CYTHON_PROFILE_REUSE_FRAME - #define CYTHON_FRAME_MODIFIER static +#ifndef CYTHON_TRACE + #define CYTHON_TRACE 0 +#endif + +#if CYTHON_TRACE + #undef CYTHON_PROFILE_REUSE_FRAME +#endif + +#ifndef CYTHON_PROFILE_REUSE_FRAME + #define CYTHON_PROFILE_REUSE_FRAME 0 +#endif + +#if CYTHON_PROFILE || CYTHON_TRACE + + #include "compile.h" + #include "frameobject.h" + #include "traceback.h" + + #if CYTHON_PROFILE_REUSE_FRAME + #define CYTHON_FRAME_MODIFIER static #define CYTHON_FRAME_DEL(frame) - #else - #define CYTHON_FRAME_MODIFIER + #else + #define CYTHON_FRAME_MODIFIER #define CYTHON_FRAME_DEL(frame) Py_CLEAR(frame) - #endif - + #endif + #define __Pyx_TraceDeclarations \ static PyCodeObject *$frame_code_cname = NULL; \ CYTHON_FRAME_MODIFIER PyFrameObject *$frame_cname = NULL; \ int __Pyx_use_tracing = 0; - + #define __Pyx_TraceFrameInit(codeobj) \ if (codeobj) $frame_code_cname = (PyCodeObject*) codeobj; @@ -118,7 +118,7 @@ __Pyx_use_tracing = __Pyx_TraceSetupAndCall(&$frame_code_cname, &$frame_cname, tstate, funcname, srcfile, firstlineno); \ if (unlikely(__Pyx_use_tracing < 0)) goto_error; \ } \ - } + } #else #define __Pyx_TraceCall(funcname, srcfile, firstlineno, nogil, goto_error) \ { PyThreadState* tstate = PyThreadState_GET(); \ @@ -128,8 +128,8 @@ } \ } #endif - - #define __Pyx_TraceException() \ + + #define __Pyx_TraceException() \ if (likely(!__Pyx_use_tracing)); else { \ PyThreadState* tstate = __Pyx_PyThreadState_Current; \ if (__Pyx_IsTracing(tstate, 0, 1)) { \ @@ -144,9 +144,9 @@ Py_DECREF(exc_info); \ } \ __Pyx_LeaveTracing(tstate); \ - } \ - } - + } \ + } + static void __Pyx_call_return_trace_func(PyThreadState *tstate, PyFrameObject *frame, PyObject *result) { PyObject *type, *value, *traceback; __Pyx_ErrFetchInState(tstate, &type, &value, &traceback); @@ -158,8 +158,8 @@ CYTHON_FRAME_DEL(frame); __Pyx_LeaveTracing(tstate); __Pyx_ErrRestoreInState(tstate, type, value, traceback); - } - + } + #ifdef WITH_THREAD #define __Pyx_TraceReturn(result, nogil) \ if (likely(!__Pyx_use_tracing)); else { \ @@ -190,21 +190,21 @@ } #endif - static PyCodeObject *__Pyx_createFrameCodeObject(const char *funcname, const char *srcfile, int firstlineno); /*proto*/ + static PyCodeObject *__Pyx_createFrameCodeObject(const char *funcname, const char *srcfile, int firstlineno); /*proto*/ static int __Pyx_TraceSetupAndCall(PyCodeObject** code, PyFrameObject** frame, PyThreadState* tstate, const char *funcname, const char *srcfile, int firstlineno); /*proto*/ - -#else - - #define __Pyx_TraceDeclarations + +#else + + #define __Pyx_TraceDeclarations #define __Pyx_TraceFrameInit(codeobj) // mark error label as used to avoid compiler warnings #define __Pyx_TraceCall(funcname, srcfile, firstlineno, nogil, goto_error) if ((1)); else goto_error; - #define __Pyx_TraceException() + #define __Pyx_TraceException() #define __Pyx_TraceReturn(result, nogil) - -#endif /* CYTHON_PROFILE */ - -#if CYTHON_TRACE + +#endif /* CYTHON_PROFILE */ + +#if CYTHON_TRACE // see call_trace_protected() in CPython's ceval.c static int __Pyx_call_line_trace_func(PyThreadState *tstate, PyFrameObject *frame, int lineno) { int ret; @@ -264,60 +264,60 @@ // XXX https://github.com/cython/cython/issues/2274 \ if (unlikely(ret)) { fprintf(stderr, "cython: line_trace_func returned %d\n", ret); } \ } \ - } + } #endif -#else +#else // mark error label as used to avoid compiler warnings #define __Pyx_TraceLine(lineno, nogil, goto_error) if ((1)); else goto_error; -#endif - -/////////////// Profile /////////////// -//@substitute: naming - -#if CYTHON_PROFILE - -static int __Pyx_TraceSetupAndCall(PyCodeObject** code, - PyFrameObject** frame, +#endif + +/////////////// Profile /////////////// +//@substitute: naming + +#if CYTHON_PROFILE + +static int __Pyx_TraceSetupAndCall(PyCodeObject** code, + PyFrameObject** frame, PyThreadState* tstate, - const char *funcname, - const char *srcfile, - int firstlineno) { + const char *funcname, + const char *srcfile, + int firstlineno) { PyObject *type, *value, *traceback; - int retval; - if (*frame == NULL || !CYTHON_PROFILE_REUSE_FRAME) { - if (*code == NULL) { - *code = __Pyx_createFrameCodeObject(funcname, srcfile, firstlineno); - if (*code == NULL) return 0; - } - *frame = PyFrame_New( - tstate, /*PyThreadState *tstate*/ - *code, /*PyCodeObject *code*/ - $moddict_cname, /*PyObject *globals*/ - 0 /*PyObject *locals*/ - ); - if (*frame == NULL) return 0; - if (CYTHON_TRACE && (*frame)->f_trace == NULL) { - // this enables "f_lineno" lookup, at least in CPython ... - Py_INCREF(Py_None); - (*frame)->f_trace = Py_None; - } -#if PY_VERSION_HEX < 0x030400B1 - } else { - (*frame)->f_tstate = tstate; -#endif - } + int retval; + if (*frame == NULL || !CYTHON_PROFILE_REUSE_FRAME) { + if (*code == NULL) { + *code = __Pyx_createFrameCodeObject(funcname, srcfile, firstlineno); + if (*code == NULL) return 0; + } + *frame = PyFrame_New( + tstate, /*PyThreadState *tstate*/ + *code, /*PyCodeObject *code*/ + $moddict_cname, /*PyObject *globals*/ + 0 /*PyObject *locals*/ + ); + if (*frame == NULL) return 0; + if (CYTHON_TRACE && (*frame)->f_trace == NULL) { + // this enables "f_lineno" lookup, at least in CPython ... + Py_INCREF(Py_None); + (*frame)->f_trace = Py_None; + } +#if PY_VERSION_HEX < 0x030400B1 + } else { + (*frame)->f_tstate = tstate; +#endif + } __Pyx_PyFrame_SetLineNumber(*frame, firstlineno); retval = 1; __Pyx_EnterTracing(tstate); __Pyx_ErrFetchInState(tstate, &type, &value, &traceback); - #if CYTHON_TRACE - if (tstate->c_tracefunc) + #if CYTHON_TRACE + if (tstate->c_tracefunc) retval = tstate->c_tracefunc(tstate->c_traceobj, *frame, PyTrace_CALL, NULL) == 0; if (retval && tstate->c_profilefunc) - #endif - retval = tstate->c_profilefunc(tstate->c_profileobj, *frame, PyTrace_CALL, NULL) == 0; + #endif + retval = tstate->c_profilefunc(tstate->c_profileobj, *frame, PyTrace_CALL, NULL) == 0; __Pyx_LeaveTracing(tstate); if (retval) { @@ -329,9 +329,9 @@ static int __Pyx_TraceSetupAndCall(PyCodeObject** code, Py_XDECREF(traceback); return -1; } -} - -static PyCodeObject *__Pyx_createFrameCodeObject(const char *funcname, const char *srcfile, int firstlineno) { +} + +static PyCodeObject *__Pyx_createFrameCodeObject(const char *funcname, const char *srcfile, int firstlineno) { PyCodeObject *py_code = 0; #if PY_MAJOR_VERSION >= 3 @@ -341,38 +341,38 @@ static PyCodeObject *__Pyx_createFrameCodeObject(const char *funcname, const cha py_code->co_flags |= CO_OPTIMIZED | CO_NEWLOCALS; } #else - PyObject *py_srcfile = 0; - PyObject *py_funcname = 0; - - py_funcname = PyString_FromString(funcname); + PyObject *py_srcfile = 0; + PyObject *py_funcname = 0; + + py_funcname = PyString_FromString(funcname); if (unlikely(!py_funcname)) goto bad; - py_srcfile = PyString_FromString(srcfile); + py_srcfile = PyString_FromString(srcfile); if (unlikely(!py_srcfile)) goto bad; - - py_code = PyCode_New( - 0, /*int argcount,*/ - 0, /*int nlocals,*/ - 0, /*int stacksize,*/ + + py_code = PyCode_New( + 0, /*int argcount,*/ + 0, /*int nlocals,*/ + 0, /*int stacksize,*/ // make CPython use a fresh dict for "f_locals" at need (see GH #1836) CO_OPTIMIZED | CO_NEWLOCALS, /*int flags,*/ - $empty_bytes, /*PyObject *code,*/ - $empty_tuple, /*PyObject *consts,*/ - $empty_tuple, /*PyObject *names,*/ - $empty_tuple, /*PyObject *varnames,*/ - $empty_tuple, /*PyObject *freevars,*/ - $empty_tuple, /*PyObject *cellvars,*/ - py_srcfile, /*PyObject *filename,*/ - py_funcname, /*PyObject *name,*/ - firstlineno, /*int firstlineno,*/ - $empty_bytes /*PyObject *lnotab*/ - ); - -bad: - Py_XDECREF(py_srcfile); - Py_XDECREF(py_funcname); + $empty_bytes, /*PyObject *code,*/ + $empty_tuple, /*PyObject *consts,*/ + $empty_tuple, /*PyObject *names,*/ + $empty_tuple, /*PyObject *varnames,*/ + $empty_tuple, /*PyObject *freevars,*/ + $empty_tuple, /*PyObject *cellvars,*/ + py_srcfile, /*PyObject *filename,*/ + py_funcname, /*PyObject *name,*/ + firstlineno, /*int firstlineno,*/ + $empty_bytes /*PyObject *lnotab*/ + ); + +bad: + Py_XDECREF(py_srcfile); + Py_XDECREF(py_funcname); #endif - - return py_code; -} - -#endif /* CYTHON_PROFILE */ + + return py_code; +} + +#endif /* CYTHON_PROFILE */ diff --git a/contrib/tools/cython/Cython/Utility/StringTools.c b/contrib/tools/cython/Cython/Utility/StringTools.c index 2fdae812a0..c60333c2a3 100644 --- a/contrib/tools/cython/Cython/Utility/StringTools.c +++ b/contrib/tools/cython/Cython/Utility/StringTools.c @@ -1,71 +1,71 @@ - -//////////////////// IncludeStringH.proto //////////////////// - -#include <string.h> - -//////////////////// IncludeCppStringH.proto //////////////////// - -#include <string> - -//////////////////// InitStrings.proto //////////////////// - -static int __Pyx_InitStrings(__Pyx_StringTabEntry *t); /*proto*/ - -//////////////////// InitStrings //////////////////// - -static int __Pyx_InitStrings(__Pyx_StringTabEntry *t) { - while (t->p) { - #if PY_MAJOR_VERSION < 3 - if (t->is_unicode) { - *t->p = PyUnicode_DecodeUTF8(t->s, t->n - 1, NULL); - } else if (t->intern) { - *t->p = PyString_InternFromString(t->s); - } else { - *t->p = PyString_FromStringAndSize(t->s, t->n - 1); - } - #else /* Python 3+ has unicode identifiers */ - if (t->is_unicode | t->is_str) { - if (t->intern) { - *t->p = PyUnicode_InternFromString(t->s); - } else if (t->encoding) { - *t->p = PyUnicode_Decode(t->s, t->n - 1, t->encoding, NULL); - } else { - *t->p = PyUnicode_FromStringAndSize(t->s, t->n - 1); - } - } else { - *t->p = PyBytes_FromStringAndSize(t->s, t->n - 1); - } - #endif - if (!*t->p) - return -1; + +//////////////////// IncludeStringH.proto //////////////////// + +#include <string.h> + +//////////////////// IncludeCppStringH.proto //////////////////// + +#include <string> + +//////////////////// InitStrings.proto //////////////////// + +static int __Pyx_InitStrings(__Pyx_StringTabEntry *t); /*proto*/ + +//////////////////// InitStrings //////////////////// + +static int __Pyx_InitStrings(__Pyx_StringTabEntry *t) { + while (t->p) { + #if PY_MAJOR_VERSION < 3 + if (t->is_unicode) { + *t->p = PyUnicode_DecodeUTF8(t->s, t->n - 1, NULL); + } else if (t->intern) { + *t->p = PyString_InternFromString(t->s); + } else { + *t->p = PyString_FromStringAndSize(t->s, t->n - 1); + } + #else /* Python 3+ has unicode identifiers */ + if (t->is_unicode | t->is_str) { + if (t->intern) { + *t->p = PyUnicode_InternFromString(t->s); + } else if (t->encoding) { + *t->p = PyUnicode_Decode(t->s, t->n - 1, t->encoding, NULL); + } else { + *t->p = PyUnicode_FromStringAndSize(t->s, t->n - 1); + } + } else { + *t->p = PyBytes_FromStringAndSize(t->s, t->n - 1); + } + #endif + if (!*t->p) + return -1; // initialise cached hash value if (PyObject_Hash(*t->p) == -1) return -1; - ++t; - } - return 0; -} - -//////////////////// BytesContains.proto //////////////////// - -static CYTHON_INLINE int __Pyx_BytesContains(PyObject* bytes, char character); /*proto*/ - -//////////////////// BytesContains //////////////////// + ++t; + } + return 0; +} + +//////////////////// BytesContains.proto //////////////////// + +static CYTHON_INLINE int __Pyx_BytesContains(PyObject* bytes, char character); /*proto*/ + +//////////////////// BytesContains //////////////////// //@requires: IncludeStringH - -static CYTHON_INLINE int __Pyx_BytesContains(PyObject* bytes, char character) { - const Py_ssize_t length = PyBytes_GET_SIZE(bytes); - char* char_start = PyBytes_AS_STRING(bytes); + +static CYTHON_INLINE int __Pyx_BytesContains(PyObject* bytes, char character) { + const Py_ssize_t length = PyBytes_GET_SIZE(bytes); + char* char_start = PyBytes_AS_STRING(bytes); return memchr(char_start, (unsigned char)character, (size_t)length) != NULL; -} - - -//////////////////// PyUCS4InUnicode.proto //////////////////// - -static CYTHON_INLINE int __Pyx_UnicodeContainsUCS4(PyObject* unicode, Py_UCS4 character); /*proto*/ - -//////////////////// PyUCS4InUnicode //////////////////// - +} + + +//////////////////// PyUCS4InUnicode.proto //////////////////// + +static CYTHON_INLINE int __Pyx_UnicodeContainsUCS4(PyObject* unicode, Py_UCS4 character); /*proto*/ + +//////////////////// PyUCS4InUnicode //////////////////// + #if PY_VERSION_HEX < 0x03090000 || (defined(PyUnicode_WCHAR_KIND) && defined(PyUnicode_AS_UNICODE)) #if PY_VERSION_HEX < 0x03090000 @@ -103,26 +103,26 @@ static int __Pyx_PyUnicodeBufferContainsUCS4_BMP(Py_UNICODE* buffer, Py_ssize_t } #endif -static CYTHON_INLINE int __Pyx_UnicodeContainsUCS4(PyObject* unicode, Py_UCS4 character) { -#if CYTHON_PEP393_ENABLED - const int kind = PyUnicode_KIND(unicode); +static CYTHON_INLINE int __Pyx_UnicodeContainsUCS4(PyObject* unicode, Py_UCS4 character) { +#if CYTHON_PEP393_ENABLED + const int kind = PyUnicode_KIND(unicode); #ifdef PyUnicode_WCHAR_KIND if (likely(kind != PyUnicode_WCHAR_KIND)) #endif { - Py_ssize_t i; - const void* udata = PyUnicode_DATA(unicode); - const Py_ssize_t length = PyUnicode_GET_LENGTH(unicode); - for (i=0; i < length; i++) { - if (unlikely(character == PyUnicode_READ(kind, udata, i))) return 1; - } - return 0; - } + Py_ssize_t i; + const void* udata = PyUnicode_DATA(unicode); + const Py_ssize_t length = PyUnicode_GET_LENGTH(unicode); + for (i=0; i < length; i++) { + if (unlikely(character == PyUnicode_READ(kind, udata, i))) return 1; + } + return 0; + } #elif PY_VERSION_HEX >= 0x03090000 #error Cannot use "UChar in Unicode" in Python 3.9 without PEP-393 unicode strings. #elif !defined(PyUnicode_AS_UNICODE) #error Cannot use "UChar in Unicode" in Python < 3.9 without Py_UNICODE support. -#endif +#endif #if PY_VERSION_HEX < 0x03090000 || (defined(PyUnicode_WCHAR_KIND) && defined(PyUnicode_AS_UNICODE)) #if !defined(Py_UNICODE_SIZE) || Py_UNICODE_SIZE == 2 @@ -138,20 +138,20 @@ static CYTHON_INLINE int __Pyx_UnicodeContainsUCS4(PyObject* unicode, Py_UCS4 ch __Pyx_PyUnicode_AS_UNICODE(unicode), __Pyx_PyUnicode_GET_SIZE(unicode), character); - - } + + } #endif -} - - -//////////////////// PyUnicodeContains.proto //////////////////// - +} + + +//////////////////// PyUnicodeContains.proto //////////////////// + static CYTHON_INLINE int __Pyx_PyUnicode_ContainsTF(PyObject* substring, PyObject* text, int eq) { - int result = PyUnicode_Contains(text, substring); - return unlikely(result < 0) ? result : (result == (eq == Py_EQ)); -} - - + int result = PyUnicode_Contains(text, substring); + return unlikely(result < 0) ? result : (result == (eq == Py_EQ)); +} + + //////////////////// CStringEquals.proto //////////////////// static CYTHON_INLINE int __Pyx_StrEq(const char *, const char *); /*proto*/ @@ -164,65 +164,65 @@ static CYTHON_INLINE int __Pyx_StrEq(const char *s1, const char *s2) { } -//////////////////// StrEquals.proto //////////////////// -//@requires: BytesEquals -//@requires: UnicodeEquals - -#if PY_MAJOR_VERSION >= 3 -#define __Pyx_PyString_Equals __Pyx_PyUnicode_Equals -#else -#define __Pyx_PyString_Equals __Pyx_PyBytes_Equals -#endif - - -//////////////////// UnicodeEquals.proto //////////////////// - -static CYTHON_INLINE int __Pyx_PyUnicode_Equals(PyObject* s1, PyObject* s2, int equals); /*proto*/ - -//////////////////// UnicodeEquals //////////////////// -//@requires: BytesEquals - -static CYTHON_INLINE int __Pyx_PyUnicode_Equals(PyObject* s1, PyObject* s2, int equals) { -#if CYTHON_COMPILING_IN_PYPY - return PyObject_RichCompareBool(s1, s2, equals); -#else -#if PY_MAJOR_VERSION < 3 - PyObject* owned_ref = NULL; -#endif - int s1_is_unicode, s2_is_unicode; - if (s1 == s2) { - /* as done by PyObject_RichCompareBool(); also catches the (interned) empty string */ - goto return_eq; - } - s1_is_unicode = PyUnicode_CheckExact(s1); - s2_is_unicode = PyUnicode_CheckExact(s2); -#if PY_MAJOR_VERSION < 3 - if ((s1_is_unicode & (!s2_is_unicode)) && PyString_CheckExact(s2)) { - owned_ref = PyUnicode_FromObject(s2); - if (unlikely(!owned_ref)) - return -1; - s2 = owned_ref; - s2_is_unicode = 1; - } else if ((s2_is_unicode & (!s1_is_unicode)) && PyString_CheckExact(s1)) { - owned_ref = PyUnicode_FromObject(s1); - if (unlikely(!owned_ref)) - return -1; - s1 = owned_ref; - s1_is_unicode = 1; - } else if (((!s2_is_unicode) & (!s1_is_unicode))) { - return __Pyx_PyBytes_Equals(s1, s2, equals); - } -#endif - if (s1_is_unicode & s2_is_unicode) { - Py_ssize_t length; - int kind; - void *data1, *data2; - if (unlikely(__Pyx_PyUnicode_READY(s1) < 0) || unlikely(__Pyx_PyUnicode_READY(s2) < 0)) - return -1; - length = __Pyx_PyUnicode_GET_LENGTH(s1); - if (length != __Pyx_PyUnicode_GET_LENGTH(s2)) { - goto return_ne; - } +//////////////////// StrEquals.proto //////////////////// +//@requires: BytesEquals +//@requires: UnicodeEquals + +#if PY_MAJOR_VERSION >= 3 +#define __Pyx_PyString_Equals __Pyx_PyUnicode_Equals +#else +#define __Pyx_PyString_Equals __Pyx_PyBytes_Equals +#endif + + +//////////////////// UnicodeEquals.proto //////////////////// + +static CYTHON_INLINE int __Pyx_PyUnicode_Equals(PyObject* s1, PyObject* s2, int equals); /*proto*/ + +//////////////////// UnicodeEquals //////////////////// +//@requires: BytesEquals + +static CYTHON_INLINE int __Pyx_PyUnicode_Equals(PyObject* s1, PyObject* s2, int equals) { +#if CYTHON_COMPILING_IN_PYPY + return PyObject_RichCompareBool(s1, s2, equals); +#else +#if PY_MAJOR_VERSION < 3 + PyObject* owned_ref = NULL; +#endif + int s1_is_unicode, s2_is_unicode; + if (s1 == s2) { + /* as done by PyObject_RichCompareBool(); also catches the (interned) empty string */ + goto return_eq; + } + s1_is_unicode = PyUnicode_CheckExact(s1); + s2_is_unicode = PyUnicode_CheckExact(s2); +#if PY_MAJOR_VERSION < 3 + if ((s1_is_unicode & (!s2_is_unicode)) && PyString_CheckExact(s2)) { + owned_ref = PyUnicode_FromObject(s2); + if (unlikely(!owned_ref)) + return -1; + s2 = owned_ref; + s2_is_unicode = 1; + } else if ((s2_is_unicode & (!s1_is_unicode)) && PyString_CheckExact(s1)) { + owned_ref = PyUnicode_FromObject(s1); + if (unlikely(!owned_ref)) + return -1; + s1 = owned_ref; + s1_is_unicode = 1; + } else if (((!s2_is_unicode) & (!s1_is_unicode))) { + return __Pyx_PyBytes_Equals(s1, s2, equals); + } +#endif + if (s1_is_unicode & s2_is_unicode) { + Py_ssize_t length; + int kind; + void *data1, *data2; + if (unlikely(__Pyx_PyUnicode_READY(s1) < 0) || unlikely(__Pyx_PyUnicode_READY(s2) < 0)) + return -1; + length = __Pyx_PyUnicode_GET_LENGTH(s1); + if (length != __Pyx_PyUnicode_GET_LENGTH(s2)) { + goto return_ne; + } #if CYTHON_USE_UNICODE_INTERNALS { Py_hash_t hash1, hash2; @@ -238,81 +238,81 @@ static CYTHON_INLINE int __Pyx_PyUnicode_Equals(PyObject* s1, PyObject* s2, int } } #endif - // len(s1) == len(s2) >= 1 (empty string is interned, and "s1 is not s2") - kind = __Pyx_PyUnicode_KIND(s1); - if (kind != __Pyx_PyUnicode_KIND(s2)) { - goto return_ne; - } - data1 = __Pyx_PyUnicode_DATA(s1); - data2 = __Pyx_PyUnicode_DATA(s2); - if (__Pyx_PyUnicode_READ(kind, data1, 0) != __Pyx_PyUnicode_READ(kind, data2, 0)) { - goto return_ne; - } else if (length == 1) { - goto return_eq; - } else { - int result = memcmp(data1, data2, (size_t)(length * kind)); - #if PY_MAJOR_VERSION < 3 - Py_XDECREF(owned_ref); - #endif - return (equals == Py_EQ) ? (result == 0) : (result != 0); - } - } else if ((s1 == Py_None) & s2_is_unicode) { - goto return_ne; - } else if ((s2 == Py_None) & s1_is_unicode) { - goto return_ne; - } else { - int result; - PyObject* py_result = PyObject_RichCompare(s1, s2, equals); + // len(s1) == len(s2) >= 1 (empty string is interned, and "s1 is not s2") + kind = __Pyx_PyUnicode_KIND(s1); + if (kind != __Pyx_PyUnicode_KIND(s2)) { + goto return_ne; + } + data1 = __Pyx_PyUnicode_DATA(s1); + data2 = __Pyx_PyUnicode_DATA(s2); + if (__Pyx_PyUnicode_READ(kind, data1, 0) != __Pyx_PyUnicode_READ(kind, data2, 0)) { + goto return_ne; + } else if (length == 1) { + goto return_eq; + } else { + int result = memcmp(data1, data2, (size_t)(length * kind)); + #if PY_MAJOR_VERSION < 3 + Py_XDECREF(owned_ref); + #endif + return (equals == Py_EQ) ? (result == 0) : (result != 0); + } + } else if ((s1 == Py_None) & s2_is_unicode) { + goto return_ne; + } else if ((s2 == Py_None) & s1_is_unicode) { + goto return_ne; + } else { + int result; + PyObject* py_result = PyObject_RichCompare(s1, s2, equals); #if PY_MAJOR_VERSION < 3 Py_XDECREF(owned_ref); #endif - if (!py_result) - return -1; - result = __Pyx_PyObject_IsTrue(py_result); - Py_DECREF(py_result); - return result; - } -return_eq: - #if PY_MAJOR_VERSION < 3 - Py_XDECREF(owned_ref); - #endif - return (equals == Py_EQ); -return_ne: - #if PY_MAJOR_VERSION < 3 - Py_XDECREF(owned_ref); - #endif - return (equals == Py_NE); -#endif -} - - -//////////////////// BytesEquals.proto //////////////////// - -static CYTHON_INLINE int __Pyx_PyBytes_Equals(PyObject* s1, PyObject* s2, int equals); /*proto*/ - -//////////////////// BytesEquals //////////////////// -//@requires: IncludeStringH - -static CYTHON_INLINE int __Pyx_PyBytes_Equals(PyObject* s1, PyObject* s2, int equals) { -#if CYTHON_COMPILING_IN_PYPY - return PyObject_RichCompareBool(s1, s2, equals); -#else - if (s1 == s2) { - /* as done by PyObject_RichCompareBool(); also catches the (interned) empty string */ - return (equals == Py_EQ); - } else if (PyBytes_CheckExact(s1) & PyBytes_CheckExact(s2)) { - const char *ps1, *ps2; - Py_ssize_t length = PyBytes_GET_SIZE(s1); - if (length != PyBytes_GET_SIZE(s2)) - return (equals == Py_NE); - // len(s1) == len(s2) >= 1 (empty string is interned, and "s1 is not s2") - ps1 = PyBytes_AS_STRING(s1); - ps2 = PyBytes_AS_STRING(s2); - if (ps1[0] != ps2[0]) { - return (equals == Py_NE); - } else if (length == 1) { - return (equals == Py_EQ); - } else { + if (!py_result) + return -1; + result = __Pyx_PyObject_IsTrue(py_result); + Py_DECREF(py_result); + return result; + } +return_eq: + #if PY_MAJOR_VERSION < 3 + Py_XDECREF(owned_ref); + #endif + return (equals == Py_EQ); +return_ne: + #if PY_MAJOR_VERSION < 3 + Py_XDECREF(owned_ref); + #endif + return (equals == Py_NE); +#endif +} + + +//////////////////// BytesEquals.proto //////////////////// + +static CYTHON_INLINE int __Pyx_PyBytes_Equals(PyObject* s1, PyObject* s2, int equals); /*proto*/ + +//////////////////// BytesEquals //////////////////// +//@requires: IncludeStringH + +static CYTHON_INLINE int __Pyx_PyBytes_Equals(PyObject* s1, PyObject* s2, int equals) { +#if CYTHON_COMPILING_IN_PYPY + return PyObject_RichCompareBool(s1, s2, equals); +#else + if (s1 == s2) { + /* as done by PyObject_RichCompareBool(); also catches the (interned) empty string */ + return (equals == Py_EQ); + } else if (PyBytes_CheckExact(s1) & PyBytes_CheckExact(s2)) { + const char *ps1, *ps2; + Py_ssize_t length = PyBytes_GET_SIZE(s1); + if (length != PyBytes_GET_SIZE(s2)) + return (equals == Py_NE); + // len(s1) == len(s2) >= 1 (empty string is interned, and "s1 is not s2") + ps1 = PyBytes_AS_STRING(s1); + ps2 = PyBytes_AS_STRING(s2); + if (ps1[0] != ps2[0]) { + return (equals == Py_NE); + } else if (length == 1) { + return (equals == Py_EQ); + } else { int result; #if CYTHON_USE_UNICODE_INTERNALS Py_hash_t hash1, hash2; @@ -323,117 +323,117 @@ static CYTHON_INLINE int __Pyx_PyBytes_Equals(PyObject* s1, PyObject* s2, int eq } #endif result = memcmp(ps1, ps2, (size_t)length); - return (equals == Py_EQ) ? (result == 0) : (result != 0); - } - } else if ((s1 == Py_None) & PyBytes_CheckExact(s2)) { - return (equals == Py_NE); - } else if ((s2 == Py_None) & PyBytes_CheckExact(s1)) { - return (equals == Py_NE); - } else { - int result; - PyObject* py_result = PyObject_RichCompare(s1, s2, equals); - if (!py_result) - return -1; - result = __Pyx_PyObject_IsTrue(py_result); - Py_DECREF(py_result); - return result; - } -#endif -} - -//////////////////// GetItemIntByteArray.proto //////////////////// - -#define __Pyx_GetItemInt_ByteArray(o, i, type, is_signed, to_py_func, is_list, wraparound, boundscheck) \ - (__Pyx_fits_Py_ssize_t(i, type, is_signed) ? \ - __Pyx_GetItemInt_ByteArray_Fast(o, (Py_ssize_t)i, wraparound, boundscheck) : \ - (PyErr_SetString(PyExc_IndexError, "bytearray index out of range"), -1)) - -static CYTHON_INLINE int __Pyx_GetItemInt_ByteArray_Fast(PyObject* string, Py_ssize_t i, - int wraparound, int boundscheck); - -//////////////////// GetItemIntByteArray //////////////////// - -static CYTHON_INLINE int __Pyx_GetItemInt_ByteArray_Fast(PyObject* string, Py_ssize_t i, - int wraparound, int boundscheck) { - Py_ssize_t length; - if (wraparound | boundscheck) { - length = PyByteArray_GET_SIZE(string); - if (wraparound & unlikely(i < 0)) i += length; + return (equals == Py_EQ) ? (result == 0) : (result != 0); + } + } else if ((s1 == Py_None) & PyBytes_CheckExact(s2)) { + return (equals == Py_NE); + } else if ((s2 == Py_None) & PyBytes_CheckExact(s1)) { + return (equals == Py_NE); + } else { + int result; + PyObject* py_result = PyObject_RichCompare(s1, s2, equals); + if (!py_result) + return -1; + result = __Pyx_PyObject_IsTrue(py_result); + Py_DECREF(py_result); + return result; + } +#endif +} + +//////////////////// GetItemIntByteArray.proto //////////////////// + +#define __Pyx_GetItemInt_ByteArray(o, i, type, is_signed, to_py_func, is_list, wraparound, boundscheck) \ + (__Pyx_fits_Py_ssize_t(i, type, is_signed) ? \ + __Pyx_GetItemInt_ByteArray_Fast(o, (Py_ssize_t)i, wraparound, boundscheck) : \ + (PyErr_SetString(PyExc_IndexError, "bytearray index out of range"), -1)) + +static CYTHON_INLINE int __Pyx_GetItemInt_ByteArray_Fast(PyObject* string, Py_ssize_t i, + int wraparound, int boundscheck); + +//////////////////// GetItemIntByteArray //////////////////// + +static CYTHON_INLINE int __Pyx_GetItemInt_ByteArray_Fast(PyObject* string, Py_ssize_t i, + int wraparound, int boundscheck) { + Py_ssize_t length; + if (wraparound | boundscheck) { + length = PyByteArray_GET_SIZE(string); + if (wraparound & unlikely(i < 0)) i += length; if ((!boundscheck) || likely(__Pyx_is_valid_index(i, length))) { - return (unsigned char) (PyByteArray_AS_STRING(string)[i]); - } else { - PyErr_SetString(PyExc_IndexError, "bytearray index out of range"); - return -1; - } - } else { - return (unsigned char) (PyByteArray_AS_STRING(string)[i]); - } -} - - -//////////////////// SetItemIntByteArray.proto //////////////////// - -#define __Pyx_SetItemInt_ByteArray(o, i, v, type, is_signed, to_py_func, is_list, wraparound, boundscheck) \ - (__Pyx_fits_Py_ssize_t(i, type, is_signed) ? \ - __Pyx_SetItemInt_ByteArray_Fast(o, (Py_ssize_t)i, v, wraparound, boundscheck) : \ - (PyErr_SetString(PyExc_IndexError, "bytearray index out of range"), -1)) - -static CYTHON_INLINE int __Pyx_SetItemInt_ByteArray_Fast(PyObject* string, Py_ssize_t i, unsigned char v, - int wraparound, int boundscheck); - -//////////////////// SetItemIntByteArray //////////////////// - -static CYTHON_INLINE int __Pyx_SetItemInt_ByteArray_Fast(PyObject* string, Py_ssize_t i, unsigned char v, - int wraparound, int boundscheck) { - Py_ssize_t length; - if (wraparound | boundscheck) { - length = PyByteArray_GET_SIZE(string); - if (wraparound & unlikely(i < 0)) i += length; + return (unsigned char) (PyByteArray_AS_STRING(string)[i]); + } else { + PyErr_SetString(PyExc_IndexError, "bytearray index out of range"); + return -1; + } + } else { + return (unsigned char) (PyByteArray_AS_STRING(string)[i]); + } +} + + +//////////////////// SetItemIntByteArray.proto //////////////////// + +#define __Pyx_SetItemInt_ByteArray(o, i, v, type, is_signed, to_py_func, is_list, wraparound, boundscheck) \ + (__Pyx_fits_Py_ssize_t(i, type, is_signed) ? \ + __Pyx_SetItemInt_ByteArray_Fast(o, (Py_ssize_t)i, v, wraparound, boundscheck) : \ + (PyErr_SetString(PyExc_IndexError, "bytearray index out of range"), -1)) + +static CYTHON_INLINE int __Pyx_SetItemInt_ByteArray_Fast(PyObject* string, Py_ssize_t i, unsigned char v, + int wraparound, int boundscheck); + +//////////////////// SetItemIntByteArray //////////////////// + +static CYTHON_INLINE int __Pyx_SetItemInt_ByteArray_Fast(PyObject* string, Py_ssize_t i, unsigned char v, + int wraparound, int boundscheck) { + Py_ssize_t length; + if (wraparound | boundscheck) { + length = PyByteArray_GET_SIZE(string); + if (wraparound & unlikely(i < 0)) i += length; if ((!boundscheck) || likely(__Pyx_is_valid_index(i, length))) { - PyByteArray_AS_STRING(string)[i] = (char) v; - return 0; - } else { - PyErr_SetString(PyExc_IndexError, "bytearray index out of range"); - return -1; - } - } else { - PyByteArray_AS_STRING(string)[i] = (char) v; - return 0; - } -} - - -//////////////////// GetItemIntUnicode.proto //////////////////// - -#define __Pyx_GetItemInt_Unicode(o, i, type, is_signed, to_py_func, is_list, wraparound, boundscheck) \ - (__Pyx_fits_Py_ssize_t(i, type, is_signed) ? \ - __Pyx_GetItemInt_Unicode_Fast(o, (Py_ssize_t)i, wraparound, boundscheck) : \ - (PyErr_SetString(PyExc_IndexError, "string index out of range"), (Py_UCS4)-1)) - -static CYTHON_INLINE Py_UCS4 __Pyx_GetItemInt_Unicode_Fast(PyObject* ustring, Py_ssize_t i, - int wraparound, int boundscheck); - -//////////////////// GetItemIntUnicode //////////////////// - -static CYTHON_INLINE Py_UCS4 __Pyx_GetItemInt_Unicode_Fast(PyObject* ustring, Py_ssize_t i, - int wraparound, int boundscheck) { - Py_ssize_t length; - if (unlikely(__Pyx_PyUnicode_READY(ustring) < 0)) return (Py_UCS4)-1; - if (wraparound | boundscheck) { - length = __Pyx_PyUnicode_GET_LENGTH(ustring); - if (wraparound & unlikely(i < 0)) i += length; + PyByteArray_AS_STRING(string)[i] = (char) v; + return 0; + } else { + PyErr_SetString(PyExc_IndexError, "bytearray index out of range"); + return -1; + } + } else { + PyByteArray_AS_STRING(string)[i] = (char) v; + return 0; + } +} + + +//////////////////// GetItemIntUnicode.proto //////////////////// + +#define __Pyx_GetItemInt_Unicode(o, i, type, is_signed, to_py_func, is_list, wraparound, boundscheck) \ + (__Pyx_fits_Py_ssize_t(i, type, is_signed) ? \ + __Pyx_GetItemInt_Unicode_Fast(o, (Py_ssize_t)i, wraparound, boundscheck) : \ + (PyErr_SetString(PyExc_IndexError, "string index out of range"), (Py_UCS4)-1)) + +static CYTHON_INLINE Py_UCS4 __Pyx_GetItemInt_Unicode_Fast(PyObject* ustring, Py_ssize_t i, + int wraparound, int boundscheck); + +//////////////////// GetItemIntUnicode //////////////////// + +static CYTHON_INLINE Py_UCS4 __Pyx_GetItemInt_Unicode_Fast(PyObject* ustring, Py_ssize_t i, + int wraparound, int boundscheck) { + Py_ssize_t length; + if (unlikely(__Pyx_PyUnicode_READY(ustring) < 0)) return (Py_UCS4)-1; + if (wraparound | boundscheck) { + length = __Pyx_PyUnicode_GET_LENGTH(ustring); + if (wraparound & unlikely(i < 0)) i += length; if ((!boundscheck) || likely(__Pyx_is_valid_index(i, length))) { - return __Pyx_PyUnicode_READ_CHAR(ustring, i); - } else { - PyErr_SetString(PyExc_IndexError, "string index out of range"); - return (Py_UCS4)-1; - } - } else { - return __Pyx_PyUnicode_READ_CHAR(ustring, i); - } -} - - + return __Pyx_PyUnicode_READ_CHAR(ustring, i); + } else { + PyErr_SetString(PyExc_IndexError, "string index out of range"); + return (Py_UCS4)-1; + } + } else { + return __Pyx_PyUnicode_READ_CHAR(ustring, i); + } +} + + /////////////// decode_c_string_utf16.proto /////////////// static CYTHON_INLINE PyObject *__Pyx_PyUnicode_DecodeUTF16(const char *s, Py_ssize_t size, const char *errors) { @@ -449,37 +449,37 @@ static CYTHON_INLINE PyObject *__Pyx_PyUnicode_DecodeUTF16BE(const char *s, Py_s return PyUnicode_DecodeUTF16(s, size, errors, &byteorder); } -/////////////// decode_cpp_string.proto /////////////// -//@requires: IncludeCppStringH -//@requires: decode_c_bytes - -static CYTHON_INLINE PyObject* __Pyx_decode_cpp_string( +/////////////// decode_cpp_string.proto /////////////// +//@requires: IncludeCppStringH +//@requires: decode_c_bytes + +static CYTHON_INLINE PyObject* __Pyx_decode_cpp_string( std::string_view cppstring, Py_ssize_t start, Py_ssize_t stop, - const char* encoding, const char* errors, - PyObject* (*decode_func)(const char *s, Py_ssize_t size, const char *errors)) { - return __Pyx_decode_c_bytes( - cppstring.data(), cppstring.size(), start, stop, encoding, errors, decode_func); -} - -/////////////// decode_c_string.proto /////////////// - -static CYTHON_INLINE PyObject* __Pyx_decode_c_string( - const char* cstring, Py_ssize_t start, Py_ssize_t stop, - const char* encoding, const char* errors, - PyObject* (*decode_func)(const char *s, Py_ssize_t size, const char *errors)); - -/////////////// decode_c_string /////////////// -//@requires: IncludeStringH + const char* encoding, const char* errors, + PyObject* (*decode_func)(const char *s, Py_ssize_t size, const char *errors)) { + return __Pyx_decode_c_bytes( + cppstring.data(), cppstring.size(), start, stop, encoding, errors, decode_func); +} + +/////////////// decode_c_string.proto /////////////// + +static CYTHON_INLINE PyObject* __Pyx_decode_c_string( + const char* cstring, Py_ssize_t start, Py_ssize_t stop, + const char* encoding, const char* errors, + PyObject* (*decode_func)(const char *s, Py_ssize_t size, const char *errors)); + +/////////////// decode_c_string /////////////// +//@requires: IncludeStringH //@requires: decode_c_string_utf16 //@substitute: naming - -/* duplicate code to avoid calling strlen() if start >= 0 and stop >= 0 */ -static CYTHON_INLINE PyObject* __Pyx_decode_c_string( - const char* cstring, Py_ssize_t start, Py_ssize_t stop, - const char* encoding, const char* errors, - PyObject* (*decode_func)(const char *s, Py_ssize_t size, const char *errors)) { - Py_ssize_t length; - if (unlikely((start < 0) | (stop < 0))) { + +/* duplicate code to avoid calling strlen() if start >= 0 and stop >= 0 */ +static CYTHON_INLINE PyObject* __Pyx_decode_c_string( + const char* cstring, Py_ssize_t start, Py_ssize_t stop, + const char* encoding, const char* errors, + PyObject* (*decode_func)(const char *s, Py_ssize_t size, const char *errors)) { + Py_ssize_t length; + if (unlikely((start < 0) | (stop < 0))) { size_t slen = strlen(cstring); if (unlikely(slen > (size_t) PY_SSIZE_T_MAX)) { PyErr_SetString(PyExc_OverflowError, @@ -487,145 +487,145 @@ static CYTHON_INLINE PyObject* __Pyx_decode_c_string( return NULL; } length = (Py_ssize_t) slen; - if (start < 0) { - start += length; - if (start < 0) - start = 0; - } - if (stop < 0) - stop += length; - } + if (start < 0) { + start += length; + if (start < 0) + start = 0; + } + if (stop < 0) + stop += length; + } if (unlikely(stop <= start)) return __Pyx_NewRef($empty_unicode); - length = stop - start; - cstring += start; - if (decode_func) { - return decode_func(cstring, length, errors); - } else { - return PyUnicode_Decode(cstring, length, encoding, errors); - } -} - -/////////////// decode_c_bytes.proto /////////////// - -static CYTHON_INLINE PyObject* __Pyx_decode_c_bytes( - const char* cstring, Py_ssize_t length, Py_ssize_t start, Py_ssize_t stop, - const char* encoding, const char* errors, - PyObject* (*decode_func)(const char *s, Py_ssize_t size, const char *errors)); - -/////////////// decode_c_bytes /////////////// + length = stop - start; + cstring += start; + if (decode_func) { + return decode_func(cstring, length, errors); + } else { + return PyUnicode_Decode(cstring, length, encoding, errors); + } +} + +/////////////// decode_c_bytes.proto /////////////// + +static CYTHON_INLINE PyObject* __Pyx_decode_c_bytes( + const char* cstring, Py_ssize_t length, Py_ssize_t start, Py_ssize_t stop, + const char* encoding, const char* errors, + PyObject* (*decode_func)(const char *s, Py_ssize_t size, const char *errors)); + +/////////////// decode_c_bytes /////////////// //@requires: decode_c_string_utf16 //@substitute: naming - -static CYTHON_INLINE PyObject* __Pyx_decode_c_bytes( - const char* cstring, Py_ssize_t length, Py_ssize_t start, Py_ssize_t stop, - const char* encoding, const char* errors, - PyObject* (*decode_func)(const char *s, Py_ssize_t size, const char *errors)) { - if (unlikely((start < 0) | (stop < 0))) { - if (start < 0) { - start += length; - if (start < 0) - start = 0; - } - if (stop < 0) - stop += length; - } - if (stop > length) - stop = length; + +static CYTHON_INLINE PyObject* __Pyx_decode_c_bytes( + const char* cstring, Py_ssize_t length, Py_ssize_t start, Py_ssize_t stop, + const char* encoding, const char* errors, + PyObject* (*decode_func)(const char *s, Py_ssize_t size, const char *errors)) { + if (unlikely((start < 0) | (stop < 0))) { + if (start < 0) { + start += length; + if (start < 0) + start = 0; + } + if (stop < 0) + stop += length; + } + if (stop > length) + stop = length; if (unlikely(stop <= start)) return __Pyx_NewRef($empty_unicode); - length = stop - start; - cstring += start; - if (decode_func) { - return decode_func(cstring, length, errors); - } else { - return PyUnicode_Decode(cstring, length, encoding, errors); - } -} - -/////////////// decode_bytes.proto /////////////// -//@requires: decode_c_bytes - -static CYTHON_INLINE PyObject* __Pyx_decode_bytes( - PyObject* string, Py_ssize_t start, Py_ssize_t stop, - const char* encoding, const char* errors, - PyObject* (*decode_func)(const char *s, Py_ssize_t size, const char *errors)) { - return __Pyx_decode_c_bytes( - PyBytes_AS_STRING(string), PyBytes_GET_SIZE(string), - start, stop, encoding, errors, decode_func); -} - -/////////////// decode_bytearray.proto /////////////// -//@requires: decode_c_bytes - -static CYTHON_INLINE PyObject* __Pyx_decode_bytearray( - PyObject* string, Py_ssize_t start, Py_ssize_t stop, - const char* encoding, const char* errors, - PyObject* (*decode_func)(const char *s, Py_ssize_t size, const char *errors)) { - return __Pyx_decode_c_bytes( - PyByteArray_AS_STRING(string), PyByteArray_GET_SIZE(string), - start, stop, encoding, errors, decode_func); -} - -/////////////// PyUnicode_Substring.proto /////////////// - -static CYTHON_INLINE PyObject* __Pyx_PyUnicode_Substring( - PyObject* text, Py_ssize_t start, Py_ssize_t stop); - -/////////////// PyUnicode_Substring /////////////// + length = stop - start; + cstring += start; + if (decode_func) { + return decode_func(cstring, length, errors); + } else { + return PyUnicode_Decode(cstring, length, encoding, errors); + } +} + +/////////////// decode_bytes.proto /////////////// +//@requires: decode_c_bytes + +static CYTHON_INLINE PyObject* __Pyx_decode_bytes( + PyObject* string, Py_ssize_t start, Py_ssize_t stop, + const char* encoding, const char* errors, + PyObject* (*decode_func)(const char *s, Py_ssize_t size, const char *errors)) { + return __Pyx_decode_c_bytes( + PyBytes_AS_STRING(string), PyBytes_GET_SIZE(string), + start, stop, encoding, errors, decode_func); +} + +/////////////// decode_bytearray.proto /////////////// +//@requires: decode_c_bytes + +static CYTHON_INLINE PyObject* __Pyx_decode_bytearray( + PyObject* string, Py_ssize_t start, Py_ssize_t stop, + const char* encoding, const char* errors, + PyObject* (*decode_func)(const char *s, Py_ssize_t size, const char *errors)) { + return __Pyx_decode_c_bytes( + PyByteArray_AS_STRING(string), PyByteArray_GET_SIZE(string), + start, stop, encoding, errors, decode_func); +} + +/////////////// PyUnicode_Substring.proto /////////////// + +static CYTHON_INLINE PyObject* __Pyx_PyUnicode_Substring( + PyObject* text, Py_ssize_t start, Py_ssize_t stop); + +/////////////// PyUnicode_Substring /////////////// //@substitute: naming - -static CYTHON_INLINE PyObject* __Pyx_PyUnicode_Substring( - PyObject* text, Py_ssize_t start, Py_ssize_t stop) { - Py_ssize_t length; - if (unlikely(__Pyx_PyUnicode_READY(text) == -1)) return NULL; - length = __Pyx_PyUnicode_GET_LENGTH(text); - if (start < 0) { - start += length; - if (start < 0) - start = 0; - } - if (stop < 0) + +static CYTHON_INLINE PyObject* __Pyx_PyUnicode_Substring( + PyObject* text, Py_ssize_t start, Py_ssize_t stop) { + Py_ssize_t length; + if (unlikely(__Pyx_PyUnicode_READY(text) == -1)) return NULL; + length = __Pyx_PyUnicode_GET_LENGTH(text); + if (start < 0) { + start += length; + if (start < 0) + start = 0; + } + if (stop < 0) stop += length; - else if (stop > length) - stop = length; + else if (stop > length) + stop = length; if (stop <= start) return __Pyx_NewRef($empty_unicode); -#if CYTHON_PEP393_ENABLED - return PyUnicode_FromKindAndData(PyUnicode_KIND(text), - PyUnicode_1BYTE_DATA(text) + start*PyUnicode_KIND(text), stop-start); -#else - return PyUnicode_FromUnicode(PyUnicode_AS_UNICODE(text)+start, stop-start); -#endif -} - - -/////////////// py_unicode_istitle.proto /////////////// - -// Py_UNICODE_ISTITLE() doesn't match unicode.istitle() as the latter -// additionally allows character that comply with Py_UNICODE_ISUPPER() - -#if PY_VERSION_HEX < 0x030200A2 -static CYTHON_INLINE int __Pyx_Py_UNICODE_ISTITLE(Py_UNICODE uchar) -#else -static CYTHON_INLINE int __Pyx_Py_UNICODE_ISTITLE(Py_UCS4 uchar) -#endif -{ - return Py_UNICODE_ISTITLE(uchar) || Py_UNICODE_ISUPPER(uchar); -} - - -/////////////// unicode_tailmatch.proto /////////////// - +#if CYTHON_PEP393_ENABLED + return PyUnicode_FromKindAndData(PyUnicode_KIND(text), + PyUnicode_1BYTE_DATA(text) + start*PyUnicode_KIND(text), stop-start); +#else + return PyUnicode_FromUnicode(PyUnicode_AS_UNICODE(text)+start, stop-start); +#endif +} + + +/////////////// py_unicode_istitle.proto /////////////// + +// Py_UNICODE_ISTITLE() doesn't match unicode.istitle() as the latter +// additionally allows character that comply with Py_UNICODE_ISUPPER() + +#if PY_VERSION_HEX < 0x030200A2 +static CYTHON_INLINE int __Pyx_Py_UNICODE_ISTITLE(Py_UNICODE uchar) +#else +static CYTHON_INLINE int __Pyx_Py_UNICODE_ISTITLE(Py_UCS4 uchar) +#endif +{ + return Py_UNICODE_ISTITLE(uchar) || Py_UNICODE_ISUPPER(uchar); +} + + +/////////////// unicode_tailmatch.proto /////////////// + static int __Pyx_PyUnicode_Tailmatch( PyObject* s, PyObject* substr, Py_ssize_t start, Py_ssize_t end, int direction); /*proto*/ /////////////// unicode_tailmatch /////////////// -// Python's unicode.startswith() and unicode.endswith() support a -// tuple of prefixes/suffixes, whereas it's much more common to -// test for a single unicode string. - +// Python's unicode.startswith() and unicode.endswith() support a +// tuple of prefixes/suffixes, whereas it's much more common to +// test for a single unicode string. + static int __Pyx_PyUnicode_TailmatchTuple(PyObject* s, PyObject* substrings, Py_ssize_t start, Py_ssize_t end, int direction) { Py_ssize_t i, count = PyTuple_GET_SIZE(substrings); @@ -634,16 +634,16 @@ static int __Pyx_PyUnicode_TailmatchTuple(PyObject* s, PyObject* substrings, #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS result = PyUnicode_Tailmatch(s, PyTuple_GET_ITEM(substrings, i), start, end, direction); -#else +#else PyObject* sub = PySequence_ITEM(substrings, i); if (unlikely(!sub)) return -1; result = PyUnicode_Tailmatch(s, sub, start, end, direction); Py_DECREF(sub); -#endif +#endif if (result) { return (int) result; - } - } + } + } return 0; } @@ -653,11 +653,11 @@ static int __Pyx_PyUnicode_Tailmatch(PyObject* s, PyObject* substr, return __Pyx_PyUnicode_TailmatchTuple(s, substr, start, end, direction); } return (int) PyUnicode_Tailmatch(s, substr, start, end, direction); -} - - -/////////////// bytes_tailmatch.proto /////////////// - +} + + +/////////////// bytes_tailmatch.proto /////////////// + static int __Pyx_PyBytes_SingleTailmatch(PyObject* self, PyObject* arg, Py_ssize_t start, Py_ssize_t end, int direction); /*proto*/ static int __Pyx_PyBytes_Tailmatch(PyObject* self, PyObject* substr, @@ -667,60 +667,60 @@ static int __Pyx_PyBytes_Tailmatch(PyObject* self, PyObject* substr, static int __Pyx_PyBytes_SingleTailmatch(PyObject* self, PyObject* arg, Py_ssize_t start, Py_ssize_t end, int direction) { - const char* self_ptr = PyBytes_AS_STRING(self); - Py_ssize_t self_len = PyBytes_GET_SIZE(self); - const char* sub_ptr; - Py_ssize_t sub_len; - int retval; - - Py_buffer view; - view.obj = NULL; - - if ( PyBytes_Check(arg) ) { - sub_ptr = PyBytes_AS_STRING(arg); - sub_len = PyBytes_GET_SIZE(arg); - } -#if PY_MAJOR_VERSION < 3 - // Python 2.x allows mixing unicode and str - else if ( PyUnicode_Check(arg) ) { + const char* self_ptr = PyBytes_AS_STRING(self); + Py_ssize_t self_len = PyBytes_GET_SIZE(self); + const char* sub_ptr; + Py_ssize_t sub_len; + int retval; + + Py_buffer view; + view.obj = NULL; + + if ( PyBytes_Check(arg) ) { + sub_ptr = PyBytes_AS_STRING(arg); + sub_len = PyBytes_GET_SIZE(arg); + } +#if PY_MAJOR_VERSION < 3 + // Python 2.x allows mixing unicode and str + else if ( PyUnicode_Check(arg) ) { return (int) PyUnicode_Tailmatch(self, arg, start, end, direction); - } -#endif - else { - if (unlikely(PyObject_GetBuffer(self, &view, PyBUF_SIMPLE) == -1)) - return -1; - sub_ptr = (const char*) view.buf; - sub_len = view.len; - } - - if (end > self_len) - end = self_len; - else if (end < 0) - end += self_len; - if (end < 0) - end = 0; - if (start < 0) - start += self_len; - if (start < 0) - start = 0; - - if (direction > 0) { - /* endswith */ - if (end-sub_len > start) - start = end - sub_len; - } - - if (start + sub_len <= end) - retval = !memcmp(self_ptr+start, sub_ptr, (size_t)sub_len); - else - retval = 0; - - if (view.obj) - PyBuffer_Release(&view); - - return retval; -} - + } +#endif + else { + if (unlikely(PyObject_GetBuffer(self, &view, PyBUF_SIMPLE) == -1)) + return -1; + sub_ptr = (const char*) view.buf; + sub_len = view.len; + } + + if (end > self_len) + end = self_len; + else if (end < 0) + end += self_len; + if (end < 0) + end = 0; + if (start < 0) + start += self_len; + if (start < 0) + start = 0; + + if (direction > 0) { + /* endswith */ + if (end-sub_len > start) + start = end - sub_len; + } + + if (start + sub_len <= end) + retval = !memcmp(self_ptr+start, sub_ptr, (size_t)sub_len); + else + retval = 0; + + if (view.obj) + PyBuffer_Release(&view); + + return retval; +} + static int __Pyx_PyBytes_TailmatchTuple(PyObject* self, PyObject* substrings, Py_ssize_t start, Py_ssize_t end, int direction) { Py_ssize_t i, count = PyTuple_GET_SIZE(substrings); @@ -729,102 +729,102 @@ static int __Pyx_PyBytes_TailmatchTuple(PyObject* self, PyObject* substrings, #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS result = __Pyx_PyBytes_SingleTailmatch(self, PyTuple_GET_ITEM(substrings, i), start, end, direction); -#else +#else PyObject* sub = PySequence_ITEM(substrings, i); if (unlikely(!sub)) return -1; result = __Pyx_PyBytes_SingleTailmatch(self, sub, start, end, direction); Py_DECREF(sub); -#endif +#endif if (result) { return result; - } - } + } + } return 0; } - + static int __Pyx_PyBytes_Tailmatch(PyObject* self, PyObject* substr, Py_ssize_t start, Py_ssize_t end, int direction) { if (unlikely(PyTuple_Check(substr))) { return __Pyx_PyBytes_TailmatchTuple(self, substr, start, end, direction); } - return __Pyx_PyBytes_SingleTailmatch(self, substr, start, end, direction); -} - - -/////////////// str_tailmatch.proto /////////////// - -static CYTHON_INLINE int __Pyx_PyStr_Tailmatch(PyObject* self, PyObject* arg, Py_ssize_t start, + return __Pyx_PyBytes_SingleTailmatch(self, substr, start, end, direction); +} + + +/////////////// str_tailmatch.proto /////////////// + +static CYTHON_INLINE int __Pyx_PyStr_Tailmatch(PyObject* self, PyObject* arg, Py_ssize_t start, Py_ssize_t end, int direction); /*proto*/ - -/////////////// str_tailmatch /////////////// -//@requires: bytes_tailmatch -//@requires: unicode_tailmatch - -static CYTHON_INLINE int __Pyx_PyStr_Tailmatch(PyObject* self, PyObject* arg, Py_ssize_t start, - Py_ssize_t end, int direction) -{ - // We do not use a C compiler macro here to avoid "unused function" - // warnings for the *_Tailmatch() function that is not being used in - // the specific CPython version. The C compiler will generate the same - // code anyway, and will usually just remove the unused function. - if (PY_MAJOR_VERSION < 3) - return __Pyx_PyBytes_Tailmatch(self, arg, start, end, direction); - else - return __Pyx_PyUnicode_Tailmatch(self, arg, start, end, direction); -} - - -/////////////// bytes_index.proto /////////////// - + +/////////////// str_tailmatch /////////////// +//@requires: bytes_tailmatch +//@requires: unicode_tailmatch + +static CYTHON_INLINE int __Pyx_PyStr_Tailmatch(PyObject* self, PyObject* arg, Py_ssize_t start, + Py_ssize_t end, int direction) +{ + // We do not use a C compiler macro here to avoid "unused function" + // warnings for the *_Tailmatch() function that is not being used in + // the specific CPython version. The C compiler will generate the same + // code anyway, and will usually just remove the unused function. + if (PY_MAJOR_VERSION < 3) + return __Pyx_PyBytes_Tailmatch(self, arg, start, end, direction); + else + return __Pyx_PyUnicode_Tailmatch(self, arg, start, end, direction); +} + + +/////////////// bytes_index.proto /////////////// + static CYTHON_INLINE char __Pyx_PyBytes_GetItemInt(PyObject* bytes, Py_ssize_t index, int check_bounds); /*proto*/ /////////////// bytes_index /////////////// -static CYTHON_INLINE char __Pyx_PyBytes_GetItemInt(PyObject* bytes, Py_ssize_t index, int check_bounds) { +static CYTHON_INLINE char __Pyx_PyBytes_GetItemInt(PyObject* bytes, Py_ssize_t index, int check_bounds) { if (index < 0) index += PyBytes_GET_SIZE(bytes); - if (check_bounds) { - Py_ssize_t size = PyBytes_GET_SIZE(bytes); + if (check_bounds) { + Py_ssize_t size = PyBytes_GET_SIZE(bytes); if (unlikely(!__Pyx_is_valid_index(index, size))) { - PyErr_SetString(PyExc_IndexError, "string index out of range"); + PyErr_SetString(PyExc_IndexError, "string index out of range"); return (char) -1; - } - } - return PyBytes_AS_STRING(bytes)[index]; -} - - -//////////////////// StringJoin.proto //////////////////// - -#if PY_MAJOR_VERSION < 3 -#define __Pyx_PyString_Join __Pyx_PyBytes_Join -#define __Pyx_PyBaseString_Join(s, v) (PyUnicode_CheckExact(s) ? PyUnicode_Join(s, v) : __Pyx_PyBytes_Join(s, v)) -#else -#define __Pyx_PyString_Join PyUnicode_Join -#define __Pyx_PyBaseString_Join PyUnicode_Join -#endif - -#if CYTHON_COMPILING_IN_CPYTHON - #if PY_MAJOR_VERSION < 3 - #define __Pyx_PyBytes_Join _PyString_Join - #else - #define __Pyx_PyBytes_Join _PyBytes_Join - #endif -#else -static CYTHON_INLINE PyObject* __Pyx_PyBytes_Join(PyObject* sep, PyObject* values); /*proto*/ -#endif - - -//////////////////// StringJoin //////////////////// - -#if !CYTHON_COMPILING_IN_CPYTHON -static CYTHON_INLINE PyObject* __Pyx_PyBytes_Join(PyObject* sep, PyObject* values) { - return PyObject_CallMethodObjArgs(sep, PYIDENT("join"), values, NULL); -} -#endif - - + } + } + return PyBytes_AS_STRING(bytes)[index]; +} + + +//////////////////// StringJoin.proto //////////////////// + +#if PY_MAJOR_VERSION < 3 +#define __Pyx_PyString_Join __Pyx_PyBytes_Join +#define __Pyx_PyBaseString_Join(s, v) (PyUnicode_CheckExact(s) ? PyUnicode_Join(s, v) : __Pyx_PyBytes_Join(s, v)) +#else +#define __Pyx_PyString_Join PyUnicode_Join +#define __Pyx_PyBaseString_Join PyUnicode_Join +#endif + +#if CYTHON_COMPILING_IN_CPYTHON + #if PY_MAJOR_VERSION < 3 + #define __Pyx_PyBytes_Join _PyString_Join + #else + #define __Pyx_PyBytes_Join _PyBytes_Join + #endif +#else +static CYTHON_INLINE PyObject* __Pyx_PyBytes_Join(PyObject* sep, PyObject* values); /*proto*/ +#endif + + +//////////////////// StringJoin //////////////////// + +#if !CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE PyObject* __Pyx_PyBytes_Join(PyObject* sep, PyObject* values) { + return PyObject_CallMethodObjArgs(sep, PYIDENT("join"), values, NULL); +} +#endif + + /////////////// JoinPyUnicode.proto /////////////// static PyObject* __Pyx_PyUnicode_Join(PyObject* value_tuple, Py_ssize_t value_count, Py_ssize_t result_ulength, @@ -989,82 +989,82 @@ done_or_error: } -//////////////////// ByteArrayAppendObject.proto //////////////////// - -static CYTHON_INLINE int __Pyx_PyByteArray_AppendObject(PyObject* bytearray, PyObject* value); - -//////////////////// ByteArrayAppendObject //////////////////// -//@requires: ByteArrayAppend - -static CYTHON_INLINE int __Pyx_PyByteArray_AppendObject(PyObject* bytearray, PyObject* value) { - Py_ssize_t ival; -#if PY_MAJOR_VERSION < 3 - if (unlikely(PyString_Check(value))) { - if (unlikely(PyString_GET_SIZE(value) != 1)) { - PyErr_SetString(PyExc_ValueError, "string must be of size 1"); - return -1; - } - ival = (unsigned char) (PyString_AS_STRING(value)[0]); - } else -#endif -#if CYTHON_USE_PYLONG_INTERNALS - if (likely(PyLong_CheckExact(value)) && likely(Py_SIZE(value) == 1 || Py_SIZE(value) == 0)) { - if (Py_SIZE(value) == 0) { - ival = 0; - } else { - ival = ((PyLongObject*)value)->ob_digit[0]; - if (unlikely(ival > 255)) goto bad_range; - } - } else +//////////////////// ByteArrayAppendObject.proto //////////////////// + +static CYTHON_INLINE int __Pyx_PyByteArray_AppendObject(PyObject* bytearray, PyObject* value); + +//////////////////// ByteArrayAppendObject //////////////////// +//@requires: ByteArrayAppend + +static CYTHON_INLINE int __Pyx_PyByteArray_AppendObject(PyObject* bytearray, PyObject* value) { + Py_ssize_t ival; +#if PY_MAJOR_VERSION < 3 + if (unlikely(PyString_Check(value))) { + if (unlikely(PyString_GET_SIZE(value) != 1)) { + PyErr_SetString(PyExc_ValueError, "string must be of size 1"); + return -1; + } + ival = (unsigned char) (PyString_AS_STRING(value)[0]); + } else #endif - { - // CPython calls PyNumber_Index() internally - ival = __Pyx_PyIndex_AsSsize_t(value); +#if CYTHON_USE_PYLONG_INTERNALS + if (likely(PyLong_CheckExact(value)) && likely(Py_SIZE(value) == 1 || Py_SIZE(value) == 0)) { + if (Py_SIZE(value) == 0) { + ival = 0; + } else { + ival = ((PyLongObject*)value)->ob_digit[0]; + if (unlikely(ival > 255)) goto bad_range; + } + } else +#endif + { + // CPython calls PyNumber_Index() internally + ival = __Pyx_PyIndex_AsSsize_t(value); if (unlikely(!__Pyx_is_valid_index(ival, 256))) { - if (ival == -1 && PyErr_Occurred()) - return -1; - goto bad_range; - } - } - return __Pyx_PyByteArray_Append(bytearray, ival); -bad_range: - PyErr_SetString(PyExc_ValueError, "byte must be in range(0, 256)"); - return -1; -} - -//////////////////// ByteArrayAppend.proto //////////////////// - -static CYTHON_INLINE int __Pyx_PyByteArray_Append(PyObject* bytearray, int value); - -//////////////////// ByteArrayAppend //////////////////// -//@requires: ObjectHandling.c::PyObjectCallMethod1 - -static CYTHON_INLINE int __Pyx_PyByteArray_Append(PyObject* bytearray, int value) { - PyObject *pyval, *retval; -#if CYTHON_COMPILING_IN_CPYTHON + if (ival == -1 && PyErr_Occurred()) + return -1; + goto bad_range; + } + } + return __Pyx_PyByteArray_Append(bytearray, ival); +bad_range: + PyErr_SetString(PyExc_ValueError, "byte must be in range(0, 256)"); + return -1; +} + +//////////////////// ByteArrayAppend.proto //////////////////// + +static CYTHON_INLINE int __Pyx_PyByteArray_Append(PyObject* bytearray, int value); + +//////////////////// ByteArrayAppend //////////////////// +//@requires: ObjectHandling.c::PyObjectCallMethod1 + +static CYTHON_INLINE int __Pyx_PyByteArray_Append(PyObject* bytearray, int value) { + PyObject *pyval, *retval; +#if CYTHON_COMPILING_IN_CPYTHON if (likely(__Pyx_is_valid_index(value, 256))) { - Py_ssize_t n = Py_SIZE(bytearray); - if (likely(n != PY_SSIZE_T_MAX)) { - if (unlikely(PyByteArray_Resize(bytearray, n + 1) < 0)) - return -1; - PyByteArray_AS_STRING(bytearray)[n] = value; - return 0; - } - } else { - PyErr_SetString(PyExc_ValueError, "byte must be in range(0, 256)"); - return -1; - } -#endif - pyval = PyInt_FromLong(value); - if (unlikely(!pyval)) - return -1; - retval = __Pyx_PyObject_CallMethod1(bytearray, PYIDENT("append"), pyval); - Py_DECREF(pyval); - if (unlikely(!retval)) - return -1; - Py_DECREF(retval); - return 0; -} + Py_ssize_t n = Py_SIZE(bytearray); + if (likely(n != PY_SSIZE_T_MAX)) { + if (unlikely(PyByteArray_Resize(bytearray, n + 1) < 0)) + return -1; + PyByteArray_AS_STRING(bytearray)[n] = value; + return 0; + } + } else { + PyErr_SetString(PyExc_ValueError, "byte must be in range(0, 256)"); + return -1; + } +#endif + pyval = PyInt_FromLong(value); + if (unlikely(!pyval)) + return -1; + retval = __Pyx_PyObject_CallMethod1(bytearray, PYIDENT("append"), pyval); + Py_DECREF(pyval); + if (unlikely(!retval)) + return -1; + Py_DECREF(retval); + return 0; +} //////////////////// PyObjectFormat.proto //////////////////// diff --git a/contrib/tools/cython/Cython/Utility/TestCyUtilityLoader.pyx b/contrib/tools/cython/Cython/Utility/TestCyUtilityLoader.pyx index 00e7a7681b..4457e4b98f 100644 --- a/contrib/tools/cython/Cython/Utility/TestCyUtilityLoader.pyx +++ b/contrib/tools/cython/Cython/Utility/TestCyUtilityLoader.pyx @@ -1,8 +1,8 @@ -########## TestCyUtilityLoader ########## -#@requires: OtherUtility - -test {{cy_loader}} impl - - -########## OtherUtility ########## -req {{cy_loader}} impl +########## TestCyUtilityLoader ########## +#@requires: OtherUtility + +test {{cy_loader}} impl + + +########## OtherUtility ########## +req {{cy_loader}} impl diff --git a/contrib/tools/cython/Cython/Utility/TestCythonScope.pyx b/contrib/tools/cython/Cython/Utility/TestCythonScope.pyx index f585be2983..5cd582d227 100644 --- a/contrib/tools/cython/Cython/Utility/TestCythonScope.pyx +++ b/contrib/tools/cython/Cython/Utility/TestCythonScope.pyx @@ -1,64 +1,64 @@ -########## TestClass ########## -# These utilities are for testing purposes - -cdef extern from *: - cdef object __pyx_test_dep(object) - -@cname('__pyx_TestClass') -cdef class TestClass(object): - cdef public int value - - def __init__(self, int value): - self.value = value - - def __str__(self): - return 'TestClass(%d)' % self.value - - cdef cdef_method(self, int value): - print 'Hello from cdef_method', value - - cpdef cpdef_method(self, int value): - print 'Hello from cpdef_method', value - - def def_method(self, int value): - print 'Hello from def_method', value - - @cname('cdef_cname') - cdef cdef_cname_method(self, int value): - print "Hello from cdef_cname_method", value - - @cname('cpdef_cname') - cpdef cpdef_cname_method(self, int value): - print "Hello from cpdef_cname_method", value - - @cname('def_cname') - def def_cname_method(self, int value): - print "Hello from def_cname_method", value - -@cname('__pyx_test_call_other_cy_util') -cdef test_call(obj): - print 'test_call' - __pyx_test_dep(obj) - -@cname('__pyx_TestClass_New') -cdef _testclass_new(int value): - return TestClass(value) - -########### TestDep ########## - -@cname('__pyx_test_dep') -cdef test_dep(obj): - print 'test_dep', obj - -########## TestScope ########## - -@cname('__pyx_testscope') -cdef object _testscope(int value): - return "hello from cython scope, value=%d" % value - -########## View.TestScope ########## - -@cname('__pyx_view_testscope') -cdef object _testscope(int value): - return "hello from cython.view scope, value=%d" % value - +########## TestClass ########## +# These utilities are for testing purposes + +cdef extern from *: + cdef object __pyx_test_dep(object) + +@cname('__pyx_TestClass') +cdef class TestClass(object): + cdef public int value + + def __init__(self, int value): + self.value = value + + def __str__(self): + return 'TestClass(%d)' % self.value + + cdef cdef_method(self, int value): + print 'Hello from cdef_method', value + + cpdef cpdef_method(self, int value): + print 'Hello from cpdef_method', value + + def def_method(self, int value): + print 'Hello from def_method', value + + @cname('cdef_cname') + cdef cdef_cname_method(self, int value): + print "Hello from cdef_cname_method", value + + @cname('cpdef_cname') + cpdef cpdef_cname_method(self, int value): + print "Hello from cpdef_cname_method", value + + @cname('def_cname') + def def_cname_method(self, int value): + print "Hello from def_cname_method", value + +@cname('__pyx_test_call_other_cy_util') +cdef test_call(obj): + print 'test_call' + __pyx_test_dep(obj) + +@cname('__pyx_TestClass_New') +cdef _testclass_new(int value): + return TestClass(value) + +########### TestDep ########## + +@cname('__pyx_test_dep') +cdef test_dep(obj): + print 'test_dep', obj + +########## TestScope ########## + +@cname('__pyx_testscope') +cdef object _testscope(int value): + return "hello from cython scope, value=%d" % value + +########## View.TestScope ########## + +@cname('__pyx_view_testscope') +cdef object _testscope(int value): + return "hello from cython.view scope, value=%d" % value + diff --git a/contrib/tools/cython/Cython/Utility/TestUtilityLoader.c b/contrib/tools/cython/Cython/Utility/TestUtilityLoader.c index 595305f211..ca277f1d3b 100644 --- a/contrib/tools/cython/Cython/Utility/TestUtilityLoader.c +++ b/contrib/tools/cython/Cython/Utility/TestUtilityLoader.c @@ -1,12 +1,12 @@ -////////// TestUtilityLoader.proto ////////// -test {{loader}} prototype - -////////// TestUtilityLoader ////////// -//@requires: OtherUtility -test {{loader}} impl - -////////// OtherUtility.proto ////////// -req {{loader}} proto - -////////// OtherUtility ////////// -req {{loader}} impl +////////// TestUtilityLoader.proto ////////// +test {{loader}} prototype + +////////// TestUtilityLoader ////////// +//@requires: OtherUtility +test {{loader}} impl + +////////// OtherUtility.proto ////////// +req {{loader}} proto + +////////// OtherUtility ////////// +req {{loader}} impl diff --git a/contrib/tools/cython/Cython/Utility/TypeConversion.c b/contrib/tools/cython/Cython/Utility/TypeConversion.c index 7a7bf0f799..3ca4711b0a 100644 --- a/contrib/tools/cython/Cython/Utility/TypeConversion.c +++ b/contrib/tools/cython/Cython/Utility/TypeConversion.c @@ -1,21 +1,21 @@ -/////////////// TypeConversions.proto /////////////// - -/* Type Conversion Predeclarations */ - +/////////////// TypeConversions.proto /////////////// + +/* Type Conversion Predeclarations */ + #define __Pyx_uchar_cast(c) ((unsigned char)c) #define __Pyx_long_cast(x) ((long)x) -#define __Pyx_fits_Py_ssize_t(v, type, is_signed) ( \ - (sizeof(type) < sizeof(Py_ssize_t)) || \ - (sizeof(type) > sizeof(Py_ssize_t) && \ - likely(v < (type)PY_SSIZE_T_MAX || \ - v == (type)PY_SSIZE_T_MAX) && \ - (!is_signed || likely(v > (type)PY_SSIZE_T_MIN || \ - v == (type)PY_SSIZE_T_MIN))) || \ - (sizeof(type) == sizeof(Py_ssize_t) && \ - (is_signed || likely(v < (type)PY_SSIZE_T_MAX || \ - v == (type)PY_SSIZE_T_MAX))) ) - +#define __Pyx_fits_Py_ssize_t(v, type, is_signed) ( \ + (sizeof(type) < sizeof(Py_ssize_t)) || \ + (sizeof(type) > sizeof(Py_ssize_t) && \ + likely(v < (type)PY_SSIZE_T_MAX || \ + v == (type)PY_SSIZE_T_MAX) && \ + (!is_signed || likely(v > (type)PY_SSIZE_T_MIN || \ + v == (type)PY_SSIZE_T_MIN))) || \ + (sizeof(type) == sizeof(Py_ssize_t) && \ + (is_signed || likely(v < (type)PY_SSIZE_T_MAX || \ + v == (type)PY_SSIZE_T_MAX))) ) + static CYTHON_INLINE int __Pyx_is_valid_index(Py_ssize_t i, Py_ssize_t limit) { // Optimisation from Section 14.2 "Bounds Checking" in // https://www.agner.org/optimize/optimizing_cpp.pdf @@ -47,21 +47,21 @@ static CYTHON_INLINE int __Pyx_is_valid_index(Py_ssize_t i, Py_ssize_t limit) { static CYTHON_INLINE const char* __Pyx_PyObject_AsString(PyObject*); static CYTHON_INLINE const char* __Pyx_PyObject_AsStringAndSize(PyObject*, Py_ssize_t* length); - -#define __Pyx_PyByteArray_FromString(s) PyByteArray_FromStringAndSize((const char*)s, strlen((const char*)s)) -#define __Pyx_PyByteArray_FromStringAndSize(s, l) PyByteArray_FromStringAndSize((const char*)s, l) -#define __Pyx_PyBytes_FromString PyBytes_FromString -#define __Pyx_PyBytes_FromStringAndSize PyBytes_FromStringAndSize -static CYTHON_INLINE PyObject* __Pyx_PyUnicode_FromString(const char*); - -#if PY_MAJOR_VERSION < 3 - #define __Pyx_PyStr_FromString __Pyx_PyBytes_FromString - #define __Pyx_PyStr_FromStringAndSize __Pyx_PyBytes_FromStringAndSize -#else - #define __Pyx_PyStr_FromString __Pyx_PyUnicode_FromString - #define __Pyx_PyStr_FromStringAndSize __Pyx_PyUnicode_FromStringAndSize -#endif - + +#define __Pyx_PyByteArray_FromString(s) PyByteArray_FromStringAndSize((const char*)s, strlen((const char*)s)) +#define __Pyx_PyByteArray_FromStringAndSize(s, l) PyByteArray_FromStringAndSize((const char*)s, l) +#define __Pyx_PyBytes_FromString PyBytes_FromString +#define __Pyx_PyBytes_FromStringAndSize PyBytes_FromStringAndSize +static CYTHON_INLINE PyObject* __Pyx_PyUnicode_FromString(const char*); + +#if PY_MAJOR_VERSION < 3 + #define __Pyx_PyStr_FromString __Pyx_PyBytes_FromString + #define __Pyx_PyStr_FromStringAndSize __Pyx_PyBytes_FromStringAndSize +#else + #define __Pyx_PyStr_FromString __Pyx_PyUnicode_FromString + #define __Pyx_PyStr_FromStringAndSize __Pyx_PyUnicode_FromStringAndSize +#endif + #define __Pyx_PyBytes_AsWritableString(s) ((char*) PyBytes_AS_STRING(s)) #define __Pyx_PyBytes_AsWritableSString(s) ((signed char*) PyBytes_AS_STRING(s)) #define __Pyx_PyBytes_AsWritableUString(s) ((unsigned char*) PyBytes_AS_STRING(s)) @@ -78,39 +78,39 @@ static CYTHON_INLINE PyObject* __Pyx_PyUnicode_FromString(const char*); #define __Pyx_PyByteArray_FromCString(s) __Pyx_PyByteArray_FromString((const char*)s) #define __Pyx_PyStr_FromCString(s) __Pyx_PyStr_FromString((const char*)s) #define __Pyx_PyUnicode_FromCString(s) __Pyx_PyUnicode_FromString((const char*)s) - + // There used to be a Py_UNICODE_strlen() in CPython 3.x, but it is deprecated since Py3.3. static CYTHON_INLINE size_t __Pyx_Py_UNICODE_strlen(const Py_UNICODE *u) { - const Py_UNICODE *u_end = u; - while (*u_end++) ; - return (size_t)(u_end - u - 1); -} - -#define __Pyx_PyUnicode_FromUnicode(u) PyUnicode_FromUnicode(u, __Pyx_Py_UNICODE_strlen(u)) -#define __Pyx_PyUnicode_FromUnicodeAndLength PyUnicode_FromUnicode -#define __Pyx_PyUnicode_AsUnicode PyUnicode_AsUnicode - + const Py_UNICODE *u_end = u; + while (*u_end++) ; + return (size_t)(u_end - u - 1); +} + +#define __Pyx_PyUnicode_FromUnicode(u) PyUnicode_FromUnicode(u, __Pyx_Py_UNICODE_strlen(u)) +#define __Pyx_PyUnicode_FromUnicodeAndLength PyUnicode_FromUnicode +#define __Pyx_PyUnicode_AsUnicode PyUnicode_AsUnicode + #define __Pyx_NewRef(obj) (Py_INCREF(obj), obj) #define __Pyx_Owned_Py_None(b) __Pyx_NewRef(Py_None) static CYTHON_INLINE PyObject * __Pyx_PyBool_FromLong(long b); -static CYTHON_INLINE int __Pyx_PyObject_IsTrue(PyObject*); +static CYTHON_INLINE int __Pyx_PyObject_IsTrue(PyObject*); static CYTHON_INLINE int __Pyx_PyObject_IsTrueAndDecref(PyObject*); static CYTHON_INLINE PyObject* __Pyx_PyNumber_IntOrLong(PyObject* x); - + #define __Pyx_PySequence_Tuple(obj) \ (likely(PyTuple_CheckExact(obj)) ? __Pyx_NewRef(obj) : PySequence_Tuple(obj)) -static CYTHON_INLINE Py_ssize_t __Pyx_PyIndex_AsSsize_t(PyObject*); -static CYTHON_INLINE PyObject * __Pyx_PyInt_FromSize_t(size_t); +static CYTHON_INLINE Py_ssize_t __Pyx_PyIndex_AsSsize_t(PyObject*); +static CYTHON_INLINE PyObject * __Pyx_PyInt_FromSize_t(size_t); static CYTHON_INLINE Py_hash_t __Pyx_PyIndex_AsHash_t(PyObject*); - + #if CYTHON_ASSUME_SAFE_MACROS -#define __pyx_PyFloat_AsDouble(x) (PyFloat_CheckExact(x) ? PyFloat_AS_DOUBLE(x) : PyFloat_AsDouble(x)) -#else -#define __pyx_PyFloat_AsDouble(x) PyFloat_AsDouble(x) -#endif -#define __pyx_PyFloat_AsFloat(x) ((float) __pyx_PyFloat_AsDouble(x)) - +#define __pyx_PyFloat_AsDouble(x) (PyFloat_CheckExact(x) ? PyFloat_AS_DOUBLE(x) : PyFloat_AsDouble(x)) +#else +#define __pyx_PyFloat_AsDouble(x) PyFloat_AsDouble(x) +#endif +#define __pyx_PyFloat_AsFloat(x) ((float) __pyx_PyFloat_AsDouble(x)) + #if PY_MAJOR_VERSION >= 3 #define __Pyx_PyNumber_Int(x) (PyLong_CheckExact(x) ? __Pyx_NewRef(x) : PyNumber_Long(x)) #else @@ -118,101 +118,101 @@ static CYTHON_INLINE Py_hash_t __Pyx_PyIndex_AsHash_t(PyObject*); #endif #define __Pyx_PyNumber_Float(x) (PyFloat_CheckExact(x) ? __Pyx_NewRef(x) : PyNumber_Float(x)) -#if PY_MAJOR_VERSION < 3 && __PYX_DEFAULT_STRING_ENCODING_IS_ASCII -static int __Pyx_sys_getdefaultencoding_not_ascii; -static int __Pyx_init_sys_getdefaultencoding_params(void) { - PyObject* sys; - PyObject* default_encoding = NULL; - PyObject* ascii_chars_u = NULL; - PyObject* ascii_chars_b = NULL; - const char* default_encoding_c; - sys = PyImport_ImportModule("sys"); - if (!sys) goto bad; +#if PY_MAJOR_VERSION < 3 && __PYX_DEFAULT_STRING_ENCODING_IS_ASCII +static int __Pyx_sys_getdefaultencoding_not_ascii; +static int __Pyx_init_sys_getdefaultencoding_params(void) { + PyObject* sys; + PyObject* default_encoding = NULL; + PyObject* ascii_chars_u = NULL; + PyObject* ascii_chars_b = NULL; + const char* default_encoding_c; + sys = PyImport_ImportModule("sys"); + if (!sys) goto bad; default_encoding = PyObject_CallMethod(sys, (char*) "getdefaultencoding", NULL); - Py_DECREF(sys); - if (!default_encoding) goto bad; - default_encoding_c = PyBytes_AsString(default_encoding); - if (!default_encoding_c) goto bad; - if (strcmp(default_encoding_c, "ascii") == 0) { - __Pyx_sys_getdefaultencoding_not_ascii = 0; - } else { - char ascii_chars[128]; - int c; - for (c = 0; c < 128; c++) { - ascii_chars[c] = c; - } - __Pyx_sys_getdefaultencoding_not_ascii = 1; - ascii_chars_u = PyUnicode_DecodeASCII(ascii_chars, 128, NULL); - if (!ascii_chars_u) goto bad; - ascii_chars_b = PyUnicode_AsEncodedString(ascii_chars_u, default_encoding_c, NULL); - if (!ascii_chars_b || !PyBytes_Check(ascii_chars_b) || memcmp(ascii_chars, PyBytes_AS_STRING(ascii_chars_b), 128) != 0) { - PyErr_Format( - PyExc_ValueError, - "This module compiled with c_string_encoding=ascii, but default encoding '%.200s' is not a superset of ascii.", - default_encoding_c); - goto bad; - } - Py_DECREF(ascii_chars_u); - Py_DECREF(ascii_chars_b); - } - Py_DECREF(default_encoding); - return 0; -bad: - Py_XDECREF(default_encoding); - Py_XDECREF(ascii_chars_u); - Py_XDECREF(ascii_chars_b); - return -1; -} -#endif - -#if __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT && PY_MAJOR_VERSION >= 3 -#define __Pyx_PyUnicode_FromStringAndSize(c_str, size) PyUnicode_DecodeUTF8(c_str, size, NULL) -#else -#define __Pyx_PyUnicode_FromStringAndSize(c_str, size) PyUnicode_Decode(c_str, size, __PYX_DEFAULT_STRING_ENCODING, NULL) - -// __PYX_DEFAULT_STRING_ENCODING is either a user provided string constant -// or we need to look it up here -#if __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT -static char* __PYX_DEFAULT_STRING_ENCODING; - -static int __Pyx_init_sys_getdefaultencoding_params(void) { - PyObject* sys; - PyObject* default_encoding = NULL; - char* default_encoding_c; - - sys = PyImport_ImportModule("sys"); - if (!sys) goto bad; - default_encoding = PyObject_CallMethod(sys, (char*) (const char*) "getdefaultencoding", NULL); - Py_DECREF(sys); - if (!default_encoding) goto bad; - default_encoding_c = PyBytes_AsString(default_encoding); - if (!default_encoding_c) goto bad; + Py_DECREF(sys); + if (!default_encoding) goto bad; + default_encoding_c = PyBytes_AsString(default_encoding); + if (!default_encoding_c) goto bad; + if (strcmp(default_encoding_c, "ascii") == 0) { + __Pyx_sys_getdefaultencoding_not_ascii = 0; + } else { + char ascii_chars[128]; + int c; + for (c = 0; c < 128; c++) { + ascii_chars[c] = c; + } + __Pyx_sys_getdefaultencoding_not_ascii = 1; + ascii_chars_u = PyUnicode_DecodeASCII(ascii_chars, 128, NULL); + if (!ascii_chars_u) goto bad; + ascii_chars_b = PyUnicode_AsEncodedString(ascii_chars_u, default_encoding_c, NULL); + if (!ascii_chars_b || !PyBytes_Check(ascii_chars_b) || memcmp(ascii_chars, PyBytes_AS_STRING(ascii_chars_b), 128) != 0) { + PyErr_Format( + PyExc_ValueError, + "This module compiled with c_string_encoding=ascii, but default encoding '%.200s' is not a superset of ascii.", + default_encoding_c); + goto bad; + } + Py_DECREF(ascii_chars_u); + Py_DECREF(ascii_chars_b); + } + Py_DECREF(default_encoding); + return 0; +bad: + Py_XDECREF(default_encoding); + Py_XDECREF(ascii_chars_u); + Py_XDECREF(ascii_chars_b); + return -1; +} +#endif + +#if __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT && PY_MAJOR_VERSION >= 3 +#define __Pyx_PyUnicode_FromStringAndSize(c_str, size) PyUnicode_DecodeUTF8(c_str, size, NULL) +#else +#define __Pyx_PyUnicode_FromStringAndSize(c_str, size) PyUnicode_Decode(c_str, size, __PYX_DEFAULT_STRING_ENCODING, NULL) + +// __PYX_DEFAULT_STRING_ENCODING is either a user provided string constant +// or we need to look it up here +#if __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT +static char* __PYX_DEFAULT_STRING_ENCODING; + +static int __Pyx_init_sys_getdefaultencoding_params(void) { + PyObject* sys; + PyObject* default_encoding = NULL; + char* default_encoding_c; + + sys = PyImport_ImportModule("sys"); + if (!sys) goto bad; + default_encoding = PyObject_CallMethod(sys, (char*) (const char*) "getdefaultencoding", NULL); + Py_DECREF(sys); + if (!default_encoding) goto bad; + default_encoding_c = PyBytes_AsString(default_encoding); + if (!default_encoding_c) goto bad; __PYX_DEFAULT_STRING_ENCODING = (char*) malloc(strlen(default_encoding_c) + 1); - if (!__PYX_DEFAULT_STRING_ENCODING) goto bad; - strcpy(__PYX_DEFAULT_STRING_ENCODING, default_encoding_c); - Py_DECREF(default_encoding); - return 0; -bad: - Py_XDECREF(default_encoding); - return -1; -} -#endif -#endif - -/////////////// TypeConversions /////////////// - -/* Type Conversion Functions */ - -static CYTHON_INLINE PyObject* __Pyx_PyUnicode_FromString(const char* c_str) { - return __Pyx_PyUnicode_FromStringAndSize(c_str, (Py_ssize_t)strlen(c_str)); -} - + if (!__PYX_DEFAULT_STRING_ENCODING) goto bad; + strcpy(__PYX_DEFAULT_STRING_ENCODING, default_encoding_c); + Py_DECREF(default_encoding); + return 0; +bad: + Py_XDECREF(default_encoding); + return -1; +} +#endif +#endif + +/////////////// TypeConversions /////////////// + +/* Type Conversion Functions */ + +static CYTHON_INLINE PyObject* __Pyx_PyUnicode_FromString(const char* c_str) { + return __Pyx_PyUnicode_FromStringAndSize(c_str, (Py_ssize_t)strlen(c_str)); +} + // Py3.7 returns a "const char*" for unicode strings static CYTHON_INLINE const char* __Pyx_PyObject_AsString(PyObject* o) { - Py_ssize_t ignore; - return __Pyx_PyObject_AsStringAndSize(o, &ignore); -} - + Py_ssize_t ignore; + return __Pyx_PyObject_AsStringAndSize(o, &ignore); +} + #if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII || __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT #if !CYTHON_PEP393_ENABLED static const char* __Pyx_PyUnicode_AsStringAndSize(PyObject* o, Py_ssize_t *length) { @@ -221,7 +221,7 @@ static const char* __Pyx_PyUnicode_AsStringAndSize(PyObject* o, Py_ssize_t *leng PyObject* defenc = _PyUnicode_AsDefaultEncodedString(o, NULL); if (!defenc) return NULL; defenc_c = PyBytes_AS_STRING(defenc); -#if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII +#if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII { char* end = defenc_c + PyBytes_GET_SIZE(defenc); char* c; @@ -230,10 +230,10 @@ static const char* __Pyx_PyUnicode_AsStringAndSize(PyObject* o, Py_ssize_t *leng // raise the error PyUnicode_AsASCIIString(o); return NULL; - } - } + } + } } -#endif /*__PYX_DEFAULT_STRING_ENCODING_IS_ASCII*/ +#endif /*__PYX_DEFAULT_STRING_ENCODING_IS_ASCII*/ *length = PyBytes_GET_SIZE(defenc); return defenc_c; } @@ -242,7 +242,7 @@ static const char* __Pyx_PyUnicode_AsStringAndSize(PyObject* o, Py_ssize_t *leng static CYTHON_INLINE const char* __Pyx_PyUnicode_AsStringAndSize(PyObject* o, Py_ssize_t *length) { if (unlikely(__Pyx_PyUnicode_READY(o) == -1)) return NULL; -#if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII +#if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII if (likely(PyUnicode_IS_ASCII(o))) { // cached for the lifetime of the object *length = PyUnicode_GET_LENGTH(o); @@ -252,9 +252,9 @@ static CYTHON_INLINE const char* __Pyx_PyUnicode_AsStringAndSize(PyObject* o, Py PyUnicode_AsASCIIString(o); return NULL; } -#else /* __PYX_DEFAULT_STRING_ENCODING_IS_ASCII */ +#else /* __PYX_DEFAULT_STRING_ENCODING_IS_ASCII */ return PyUnicode_AsUTF8AndSize(o, length); -#endif /* __PYX_DEFAULT_STRING_ENCODING_IS_ASCII */ +#endif /* __PYX_DEFAULT_STRING_ENCODING_IS_ASCII */ } #endif /* CYTHON_PEP393_ENABLED */ #endif @@ -268,33 +268,33 @@ static CYTHON_INLINE const char* __Pyx_PyObject_AsStringAndSize(PyObject* o, Py_ #endif PyUnicode_Check(o)) { return __Pyx_PyUnicode_AsStringAndSize(o, length); - } else -#endif /* __PYX_DEFAULT_STRING_ENCODING_IS_ASCII || __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT */ - + } else +#endif /* __PYX_DEFAULT_STRING_ENCODING_IS_ASCII || __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT */ + #if (!CYTHON_COMPILING_IN_PYPY) || (defined(PyByteArray_AS_STRING) && defined(PyByteArray_GET_SIZE)) - if (PyByteArray_Check(o)) { - *length = PyByteArray_GET_SIZE(o); - return PyByteArray_AS_STRING(o); - } else -#endif - { - char* result; - int r = PyBytes_AsStringAndSize(o, &result, length); - if (unlikely(r < 0)) { - return NULL; - } else { - return result; - } - } -} - -/* Note: __Pyx_PyObject_IsTrue is written to minimize branching. */ -static CYTHON_INLINE int __Pyx_PyObject_IsTrue(PyObject* x) { - int is_true = x == Py_True; - if (is_true | (x == Py_False) | (x == Py_None)) return is_true; - else return PyObject_IsTrue(x); -} - + if (PyByteArray_Check(o)) { + *length = PyByteArray_GET_SIZE(o); + return PyByteArray_AS_STRING(o); + } else +#endif + { + char* result; + int r = PyBytes_AsStringAndSize(o, &result, length); + if (unlikely(r < 0)) { + return NULL; + } else { + return result; + } + } +} + +/* Note: __Pyx_PyObject_IsTrue is written to minimize branching. */ +static CYTHON_INLINE int __Pyx_PyObject_IsTrue(PyObject* x) { + int is_true = x == Py_True; + if (is_true | (x == Py_False) | (x == Py_None)) return is_true; + else return PyObject_IsTrue(x); +} + static CYTHON_INLINE int __Pyx_PyObject_IsTrueAndDecref(PyObject* x) { int retval; if (unlikely(!x)) return -1; @@ -327,68 +327,68 @@ static PyObject* __Pyx_PyNumber_IntOrLongWrongResultType(PyObject* result, const static CYTHON_INLINE PyObject* __Pyx_PyNumber_IntOrLong(PyObject* x) { #if CYTHON_USE_TYPE_SLOTS - PyNumberMethods *m; + PyNumberMethods *m; #endif - const char *name = NULL; - PyObject *res = NULL; -#if PY_MAJOR_VERSION < 3 + const char *name = NULL; + PyObject *res = NULL; +#if PY_MAJOR_VERSION < 3 if (likely(PyInt_Check(x) || PyLong_Check(x))) -#else +#else if (likely(PyLong_Check(x))) -#endif +#endif return __Pyx_NewRef(x); #if CYTHON_USE_TYPE_SLOTS - m = Py_TYPE(x)->tp_as_number; + m = Py_TYPE(x)->tp_as_number; #if PY_MAJOR_VERSION < 3 - if (m && m->nb_int) { - name = "int"; + if (m && m->nb_int) { + name = "int"; res = m->nb_int(x); - } - else if (m && m->nb_long) { - name = "long"; + } + else if (m && m->nb_long) { + name = "long"; res = m->nb_long(x); - } + } #else if (likely(m && m->nb_int)) { - name = "int"; + name = "int"; res = m->nb_int(x); - } + } #endif #else if (!PyBytes_CheckExact(x) && !PyUnicode_CheckExact(x)) { res = PyNumber_Int(x); } -#endif +#endif if (likely(res)) { -#if PY_MAJOR_VERSION < 3 +#if PY_MAJOR_VERSION < 3 if (unlikely(!PyInt_Check(res) && !PyLong_Check(res))) { -#else +#else if (unlikely(!PyLong_CheckExact(res))) { -#endif +#endif return __Pyx_PyNumber_IntOrLongWrongResultType(res, name); - } - } - else if (!PyErr_Occurred()) { - PyErr_SetString(PyExc_TypeError, - "an integer is required"); - } - return res; -} - + } + } + else if (!PyErr_Occurred()) { + PyErr_SetString(PyExc_TypeError, + "an integer is required"); + } + return res; +} + {{py: from Cython.Utility import pylong_join }} -static CYTHON_INLINE Py_ssize_t __Pyx_PyIndex_AsSsize_t(PyObject* b) { - Py_ssize_t ival; - PyObject *x; -#if PY_MAJOR_VERSION < 3 +static CYTHON_INLINE Py_ssize_t __Pyx_PyIndex_AsSsize_t(PyObject* b) { + Py_ssize_t ival; + PyObject *x; +#if PY_MAJOR_VERSION < 3 if (likely(PyInt_CheckExact(b))) { if (sizeof(Py_ssize_t) >= sizeof(long)) return PyInt_AS_LONG(b); else return PyInt_AsSsize_t(b); } -#endif - if (likely(PyLong_CheckExact(b))) { +#endif + if (likely(PyLong_CheckExact(b))) { #if CYTHON_USE_PYLONG_INTERNALS const digit* digits = ((PyLongObject*)b)->ob_digit; const Py_ssize_t size = Py_SIZE(b); @@ -410,16 +410,16 @@ static CYTHON_INLINE Py_ssize_t __Pyx_PyIndex_AsSsize_t(PyObject* b) { {{endfor}} } } - #endif - return PyLong_AsSsize_t(b); - } - x = PyNumber_Index(b); - if (!x) return -1; - ival = PyInt_AsSsize_t(x); - Py_DECREF(x); - return ival; -} - + #endif + return PyLong_AsSsize_t(b); + } + x = PyNumber_Index(b); + if (!x) return -1; + ival = PyInt_AsSsize_t(x); + Py_DECREF(x); + return ival; +} + static CYTHON_INLINE Py_hash_t __Pyx_PyIndex_AsHash_t(PyObject* o) { if (sizeof(Py_hash_t) == sizeof(Py_ssize_t)) { @@ -445,11 +445,11 @@ static CYTHON_INLINE PyObject * __Pyx_PyBool_FromLong(long b) { } -static CYTHON_INLINE PyObject * __Pyx_PyInt_FromSize_t(size_t ival) { - return PyInt_FromSize_t(ival); -} - - +static CYTHON_INLINE PyObject * __Pyx_PyInt_FromSize_t(size_t ival) { + return PyInt_FromSize_t(ival); +} + + /////////////// GCCDiagnostics.proto /////////////// // GCC diagnostic pragmas were introduced in GCC 4.6 @@ -484,23 +484,23 @@ bad: /////////////// FromPyCTupleUtility.proto /////////////// -static {{struct_type_decl}} {{funcname}}(PyObject *); - +static {{struct_type_decl}} {{funcname}}(PyObject *); + /////////////// FromPyCTupleUtility /////////////// -static {{struct_type_decl}} {{funcname}}(PyObject * o) { - {{struct_type_decl}} result; - +static {{struct_type_decl}} {{funcname}}(PyObject * o) { + {{struct_type_decl}} result; + if (!PyTuple_Check(o) || PyTuple_GET_SIZE(o) != {{size}}) { PyErr_Format(PyExc_TypeError, "Expected %.16s of size %d, got %.200s", "a tuple", {{size}}, Py_TYPE(o)->tp_name); - goto bad; - } - + goto bad; + } + #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS {{for ix, component in enumerate(components):}} {{py:attr = "result.f%s" % ix}} {{attr}} = {{component.from_py_function}}(PyTuple_GET_ITEM(o, {{ix}})); if ({{component.error_condition(attr)}}) goto bad; - {{endfor}} + {{endfor}} #else { PyObject *item; @@ -513,12 +513,12 @@ static {{struct_type_decl}} {{funcname}}(PyObject * o) { {{endfor}} } #endif - - return result; -bad: - return result; -} - + + return result; +bad: + return result; +} + /////////////// UnicodeAsUCS4.proto /////////////// @@ -557,24 +557,24 @@ static CYTHON_INLINE Py_UCS4 __Pyx_PyUnicode_AsPy_UCS4(PyObject* x) { } -/////////////// ObjectAsUCS4.proto /////////////// +/////////////// ObjectAsUCS4.proto /////////////// //@requires: UnicodeAsUCS4 - + #define __Pyx_PyObject_AsPy_UCS4(x) \ (likely(PyUnicode_Check(x)) ? __Pyx_PyUnicode_AsPy_UCS4(x) : __Pyx__PyObject_AsPy_UCS4(x)) static Py_UCS4 __Pyx__PyObject_AsPy_UCS4(PyObject*); - -/////////////// ObjectAsUCS4 /////////////// - + +/////////////// ObjectAsUCS4 /////////////// + static Py_UCS4 __Pyx__PyObject_AsPy_UCS4_raise_error(long ival) { if (ival < 0) { - if (!PyErr_Occurred()) - PyErr_SetString(PyExc_OverflowError, - "cannot convert negative value to Py_UCS4"); + if (!PyErr_Occurred()) + PyErr_SetString(PyExc_OverflowError, + "cannot convert negative value to Py_UCS4"); } else { - PyErr_SetString(PyExc_OverflowError, - "value too large to convert to Py_UCS4"); - } + PyErr_SetString(PyExc_OverflowError, + "value too large to convert to Py_UCS4"); + } return (Py_UCS4)-1; } @@ -584,46 +584,46 @@ static Py_UCS4 __Pyx__PyObject_AsPy_UCS4(PyObject* x) { if (unlikely(!__Pyx_is_valid_index(ival, 1114111 + 1))) { return __Pyx__PyObject_AsPy_UCS4_raise_error(ival); } - return (Py_UCS4)ival; -} - - -/////////////// ObjectAsPyUnicode.proto /////////////// - -static CYTHON_INLINE Py_UNICODE __Pyx_PyObject_AsPy_UNICODE(PyObject*); - -/////////////// ObjectAsPyUnicode /////////////// - -static CYTHON_INLINE Py_UNICODE __Pyx_PyObject_AsPy_UNICODE(PyObject* x) { - long ival; - #if CYTHON_PEP393_ENABLED - #if Py_UNICODE_SIZE > 2 - const long maxval = 1114111; - #else - const long maxval = 65535; - #endif - #else - static long maxval = 0; - #endif - if (PyUnicode_Check(x)) { - if (unlikely(__Pyx_PyUnicode_GET_LENGTH(x) != 1)) { - PyErr_Format(PyExc_ValueError, - "only single character unicode strings can be converted to Py_UNICODE, " - "got length %" CYTHON_FORMAT_SSIZE_T "d", __Pyx_PyUnicode_GET_LENGTH(x)); - return (Py_UNICODE)-1; - } - #if CYTHON_PEP393_ENABLED - ival = PyUnicode_READ_CHAR(x, 0); - #else - return PyUnicode_AS_UNICODE(x)[0]; - #endif - } else { - #if !CYTHON_PEP393_ENABLED - if (unlikely(!maxval)) - maxval = (long)PyUnicode_GetMax(); - #endif - ival = __Pyx_PyInt_As_long(x); - } + return (Py_UCS4)ival; +} + + +/////////////// ObjectAsPyUnicode.proto /////////////// + +static CYTHON_INLINE Py_UNICODE __Pyx_PyObject_AsPy_UNICODE(PyObject*); + +/////////////// ObjectAsPyUnicode /////////////// + +static CYTHON_INLINE Py_UNICODE __Pyx_PyObject_AsPy_UNICODE(PyObject* x) { + long ival; + #if CYTHON_PEP393_ENABLED + #if Py_UNICODE_SIZE > 2 + const long maxval = 1114111; + #else + const long maxval = 65535; + #endif + #else + static long maxval = 0; + #endif + if (PyUnicode_Check(x)) { + if (unlikely(__Pyx_PyUnicode_GET_LENGTH(x) != 1)) { + PyErr_Format(PyExc_ValueError, + "only single character unicode strings can be converted to Py_UNICODE, " + "got length %" CYTHON_FORMAT_SSIZE_T "d", __Pyx_PyUnicode_GET_LENGTH(x)); + return (Py_UNICODE)-1; + } + #if CYTHON_PEP393_ENABLED + ival = PyUnicode_READ_CHAR(x, 0); + #else + return PyUnicode_AS_UNICODE(x)[0]; + #endif + } else { + #if !CYTHON_PEP393_ENABLED + if (unlikely(!maxval)) + maxval = (long)PyUnicode_GetMax(); + #endif + ival = __Pyx_PyInt_As_long(x); + } if (unlikely(!__Pyx_is_valid_index(ival, maxval + 1))) { if (ival < 0) { if (!PyErr_Occurred()) @@ -631,23 +631,23 @@ static CYTHON_INLINE Py_UNICODE __Pyx_PyObject_AsPy_UNICODE(PyObject* x) { "cannot convert negative value to Py_UNICODE"); return (Py_UNICODE)-1; } else { - PyErr_SetString(PyExc_OverflowError, + PyErr_SetString(PyExc_OverflowError, "value too large to convert to Py_UNICODE"); } - return (Py_UNICODE)-1; - } - return (Py_UNICODE)ival; -} - - -/////////////// CIntToPy.proto /////////////// - -static CYTHON_INLINE PyObject* {{TO_PY_FUNCTION}}({{TYPE}} value); - -/////////////// CIntToPy /////////////// + return (Py_UNICODE)-1; + } + return (Py_UNICODE)ival; +} + + +/////////////// CIntToPy.proto /////////////// + +static CYTHON_INLINE PyObject* {{TO_PY_FUNCTION}}({{TYPE}} value); + +/////////////// CIntToPy /////////////// //@requires: GCCDiagnostics - -static CYTHON_INLINE PyObject* {{TO_PY_FUNCTION}}({{TYPE}} value) { + +static CYTHON_INLINE PyObject* {{TO_PY_FUNCTION}}({{TYPE}} value) { #ifdef __Pyx_HAS_GCC_DIAGNOSTIC #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wconversion" @@ -656,35 +656,35 @@ static CYTHON_INLINE PyObject* {{TO_PY_FUNCTION}}({{TYPE}} value) { #ifdef __Pyx_HAS_GCC_DIAGNOSTIC #pragma GCC diagnostic pop #endif - const int is_unsigned = neg_one > const_zero; - if (is_unsigned) { - if (sizeof({{TYPE}}) < sizeof(long)) { - return PyInt_FromLong((long) value); - } else if (sizeof({{TYPE}}) <= sizeof(unsigned long)) { - return PyLong_FromUnsignedLong((unsigned long) value); + const int is_unsigned = neg_one > const_zero; + if (is_unsigned) { + if (sizeof({{TYPE}}) < sizeof(long)) { + return PyInt_FromLong((long) value); + } else if (sizeof({{TYPE}}) <= sizeof(unsigned long)) { + return PyLong_FromUnsignedLong((unsigned long) value); #ifdef HAVE_LONG_LONG } else if (sizeof({{TYPE}}) <= sizeof(unsigned PY_LONG_LONG)) { return PyLong_FromUnsignedLongLong((unsigned PY_LONG_LONG) value); #endif - } - } else { - if (sizeof({{TYPE}}) <= sizeof(long)) { - return PyInt_FromLong((long) value); + } + } else { + if (sizeof({{TYPE}}) <= sizeof(long)) { + return PyInt_FromLong((long) value); #ifdef HAVE_LONG_LONG } else if (sizeof({{TYPE}}) <= sizeof(PY_LONG_LONG)) { return PyLong_FromLongLong((PY_LONG_LONG) value); #endif - } - } - { - int one = 1; int little = (int)*(unsigned char *)&one; - unsigned char *bytes = (unsigned char *)&value; - return _PyLong_FromByteArray(bytes, sizeof({{TYPE}}), - little, !is_unsigned); - } -} - - + } + } + { + int one = 1; int little = (int)*(unsigned char *)&one; + unsigned char *bytes = (unsigned char *)&value; + return _PyLong_FromByteArray(bytes, sizeof({{TYPE}}), + little, !is_unsigned); + } +} + + /////////////// CIntToDigits /////////////// static const char DIGIT_PAIRS_10[2*10*10+1] = { @@ -837,44 +837,44 @@ static CYTHON_INLINE PyObject* __Pyx_PyInt_FromDouble(double value) { #endif -/////////////// CIntFromPyVerify /////////////// - -// see CIntFromPy -#define __PYX_VERIFY_RETURN_INT(target_type, func_type, func_value) \ +/////////////// CIntFromPyVerify /////////////// + +// see CIntFromPy +#define __PYX_VERIFY_RETURN_INT(target_type, func_type, func_value) \ __PYX__VERIFY_RETURN_INT(target_type, func_type, func_value, 0) #define __PYX_VERIFY_RETURN_INT_EXC(target_type, func_type, func_value) \ __PYX__VERIFY_RETURN_INT(target_type, func_type, func_value, 1) #define __PYX__VERIFY_RETURN_INT(target_type, func_type, func_value, exc) \ - { \ - func_type value = func_value; \ - if (sizeof(target_type) < sizeof(func_type)) { \ - if (unlikely(value != (func_type) (target_type) value)) { \ - func_type zero = 0; \ + { \ + func_type value = func_value; \ + if (sizeof(target_type) < sizeof(func_type)) { \ + if (unlikely(value != (func_type) (target_type) value)) { \ + func_type zero = 0; \ if (exc && unlikely(value == (func_type)-1 && PyErr_Occurred())) \ return (target_type) -1; \ - if (is_unsigned && unlikely(value < zero)) \ - goto raise_neg_overflow; \ - else \ - goto raise_overflow; \ - } \ - } \ - return (target_type) value; \ - } - - -/////////////// CIntFromPy.proto /////////////// - -static CYTHON_INLINE {{TYPE}} {{FROM_PY_FUNCTION}}(PyObject *); - -/////////////// CIntFromPy /////////////// -//@requires: CIntFromPyVerify + if (is_unsigned && unlikely(value < zero)) \ + goto raise_neg_overflow; \ + else \ + goto raise_overflow; \ + } \ + } \ + return (target_type) value; \ + } + + +/////////////// CIntFromPy.proto /////////////// + +static CYTHON_INLINE {{TYPE}} {{FROM_PY_FUNCTION}}(PyObject *); + +/////////////// CIntFromPy /////////////// +//@requires: CIntFromPyVerify //@requires: GCCDiagnostics - + {{py: from Cython.Utility import pylong_join }} -static CYTHON_INLINE {{TYPE}} {{FROM_PY_FUNCTION}}(PyObject *x) { +static CYTHON_INLINE {{TYPE}} {{FROM_PY_FUNCTION}}(PyObject *x) { #ifdef __Pyx_HAS_GCC_DIAGNOSTIC #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wconversion" @@ -883,25 +883,25 @@ static CYTHON_INLINE {{TYPE}} {{FROM_PY_FUNCTION}}(PyObject *x) { #ifdef __Pyx_HAS_GCC_DIAGNOSTIC #pragma GCC diagnostic pop #endif - const int is_unsigned = neg_one > const_zero; -#if PY_MAJOR_VERSION < 3 - if (likely(PyInt_Check(x))) { - if (sizeof({{TYPE}}) < sizeof(long)) { - __PYX_VERIFY_RETURN_INT({{TYPE}}, long, PyInt_AS_LONG(x)) - } else { - long val = PyInt_AS_LONG(x); - if (is_unsigned && unlikely(val < 0)) { - goto raise_neg_overflow; - } - return ({{TYPE}}) val; - } - } else -#endif - if (likely(PyLong_Check(x))) { - if (is_unsigned) { + const int is_unsigned = neg_one > const_zero; +#if PY_MAJOR_VERSION < 3 + if (likely(PyInt_Check(x))) { + if (sizeof({{TYPE}}) < sizeof(long)) { + __PYX_VERIFY_RETURN_INT({{TYPE}}, long, PyInt_AS_LONG(x)) + } else { + long val = PyInt_AS_LONG(x); + if (is_unsigned && unlikely(val < 0)) { + goto raise_neg_overflow; + } + return ({{TYPE}}) val; + } + } else +#endif + if (likely(PyLong_Check(x))) { + if (is_unsigned) { #if CYTHON_USE_PYLONG_INTERNALS const digit* digits = ((PyLongObject*)x)->ob_digit; - switch (Py_SIZE(x)) { + switch (Py_SIZE(x)) { case 0: return ({{TYPE}}) 0; case 1: __PYX_VERIFY_RETURN_INT({{TYPE}}, digit, digits[0]) {{for _size in (2, 3, 4)}} @@ -915,12 +915,12 @@ static CYTHON_INLINE {{TYPE}} {{FROM_PY_FUNCTION}}(PyObject *x) { } break; {{endfor}} - } -#endif + } +#endif #if CYTHON_COMPILING_IN_CPYTHON - if (unlikely(Py_SIZE(x) < 0)) { - goto raise_neg_overflow; - } + if (unlikely(Py_SIZE(x) < 0)) { + goto raise_neg_overflow; + } #else { // misuse Py_False as a quick way to compare to a '0' int object in PyPy @@ -931,18 +931,18 @@ static CYTHON_INLINE {{TYPE}} {{FROM_PY_FUNCTION}}(PyObject *x) { goto raise_neg_overflow; } #endif - if (sizeof({{TYPE}}) <= sizeof(unsigned long)) { + if (sizeof({{TYPE}}) <= sizeof(unsigned long)) { __PYX_VERIFY_RETURN_INT_EXC({{TYPE}}, unsigned long, PyLong_AsUnsignedLong(x)) #ifdef HAVE_LONG_LONG } else if (sizeof({{TYPE}}) <= sizeof(unsigned PY_LONG_LONG)) { __PYX_VERIFY_RETURN_INT_EXC({{TYPE}}, unsigned PY_LONG_LONG, PyLong_AsUnsignedLongLong(x)) #endif - } - } else { + } + } else { // signed #if CYTHON_USE_PYLONG_INTERNALS const digit* digits = ((PyLongObject*)x)->ob_digit; - switch (Py_SIZE(x)) { + switch (Py_SIZE(x)) { case 0: return ({{TYPE}}) 0; case -1: __PYX_VERIFY_RETURN_INT({{TYPE}}, sdigit, (sdigit) (-(sdigit)digits[0])) case 1: __PYX_VERIFY_RETURN_INT({{TYPE}}, digit, +digits[0]) @@ -959,59 +959,59 @@ static CYTHON_INLINE {{TYPE}} {{FROM_PY_FUNCTION}}(PyObject *x) { break; {{endfor}} {{endfor}} - } -#endif - if (sizeof({{TYPE}}) <= sizeof(long)) { + } +#endif + if (sizeof({{TYPE}}) <= sizeof(long)) { __PYX_VERIFY_RETURN_INT_EXC({{TYPE}}, long, PyLong_AsLong(x)) #ifdef HAVE_LONG_LONG } else if (sizeof({{TYPE}}) <= sizeof(PY_LONG_LONG)) { __PYX_VERIFY_RETURN_INT_EXC({{TYPE}}, PY_LONG_LONG, PyLong_AsLongLong(x)) #endif - } - } - { -#if CYTHON_COMPILING_IN_PYPY && !defined(_PyLong_AsByteArray) - PyErr_SetString(PyExc_RuntimeError, - "_PyLong_AsByteArray() not available in PyPy, cannot convert large numbers"); -#else - {{TYPE}} val; + } + } + { +#if CYTHON_COMPILING_IN_PYPY && !defined(_PyLong_AsByteArray) + PyErr_SetString(PyExc_RuntimeError, + "_PyLong_AsByteArray() not available in PyPy, cannot convert large numbers"); +#else + {{TYPE}} val; PyObject *v = __Pyx_PyNumber_IntOrLong(x); - #if PY_MAJOR_VERSION < 3 - if (likely(v) && !PyLong_Check(v)) { - PyObject *tmp = v; - v = PyNumber_Long(tmp); - Py_DECREF(tmp); - } - #endif - if (likely(v)) { - int one = 1; int is_little = (int)*(unsigned char *)&one; - unsigned char *bytes = (unsigned char *)&val; - int ret = _PyLong_AsByteArray((PyLongObject *)v, - bytes, sizeof(val), - is_little, !is_unsigned); - Py_DECREF(v); - if (likely(!ret)) - return val; - } -#endif - return ({{TYPE}}) -1; - } - } else { - {{TYPE}} val; + #if PY_MAJOR_VERSION < 3 + if (likely(v) && !PyLong_Check(v)) { + PyObject *tmp = v; + v = PyNumber_Long(tmp); + Py_DECREF(tmp); + } + #endif + if (likely(v)) { + int one = 1; int is_little = (int)*(unsigned char *)&one; + unsigned char *bytes = (unsigned char *)&val; + int ret = _PyLong_AsByteArray((PyLongObject *)v, + bytes, sizeof(val), + is_little, !is_unsigned); + Py_DECREF(v); + if (likely(!ret)) + return val; + } +#endif + return ({{TYPE}}) -1; + } + } else { + {{TYPE}} val; PyObject *tmp = __Pyx_PyNumber_IntOrLong(x); - if (!tmp) return ({{TYPE}}) -1; - val = {{FROM_PY_FUNCTION}}(tmp); - Py_DECREF(tmp); - return val; - } - -raise_overflow: - PyErr_SetString(PyExc_OverflowError, - "value too large to convert to {{TYPE}}"); - return ({{TYPE}}) -1; - -raise_neg_overflow: - PyErr_SetString(PyExc_OverflowError, - "can't convert negative value to {{TYPE}}"); - return ({{TYPE}}) -1; -} + if (!tmp) return ({{TYPE}}) -1; + val = {{FROM_PY_FUNCTION}}(tmp); + Py_DECREF(tmp); + return val; + } + +raise_overflow: + PyErr_SetString(PyExc_OverflowError, + "value too large to convert to {{TYPE}}"); + return ({{TYPE}}) -1; + +raise_neg_overflow: + PyErr_SetString(PyExc_OverflowError, + "can't convert negative value to {{TYPE}}"); + return ({{TYPE}}) -1; +} diff --git a/contrib/tools/cython/Cython/Utility/arrayarray.h b/contrib/tools/cython/Cython/Utility/arrayarray.h index a9e4923785..fa7fa58d16 100644 --- a/contrib/tools/cython/Cython/Utility/arrayarray.h +++ b/contrib/tools/cython/Cython/Utility/arrayarray.h @@ -1,149 +1,149 @@ -/////////////// ArrayAPI.proto /////////////// - -// arrayarray.h -// -// Artificial C-API for Python's <array.array> type, -// used by array.pxd -// -// last changes: 2009-05-15 rk -// 2012-05-02 andreasvc -// (see revision control) -// - -#ifndef _ARRAYARRAY_H -#define _ARRAYARRAY_H - -// These two forward declarations are explicitly handled in the type -// declaration code, as including them here is too late for cython-defined -// types to use them. -// struct arrayobject; -// typedef struct arrayobject arrayobject; - -// All possible arraydescr values are defined in the vector "descriptors" -// below. That's defined later because the appropriate get and set -// functions aren't visible yet. -typedef struct arraydescr { - int typecode; - int itemsize; - PyObject * (*getitem)(struct arrayobject *, Py_ssize_t); - int (*setitem)(struct arrayobject *, Py_ssize_t, PyObject *); -#if PY_MAJOR_VERSION >= 3 - char *formats; +/////////////// ArrayAPI.proto /////////////// + +// arrayarray.h +// +// Artificial C-API for Python's <array.array> type, +// used by array.pxd +// +// last changes: 2009-05-15 rk +// 2012-05-02 andreasvc +// (see revision control) +// + +#ifndef _ARRAYARRAY_H +#define _ARRAYARRAY_H + +// These two forward declarations are explicitly handled in the type +// declaration code, as including them here is too late for cython-defined +// types to use them. +// struct arrayobject; +// typedef struct arrayobject arrayobject; + +// All possible arraydescr values are defined in the vector "descriptors" +// below. That's defined later because the appropriate get and set +// functions aren't visible yet. +typedef struct arraydescr { + int typecode; + int itemsize; + PyObject * (*getitem)(struct arrayobject *, Py_ssize_t); + int (*setitem)(struct arrayobject *, Py_ssize_t, PyObject *); +#if PY_MAJOR_VERSION >= 3 + char *formats; #endif -} arraydescr; - - -struct arrayobject { - PyObject_HEAD - Py_ssize_t ob_size; - union { - char *ob_item; - float *as_floats; - double *as_doubles; - int *as_ints; - unsigned int *as_uints; - unsigned char *as_uchars; - signed char *as_schars; - char *as_chars; - unsigned long *as_ulongs; - long *as_longs; +} arraydescr; + + +struct arrayobject { + PyObject_HEAD + Py_ssize_t ob_size; + union { + char *ob_item; + float *as_floats; + double *as_doubles; + int *as_ints; + unsigned int *as_uints; + unsigned char *as_uchars; + signed char *as_schars; + char *as_chars; + unsigned long *as_ulongs; + long *as_longs; #if PY_MAJOR_VERSION >= 3 unsigned long long *as_ulonglongs; long long *as_longlongs; #endif - short *as_shorts; - unsigned short *as_ushorts; - Py_UNICODE *as_pyunicodes; - void *as_voidptr; - } data; - Py_ssize_t allocated; - struct arraydescr *ob_descr; - PyObject *weakreflist; /* List of weak references */ -#if PY_MAJOR_VERSION >= 3 - int ob_exports; /* Number of exported buffers */ -#endif -}; - -#ifndef NO_NEWARRAY_INLINE -// fast creation of a new array -static CYTHON_INLINE PyObject * newarrayobject(PyTypeObject *type, Py_ssize_t size, - struct arraydescr *descr) { - arrayobject *op; - size_t nbytes; - - if (size < 0) { - PyErr_BadInternalCall(); - return NULL; - } - - nbytes = size * descr->itemsize; - // Check for overflow - if (nbytes / descr->itemsize != (size_t)size) { - return PyErr_NoMemory(); - } - op = (arrayobject *) type->tp_alloc(type, 0); - if (op == NULL) { - return NULL; - } - op->ob_descr = descr; - op->allocated = size; - op->weakreflist = NULL; + short *as_shorts; + unsigned short *as_ushorts; + Py_UNICODE *as_pyunicodes; + void *as_voidptr; + } data; + Py_ssize_t allocated; + struct arraydescr *ob_descr; + PyObject *weakreflist; /* List of weak references */ +#if PY_MAJOR_VERSION >= 3 + int ob_exports; /* Number of exported buffers */ +#endif +}; + +#ifndef NO_NEWARRAY_INLINE +// fast creation of a new array +static CYTHON_INLINE PyObject * newarrayobject(PyTypeObject *type, Py_ssize_t size, + struct arraydescr *descr) { + arrayobject *op; + size_t nbytes; + + if (size < 0) { + PyErr_BadInternalCall(); + return NULL; + } + + nbytes = size * descr->itemsize; + // Check for overflow + if (nbytes / descr->itemsize != (size_t)size) { + return PyErr_NoMemory(); + } + op = (arrayobject *) type->tp_alloc(type, 0); + if (op == NULL) { + return NULL; + } + op->ob_descr = descr; + op->allocated = size; + op->weakreflist = NULL; __Pyx_SET_SIZE(op, size); - if (size <= 0) { - op->data.ob_item = NULL; - } - else { - op->data.ob_item = PyMem_NEW(char, nbytes); - if (op->data.ob_item == NULL) { - Py_DECREF(op); - return PyErr_NoMemory(); - } + if (size <= 0) { + op->data.ob_item = NULL; + } + else { + op->data.ob_item = PyMem_NEW(char, nbytes); + if (op->data.ob_item == NULL) { + Py_DECREF(op); + return PyErr_NoMemory(); + } + } + return (PyObject *) op; +} +#else +PyObject* newarrayobject(PyTypeObject *type, Py_ssize_t size, + struct arraydescr *descr); +#endif /* ifndef NO_NEWARRAY_INLINE */ + +// fast resize (reallocation to the point) +// not designed for filing small increments (but for fast opaque array apps) +static CYTHON_INLINE int resize(arrayobject *self, Py_ssize_t n) { + void *items = (void*) self->data.ob_item; + PyMem_Resize(items, char, (size_t)(n * self->ob_descr->itemsize)); + if (items == NULL) { + PyErr_NoMemory(); + return -1; } - return (PyObject *) op; -} -#else -PyObject* newarrayobject(PyTypeObject *type, Py_ssize_t size, - struct arraydescr *descr); -#endif /* ifndef NO_NEWARRAY_INLINE */ - -// fast resize (reallocation to the point) -// not designed for filing small increments (but for fast opaque array apps) -static CYTHON_INLINE int resize(arrayobject *self, Py_ssize_t n) { - void *items = (void*) self->data.ob_item; - PyMem_Resize(items, char, (size_t)(n * self->ob_descr->itemsize)); - if (items == NULL) { - PyErr_NoMemory(); - return -1; - } - self->data.ob_item = (char*) items; + self->data.ob_item = (char*) items; __Pyx_SET_SIZE(self, n); - self->allocated = n; - return 0; -} - -// suitable for small increments; over allocation 50% ; -static CYTHON_INLINE int resize_smart(arrayobject *self, Py_ssize_t n) { - void *items = (void*) self->data.ob_item; - Py_ssize_t newsize; + self->allocated = n; + return 0; +} + +// suitable for small increments; over allocation 50% ; +static CYTHON_INLINE int resize_smart(arrayobject *self, Py_ssize_t n) { + void *items = (void*) self->data.ob_item; + Py_ssize_t newsize; if (n < self->allocated && n*4 > self->allocated) { __Pyx_SET_SIZE(self, n); return 0; - } + } newsize = n + (n / 2) + 1; if (newsize <= n) { /* overflow */ PyErr_NoMemory(); return -1; } - PyMem_Resize(items, char, (size_t)(newsize * self->ob_descr->itemsize)); - if (items == NULL) { - PyErr_NoMemory(); - return -1; + PyMem_Resize(items, char, (size_t)(newsize * self->ob_descr->itemsize)); + if (items == NULL) { + PyErr_NoMemory(); + return -1; } - self->data.ob_item = (char*) items; + self->data.ob_item = (char*) items; __Pyx_SET_SIZE(self, n); - self->allocated = newsize; - return 0; -} - -#endif -/* _ARRAYARRAY_H */ + self->allocated = newsize; + return 0; +} + +#endif +/* _ARRAYARRAY_H */ |