Esempio n. 1
0
 def function_type(self):
     #  Construct a C function type descriptor for this signature
     args = []
     for i in xrange(self.num_fixed_args()):
         arg_type = self.fixed_arg_type(i)
         args.append(PyrexTypes.CFuncTypeArg("", arg_type, None))
     ret_type = self.return_type()
     exc_value = self.exception_value()
     return PyrexTypes.CFuncType(ret_type, args, exception_value=exc_value)
Esempio n. 2
0
	def function_type(self, self_type = None):
		#  Construct a C function type descriptor for this signature
		args = []
		#for i in xrange(self.num_fixed_args()):
		#	arg_type = self.fixed_arg_type(i)
		for c in self.fixed_arg_format:
			if c == "T":
				assert self_type is not None
				arg_type = self_type
			else:
				arg_type = self.format_map[c]
			args.append(PyrexTypes.CFuncTypeArg("", arg_type, None))
		ret_type = self.return_type()
		exc_value = self.exception_value()
		return PyrexTypes.CFuncType(ret_type, args, exception_value = exc_value)
Esempio n. 3
0
def init_builtins():
    init_builtin_structs()
    init_builtin_types()
    init_builtin_funcs()
    builtin_scope.declare_var('__debug__',
                              PyrexTypes.c_const_type(PyrexTypes.c_bint_type),
                              pos=None,
                              cname='(!Py_OptimizeFlag)',
                              is_cdef=True)
    global list_type, tuple_type, dict_type, set_type, frozenset_type
    global bytes_type, str_type, unicode_type, basestring_type, slice_type
    global float_type, bool_type, type_type, complex_type, bytearray_type
    type_type = builtin_scope.lookup('type').type
    list_type = builtin_scope.lookup('list').type
    tuple_type = builtin_scope.lookup('tuple').type
    dict_type = builtin_scope.lookup('dict').type
    set_type = builtin_scope.lookup('set').type
    frozenset_type = builtin_scope.lookup('frozenset').type
    slice_type = builtin_scope.lookup('slice').type
    bytes_type = builtin_scope.lookup('bytes').type
    str_type = builtin_scope.lookup('str').type
    unicode_type = builtin_scope.lookup('unicode').type
    basestring_type = builtin_scope.lookup('basestring').type
    bytearray_type = builtin_scope.lookup('bytearray').type
    float_type = builtin_scope.lookup('float').type
    bool_type = builtin_scope.lookup('bool').type
    complex_type = builtin_scope.lookup('complex').type
Esempio n. 4
0
 def function_type(self, self_arg_override=None):
     #  Construct a C function type descriptor for this signature
     args = []
     for i in xrange(self.num_fixed_args()):
         if self_arg_override is not None and self.is_self_arg(i):
             assert isinstance(self_arg_override, PyrexTypes.CFuncTypeArg)
             args.append(self_arg_override)
         else:
             arg_type = self.fixed_arg_type(i)
             args.append(PyrexTypes.CFuncTypeArg("", arg_type, None))
     if self_arg_override is not None and self.returns_self_type():
         ret_type = self_arg_override.type
     else:
         ret_type = self.return_type()
     exc_value = self.exception_value()
     return PyrexTypes.CFuncType(ret_type, args, exception_value=exc_value)
Esempio n. 5
0
def init_builtins():
    init_builtin_structs()
    init_builtin_types()
    init_builtin_funcs()
    builtin_scope.declare_var(
        '__debug__', PyrexTypes.c_const_type(PyrexTypes.c_bint_type),
        pos=None, cname='(!Py_OptimizeFlag)', is_cdef=True)
    global list_type, tuple_type, dict_type, set_type, frozenset_type
    global bytes_type, str_type, unicode_type, basestring_type, slice_type
    global float_type, bool_type, type_type, complex_type, bytearray_type
    type_type  = builtin_scope.lookup('type').type
    list_type  = builtin_scope.lookup('list').type
    tuple_type = builtin_scope.lookup('tuple').type
    dict_type  = builtin_scope.lookup('dict').type
    set_type   = builtin_scope.lookup('set').type
    frozenset_type = builtin_scope.lookup('frozenset').type
    slice_type   = builtin_scope.lookup('slice').type
    bytes_type = builtin_scope.lookup('bytes').type
    str_type   = builtin_scope.lookup('str').type
    unicode_type = builtin_scope.lookup('unicode').type
    basestring_type = builtin_scope.lookup('basestring').type
    bytearray_type = builtin_scope.lookup('bytearray').type
    float_type = builtin_scope.lookup('float').type
    bool_type  = builtin_scope.lookup('bool').type
    complex_type  = builtin_scope.lookup('complex').type
Esempio n. 6
0
    def __init__(self, entry):
        self.entry = entry
        self.type = entry.type
        self.cname = entry.cname
        self.buf_ptr = "%s.data" % self.cname

        dtype = self.entry.type.dtype
        dtype = PyrexTypes.CPtrType(dtype)

        self.buf_ptr_type = dtype
Esempio n. 7
0
 def declare_in_type(self, self_type):
     method_type, sig = self.func_type, self.sig
     if method_type is None:
         # override 'self' type (first argument)
         self_arg = PyrexTypes.CFuncTypeArg("", self_type, None)
         self_arg.not_none = True
         self_arg.accept_builtin_subtypes = True
         method_type = self.build_func_type(sig, self_arg)
     self_type.scope.declare_builtin_cfunction(
         self.py_name, method_type, self.cname, utility_code=self.utility_code)
Esempio n. 8
0
 def declare_in_type(self, self_type):
     method_type, sig = self.func_type, self.sig
     if method_type is None:
         if sig is None:
             sig = Signature(self.args, self.ret_type)
         # override 'self' type (first argument)
         self_arg = PyrexTypes.CFuncTypeArg("", self_type, None)
         self_arg.not_none = True
         method_type = sig.function_type(self_arg)
     self_type.scope.declare_builtin_cfunction(
         self.py_name, method_type, self.cname, utility_code = self.utility_code)
Esempio n. 9
0
def find_spanning_type(type1, type2):
    if type1 is type2:
        return type1
    elif type1 is PyrexTypes.c_bint_type or type2 is PyrexTypes.c_bint_type:
        # type inference can break the coercion back to a Python bool
        # if it returns an arbitrary int type here
        return py_object_type
    result_type = PyrexTypes.spanning_type(type1, type2)
    if result_type in (PyrexTypes.c_double_type, PyrexTypes.c_float_type, Builtin.float_type):
        # Python's float type is just a C double, so it's safe to
        # use the C type instead
        return PyrexTypes.c_double_type
    return result_type
Esempio n. 10
0
def find_spanning_type(type1, type2):
    if type1 is type2:
        return type1
    elif type1 is PyrexTypes.c_bint_type or type2 is PyrexTypes.c_bint_type:
        # type inference can break the coercion back to a Python bool
        # if it returns an arbitrary int type here
        return py_object_type
    result_type = PyrexTypes.spanning_type(type1, type2)
    if result_type in (PyrexTypes.c_double_type, PyrexTypes.c_float_type,
                       Builtin.float_type):
        # Python's float type is just a C double, so it's safe to
        # use the C type instead
        return PyrexTypes.c_double_type
    return result_type
Esempio n. 11
0
def put_assign_to_buffer(lhs_cname, rhs_cname, buffer_aux, buffer_type,
                         is_initialized, pos, code):
    """
    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).
    """

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

    code.putln("{")  # Set up necesarry stack for getbuffer
    code.putln("__Pyx_BufFmt_StackElem __pyx_stack[%d];" % buffer_type.dtype.struct_nesting_depth())
    
    getbuffer = get_getbuffer_call(code, "%s", buffer_aux, buffer_type) # fill in object below

    if is_initialized:
        # Release any existing buffer
        code.putln('__Pyx_SafeReleaseBuffer(&%s);' % bufstruct)
        # Acquire
        retcode_cname = code.funcstate.allocate_temp(PyrexTypes.c_int_type, manage_ref=False)
        code.putln("%s = %s;" % (retcode_cname, getbuffer % rhs_cname))
        code.putln('if (%s) {' % (code.unlikely("%s < 0" % retcode_cname)))
        # 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.
        type, value, tb = [code.funcstate.allocate_temp(PyrexTypes.py_object_type, manage_ref=False)
                           for i in range(3)]
        code.putln('PyErr_Fetch(&%s, &%s, &%s);' % (type, value, tb))
        code.putln('if (%s) {' % code.unlikely("%s == -1" % (getbuffer % lhs_cname)))
        code.putln('Py_XDECREF(%s); Py_XDECREF(%s); Py_XDECREF(%s);' % (type, value, tb)) # Do not refnanny these!
        code.globalstate.use_utility_code(raise_buffer_fallback_code)
        code.putln('__Pyx_RaiseBufferFallbackError();')
        code.putln('} else {')
        code.putln('PyErr_Restore(%s, %s, %s);' % (type, value, tb))
        for t in (type, value, tb):
            code.funcstate.release_temp(t)
        code.putln('}')
        code.putln('}')
        # Unpack indices
        put_unpack_buffer_aux_into_scope(buffer_aux, buffer_type.mode, code)
        code.putln(code.error_goto_if_neg(retcode_cname, pos))
        code.funcstate.release_temp(retcode_cname)
    else:
        # 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)))
        code.putln('%s = %s; __Pyx_INCREF(Py_None); %s.buf = NULL;' %
                   (lhs_cname,
                    PyrexTypes.typecast(buffer_type, PyrexTypes.py_object_type, "Py_None"),
                    bufstruct))
        code.putln(code.error_goto(pos))
        code.put('} else {')
        # Unpack indices
        put_unpack_buffer_aux_into_scope(buffer_aux, buffer_type.mode, code)
        code.putln('}')

    code.putln("}") # Release stack
Esempio n. 12
0
    # 'str',             # only in Py3.x
    # 'file',            # only in Py2.x
)

builtin_structs_table = [('Py_buffer', 'Py_buffer', [
    ("buf", PyrexTypes.c_void_ptr_type),
    ("obj", PyrexTypes.py_object_type),
    ("len", PyrexTypes.c_py_ssize_t_type),
    ("itemsize", PyrexTypes.c_py_ssize_t_type),
    ("readonly", PyrexTypes.c_bint_type),
    ("ndim", PyrexTypes.c_int_type),
    ("format", PyrexTypes.c_char_ptr_type),
    ("shape", PyrexTypes.c_py_ssize_t_ptr_type),
    ("strides", PyrexTypes.c_py_ssize_t_ptr_type),
    ("suboffsets", PyrexTypes.c_py_ssize_t_ptr_type),
    ("smalltable", PyrexTypes.CArrayType(PyrexTypes.c_py_ssize_t_type, 2)),
    ("internal", PyrexTypes.c_void_ptr_type),
]),
                         ('Py_complex', 'Py_complex', [
                             ('real', PyrexTypes.c_double_type),
                             ('imag', PyrexTypes.c_double_type),
                         ])]

# set up builtin scope

builtin_scope = BuiltinScope()


def init_builtin_funcs():
    for bf in builtin_function_table:
        bf.declare_in_scope(builtin_scope)
Esempio n. 13
0
                method_type.is_strict_signature = True
        self_type.scope.declare_builtin_cfunction(
            self.py_name, method_type, self.cname, utility_code = self.utility_code)


builtin_function_table = [
    # name,        args,   return,  C API func,           py equiv = "*"
    BuiltinFunction('abs',        "d",    "d",     "fabs",
                    is_strict_signature = True),
    BuiltinFunction('abs',        "f",    "f",     "fabsf",
                    is_strict_signature = True),
    BuiltinFunction('abs',        None,    None,   "__Pyx_abs_int",
                    utility_code = UtilityCode.load("abs_int", "Builtins.c"),
                    func_type = PyrexTypes.CFuncType(
                        PyrexTypes.c_uint_type, [
                            PyrexTypes.CFuncTypeArg("arg", PyrexTypes.c_int_type, None)
                            ],
                        is_strict_signature = True)),
    BuiltinFunction('abs',        None,    None,   "__Pyx_abs_long",
                    utility_code = UtilityCode.load("abs_long", "Builtins.c"),
                    func_type = PyrexTypes.CFuncType(
                        PyrexTypes.c_ulong_type, [
                            PyrexTypes.CFuncTypeArg("arg", PyrexTypes.c_long_type, None)
                            ],
                        is_strict_signature = True)),
    BuiltinFunction('abs',        None,    None,   "__Pyx_abs_longlong",
                    utility_code = UtilityCode.load("abs_longlong", "Builtins.c"),
                    func_type = PyrexTypes.CFuncType(
                        PyrexTypes.c_ulonglong_type, [
                            PyrexTypes.CFuncTypeArg("arg", PyrexTypes.c_longlong_type, None)
                        ],
Esempio n. 14
0
def put_assign_to_buffer(lhs_cname, rhs_cname, buffer_aux, buffer_type,
                         is_initialized, pos, code):
    """
    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).
    """

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

    code.putln("{")  # Set up necesarry stack for getbuffer
    code.putln("__Pyx_BufFmt_StackElem __pyx_stack[%d];" % buffer_type.dtype.struct_nesting_depth())

    getbuffer = get_getbuffer_call(code, "%s", buffer_aux, buffer_type) # fill in object below

    if is_initialized:
        # Release any existing buffer
        code.putln('__Pyx_SafeReleaseBuffer(&%s);' % bufstruct)
        # Acquire
        retcode_cname = code.funcstate.allocate_temp(PyrexTypes.c_int_type, manage_ref=False)
        code.putln("%s = %s;" % (retcode_cname, getbuffer % rhs_cname))
        code.putln('if (%s) {' % (code.unlikely("%s < 0" % retcode_cname)))
        # 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.
        type, value, tb = [code.funcstate.allocate_temp(PyrexTypes.py_object_type, manage_ref=False)
                           for i in range(3)]
        code.putln('PyErr_Fetch(&%s, &%s, &%s);' % (type, value, tb))
        code.putln('if (%s) {' % code.unlikely("%s == -1" % (getbuffer % lhs_cname)))
        code.putln('Py_XDECREF(%s); Py_XDECREF(%s); Py_XDECREF(%s);' % (type, value, tb)) # Do not refnanny these!
        code.globalstate.use_utility_code(raise_buffer_fallback_code)
        code.putln('__Pyx_RaiseBufferFallbackError();')
        code.putln('} else {')
        code.putln('PyErr_Restore(%s, %s, %s);' % (type, value, tb))
        for t in (type, value, tb):
            code.funcstate.release_temp(t)
        code.putln('}')
        code.putln('}')
        # Unpack indices
        put_unpack_buffer_aux_into_scope(buffer_aux, buffer_type.mode, code)
        code.putln(code.error_goto_if_neg(retcode_cname, pos))
        code.funcstate.release_temp(retcode_cname)
    else:
        # 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)))
        code.putln('%s = %s; __Pyx_INCREF(Py_None); %s.buf = NULL;' %
                   (lhs_cname,
                    PyrexTypes.typecast(buffer_type, PyrexTypes.py_object_type, "Py_None"),
                    bufstruct))
        code.putln(code.error_goto(pos))
        code.put('} else {')
        # Unpack indices
        put_unpack_buffer_aux_into_scope(buffer_aux, buffer_type.mode, code)
        code.putln('}')

    code.putln("}") # Release stack
Esempio n. 15
0
def insert_newaxes(memoryviewtype, n):
    axes = [('direct', 'strided')] * n
    axes.extend(memoryviewtype.axes)
    return PyrexTypes.MemoryViewSliceType(memoryviewtype.dtype, axes)