Exemplo n.º 1
0
    def put_code(self, output):
        code = output['utility_code_def']
        proto = output['utility_code_proto']

        proto.put(
            Buffer.dedent("""\
                static __Pyx_memviewslice %s(const __Pyx_memviewslice from_mvs); /* proto */
        """ % self.copy_func_name))

        copy_contents_name = get_copy_contents_name(self.from_memview,
                                                    self.to_memview)

        if self.to_memview.is_c_contig:
            mode = 'c'
            contig_flag = memview_c_contiguous
        elif self.to_memview.is_f_contig:
            mode = 'fortran'
            contig_flag = memview_f_contiguous

        C = dict(context,
                 copy_name=self.copy_func_name,
                 mode=mode,
                 sizeof_dtype="sizeof(%s)" %
                 self.from_memview.dtype.declaration_code(''),
                 contig_flag=contig_flag,
                 copy_contents_name=copy_contents_name)

        _, copy_code = UtilityCode.load_as_string("MemviewSliceCopyTemplate",
                                                  from_file="MemoryView_C.c",
                                                  context=C)
        code.put(copy_code)
Exemplo n.º 2
0
    def put_code(self, output):
        code = output['utility_code_def']
        proto = output['utility_code_proto']

        proto.put(Buffer.dedent("""\
                static __Pyx_memviewslice %s(const __Pyx_memviewslice from_mvs); /* proto */
        """ % self.copy_func_name))

        copy_contents_name = get_copy_contents_name(self.from_memview, self.to_memview)

        if self.to_memview.is_c_contig:
            mode = 'c'
            contig_flag = memview_c_contiguous
        elif self.to_memview.is_f_contig:
            mode = 'fortran'
            contig_flag = memview_f_contiguous

        C = dict(
            context,
            copy_name=self.copy_func_name,
            mode=mode,
            sizeof_dtype="sizeof(%s)" % self.from_memview.dtype.declaration_code(''),
            contig_flag=contig_flag,
            copy_contents_name=copy_contents_name
        )

        _, copy_code = UtilityCode.load_as_string("MemviewSliceCopyTemplate",
                                                  from_file="MemoryView_C.c",
                                                  context=C)
        code.put(copy_code)
Exemplo n.º 3
0
def load_memview_c_utility(util_code_name, context=None, **kwargs):
    if context is None:
        return UtilityCode.load(util_code_name, "MemoryView_C.c", **kwargs)
    else:
        return TempitaUtilityCode.load(util_code_name,
                                       "MemoryView_C.c",
                                       context=context,
                                       **kwargs)
Exemplo n.º 4
0
def load_buffer_utility(util_code_name, context=None, **kwargs):
    if context is None:
        return UtilityCode.load(util_code_name, "Buffer.c", **kwargs)
    else:
        return TempitaUtilityCode.load(util_code_name,
                                       "Buffer.c",
                                       context=context,
                                       **kwargs)
Exemplo n.º 5
0
def get_empty_bufstruct_code(max_ndim):
    code = dedent("""
        static Py_ssize_t __Pyx_zeros[] = {%s};
        static Py_ssize_t __Pyx_minusones[] = {%s};
    """) % (", ".join(["0"] * max_ndim), ", ".join(["-1"] * max_ndim))
    return UtilityCode(proto=code)
Exemplo n.º 6
0
#else
    // copied from pyport.h in CPython 3.3, missing in 2.4
    const PY_LONG_LONG PY_LLONG_MAX = (1 + 2 * ((1LL << (CHAR_BIT * sizeof(PY_LONG_LONG) - 2)) - 1));
#endif
#endif
    if (unlikely(x == -PY_LLONG_MAX-1))
        return ((unsigned PY_LONG_LONG)PY_LLONG_MAX) + 1U;
#if defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L
    return (unsigned PY_LONG_LONG) llabs(x);
#else
    return (x<0) ? (unsigned PY_LONG_LONG)-x : (unsigned PY_LONG_LONG)x;
#endif
}
''')

iter_next_utility_code = UtilityCode.load_cached("IterNext", "ObjectHandling.c")

getattr3_utility_code = UtilityCode(
proto = """
static CYTHON_INLINE PyObject *__Pyx_GetAttr3(PyObject *, PyObject *, PyObject *); /*proto*/
""",
impl = """
static CYTHON_INLINE PyObject *__Pyx_GetAttr3(PyObject *o, PyObject *n, PyObject *d) {
    PyObject *r = PyObject_GetAttr(o, n);
    if (!r) {
        if (!PyErr_ExceptionMatches(PyExc_AttributeError))
            goto bad;
        PyErr_Clear();
        r = d;
        Py_INCREF(d);
    }
Exemplo n.º 7
0
#
#   Pyrex - Builtin Definitions
#

from Symtab import BuiltinScope, StructOrUnionScope
from Code import UtilityCode
from TypeSlots import Signature
import PyrexTypes
import Naming

# C-level implementations of builtin types, functions and methods

pow2_utility_code = UtilityCode(proto="""
#define __Pyx_PyNumber_Power2(a, b) PyNumber_Power(a, b, Py_None)
""")

include_string_h_utility_code = UtilityCode(proto="""
#include <string.h>
""")

iter_next_utility_code = UtilityCode(
    proto="""
#define __Pyx_PyIter_Next(obj) __Pyx_PyIter_Next2(obj, NULL);
static CYTHON_INLINE PyObject *__Pyx_PyIter_Next2(PyObject *, PyObject *); /*proto*/
""",
    # copied from Py3's builtin_next()
    impl='''
static CYTHON_INLINE PyObject *__Pyx_PyIter_Next2(PyObject* iterator, PyObject* defval) {
    PyObject* next;
    if (unlikely(!PyIter_Check(iterator))) {
        PyErr_Format(PyExc_TypeError,
Exemplo n.º 8
0
def use_py2_buffer_functions(env):
    # Emulation of PyObject_GetBuffer and PyBuffer_Release for Python 2.
    # For >= 2.6 we do double mode -- use the new buffer interface on objects
    # which has the right tp_flags set, but emulation otherwise.

    # Search all types for __getbuffer__ overloads
    types = []
    visited_scopes = set()
    def find_buffer_types(scope):
        if scope in visited_scopes:
            return
        visited_scopes.add(scope)
        for m in scope.cimported_modules:
            find_buffer_types(m)
        for e in scope.type_entries:
            t = e.type
            if t.is_extension_type:
                release = get = None
                for x in t.scope.pyfunc_entries:
                    if x.name == u"__getbuffer__": get = x.func_cname
                    elif x.name == u"__releasebuffer__": release = x.func_cname
                if get:
                    types.append((t.typeptr_cname, get, release))

    find_buffer_types(env)

    code = dedent("""
        #if PY_MAJOR_VERSION < 3
        static int __Pyx_GetBuffer(PyObject *obj, Py_buffer *view, int flags) {
          #if PY_VERSION_HEX >= 0x02060000
          if (PyObject_CheckBuffer(obj)) return PyObject_GetBuffer(obj, view, flags);
          #endif
    """)
    if len(types) > 0:
        clause = "if"
        for t, get, release in types:
            code += "  %s (PyObject_TypeCheck(obj, %s)) return %s(obj, view, flags);\n" % (clause, t, get)
            clause = "else if"
        code += "  else {\n"
    code += dedent("""\
        PyErr_Format(PyExc_TypeError, "'%100s' does not have the buffer interface", Py_TYPE(obj)->tp_name);
        return -1;
    """, 2)
    if len(types) > 0: code += "  }"
    code += dedent("""
        }

        static void __Pyx_ReleaseBuffer(Py_buffer *view) {
          PyObject* obj = view->obj;
          if (obj) {
            #if PY_VERSION_HEX >= 0x02060000
            if (PyObject_CheckBuffer(obj)) {PyBuffer_Release(view); return;}
            #endif
    """)
    if len(types) > 0:
        clause = "if"
        for t, get, release in types:
            if release:
                code += "    "
                code += "%s (PyObject_TypeCheck(obj, %s)) %s(obj, view);" % (clause, t, release)
                clause = "else if"
    code += dedent("""
            Py_DECREF(obj);
            view->obj = NULL;
          }
        }

        #endif
    """)

    env.use_utility_code(UtilityCode(
            proto = dedent("""\
        #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
    """), impl = code))
Exemplo n.º 9
0
                             rep,
                             structinfo_name,
                             declcode,
                             typegroup,
                        ), safe=True)
    return name


# Utility function to set the right exception
# The caller should immediately goto_error
raise_indexerror_code = UtilityCode(
proto = """\
static void __Pyx_RaiseBufferIndexError(int axis); /*proto*/
""",
impl = """\
static void __Pyx_RaiseBufferIndexError(int axis) {
  PyErr_Format(PyExc_IndexError,
     "Out of bounds on buffer access (axis %d)", axis);
}

""")

parse_typestring_repeat_code = UtilityCode(
proto = """
""",
impl = """
""")

raise_buffer_fallback_code = UtilityCode(
proto = """
static void __Pyx_RaiseBufferFallbackError(void); /*proto*/
Exemplo n.º 10
0
#
#   Builtin Definitions
#

from Symtab import BuiltinScope, StructOrUnionScope
from Code import UtilityCode
from TypeSlots import Signature
import PyrexTypes
import Naming
import Options


# C-level implementations of builtin types, functions and methods

pow2_utility_code = UtilityCode(
proto = """
#define __Pyx_PyNumber_Power2(a, b) PyNumber_Power(a, b, Py_None)
""")

abs_int_utility_code = UtilityCode(
proto = '''
#if HAVE_LONG_LONG && defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L
#define __Pyx_abs_int(x) \
    ((sizeof(x) <= sizeof(int)) ? ((unsigned int)abs(x)) : \
     ((sizeof(x) <= sizeof(long)) ? ((unsigned long)labs(x)) : \
      ((unsigned PY_LONG_LONG)llabs(x))))
#else
#define __Pyx_abs_int(x) \
    ((sizeof(x) <= sizeof(int)) ? ((unsigned int)abs(x)) : ((unsigned long)labs(x)))
#endif
#define __Pyx_abs_long(x) __Pyx_abs_int(x)
''')
Exemplo n.º 11
0
#
#   Builtin Definitions
#

from Symtab import BuiltinScope, StructOrUnionScope
from Code import UtilityCode
from TypeSlots import Signature
import PyrexTypes
import Naming
import Options

# C-level implementations of builtin types, functions and methods

pow2_utility_code = UtilityCode(proto="""
#define __Pyx_PyNumber_Power2(a, b) PyNumber_Power(a, b, Py_None)
""")

abs_int_utility_code = UtilityCode(proto='''
#if HAVE_LONG_LONG && defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L
#define __Pyx_abs_int(x) \
    ((sizeof(x) <= sizeof(int)) ? ((unsigned int)abs(x)) : \
     ((sizeof(x) <= sizeof(long)) ? ((unsigned long)labs(x)) : \
      ((unsigned PY_LONG_LONG)llabs(x))))
#else
#define __Pyx_abs_int(x) \
    ((sizeof(x) <= sizeof(int)) ? ((unsigned int)abs(x)) : ((unsigned long)labs(x)))
#endif
#define __Pyx_abs_long(x) __Pyx_abs_int(x)
''')

iter_next_utility_code = UtilityCode.load_cached("IterNext",
Exemplo n.º 12
0
def load_buffer_utility(util_code_name, **kwargs):
    return UtilityCode.load(util_code_name, "Buffer.c", **kwargs)
Exemplo n.º 13
0
                       safe=True)
    return name


def load_buffer_utility(util_code_name, **kwargs):
    return UtilityCode.load(util_code_name, "Buffer.c", **kwargs)


context = dict(max_dims=str(Options.buffer_max_dims))
buffer_struct_declare_code = load_buffer_utility("BufferStructDeclare",
                                                 context=context)

# Utility function to set the right exception
# The caller should immediately goto_error
raise_indexerror_code = load_buffer_utility("BufferIndexError")

parse_typestring_repeat_code = UtilityCode(proto="""
""", impl="""
""")

raise_buffer_fallback_code = load_buffer_utility("BufferFallbackError")
buffer_structs_code = load_buffer_utility("BufferFormatStructs")
acquire_utility_code = load_buffer_utility("BufferFormatCheck",
                                           context=context,
                                           requires=[buffer_structs_code])

# See utility code BufferFormatFromTypeInfo
_typeinfo_to_format_code = load_buffer_utility("TypeInfoToFormat",
                                               context={},
                                               requires=[buffer_structs_code])
Exemplo n.º 14
0
def load_memview_c_utility(util_code_name, context=None, **kwargs):
    return UtilityCode.load(util_code_name,
                            "MemoryView_C.c",
                            context=context,
                            **kwargs)
Exemplo n.º 15
0
Arquivo: Buffer.py Projeto: 87/cython
def load_buffer_utility(util_code_name, context=None, **kwargs):
    if context is None:
        return UtilityCode.load(util_code_name, "Buffer.c", **kwargs)
    else:
        return TempitaUtilityCode.load(util_code_name, "Buffer.c", context=context, **kwargs)
Exemplo n.º 16
0
abs_int_utility_code = UtilityCode(
proto = '''
#if HAVE_LONG_LONG && defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L
#define __Pyx_abs_int(x) \
    ((sizeof(x) <= sizeof(int)) ? ((unsigned int)abs(x)) : \
     ((sizeof(x) <= sizeof(long)) ? ((unsigned long)labs(x)) : \
      ((unsigned PY_LONG_LONG)llabs(x))))
#else
#define __Pyx_abs_int(x) \
    ((sizeof(x) <= sizeof(int)) ? ((unsigned int)abs(x)) : ((unsigned long)labs(x)))
#endif
#define __Pyx_abs_long(x) __Pyx_abs_int(x)
''')

iter_next_utility_code = UtilityCode.load_cached("IterNext", "ObjectHandling.c")

getattr3_utility_code = UtilityCode(
proto = """
static CYTHON_INLINE PyObject *__Pyx_GetAttr3(PyObject *, PyObject *, PyObject *); /*proto*/
""",
impl = """
static CYTHON_INLINE PyObject *__Pyx_GetAttr3(PyObject *o, PyObject *n, PyObject *d) {
    PyObject *r = PyObject_GetAttr(o, n);
    if (!r) {
        if (!PyErr_ExceptionMatches(PyExc_AttributeError))
            goto bad;
        PyErr_Clear();
        r = d;
        Py_INCREF(d);
    }
Exemplo n.º 17
0
#
#   Builtin Definitions
#

from Symtab import BuiltinScope, StructOrUnionScope
from Code import UtilityCode
from TypeSlots import Signature
import PyrexTypes
import Options

# C-level implementations of builtin types, functions and methods

iter_next_utility_code = UtilityCode.load("IterNext", "ObjectHandling.c")
getattr_utility_code = UtilityCode.load("GetAttr", "ObjectHandling.c")
getattr3_utility_code = UtilityCode.load("GetAttr3", "Builtins.c")
pyexec_utility_code = UtilityCode.load("PyExec", "Builtins.c")
pyexec_globals_utility_code = UtilityCode.load("PyExecGlobals", "Builtins.c")
globals_utility_code = UtilityCode.load("Globals", "Builtins.c")

py_set_utility_code = UtilityCode.load("pyset_compat", "Builtins.c")

builtin_utility_code = {
    'set': py_set_utility_code,
    'frozenset': py_set_utility_code,
}

# mapping from builtins to their C-level equivalents


class _BuiltinOverride(object):
    def __init__(self,
Exemplo n.º 18
0
def use_empty_bufstruct_code(env, max_ndim):
    code = dedent("""
        Py_ssize_t __Pyx_zeros[] = {%s};
        Py_ssize_t __Pyx_minusones[] = {%s};
    """) % (", ".join(["0"] * max_ndim), ", ".join(["-1"] * max_ndim))
    env.use_utility_code(UtilityCode(proto=code))
Exemplo n.º 19
0
abs_int_utility_code = UtilityCode(
    proto="""
#if HAVE_LONG_LONG && defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L
#define __Pyx_abs_int(x) \
    ((sizeof(x) <= sizeof(int)) ? ((unsigned int)abs(x)) : \
     ((sizeof(x) <= sizeof(long)) ? ((unsigned long)labs(x)) : \
      ((unsigned PY_LONG_LONG)llabs(x))))
#else
#define __Pyx_abs_int(x) \
    ((sizeof(x) <= sizeof(int)) ? ((unsigned int)abs(x)) : ((unsigned long)labs(x)))
#endif
#define __Pyx_abs_long(x) __Pyx_abs_int(x)
"""
)

iter_next_utility_code = UtilityCode.load_cached("IterNext", "ObjectHandling.c")

getattr3_utility_code = UtilityCode(
    proto="""
static CYTHON_INLINE PyObject *__Pyx_GetAttr3(PyObject *, PyObject *, PyObject *); /*proto*/
""",
    impl="""
static CYTHON_INLINE PyObject *__Pyx_GetAttr3(PyObject *o, PyObject *n, PyObject *d) {
    PyObject *r = PyObject_GetAttr(o, n);
    if (!r) {
        if (!PyErr_ExceptionMatches(PyExc_AttributeError))
            goto bad;
        PyErr_Clear();
        r = d;
        Py_INCREF(d);
    }
Exemplo n.º 20
0
#
#   Builtin Definitions
#

from Symtab import BuiltinScope, StructOrUnionScope
from Code import UtilityCode
from TypeSlots import Signature
import PyrexTypes
import Options


# C-level implementations of builtin types, functions and methods

iter_next_utility_code = UtilityCode.load("IterNext", "ObjectHandling.c")
getattr3_utility_code = UtilityCode.load("GetAttr3", "Builtins.c")
getattr_utility_code = UtilityCode.load("GetAttr", "Builtins.c")
pyexec_utility_code = UtilityCode.load("PyExec", "Builtins.c")
pyexec_globals_utility_code = UtilityCode.load("PyExecGlobals", "Builtins.c")
globals_utility_code = UtilityCode.load("Globals", "Builtins.c")

py_set_utility_code = UtilityCode(
proto = """
#if PY_VERSION_HEX < 0x02050000
#ifndef PyAnySet_CheckExact

#define PyAnySet_CheckExact(ob) \\
    ((ob)->ob_type == &PySet_Type || \\
     (ob)->ob_type == &PyFrozenSet_Type)

#define PySet_New(iterable) \\
    PyObject_CallFunctionObjArgs((PyObject *)&PySet_Type, (iterable), NULL)
Exemplo n.º 21
0
def load_buffer_utility(util_code_name, **kwargs):
    return UtilityCode.load(util_code_name, "Buffer.c", **kwargs)
Exemplo n.º 22
0
def load_memview_c_utility(util_code_name, context=None, **kwargs):
    if context is None:
        return UtilityCode.load(util_code_name, "MemoryView_C.c", **kwargs)
    else:
        return TempitaUtilityCode.load(util_code_name, "MemoryView_C.c",
                                       context=context, **kwargs)
Exemplo n.º 23
0
def load_memview_c_utility(util_code_name, context=None, **kwargs):
    return UtilityCode.load(util_code_name, "MemoryView_C.c",
                            context=context, **kwargs)