Buffer.py 26.4 KB
Newer Older
1 2 3 4 5
from Cython.Compiler.Visitor import VisitorTransform, temp_name_handle, CythonTransform
from Cython.Compiler.ModuleNode import ModuleNode
from Cython.Compiler.Nodes import *
from Cython.Compiler.ExprNodes import *
from Cython.Compiler.TreeFragment import TreeFragment
6
from Cython.Compiler.StringEncoding import EncodedString
7
from Cython.Compiler.Errors import CompileError
8
import Interpreter
9
import PyrexTypes
10

Stefan Behnel's avatar
Stefan Behnel committed
11 12 13 14 15
try:
    set
except NameError:
    from sets import Set as set

16 17
import textwrap

18 19 20 21 22 23
# Code cleanup ideas:
# - One could be more smart about casting in some places
# - Start using CCodeWriters to generate utility functions
# - Create a struct type per ndim rather than keeping loose local vars


24 25 26 27 28 29
def dedent(text, reindent=0):
    text = textwrap.dedent(text)
    if reindent > 0:
        indent = " " * reindent
        text = '\n'.join([indent + x for x in text.split('\n')])
    return text
30 31 32 33 34 35 36 37 38 39 40

class IntroduceBufferAuxiliaryVars(CythonTransform):

    #
    # Entry point
    #

    buffers_exists = False

    def __call__(self, node):
        assert isinstance(node, ModuleNode)
41
        self.max_ndim = 0
42 43 44
        result = super(IntroduceBufferAuxiliaryVars, self).__call__(node)
        if self.buffers_exists:
            use_py2_buffer_functions(node.scope)
45
            use_empty_bufstruct_code(node.scope, self.max_ndim)
46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68
        return result


    #
    # Basic operations for transforms
    #
    def handle_scope(self, node, scope):
        # For all buffers, insert extra variables in the scope.
        # The variables are also accessible from the buffer_info
        # on the buffer entry
        bufvars = [entry for name, entry
                   in scope.entries.iteritems()
                   if entry.type.is_buffer]
        if len(bufvars) > 0:
            self.buffers_exists = True


        if isinstance(node, ModuleNode) and len(bufvars) > 0:
            # for now...note that pos is wrong 
            raise CompileError(node.pos, "Buffer vars not allowed in module scope")
        for entry in bufvars:
            name = entry.name
            buftype = entry.type
69 70
            if buftype.ndim > self.max_ndim:
                self.max_ndim = buftype.ndim
71 72 73 74 75

            # Declare auxiliary vars
            cname = scope.mangle(Naming.bufstruct_prefix, name)
            bufinfo = scope.declare_var(name="$%s" % cname, cname=cname,
                                        type=PyrexTypes.c_py_buffer_type, pos=node.pos)
76 77
            if entry.is_arg:
                bufinfo.used = True # otherwise, NameNode will mark whether it is used
78

79
            def var(prefix, idx, initval):
80 81 82 83
                cname = scope.mangle(prefix, "%d_%s" % (idx, name))
                result = scope.declare_var("$%s" % cname, PyrexTypes.c_py_ssize_t_type,
                                         node.pos, cname=cname, is_cdef=True)

84
                result.init = initval
85 86 87 88
                if entry.is_arg:
                    result.used = True
                return result
            
89

90 91
            stridevars = [var(Naming.bufstride_prefix, i, "0") for i in range(entry.type.ndim)]
            shapevars = [var(Naming.bufshape_prefix, i, "0") for i in range(entry.type.ndim)]            
92 93 94 95 96 97
            mode = entry.type.mode
            if mode == 'full':
                suboffsetvars = [var(Naming.bufsuboffset_prefix, i, "-1") for i in range(entry.type.ndim)]
            elif mode == 'strided':
                suboffsetvars = None

98
            entry.buffer_aux = Symtab.BufferAux(bufinfo, stridevars, shapevars, suboffsetvars)
99 100 101 102 103 104 105 106 107 108 109 110 111 112
            
        scope.buffer_entries = bufvars
        self.scope = scope

    def visit_ModuleNode(self, node):
        self.handle_scope(node, node.scope)
        self.visitchildren(node)
        return node

    def visit_FuncDefNode(self, node):
        self.handle_scope(node, node.local_scope)
        self.visitchildren(node)
        return node

113 114 115 116 117 118 119 120 121 122 123 124
#
# Analysis
#
buffer_options = ("dtype", "ndim", "mode") # ordered!
buffer_defaults = {"ndim": 1, "mode": "full"}

ERR_BUF_OPTION_UNKNOWN = '"%s" is not a buffer option'
ERR_BUF_TOO_MANY = 'Too many buffer options'
ERR_BUF_DUP = '"%s" buffer option already supplied'
ERR_BUF_MISSING = '"%s" missing'
ERR_BUF_MODE = 'Only allowed buffer modes are "full" or "strided" (as a compile-time string)'
ERR_BUF_NDIM = 'ndim must be a non-negative integer'
125
ERR_BUF_DTYPE = 'dtype must be "object", numeric type or a struct'
126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167

def analyse_buffer_options(globalpos, env, posargs, dictargs, defaults=None, need_complete=True):
    """
    Must be called during type analysis, as analyse is called
    on the dtype argument.

    posargs and dictargs should consist of a list and a dict
    of tuples (value, pos). Defaults should be a dict of values.

    Returns a dict containing all the options a buffer can have and
    its value (with the positions stripped).
    """
    if defaults is None:
        defaults = buffer_defaults
    
    posargs, dictargs = Interpreter.interpret_compiletime_options(posargs, dictargs, type_env=env)
    
    if len(posargs) > len(buffer_options):
        raise CompileError(posargs[-1][1], ERR_BUF_TOO_MANY)

    options = {}
    for name, (value, pos) in dictargs.iteritems():
        if not name in buffer_options:
            raise CompileError(pos, ERR_BUF_OPTION_UNKNOWN % name)
        options[name] = value
    
    for name, (value, pos) in zip(buffer_options, posargs):
        if not name in buffer_options:
            raise CompileError(pos, ERR_BUF_OPTION_UNKNOWN % name)
        if name in options:
            raise CompileError(pos, ERR_BUF_DUP % name)
        options[name] = value

    # Check that they are all there and copy defaults
    for name in buffer_options:
        if not name in options:
            try:
                options[name] = defaults[name]
            except KeyError:
                if need_complete:
                    raise CompileError(globalpos, ERR_BUF_MISSING % name)

168 169 170 171 172 173
    dtype = options.get("dtype")
    if dtype and dtype.is_extension_type:
        raise CompileError(globalpos, ERR_BUF_DTYPE)

    ndim = options.get("ndim")
    if ndim and (not isinstance(ndim, int) or ndim < 0):
174 175
        raise CompileError(globalpos, ERR_BUF_NDIM)

176 177
    mode = options.get("mode")
    if mode and not (mode in ('full', 'strided')):
178 179 180 181 182 183 184 185
        raise CompileError(globalpos, ERR_BUF_MODE)

    return options
    

#
# Code generation
#
186 187


188
def get_flags(buffer_aux, buffer_type):
189 190 191 192 193 194 195
    flags = 'PyBUF_FORMAT'
    if buffer_type.mode == 'full':
        flags += '| PyBUF_INDIRECT'
    elif buffer_type.mode == 'strided':
        flags += '| PyBUF_STRIDES'
    else:
        assert False
196 197 198
    if buffer_aux.writable_needed: flags += "| PyBUF_WRITABLE"
    return flags
        
199 200 201 202 203
def used_buffer_aux_vars(entry):
    buffer_aux = entry.buffer_aux
    buffer_aux.buffer_info_var.used = True
    for s in buffer_aux.shapevars: s.used = True
    for s in buffer_aux.stridevars: s.used = True
204 205
    if buffer_aux.suboffsetvars:
        for s in buffer_aux.suboffsetvars: s.used = True
206

207 208 209
def put_unpack_buffer_aux_into_scope(buffer_aux, mode, code):
    # Generate code to copy the needed struct info into local
    # variables.
210 211
    bufstruct = buffer_aux.buffer_info_var.cname

212 213 214 215
    varspec = [("strides", buffer_aux.stridevars),
               ("shape", buffer_aux.shapevars)]
    if mode == 'full':
        varspec.append(("suboffsets", buffer_aux.suboffsetvars))
216

217
    for field, vars in varspec:
218 219 220
        code.putln(" ".join(["%s = %s.%s[%d];" %
                             (s.cname, bufstruct, field, idx)
                             for idx, s in enumerate(vars)]))
221 222

def put_acquire_arg_buffer(entry, code, pos):
223
    code.globalstate.use_utility_code(acquire_utility_code)
224
    buffer_aux = entry.buffer_aux
225
    getbuffer_cname = get_getbuffer_code(entry.type.dtype, code)
226
    # Acquire any new buffer
227
    code.putln(code.error_goto_if("%s((PyObject*)%s, &%s, %s, %d) == -1" % (
228 229 230 231 232
        getbuffer_cname,
        entry.cname,
        entry.buffer_aux.buffer_info_var.cname,
        get_flags(buffer_aux, entry.type),
        entry.type.ndim), pos))
233
    # An exception raised in arg parsing cannot be catched, so no
234
    # need to care about the buffer then.
235
    put_unpack_buffer_aux_into_scope(buffer_aux, entry.type.mode, code)
236

237 238 239 240 241 242
#def put_release_buffer_normal(entry, code):
#    code.putln("if (%s != Py_None) PyObject_ReleaseBuffer(%s, &%s);" % (
#        entry.cname,
#        entry.cname,
#        entry.buffer_aux.buffer_info_var.cname))

243
def get_release_buffer_code(entry):
244
    return "__Pyx_SafeReleaseBuffer((PyObject*)%s, &%s)" % (
245 246
        entry.cname,
        entry.buffer_aux.buffer_info_var.cname)
247

248
def put_assign_to_buffer(lhs_cname, rhs_cname, buffer_aux, buffer_type,
249
                         is_initialized, pos, code):
250 251 252 253 254 255 256 257 258 259 260 261 262
    """
    Generate code for reassigning a buffer variables. This only deals with getting
    the buffer auxiliary structure and variables set up correctly, the assignment
    itself and refcounting is the responsibility of the caller.

    However, the assignment operation may throw an exception so that the reassignment
    never happens.
    
    Depending on the circumstances there are two possible outcomes:
    - Old buffer released, new acquired, rhs assigned to lhs
    - Old buffer released, new acquired which fails, reaqcuire old lhs buffer
      (which may or may not succeed).
    """
263

264
    code.globalstate.use_utility_code(acquire_utility_code)
265
    bufstruct = buffer_aux.buffer_info_var.cname
266
    flags = get_flags(buffer_aux, buffer_type)
267

268
    getbuffer = "%s((PyObject*)%%s, &%s, %s, %d)" % (get_getbuffer_code(buffer_type.dtype, code),
269
                                          # note: object is filled in later (%%s)
270 271 272 273
                                          bufstruct,
                                          flags,
                                          buffer_type.ndim)

274 275
    if is_initialized:
        # Release any existing buffer
276
        code.putln('__Pyx_SafeReleaseBuffer((PyObject*)%s, &%s);' % (
277
            lhs_cname, bufstruct))
278
        # Acquire
279
        retcode_cname = code.funcstate.allocate_temp(PyrexTypes.c_int_type)
280
        code.putln("%s = %s;" % (retcode_cname, getbuffer % rhs_cname))
281
        code.putln('if (%s) ' % (code.unlikely("%s < 0" % retcode_cname)))
282 283 284 285 286
        # If acquisition failed, attempt to reacquire the old buffer
        # before raising the exception. A failure of reacquisition
        # will cause the reacquisition exception to be reported, one
        # can consider working around this later.
        code.begin_block()
287
        type, value, tb = [code.funcstate.allocate_temp(PyrexTypes.py_object_type)
288 289
                           for i in range(3)]
        code.putln('PyErr_Fetch(&%s, &%s, &%s);' % (type, value, tb))
290
        code.put('if (%s) ' % code.unlikely("%s == -1" % (getbuffer % lhs_cname)))
291
        code.begin_block()
292
        code.putln('Py_XDECREF(%s); Py_XDECREF(%s); Py_XDECREF(%s);' % (type, value, tb))
293
        code.globalstate.use_utility_code(raise_buffer_fallback_code)
294
        code.putln('__Pyx_RaiseBufferFallbackError();')
295
        code.putln('} else {')
296 297
        code.putln('PyErr_Restore(%s, %s, %s);' % (type, value, tb))
        for t in (type, value, tb):
298
            code.funcstate.release_temp(t)
299 300
        code.end_block()
        # Unpack indices
301
        code.end_block()
302
        put_unpack_buffer_aux_into_scope(buffer_aux, buffer_type.mode, code)
303
        code.putln(code.error_goto_if_neg(retcode_cname, pos))
304
        code.funcstate.release_temp(retcode_cname)
305
    else:
306 307 308 309
        # Our entry had no previous value, so set to None when acquisition fails.
        # In this case, auxiliary vars should be set up right in initialization to a zero-buffer,
        # so it suffices to set the buf field to NULL.
        code.putln('if (%s) {' % code.unlikely("%s == -1" % (getbuffer % rhs_cname)))
310 311 312 313
        code.putln('%s = %s; Py_INCREF(Py_None); %s.buf = NULL;' %
                   (lhs_cname,
                    PyrexTypes.typecast(buffer_type, PyrexTypes.py_object_type, "Py_None"),
                    bufstruct))
314 315 316
        code.putln(code.error_goto(pos))
        code.put('} else {')
        # Unpack indices
317
        put_unpack_buffer_aux_into_scope(buffer_aux, buffer_type.mode, code)
318
        code.putln('}')
319

320

321 322 323 324 325 326
def put_buffer_lookup_code(entry, index_signeds, index_cnames, options, pos, code):
    """
    Generates code to process indices and calculate an offset into
    a buffer. Returns a C string which gives a pointer which can be
    read from or written to at will (it is an expression so caller should
    store it in a temporary if it is used more than once).
327 328 329 330 331

    As the bounds checking can have any number of combinations of unsigned
    arguments, smart optimizations etc. we insert it directly in the function
    body. The lookup however is delegated to a inline function that is instantiated
    once per ndim (lookup with suboffsets tend to get quite complicated).
332

333
    """
334 335
    bufaux = entry.buffer_aux
    bufstruct = bufaux.buffer_info_var.cname
336

337 338 339 340 341 342
    if options['boundscheck']:
        # Check bounds and fix negative indices.
        # We allocate a temporary which is initialized to -1, meaning OK (!).
        # If an error occurs, the temp is set to the dimension index the
        # error is occuring at.
        tmp_cname = code.funcstate.allocate_temp(PyrexTypes.c_int_type)
343
        code.putln("%s = -1;" % tmp_cname)
344 345 346 347 348 349
        for dim, (signed, cname, shape) in enumerate(zip(index_signeds, index_cnames,
                                                         bufaux.shapevars)):
            if signed != 0:
                # not unsigned, deal with negative index
                code.putln("if (%s < 0) {" % cname)
                code.putln("%s += %s;" % (cname, shape.cname))
350
                code.putln("if (%s) %s = %d;" % (
351 352
                    code.unlikely("%s < 0" % cname), tmp_cname, dim))
                code.put("} else ")
353 354 355
            # check bounds in positive direction
            code.putln("if (%s) %s = %d;" % (
                code.unlikely("%s >= %s" % (cname, shape.cname)),
356 357
                tmp_cname, dim))
        code.globalstate.use_utility_code(raise_indexerror_code)
358 359
        code.put("if (%s) " % code.unlikely("%s != -1" % tmp_cname))
        code.begin_block()
360
        code.putln('__Pyx_RaiseBufferIndexError(%s);' % tmp_cname)
361
        code.putln(code.error_goto(pos))
362
        code.end_block()
363 364 365 366 367 368 369 370
        code.funcstate.release_temp(tmp_cname)
    else:
        # Only fix negative indices.
        for signed, cname, shape in zip(index_signeds, index_cnames,
                                        bufaux.shapevars):
            if signed != 0:
                code.putln("if (%s < 0) %s += %s;" % (cname, cname, shape.cname))
        
371 372
    # Create buffer lookup and return it
    params = []
373
    nd = entry.type.ndim
374 375 376 377 378
    if entry.type.mode == 'full':
        for i, s, o in zip(index_cnames, bufaux.stridevars, bufaux.suboffsetvars):
            params.append(i)
            params.append(s.cname)
            params.append(o.cname)
379 380 381

        funcname = "__Pyx_BufPtrFull%dd" % nd
        funcgen = buf_lookup_full_code
382 383 384 385
    else:
        for i, s in zip(index_cnames, bufaux.stridevars):
            params.append(i)
            params.append(s.cname)
386 387 388
        funcname = "__Pyx_BufPtrStrided%dd" % nd
        funcgen = buf_lookup_strided_code
        
389
    # Make sure the utility code is available
390 391 392
    code.globalstate.use_generated_code(funcgen, name=funcname, nd=nd)

    ptrcode = "%s(%s.buf, %s)" % (funcname, bufstruct, ", ".join(params))
393
    return entry.type.buffer_ptr_type.cast_code(ptrcode)
394

395 396 397 398 399 400

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))
401
    env.use_utility_code([code, ""], "empty_bufstruct_code")
402

403

404
def buf_lookup_strided_code(proto, defin, name, nd):
405
    """
406
    Generates a buffer lookup function for the right number
407 408
    of dimensions. The function gives back a void* at the right location.
    """
409 410 411 412
    # _i_ndex, _s_tride
    args = ", ".join(["i%d, s%d" % (i, i) for i in range(nd)])
    offset = " + ".join(["i%d * s%d" % (i, i) for i in range(nd)])
    proto.putln("#define %s(buf, %s) ((char*)buf + %s)" % (name, args, offset))
413

414
def buf_lookup_full_code(proto, defin, name, nd):
415
    """
416
    Generates a buffer lookup function for the right number
417 418
    of dimensions. The function gives back a void* at the right location.
    """
419 420 421 422
    # _i_ndex, _s_tride, sub_o_ffset
    args = ", ".join(["Py_ssize_t i%d, Py_ssize_t s%d, Py_ssize_t o%d" % (i, i, i) for i in range(nd)])
    proto.putln("static INLINE void* %s(void* buf, %s);" % (name, args))
    defin.putln(dedent("""
423 424 425 426 427 428
        static INLINE void* %s(void* buf, %s) {
          char* ptr = (char*)buf;
        """) % (name, args) + "".join([dedent("""\
          ptr += s%d * i%d;
          if (o%d >= 0) ptr = *((char**)ptr) + o%d; 
        """) % (i, i, i, i) for i in range(nd)]
429
        ) + "\nreturn ptr;\n}")
430 431


432 433 434 435 436 437
#
# Utils for creating type string checkers
#
def mangle_dtype_name(dtype):
    # Use prefixes to seperate user defined types from builtins
    # (consider "typedef float unsigned_int")
438 439 440 441
    if dtype.is_pyobject:
        return "object"
    elif dtype.is_ptr:
        return "ptr"
442
    else:
443 444 445 446 447
        if dtype.typestring is None:
            prefix = "nn_"
        else:
            prefix = ""
        return prefix + dtype.declaration_code("").replace(" ", "_")
448

449
def get_ts_check_item(dtype, writer):
450 451 452
    # See if we can consume one (unnamed) dtype as next item
    # Put native types and structs in seperate namespaces (as one could create a struct named unsigned_int...)
    name = "__Pyx_BufferTypestringCheck_item_%s" % mangle_dtype_name(dtype)
453
    if not writer.globalstate.has_utility_code(name):
454 455
        char = dtype.typestring
        if char is not None:
456
                # Can use direct comparison
457
            code = dedent("""\
458
                if (*ts == '1') ++ts;
459 460 461 462 463
                if (*ts != '%s') {
                  PyErr_Format(PyExc_ValueError, "Buffer datatype mismatch (rejecting on '%%s')", ts);
                  return NULL;
                } else return ts + 1;
            """, 2) % char
464 465 466 467
        else:
            # Cannot trust declared size; but rely on int vs float and
            # signed/unsigned to be correctly declared
            ctype = dtype.declaration_code("")
468 469
            code = dedent("""\
                int ok;
470
                if (*ts == '1') ++ts;
471
                switch (*ts) {""", 2)
472 473 474 475 476 477 478 479 480 481 482
            if dtype.is_int:
                types = [
                    ('b', 'char'), ('h', 'short'), ('i', 'int'),
                    ('l', 'long'), ('q', 'long long')
                ]
                if dtype.signed == 0:
                    code += "".join(["\n    case '%s': ok = (sizeof(%s) == sizeof(%s) && (%s)-1 > 0); break;" %
                                 (char.upper(), ctype, against, ctype) for char, against in types])
                else:
                    code += "".join(["\n    case '%s': ok = (sizeof(%s) == sizeof(%s) && (%s)-1 < 0); break;" %
                                 (char, ctype, against, ctype) for char, against in types])
483 484 485 486 487 488 489 490
                code += dedent("""\
                      default: ok = 0;
                    }
                    if (!ok) {
                      PyErr_Format(PyExc_ValueError, "Buffer datatype mismatch (rejecting on '%s')", ts);
                      return NULL;
                    } else return ts + 1;
                """, 2)
491
        writer.globalstate.use_utility_code([dedent("""\
492 493 494 495 496 497
            static const char* %s(const char* ts); /*proto*/
        """) % name, dedent("""
            static const char* %s(const char* ts) {
            %s
            }
        """) % (name, code)], name=name)
498

499
    return name
500

501
def get_getbuffer_code(dtype, code):
502 503 504 505 506 507 508 509 510 511
    """
    Generate a utility function for getting a buffer for the given dtype.
    The function will:
    - Call PyObject_GetBuffer
    - Check that ndim matched the expected value
    - Check that the format string is right
    - Set suboffsets to all -1 if it is returned as NULL.
    """

    name = "__Pyx_GetBuffer_%s" % mangle_dtype_name(dtype)
512 513 514
    if not code.globalstate.has_utility_code(name):
        code.globalstate.use_utility_code(acquire_utility_code)
        itemchecker = get_ts_check_item(dtype, code)
515 516 517 518 519 520 521 522 523 524
        utilcode = [dedent("""
        static int %s(PyObject* obj, Py_buffer* buf, int flags, int nd); /*proto*/
        """) % name, dedent("""
        static int %(name)s(PyObject* obj, Py_buffer* buf, int flags, int nd) {
          const char* ts;
          if (obj == Py_None) {
            __Pyx_ZeroBuffer(buf);
            return 0;
          }
          buf->buf = NULL;
525
          if (__Pyx_GetBuffer(obj, buf, flags) == -1) goto fail;
526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548
          if (buf->ndim != nd) {
            __Pyx_BufferNdimError(buf, nd);
            goto fail;
          }
          ts = buf->format;
          ts = __Pyx_ConsumeWhitespace(ts);
          ts = __Pyx_BufferTypestringCheckEndian(ts);
          if (!ts) goto fail;
          ts = __Pyx_ConsumeWhitespace(ts);
          ts = %(itemchecker)s(ts);
          if (!ts) goto fail;
          ts = __Pyx_ConsumeWhitespace(ts);
          if (*ts != 0) {
            PyErr_Format(PyExc_ValueError,
              "Expected non-struct buffer data type (rejecting on '%%s')", ts);
            goto fail;
          }
          if (buf->suboffsets == NULL) buf->suboffsets = __Pyx_minusones;
          return 0;
        fail:;
          __Pyx_ZeroBuffer(buf);
          return -1;
        }""") % locals()]
549
        code.globalstate.use_utility_code(utilcode, name)
550 551
    return name

552
def buffer_type_checker(dtype, code):
553 554 555 556 557
    # Creates a type checker function for the given type.
    if dtype.is_struct_or_union:
        assert False
    elif dtype.is_int or dtype.is_float:
        # This includes simple typedef-ed types
558
        funcname = get_getbuffer_code(dtype, code)
559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582
    else:
        assert False
    return funcname

def use_py2_buffer_functions(env):
    codename = "PyObject_GetBuffer" # just a representative unique key

    # Search all types for __getbuffer__ overloads
    types = []
    def find_buffer_types(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)

583
    code = dedent("""
584 585
        #if (PY_MAJOR_VERSION < 3) && !(Py_TPFLAGS_DEFAULT & Py_TPFLAGS_HAVE_NEWBUFFER)
        static int __Pyx_GetBuffer(PyObject *obj, Py_buffer *view, int flags) {
586
    """)
587 588 589 590 591 592
    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"
593 594 595 596
    code += dedent("""\
        PyErr_Format(PyExc_TypeError, "'%100s' does not have the buffer interface", Py_TYPE(obj)->tp_name);
        return -1;
    """, 2)
597
    if len(types) > 0: code += "  }"
598 599
    code += dedent("""
        }
600

601
        static void __Pyx_ReleaseBuffer(PyObject *obj, Py_buffer *view) {
602
    """)
603 604 605 606 607 608
    if len(types) > 0:
        clause = "if"
        for t, get, release in types:
            if release:
                code += "%s (PyObject_TypeCheck(obj, %s)) %s(obj, view);" % (clause, t, release)
                clause = "else if"
609 610 611 612 613 614 615
    code += dedent("""
        }

        #endif
    """)
                   
    env.use_utility_code([dedent("""\
616 617 618 619 620 621
        #if (PY_MAJOR_VERSION < 3) && !(Py_TPFLAGS_DEFAULT & Py_TPFLAGS_HAVE_NEWBUFFER)
        static int __Pyx_GetBuffer(PyObject *obj, Py_buffer *view, int flags);
        static void __Pyx_ReleaseBuffer(PyObject *obj, Py_buffer *view);
        #else
        #define __Pyx_GetBuffer PyObject_GetBuffer
        #define __Pyx_ReleaseBuffer PyObject_ReleaseBuffer
622
        #endif
623
    """), code], codename)
624 625 626 627 628 629 630 631

#
# Static utility code
#


# Utility function to set the right exception
# The caller should immediately goto_error
632
raise_indexerror_code = [
633
"""\
634
static void __Pyx_RaiseBufferIndexError(int axis); /*proto*/
635
""","""\
636
static void __Pyx_RaiseBufferIndexError(int axis) {
637 638
  PyErr_Format(PyExc_IndexError,
     "Out of bounds on buffer access (axis %d)", axis);
639
}
640

641 642 643 644 645 646 647 648 649
"""]

#
# Buffer type checking. Utility code for checking that acquired
# buffers match our assumptions. We only need to check ndim and
# the format string; the access mode/flags is checked by the
# exporter.
#
acquire_utility_code = ["""\
650
static INLINE void __Pyx_SafeReleaseBuffer(PyObject* obj, Py_buffer* info);
651 652 653 654 655
static INLINE void __Pyx_ZeroBuffer(Py_buffer* buf); /*proto*/
static INLINE const char* __Pyx_ConsumeWhitespace(const char* ts); /*proto*/
static INLINE const char* __Pyx_BufferTypestringCheckEndian(const char* ts); /*proto*/
static void __Pyx_BufferNdimError(Py_buffer* buffer, int expected_ndim); /*proto*/
""", """
656
static INLINE void __Pyx_SafeReleaseBuffer(PyObject* obj, Py_buffer* info) {
657
  if (info->buf == NULL) return;
658
  if (info->suboffsets == __Pyx_minusones) info->suboffsets = NULL;
659
  __Pyx_ReleaseBuffer(obj, info);
660 661
}

662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682
static INLINE void __Pyx_ZeroBuffer(Py_buffer* buf) {
  buf->buf = NULL;
  buf->strides = __Pyx_zeros;
  buf->shape = __Pyx_zeros;
  buf->suboffsets = __Pyx_minusones;
}

static INLINE const char* __Pyx_ConsumeWhitespace(const char* ts) {
  while (1) {
    switch (*ts) {
      case 10:
      case 13:
      case ' ':
        ++ts;
      default:
        return ts;
    }
  }
}

static INLINE const char* __Pyx_BufferTypestringCheckEndian(const char* ts) {
683 684
  int num = 1;
  int little_endian = ((char*)&num)[0];
685 686 687 688 689 690
  int ok = 1;
  switch (*ts) {
    case '@':
    case '=':
      ++ts; break;
    case '<':
691
      if (little_endian) ++ts;
692 693 694 695
      else ok = 0;
      break;
    case '>':
    case '!':
696
      if (!little_endian) ++ts;
697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712
      else ok = 0;
      break;
  }
  if (!ok) {
    PyErr_Format(PyExc_ValueError, "Buffer has wrong endianness (rejecting on '%s')", ts);
    return NULL;
  }
  return ts;
}

static void __Pyx_BufferNdimError(Py_buffer* buffer, int expected_ndim) {
  PyErr_Format(PyExc_ValueError,
               "Buffer has wrong number of dimensions (expected %d, got %d)",
               expected_ndim, buffer->ndim);
}

713 714 715 716 717
"""]

raise_buffer_fallback_code = ["""
static void __Pyx_RaiseBufferFallbackError(void); /*proto*/
""","""
718 719 720 721 722 723
static void __Pyx_RaiseBufferFallbackError(void) {
  PyErr_Format(PyExc_ValueError,
     "Buffer acquisition failed on assignment; and then reacquiring the old buffer failed too!");
}

"""]
724