Cython has moved to github.
cython-devel
view Cython/Compiler/PyrexTypes.py @ 1802:fa0111c401cc
fix ticket #227: type check for bool is called PyBool_Check, not CheckExact
| author | Stefan Behnel <scoder@users.berlios.de> |
|---|---|
| date | Sun Mar 01 20:59:01 2009 +0100 (3 years ago) |
| parents | 2b34cb4ed73f |
| children | a7c984cb7a24 |
line source
1 #
2 # Pyrex - Types
3 #
5 from Cython.Utils import UtilityCode
6 import StringEncoding
7 import Naming
8 import copy
10 class BaseType(object):
11 #
12 # Base class for all Pyrex types including pseudo-types.
14 def cast_code(self, expr_code):
15 return "((%s)%s)" % (self.declaration_code(""), expr_code)
17 def base_declaration_code(self, base_code, entity_code):
18 if entity_code:
19 return "%s %s" % (base_code, entity_code)
20 else:
21 return base_code
23 class PyrexType(BaseType):
24 #
25 # Base class for all Pyrex types.
26 #
27 # is_pyobject boolean Is a Python object type
28 # is_extension_type boolean Is a Python extension type
29 # is_numeric boolean Is a C numeric type
30 # is_int boolean Is a C integer type
31 # is_longlong boolean Is a long long or unsigned long long.
32 # is_float boolean Is a C floating point type
33 # is_void boolean Is the C void type
34 # is_array boolean Is a C array type
35 # is_ptr boolean Is a C pointer type
36 # is_null_ptr boolean Is the type of NULL
37 # is_cfunction boolean Is a C function type
38 # is_struct_or_union boolean Is a C struct or union type
39 # is_struct boolean Is a C struct type
40 # is_enum boolean Is a C enum type
41 # is_typedef boolean Is a typedef type
42 # is_string boolean Is a C char * type
43 # is_unicode boolean Is a UTF-8 encoded C char * type
44 # is_returncode boolean Is used only to signal exceptions
45 # is_error boolean Is the dummy error type
46 # is_buffer boolean Is buffer access type
47 # has_attributes boolean Has C dot-selectable attributes
48 # default_value string Initial value
49 # parsetuple_format string Format char for PyArg_ParseTuple
50 # pymemberdef_typecode string Type code for PyMemberDef struct
51 #
52 # declaration_code(entity_code,
53 # for_display = 0, dll_linkage = None, pyrex = 0)
54 # Returns a code fragment for the declaration of an entity
55 # of this type, given a code fragment for the entity.
56 # * If for_display, this is for reading by a human in an error
57 # message; otherwise it must be valid C code.
58 # * If dll_linkage is not None, it must be 'DL_EXPORT' or
59 # 'DL_IMPORT', and will be added to the base type part of
60 # the declaration.
61 # * If pyrex = 1, this is for use in a 'cdef extern'
62 # statement of a Pyrex include file.
63 #
64 # assignable_from(src_type)
65 # Tests whether a variable of this type can be
66 # assigned a value of type src_type.
67 #
68 # same_as(other_type)
69 # Tests whether this type represents the same type
70 # as other_type.
71 #
72 # as_argument_type():
73 # Coerces array type into pointer type for use as
74 # a formal argument type.
75 #
77 is_pyobject = 0
78 is_extension_type = 0
79 is_builtin_type = 0
80 is_numeric = 0
81 is_int = 0
82 is_longlong = 0
83 is_float = 0
84 is_void = 0
85 is_array = 0
86 is_ptr = 0
87 is_null_ptr = 0
88 is_cfunction = 0
89 is_struct_or_union = 0
90 is_struct = 0
91 is_enum = 0
92 is_typedef = 0
93 is_string = 0
94 is_unicode = 0
95 is_returncode = 0
96 is_error = 0
97 is_buffer = 0
98 has_attributes = 0
99 default_value = ""
100 parsetuple_format = ""
101 pymemberdef_typecode = None
103 def resolve(self):
104 # If a typedef, returns the base type.
105 return self
107 def literal_code(self, value):
108 # Returns a C code fragment representing a literal
109 # value of this type.
110 return str(value)
112 def __str__(self):
113 return self.declaration_code("", for_display = 1).strip()
115 def same_as(self, other_type, **kwds):
116 return self.same_as_resolved_type(other_type.resolve(), **kwds)
118 def same_as_resolved_type(self, other_type):
119 return self == other_type or other_type is error_type
121 def subtype_of(self, other_type):
122 return self.subtype_of_resolved_type(other_type.resolve())
124 def subtype_of_resolved_type(self, other_type):
125 return self.same_as(other_type)
127 def assignable_from(self, src_type):
128 return self.assignable_from_resolved_type(src_type.resolve())
130 def assignable_from_resolved_type(self, src_type):
131 return self.same_as(src_type)
133 def as_argument_type(self):
134 return self
136 def is_complete(self):
137 # A type is incomplete if it is an unsized array,
138 # a struct whose attributes are not defined, etc.
139 return 1
141 def is_simple_buffer_dtype(self):
142 return (self.is_int or self.is_float or self.is_pyobject or
143 self.is_extension_type or self.is_ptr)
145 class CTypedefType(BaseType):
146 #
147 # Pseudo-type defined with a ctypedef statement in a
148 # 'cdef extern from' block. Delegates most attribute
149 # lookups to the base type. ANYTHING NOT DEFINED
150 # HERE IS DELEGATED!
151 #
152 # qualified_name string
153 # typedef_cname string
154 # typedef_base_type PyrexType
156 is_typedef = 1
158 def __init__(self, cname, base_type):
159 self.typedef_cname = cname
160 self.typedef_base_type = base_type
162 def resolve(self):
163 return self.typedef_base_type.resolve()
165 def declaration_code(self, entity_code,
166 for_display = 0, dll_linkage = None, pyrex = 0):
167 name = self.declaration_name(for_display, pyrex)
168 return self.base_declaration_code(name, entity_code)
170 def declaration_name(self, for_display = 0, pyrex = 0):
171 if pyrex or for_display:
172 return self.qualified_name
173 else:
174 return self.typedef_cname
176 def as_argument_type(self):
177 return self
179 def cast_code(self, expr_code):
180 # If self is really an array (rather than pointer), we can't cast.
181 # For example, the gmp mpz_t.
182 if self.typedef_base_type.is_ptr:
183 return self.typedef_base_type.cast_code(expr_code)
184 else:
185 return BaseType.cast_code(self, expr_code)
187 def __repr__(self):
188 return "<CTypedefType %s>" % self.typedef_cname
190 def __str__(self):
191 return self.declaration_name(for_display = 1)
193 def __getattr__(self, name):
194 return getattr(self.typedef_base_type, name)
196 class BufferType(BaseType):
197 #
198 # Delegates most attribute
199 # lookups to the base type. ANYTHING NOT DEFINED
200 # HERE IS DELEGATED!
202 # dtype PyrexType
203 # ndim int
204 # mode str
205 # negative_indices bool
206 # cast bool
207 # is_buffer bool
208 # writable bool
210 is_buffer = 1
211 writable = True
212 def __init__(self, base, dtype, ndim, mode, negative_indices, cast):
213 self.base = base
214 self.dtype = dtype
215 self.ndim = ndim
216 self.buffer_ptr_type = CPtrType(dtype)
217 self.mode = mode
218 self.negative_indices = negative_indices
219 self.cast = cast
221 def as_argument_type(self):
222 return self
224 def __getattr__(self, name):
225 return getattr(self.base, name)
227 def __repr__(self):
228 return "<BufferType %r>" % self.base
231 class PyObjectType(PyrexType):
232 #
233 # Base class for all Python object types (reference-counted).
234 #
235 # buffer_defaults dict or None Default options for bu
237 is_pyobject = 1
238 default_value = "0"
239 parsetuple_format = "O"
240 pymemberdef_typecode = "T_OBJECT"
241 buffer_defaults = None
243 def __str__(self):
244 return "Python object"
246 def __repr__(self):
247 return "<PyObjectType>"
249 def assignable_from(self, src_type):
250 return 1 # Conversion will be attempted
252 def declaration_code(self, entity_code,
253 for_display = 0, dll_linkage = None, pyrex = 0):
254 if pyrex or for_display:
255 return self.base_declaration_code("object", entity_code)
256 else:
257 return "%s *%s" % (public_decl("PyObject", dll_linkage), entity_code)
259 def as_pyobject(self, cname):
260 if (not self.is_complete()) or self.is_extension_type:
261 return "(PyObject *)" + cname
262 else:
263 return cname
265 class BuiltinObjectType(PyObjectType):
267 is_builtin_type = 1
268 has_attributes = 1
269 base_type = None
270 module_name = '__builtin__'
272 def __init__(self, name, cname):
273 self.name = name
274 self.cname = cname
275 self.typeptr_cname = "&" + cname
277 def set_scope(self, scope):
278 self.scope = scope
279 if scope:
280 scope.parent_type = self
282 def __str__(self):
283 return "%s object" % self.name
285 def __repr__(self):
286 return "<%s>"% self.cname
288 def assignable_from(self, src_type):
289 if isinstance(src_type, BuiltinObjectType):
290 return src_type.name == self.name
291 else:
292 return not src_type.is_extension_type
294 def typeobj_is_available(self):
295 return True
297 def attributes_known(self):
298 return True
300 def subtype_of(self, type):
301 return type.is_pyobject and self.assignable_from(type)
303 def type_test_code(self, arg):
304 type_name = self.name
305 if type_name == 'str':
306 check = 'PyString_CheckExact'
307 elif type_name == 'set':
308 check = 'PyAnySet_CheckExact'
309 elif type_name == 'frozenset':
310 check = 'PyFrozenSet_CheckExact'
311 elif type_name == 'bool':
312 check = 'PyBool_Check'
313 else:
314 check = 'Py%s_CheckExact' % type_name.capitalize()
315 return 'likely(%s(%s)) || (%s) == Py_None || (PyErr_Format(PyExc_TypeError, "Expected %s, got %%s", Py_TYPE(%s)->tp_name), 0)' % (check, arg, arg, self.name, arg)
317 def declaration_code(self, entity_code,
318 for_display = 0, dll_linkage = None, pyrex = 0):
319 if pyrex or for_display:
320 return self.base_declaration_code(self.name, entity_code)
321 else:
322 return "%s *%s" % (public_decl("PyObject", dll_linkage), entity_code)
325 class PyExtensionType(PyObjectType):
326 #
327 # A Python extension type.
328 #
329 # name string
330 # scope CClassScope Attribute namespace
331 # visibility string
332 # typedef_flag boolean
333 # base_type PyExtensionType or None
334 # module_name string or None Qualified name of defining module
335 # objstruct_cname string Name of PyObject struct
336 # typeobj_cname string or None C code fragment referring to type object
337 # typeptr_cname string or None Name of pointer to external type object
338 # vtabslot_cname string Name of C method table member
339 # vtabstruct_cname string Name of C method table struct
340 # vtabptr_cname string Name of pointer to C method table
341 # vtable_cname string Name of C method table definition
343 is_extension_type = 1
344 has_attributes = 1
346 def __init__(self, name, typedef_flag, base_type):
347 self.name = name
348 self.scope = None
349 self.typedef_flag = typedef_flag
350 self.base_type = base_type
351 self.module_name = None
352 self.objstruct_cname = None
353 self.typeobj_cname = None
354 self.typeptr_cname = None
355 self.vtabslot_cname = None
356 self.vtabstruct_cname = None
357 self.vtabptr_cname = None
358 self.vtable_cname = None
360 def set_scope(self, scope):
361 self.scope = scope
362 if scope:
363 scope.parent_type = self
365 def subtype_of_resolved_type(self, other_type):
366 if other_type.is_extension_type:
367 return self is other_type or (
368 self.base_type and self.base_type.subtype_of(other_type))
369 else:
370 return other_type is py_object_type
372 def typeobj_is_available(self):
373 # Do we have a pointer to the type object?
374 return self.typeptr_cname
376 def typeobj_is_imported(self):
377 # If we don't know the C name of the type object but we do
378 # know which module it's defined in, it will be imported.
379 return self.typeobj_cname is None and self.module_name is not None
381 def declaration_code(self, entity_code,
382 for_display = 0, dll_linkage = None, pyrex = 0, deref = 0):
383 if pyrex or for_display:
384 return self.base_declaration_code(self.name, entity_code)
385 else:
386 if self.typedef_flag:
387 base_format = "%s"
388 else:
389 base_format = "struct %s"
390 base = public_decl(base_format % self.objstruct_cname, dll_linkage)
391 if deref:
392 return "%s %s" % (base, entity_code)
393 else:
394 return "%s *%s" % (base, entity_code)
396 def type_test_code(self, py_arg):
397 return "__Pyx_TypeTest(%s, %s)" % (py_arg, self.typeptr_cname)
399 def attributes_known(self):
400 return self.scope is not None
402 def __str__(self):
403 return self.name
405 def __repr__(self):
406 return "<PyExtensionType %s%s>" % (self.scope.class_name,
407 ("", " typedef")[self.typedef_flag])
410 class CType(PyrexType):
411 #
412 # Base class for all C types (non-reference-counted).
413 #
414 # to_py_function string C function for converting to Python object
415 # from_py_function string C function for constructing from Python object
416 #
418 to_py_function = None
419 from_py_function = None
420 exception_value = None
421 exception_check = 1
423 def create_convert_utility_code(self, env):
424 return True
426 def error_condition(self, result_code):
427 conds = []
428 if self.is_string:
429 conds.append("(!%s)" % result_code)
430 elif self.exception_value is not None:
431 conds.append("(%s == (%s)%s)" % (result_code, self.sign_and_name(), self.exception_value))
432 if self.exception_check:
433 conds.append("PyErr_Occurred()")
434 if len(conds) > 0:
435 return " && ".join(conds)
436 else:
437 return 0
440 class CVoidType(CType):
441 is_void = 1
443 def __repr__(self):
444 return "<CVoidType>"
446 def declaration_code(self, entity_code,
447 for_display = 0, dll_linkage = None, pyrex = 0):
448 base = public_decl("void", dll_linkage)
449 return self.base_declaration_code(base, entity_code)
451 def is_complete(self):
452 return 0
455 class CNumericType(CType):
456 #
457 # Base class for all C numeric types.
458 #
459 # rank integer Relative size
460 # signed integer 0 = unsigned, 1 = unspecified, 2 = explicitly signed
461 #
463 is_numeric = 1
464 default_value = "0"
466 parsetuple_formats = ( # rank -> format
467 "BHIk??K???", # unsigned
468 "bhil??Lfd?", # assumed signed
469 "bhil??Lfd?", # explicitly signed
470 )
472 sign_words = ("unsigned ", "", "signed ")
474 def __init__(self, rank, signed = 1, pymemberdef_typecode = None):
475 self.rank = rank
476 self.signed = signed
477 ptf = self.parsetuple_formats[signed][rank]
478 if ptf == '?':
479 ptf = None
480 self.parsetuple_format = ptf
481 self.pymemberdef_typecode = pymemberdef_typecode
483 def sign_and_name(self):
484 s = self.sign_words[self.signed]
485 n = rank_to_type_name[self.rank]
486 return s + n
488 def __repr__(self):
489 return "<CNumericType %s>" % self.sign_and_name()
491 def declaration_code(self, entity_code,
492 for_display = 0, dll_linkage = None, pyrex = 0):
493 base = public_decl(self.sign_and_name(), dll_linkage)
494 if for_display and self.is_longlong:
495 base = base.replace('PY_LONG_LONG', 'long long')
496 return self.base_declaration_code(base, entity_code)
499 int_conversion_list = {}
500 type_conversion_functions = ""
501 type_conversion_predeclarations = ""
503 class CIntType(CNumericType):
505 is_int = 1
506 typedef_flag = 0
507 to_py_function = "PyInt_FromLong"
508 from_py_function = "__pyx_PyInt_AsLong"
509 exception_value = -1
511 def __init__(self, rank, signed, pymemberdef_typecode = None, is_returncode = 0):
512 CNumericType.__init__(self, rank, signed, pymemberdef_typecode)
513 self.is_returncode = is_returncode
514 if self.from_py_function == '__pyx_PyInt_AsLong':
515 self.from_py_function = self.get_type_conversion()
517 def get_type_conversion(self):
518 # error on overflow
519 c_type = self.sign_and_name()
520 c_name = c_type.replace(' ', '_');
521 func_name = "__pyx_PyInt_%s" % c_name;
522 if func_name not in int_conversion_list:
523 # no env to add utility code to
524 global type_conversion_predeclarations, type_conversion_functions
525 if self.signed:
526 neg_test = ""
527 else:
528 neg_test = " || (long_val < 0)"
529 type_conversion_predeclarations += """
530 static INLINE %(c_type)s %(func_name)s(PyObject* x);""" % {'c_type': c_type, 'c_name': c_name, 'func_name': func_name }
531 type_conversion_functions += """
532 static INLINE %(c_type)s %(func_name)s(PyObject* x) {
533 if (sizeof(%(c_type)s) < sizeof(long)) {
534 long long_val = __pyx_PyInt_AsLong(x);
535 %(c_type)s val = (%(c_type)s)long_val;
536 if (unlikely((val != long_val) %(neg_test)s)) {
537 PyErr_SetString(PyExc_OverflowError, "value too large to convert to %(c_type)s");
538 return (%(c_type)s)-1;
539 }
540 return val;
541 }
542 else {
543 return __pyx_PyInt_AsLong(x);
544 }
545 }
546 """ % {'c_type': c_type, 'c_name': c_name, 'func_name': func_name, 'neg_test': neg_test }
547 int_conversion_list[func_name] = True
548 return func_name
550 def assignable_from_resolved_type(self, src_type):
551 return src_type.is_int or src_type.is_enum or src_type is error_type
554 class CBIntType(CIntType):
556 to_py_function = "__Pyx_PyBool_FromLong"
557 from_py_function = "__Pyx_PyObject_IsTrue"
558 exception_check = 0
561 class CAnonEnumType(CIntType):
563 is_enum = 1
566 class CUIntType(CIntType):
568 to_py_function = "PyLong_FromUnsignedLong"
569 from_py_function = "PyInt_AsUnsignedLongMask"
570 exception_value = -1
573 class CULongType(CUIntType):
575 to_py_function = "PyLong_FromUnsignedLong"
576 from_py_function = "PyInt_AsUnsignedLongMask"
579 class CLongLongType(CIntType):
581 is_longlong = 1
582 to_py_function = "PyLong_FromLongLong"
583 from_py_function = "__pyx_PyInt_AsLongLong"
586 class CULongLongType(CUIntType):
588 is_longlong = 1
589 to_py_function = "PyLong_FromUnsignedLongLong"
590 from_py_function = "__pyx_PyInt_AsUnsignedLongLong"
593 class CPySSizeTType(CIntType):
595 to_py_function = "PyInt_FromSsize_t"
596 from_py_function = "__pyx_PyIndex_AsSsize_t"
598 def sign_and_name(self):
599 return rank_to_type_name[self.rank]
602 class CSizeTType(CUIntType):
604 to_py_function = "__pyx_PyInt_FromSize_t"
605 from_py_function = "__pyx_PyInt_AsSize_t"
607 def sign_and_name(self):
608 return rank_to_type_name[self.rank]
611 class CFloatType(CNumericType):
613 is_float = 1
614 to_py_function = "PyFloat_FromDouble"
615 from_py_function = "__pyx_PyFloat_AsDouble"
617 def __init__(self, rank, pymemberdef_typecode = None):
618 CNumericType.__init__(self, rank, 1, pymemberdef_typecode)
620 def assignable_from_resolved_type(self, src_type):
621 return src_type.is_numeric or src_type is error_type
624 class CArrayType(CType):
625 # base_type CType Element type
626 # size integer or None Number of elements
628 is_array = 1
630 def __init__(self, base_type, size):
631 self.base_type = base_type
632 self.size = size
633 if base_type is c_char_type:
634 self.is_string = 1
636 def __repr__(self):
637 return "<CArrayType %s %s>" % (self.size, repr(self.base_type))
639 def same_as_resolved_type(self, other_type):
640 return ((other_type.is_array and
641 self.base_type.same_as(other_type.base_type))
642 or other_type is error_type)
644 def assignable_from_resolved_type(self, src_type):
645 # Can't assign to a variable of an array type
646 return 0
648 def element_ptr_type(self):
649 return c_ptr_type(self.base_type)
651 def declaration_code(self, entity_code,
652 for_display = 0, dll_linkage = None, pyrex = 0):
653 if self.size is not None:
654 dimension_code = self.size
655 else:
656 dimension_code = ""
657 if entity_code.startswith("*"):
658 entity_code = "(%s)" % entity_code
659 return self.base_type.declaration_code(
660 "%s[%s]" % (entity_code, dimension_code),
661 for_display, dll_linkage, pyrex)
663 def as_argument_type(self):
664 return c_ptr_type(self.base_type)
666 def is_complete(self):
667 return self.size is not None
670 class CPtrType(CType):
671 # base_type CType Referenced type
673 is_ptr = 1
674 default_value = "0"
676 def __init__(self, base_type):
677 self.base_type = base_type
679 def __repr__(self):
680 return "<CPtrType %s>" % repr(self.base_type)
682 def same_as_resolved_type(self, other_type):
683 return ((other_type.is_ptr and
684 self.base_type.same_as(other_type.base_type))
685 or other_type is error_type)
687 def declaration_code(self, entity_code,
688 for_display = 0, dll_linkage = None, pyrex = 0):
689 #print "CPtrType.declaration_code: pointer to", self.base_type ###
690 return self.base_type.declaration_code(
691 "*%s" % entity_code,
692 for_display, dll_linkage, pyrex)
694 def assignable_from_resolved_type(self, other_type):
695 if other_type is error_type:
696 return 1
697 if other_type.is_null_ptr:
698 return 1
699 if self.base_type.is_cfunction:
700 if other_type.is_ptr:
701 other_type = other_type.base_type.resolve()
702 if other_type.is_cfunction:
703 return self.base_type.pointer_assignable_from_resolved_type(other_type)
704 else:
705 return 0
706 if other_type.is_array or other_type.is_ptr:
707 return self.base_type.is_void or self.base_type.same_as(other_type.base_type)
708 return 0
711 class CNullPtrType(CPtrType):
713 is_null_ptr = 1
716 class CFuncType(CType):
717 # return_type CType
718 # args [CFuncTypeArg]
719 # has_varargs boolean
720 # exception_value string
721 # exception_check boolean True if PyErr_Occurred check needed
722 # calling_convention string Function calling convention
723 # nogil boolean Can be called without gil
724 # with_gil boolean Acquire gil around function body
726 is_cfunction = 1
727 original_sig = None
729 def __init__(self, return_type, args, has_varargs = 0,
730 exception_value = None, exception_check = 0, calling_convention = "",
731 nogil = 0, with_gil = 0, is_overridable = 0, optional_arg_count = 0):
732 self.return_type = return_type
733 self.args = args
734 self.has_varargs = has_varargs
735 self.optional_arg_count = optional_arg_count
736 self.exception_value = exception_value
737 self.exception_check = exception_check
738 self.calling_convention = calling_convention
739 self.nogil = nogil
740 self.with_gil = with_gil
741 self.is_overridable = is_overridable
743 def __repr__(self):
744 arg_reprs = map(repr, self.args)
745 if self.has_varargs:
746 arg_reprs.append("...")
747 return "<CFuncType %s %s[%s]>" % (
748 repr(self.return_type),
749 self.calling_convention_prefix(),
750 ",".join(arg_reprs))
752 def calling_convention_prefix(self):
753 cc = self.calling_convention
754 if cc:
755 return cc + " "
756 else:
757 return ""
759 def same_c_signature_as(self, other_type, as_cmethod = 0):
760 return self.same_c_signature_as_resolved_type(
761 other_type.resolve(), as_cmethod)
763 def same_c_signature_as_resolved_type(self, other_type, as_cmethod = 0):
764 #print "CFuncType.same_c_signature_as_resolved_type:", \
765 # self, other_type, "as_cmethod =", as_cmethod ###
766 if other_type is error_type:
767 return 1
768 if not other_type.is_cfunction:
769 return 0
770 if self.is_overridable != other_type.is_overridable:
771 return 0
772 nargs = len(self.args)
773 if nargs != len(other_type.args):
774 return 0
775 # When comparing C method signatures, the first argument
776 # is exempt from compatibility checking (the proper check
777 # is performed elsewhere).
778 for i in range(as_cmethod, nargs):
779 if not self.args[i].type.same_as(
780 other_type.args[i].type):
781 return 0
782 if self.has_varargs != other_type.has_varargs:
783 return 0
784 if self.optional_arg_count != other_type.optional_arg_count:
785 return 0
786 if not self.return_type.same_as(other_type.return_type):
787 return 0
788 if not self.same_calling_convention_as(other_type):
789 return 0
790 return 1
792 def compatible_signature_with(self, other_type, as_cmethod = 0):
793 return self.compatible_signature_with_resolved_type(other_type.resolve(), as_cmethod)
795 def compatible_signature_with_resolved_type(self, other_type, as_cmethod):
796 #print "CFuncType.same_c_signature_as_resolved_type:", \
797 # self, other_type, "as_cmethod =", as_cmethod ###
798 if other_type is error_type:
799 return 1
800 if not other_type.is_cfunction:
801 return 0
802 if not self.is_overridable and other_type.is_overridable:
803 return 0
804 nargs = len(self.args)
805 if nargs - self.optional_arg_count != len(other_type.args) - other_type.optional_arg_count:
806 return 0
807 if self.optional_arg_count < other_type.optional_arg_count:
808 return 0
809 # When comparing C method signatures, the first argument
810 # is exempt from compatibility checking (the proper check
811 # is performed elsewhere).
812 for i in range(as_cmethod, len(other_type.args)):
813 if not self.args[i].type.same_as(
814 other_type.args[i].type):
815 return 0
816 if self.has_varargs != other_type.has_varargs:
817 return 0
818 if not self.return_type.subtype_of_resolved_type(other_type.return_type):
819 return 0
820 if not self.same_calling_convention_as(other_type):
821 return 0
822 if self.nogil != other_type.nogil:
823 return 0
824 self.original_sig = other_type.original_sig or other_type
825 if as_cmethod:
826 self.args[0] = other_type.args[0]
827 return 1
830 def narrower_c_signature_than(self, other_type, as_cmethod = 0):
831 return self.narrower_c_signature_than_resolved_type(other_type.resolve(), as_cmethod)
833 def narrower_c_signature_than_resolved_type(self, other_type, as_cmethod):
834 if other_type is error_type:
835 return 1
836 if not other_type.is_cfunction:
837 return 0
838 nargs = len(self.args)
839 if nargs != len(other_type.args):
840 return 0
841 for i in range(as_cmethod, nargs):
842 if not self.args[i].type.subtype_of_resolved_type(other_type.args[i].type):
843 return 0
844 else:
845 self.args[i].needs_type_test = other_type.args[i].needs_type_test \
846 or not self.args[i].type.same_as(other_type.args[i].type)
847 if self.has_varargs != other_type.has_varargs:
848 return 0
849 if self.optional_arg_count != other_type.optional_arg_count:
850 return 0
851 if not self.return_type.subtype_of_resolved_type(other_type.return_type):
852 return 0
853 return 1
855 def same_calling_convention_as(self, other):
856 sc1 = self.calling_convention == '__stdcall'
857 sc2 = other.calling_convention == '__stdcall'
858 return sc1 == sc2
860 def same_exception_signature_as(self, other_type):
861 return self.same_exception_signature_as_resolved_type(
862 other_type.resolve())
864 def same_exception_signature_as_resolved_type(self, other_type):
865 return self.exception_value == other_type.exception_value \
866 and self.exception_check == other_type.exception_check
868 def same_as_resolved_type(self, other_type, as_cmethod = 0):
869 return self.same_c_signature_as_resolved_type(other_type, as_cmethod) \
870 and self.same_exception_signature_as_resolved_type(other_type) \
871 and self.nogil == other_type.nogil
873 def pointer_assignable_from_resolved_type(self, other_type):
874 return self.same_c_signature_as_resolved_type(other_type) \
875 and self.same_exception_signature_as_resolved_type(other_type) \
876 and not (self.nogil and not other_type.nogil)
878 def declaration_code(self, entity_code,
879 for_display = 0, dll_linkage = None, pyrex = 0,
880 with_calling_convention = 1):
881 arg_decl_list = []
882 for arg in self.args[:len(self.args)-self.optional_arg_count]:
883 arg_decl_list.append(
884 arg.type.declaration_code("", for_display, pyrex = pyrex))
885 if self.is_overridable:
886 arg_decl_list.append("int %s" % Naming.skip_dispatch_cname)
887 if self.optional_arg_count:
888 arg_decl_list.append(self.op_arg_struct.declaration_code(Naming.optional_args_cname))
889 if self.has_varargs:
890 arg_decl_list.append("...")
891 arg_decl_code = ", ".join(arg_decl_list)
892 if not arg_decl_code and not pyrex:
893 arg_decl_code = "void"
894 trailer = ""
895 if (pyrex or for_display) and not self.return_type.is_pyobject:
896 if self.exception_value and self.exception_check:
897 trailer = " except? %s" % self.exception_value
898 elif self.exception_value:
899 trailer = " except %s" % self.exception_value
900 elif self.exception_check == '+':
901 trailer = " except +"
902 else:
903 " except *" # ignored
904 if self.nogil:
905 trailer += " nogil"
906 if not with_calling_convention:
907 cc = ''
908 else:
909 cc = self.calling_convention_prefix()
910 if (not entity_code and cc) or entity_code.startswith("*"):
911 entity_code = "(%s%s)" % (cc, entity_code)
912 cc = ""
913 return self.return_type.declaration_code(
914 "%s%s(%s)%s" % (cc, entity_code, arg_decl_code, trailer),
915 for_display, dll_linkage, pyrex)
917 def function_header_code(self, func_name, arg_code):
918 return "%s%s(%s)" % (self.calling_convention_prefix(),
919 func_name, arg_code)
921 def signature_string(self):
922 s = self.declaration_code("")
923 return s
925 def signature_cast_string(self):
926 s = self.declaration_code("(*)", with_calling_convention=False)
927 return '(%s)' % s
930 class CFuncTypeArg:
931 # name string
932 # cname string
933 # type PyrexType
934 # pos source file position
936 def __init__(self, name, type, pos, cname=None):
937 self.name = name
938 if cname is not None:
939 self.cname = cname
940 else:
941 self.cname = Naming.var_prefix + name
942 self.type = type
943 self.pos = pos
944 self.not_none = False
945 self.needs_type_test = False # TODO: should these defaults be set in analyse_types()?
947 def __repr__(self):
948 return "%s:%s" % (self.name, repr(self.type))
950 def declaration_code(self, for_display = 0):
951 return self.type.declaration_code(self.cname, for_display)
954 class CStructOrUnionType(CType):
955 # name string
956 # cname string
957 # kind string "struct" or "union"
958 # scope StructOrUnionScope, or None if incomplete
959 # typedef_flag boolean
961 is_struct_or_union = 1
962 has_attributes = 1
964 def __init__(self, name, kind, scope, typedef_flag, cname):
965 self.name = name
966 self.cname = cname
967 self.kind = kind
968 self.scope = scope
969 self.typedef_flag = typedef_flag
970 self.is_struct = kind == 'struct'
971 if self.is_struct:
972 self.to_py_function = "%s_to_py_%s" % (Naming.convert_func_prefix, self.cname)
973 self.exception_check = True
974 self._convert_code = None
976 def create_convert_utility_code(self, env):
977 if env.outer_scope is None:
978 return False
979 if self._convert_code is None:
980 import Code
981 code = Code.CCodeWriter()
982 header = "static PyObject* %s(%s)" % (self.to_py_function, self.declaration_code('s'))
983 code.putln("%s {" % header)
984 code.putln("PyObject* res;")
985 code.putln("PyObject* member;")
986 code.putln("res = PyDict_New(); if (res == NULL) return NULL;")
987 for member in self.scope.var_entries:
988 if member.type.to_py_function and member.type.create_convert_utility_code(env):
989 interned_name = env.get_string_const(member.name, identifier=True)
990 env.add_py_string(interned_name)
991 code.putln("member = %s(s.%s); if (member == NULL) goto bad;" % (
992 member.type.to_py_function, member.cname))
993 code.putln("if (PyDict_SetItem(res, %s, member) < 0) goto bad;" % interned_name.pystring_cname)
994 code.putln("Py_DECREF(member);")
995 else:
996 self.to_py_function = None
997 return False
998 code.putln("return res;")
999 code.putln("bad:")
1000 code.putln("Py_XDECREF(member);")
1001 code.putln("Py_DECREF(res);")
1002 code.putln("return NULL;")
1003 code.putln("}")
1004 proto = header + ";"
1005 # This is a bit of a hack, we need a forward declaration
1006 # due to the way things are ordered in the module...
1007 entry = env.lookup(self.name)
1008 if entry.visibility != 'extern':
1009 proto = self.declaration_code('') + ';\n' + proto
1010 self._convert_code = UtilityCode(proto=proto, impl=code.buffer.getvalue())
1012 env.use_utility_code(self._convert_code)
1013 return True
1015 def __repr__(self):
1016 return "<CStructOrUnionType %s %s%s>" % (self.name, self.cname,
1017 ("", " typedef")[self.typedef_flag])
1019 def declaration_code(self, entity_code,
1020 for_display = 0, dll_linkage = None, pyrex = 0):
1021 if pyrex:
1022 return self.base_declaration_code(self.name, entity_code)
1023 else:
1024 if for_display:
1025 base = self.name
1026 elif self.typedef_flag:
1027 base = self.cname
1028 else:
1029 base = "%s %s" % (self.kind, self.cname)
1030 return self.base_declaration_code(public_decl(base, dll_linkage), entity_code)
1032 def __cmp__(self, other):
1033 try:
1034 if self.name == other.name:
1035 return 0
1036 else:
1037 return 1
1038 except AttributeError:
1039 return 1
1041 def is_complete(self):
1042 return self.scope is not None
1044 def attributes_known(self):
1045 return self.is_complete()
1047 def can_be_complex(self):
1048 # Does the struct consist of exactly two floats?
1049 fields = self.scope.var_entries
1050 return len(fields) == 2 and fields[0].type.is_float and fields[1].type.is_float
1053 class CEnumType(CType):
1054 # name string
1055 # cname string or None
1056 # typedef_flag boolean
1058 is_enum = 1
1059 signed = 1
1060 rank = -1 # Ranks below any integer type
1061 to_py_function = "PyInt_FromLong"
1062 from_py_function = "PyInt_AsLong"
1064 def __init__(self, name, cname, typedef_flag):
1065 self.name = name
1066 self.cname = cname
1067 self.values = []
1068 self.typedef_flag = typedef_flag
1070 def __str__(self):
1071 return self.name
1073 def __repr__(self):
1074 return "<CEnumType %s %s%s>" % (self.name, self.cname,
1075 ("", " typedef")[self.typedef_flag])
1077 def declaration_code(self, entity_code,
1078 for_display = 0, dll_linkage = None, pyrex = 0):
1079 if pyrex:
1080 return self.base_declaration_code(self.cname, entity_code)
1081 else:
1082 if self.typedef_flag:
1083 base = self.cname
1084 else:
1085 base = "enum %s" % self.cname
1086 return self.base_declaration_code(public_decl(base, dll_linkage), entity_code)
1089 class CStringType:
1090 # Mixin class for C string types.
1092 is_string = 1
1093 is_unicode = 0
1095 to_py_function = "__Pyx_PyBytes_FromString"
1096 from_py_function = "__Pyx_PyBytes_AsString"
1097 exception_value = "NULL"
1099 def literal_code(self, value):
1100 assert isinstance(value, str)
1101 return '"%s"' % StringEncoding.escape_byte_string(value)
1104 class CUTF8CharArrayType(CStringType, CArrayType):
1105 # C 'char []' type.
1107 parsetuple_format = "s"
1108 pymemberdef_typecode = "T_STRING_INPLACE"
1109 is_unicode = 1
1111 to_py_function = "PyUnicode_DecodeUTF8"
1112 exception_value = "NULL"
1114 def __init__(self, size):
1115 CArrayType.__init__(self, c_char_type, size)
1117 class CCharArrayType(CStringType, CArrayType):
1118 # C 'char []' type.
1120 parsetuple_format = "s"
1121 pymemberdef_typecode = "T_STRING_INPLACE"
1123 def __init__(self, size):
1124 CArrayType.__init__(self, c_char_type, size)
1127 class CCharPtrType(CStringType, CPtrType):
1128 # C 'char *' type.
1130 parsetuple_format = "s"
1131 pymemberdef_typecode = "T_STRING"
1133 def __init__(self):
1134 CPtrType.__init__(self, c_char_type)
1137 class UnspecifiedType(PyrexType):
1138 # Used as a placeholder until the type can be determined.
1140 def declaration_code(self, entity_code,
1141 for_display = 0, dll_linkage = None, pyrex = 0):
1142 return "<unspecified>"
1144 def same_as_resolved_type(self, other_type):
1145 return False
1148 class ErrorType(PyrexType):
1149 # Used to prevent propagation of error messages.
1151 is_error = 1
1152 exception_value = "0"
1153 exception_check = 0
1154 to_py_function = "dummy"
1155 from_py_function = "dummy"
1157 def create_convert_utility_code(self, env):
1158 return True
1160 def declaration_code(self, entity_code,
1161 for_display = 0, dll_linkage = None, pyrex = 0):
1162 return "<error>"
1164 def same_as_resolved_type(self, other_type):
1165 return 1
1167 def error_condition(self, result_code):
1168 return "dummy"
1171 rank_to_type_name = (
1172 "char", # 0
1173 "short", # 1
1174 "int", # 2
1175 "long", # 3
1176 "Py_ssize_t", # 4
1177 "size_t", # 5
1178 "PY_LONG_LONG", # 6
1179 "float", # 7
1180 "double", # 8
1181 "long double", # 9
1182 )
1184 py_object_type = PyObjectType()
1186 c_void_type = CVoidType()
1187 c_void_ptr_type = CPtrType(c_void_type)
1188 c_void_ptr_ptr_type = CPtrType(c_void_ptr_type)
1190 c_uchar_type = CIntType(0, 0, "T_UBYTE")
1191 c_ushort_type = CIntType(1, 0, "T_USHORT")
1192 c_uint_type = CUIntType(2, 0, "T_UINT")
1193 c_ulong_type = CULongType(3, 0, "T_ULONG")
1194 c_ulonglong_type = CULongLongType(6, 0, "T_ULONGLONG")
1196 c_char_type = CIntType(0, 1, "T_CHAR")
1197 c_short_type = CIntType(1, 1, "T_SHORT")
1198 c_int_type = CIntType(2, 1, "T_INT")
1199 c_long_type = CIntType(3, 1, "T_LONG")
1200 c_longlong_type = CLongLongType(6, 1, "T_LONGLONG")
1201 c_bint_type = CBIntType(2, 1, "T_INT")
1203 c_schar_type = CIntType(0, 2, "T_CHAR")
1204 c_sshort_type = CIntType(1, 2, "T_SHORT")
1205 c_sint_type = CIntType(2, 2, "T_INT")
1206 c_slong_type = CIntType(3, 2, "T_LONG")
1207 c_slonglong_type = CLongLongType(6, 2, "T_LONGLONG")
1209 c_py_ssize_t_type = CPySSizeTType(4, 2, "T_PYSSIZET")
1210 c_size_t_type = CSizeTType(5, 0, "T_SIZET")
1212 c_float_type = CFloatType(7, "T_FLOAT")
1213 c_double_type = CFloatType(8, "T_DOUBLE")
1214 c_longdouble_type = CFloatType(9)
1216 c_null_ptr_type = CNullPtrType(c_void_type)
1217 c_char_array_type = CCharArrayType(None)
1218 c_char_ptr_type = CCharPtrType()
1219 c_utf8_char_array_type = CUTF8CharArrayType(None)
1220 c_char_ptr_ptr_type = CPtrType(c_char_ptr_type)
1221 c_int_ptr_type = CPtrType(c_int_type)
1222 c_py_ssize_t_ptr_type = CPtrType(c_py_ssize_t_type)
1223 c_size_t_ptr_type = CPtrType(c_size_t_type)
1225 c_returncode_type = CIntType(2, 1, "T_INT", is_returncode = 1)
1227 c_anon_enum_type = CAnonEnumType(-1, 1)
1229 # the Py_buffer type is defined in Builtin.py
1230 c_py_buffer_type = CStructOrUnionType("Py_buffer", "struct", None, 1, "Py_buffer")
1231 c_py_buffer_ptr_type = CPtrType(c_py_buffer_type)
1233 error_type = ErrorType()
1234 unspecified_type = UnspecifiedType()
1236 sign_and_rank_to_type = {
1237 #(signed, rank)
1238 (0, 0): c_uchar_type,
1239 (0, 1): c_ushort_type,
1240 (0, 2): c_uint_type,
1241 (0, 3): c_ulong_type,
1242 (0, 6): c_ulonglong_type,
1244 (1, 0): c_char_type,
1245 (1, 1): c_short_type,
1246 (1, 2): c_int_type,
1247 (1, 3): c_long_type,
1248 (1, 6): c_longlong_type,
1250 (2, 0): c_schar_type,
1251 (2, 1): c_sshort_type,
1252 (2, 2): c_sint_type,
1253 (2, 3): c_slong_type,
1254 (2, 6): c_slonglong_type,
1256 (0, 4): c_py_ssize_t_type,
1257 (1, 4): c_py_ssize_t_type,
1258 (2, 4): c_py_ssize_t_type,
1259 (0, 5): c_size_t_type,
1260 (1, 5): c_size_t_type,
1261 (2, 5): c_size_t_type,
1263 (1, 7): c_float_type,
1264 (1, 8): c_double_type,
1265 (1, 9): c_longdouble_type,
1266 # In case we're mixing unsigned ints and floats...
1267 (0, 7): c_float_type,
1268 (0, 8): c_double_type,
1269 (0, 9): c_longdouble_type,
1270 }
1272 modifiers_and_name_to_type = {
1273 #(signed, longness, name)
1274 (0, 0, "char"): c_uchar_type,
1275 (0, -1, "int"): c_ushort_type,
1276 (0, 0, "int"): c_uint_type,
1277 (0, 1, "int"): c_ulong_type,
1278 (0, 2, "int"): c_ulonglong_type,
1279 (1, 0, "void"): c_void_type,
1280 (1, 0, "char"): c_char_type,
1281 (1, -1, "int"): c_short_type,
1282 (1, 0, "int"): c_int_type,
1283 (1, 1, "int"): c_long_type,
1284 (1, 2, "int"): c_longlong_type,
1285 (1, 0, "float"): c_float_type,
1286 (1, 0, "double"): c_double_type,
1287 (1, 1, "double"): c_longdouble_type,
1288 (1, 0, "object"): py_object_type,
1289 (1, 0, "bint"): c_bint_type,
1290 (2, 0, "char"): c_schar_type,
1291 (2, -1, "int"): c_sshort_type,
1292 (2, 0, "int"): c_sint_type,
1293 (2, 1, "int"): c_slong_type,
1294 (2, 2, "int"): c_slonglong_type,
1296 (2, 0, "Py_ssize_t"): c_py_ssize_t_type,
1297 (0, 0, "size_t") : c_size_t_type,
1299 (1, 0, "long"): c_long_type,
1300 (1, 0, "short"): c_short_type,
1301 (1, 0, "longlong"): c_longlong_type,
1302 (1, 0, "bint"): c_bint_type,
1303 }
1305 def widest_numeric_type(type1, type2):
1306 # Given two numeric types, return the narrowest type
1307 # encompassing both of them.
1308 if type1.is_enum and type2.is_enum:
1309 return c_int_type
1310 elif type1 is type2:
1311 return type1
1312 elif (type1.signed and type2.signed) or (not type1.signed and not type2.signed):
1313 if type2.rank > type1.rank:
1314 return type2
1315 else:
1316 return type1
1317 else:
1318 return sign_and_rank_to_type[min(type1.signed, type2.signed), max(type1.rank, type2.rank)]
1319 return widest_type
1321 def simple_c_type(signed, longness, name):
1322 # Find type descriptor for simple type given name and modifiers.
1323 # Returns None if arguments don't make sense.
1324 return modifiers_and_name_to_type.get((signed, longness, name))
1326 def parse_basic_type(name):
1327 base = None
1328 if name.startswith('p_'):
1329 base = parse_basic_type(name[2:])
1330 elif name.startswith('p'):
1331 base = parse_basic_type(name[1:])
1332 elif name.endswith('*'):
1333 base = parse_basic_type(name[:-1])
1334 if base:
1335 return CPtrType(base)
1336 elif name.startswith('u'):
1337 return simple_c_type(0, 0, name[1:])
1338 else:
1339 return simple_c_type(1, 0, name)
1341 def c_array_type(base_type, size):
1342 # Construct a C array type.
1343 if base_type is c_char_type:
1344 return CCharArrayType(size)
1345 elif base_type is error_type:
1346 return error_type
1347 else:
1348 return CArrayType(base_type, size)
1350 def c_ptr_type(base_type):
1351 # Construct a C pointer type.
1352 if base_type is c_char_type:
1353 return c_char_ptr_type
1354 elif base_type is error_type:
1355 return error_type
1356 else:
1357 return CPtrType(base_type)
1359 def Node_to_type(node, env):
1360 from ExprNodes import NameNode, AttributeNode, StringNode, error
1361 if isinstance(node, StringNode):
1362 node = NameNode(node.pos, name=node.value)
1363 if isinstance(node, NameNode) and node.name in rank_to_type_name:
1364 return simple_c_type(1, 0, node.name)
1365 elif isinstance(node, (AttributeNode, NameNode)):
1366 node.analyze_types(env)
1367 if not node.entry.is_type:
1368 pass
1369 else:
1370 error(node.pos, "Bad type")
1372 def public_decl(base, dll_linkage):
1373 if dll_linkage:
1374 return "%s(%s)" % (dll_linkage, base)
1375 else:
1376 return base
1378 def same_type(type1, type2):
1379 return type1.same_as(type2)
1381 def assignable_from(type1, type2):
1382 return type1.assignable_from(type2)
1384 def typecast(to_type, from_type, expr_code):
1385 # Return expr_code cast to a C type which can be
1386 # assigned to to_type, assuming its existing C type
1387 # is from_type.
1388 if to_type is from_type or \
1389 (not to_type.is_pyobject and assignable_from(to_type, from_type)):
1390 return expr_code
1391 else:
1392 #print "typecast: to", to_type, "from", from_type ###
1393 return to_type.cast_code(expr_code)
1396 type_conversion_predeclarations = """
1397 /* Type Conversion Predeclarations */
1399 #if PY_MAJOR_VERSION < 3
1400 #define __Pyx_PyBytes_FromString PyString_FromString
1401 #define __Pyx_PyBytes_FromStringAndSize PyString_FromStringAndSize
1402 #define __Pyx_PyBytes_AsString PyString_AsString
1403 #else
1404 #define __Pyx_PyBytes_FromString PyBytes_FromString
1405 #define __Pyx_PyBytes_FromStringAndSize PyBytes_FromStringAndSize
1406 #define __Pyx_PyBytes_AsString PyBytes_AsString
1407 #endif
1409 #define __Pyx_PyBool_FromLong(b) ((b) ? (Py_INCREF(Py_True), Py_True) : (Py_INCREF(Py_False), Py_False))
1410 static INLINE int __Pyx_PyObject_IsTrue(PyObject* x);
1411 static INLINE PY_LONG_LONG __pyx_PyInt_AsLongLong(PyObject* x);
1412 static INLINE unsigned PY_LONG_LONG __pyx_PyInt_AsUnsignedLongLong(PyObject* x);
1414 #if !defined(T_PYSSIZET)
1415 #if PY_VERSION_HEX < 0x02050000
1416 #define T_PYSSIZET T_INT
1417 #elif !defined(T_LONGLONG)
1418 #define T_PYSSIZET \\
1419 ((sizeof(Py_ssize_t) == sizeof(int)) ? T_INT : \\
1420 ((sizeof(Py_ssize_t) == sizeof(long)) ? T_LONG : -1))
1421 #else
1422 #define T_PYSSIZET \\
1423 ((sizeof(Py_ssize_t) == sizeof(int)) ? T_INT : \\
1424 ((sizeof(Py_ssize_t) == sizeof(long)) ? T_LONG : \\
1425 ((sizeof(Py_ssize_t) == sizeof(PY_LONG_LONG)) ? T_LONGLONG : -1)))
1426 #endif
1427 #endif
1429 #if !defined(T_SIZET)
1430 #if !defined(T_ULONGLONG)
1431 #define T_SIZET \\
1432 ((sizeof(size_t) == sizeof(unsigned int)) ? T_UINT : \\
1433 ((sizeof(size_t) == sizeof(unsigned long)) ? T_ULONG : -1))
1434 #else
1435 #define T_SIZET \\
1436 ((sizeof(size_t) == sizeof(unsigned int)) ? T_UINT : \\
1437 ((sizeof(size_t) == sizeof(unsigned long)) ? T_ULONG : \\
1438 ((sizeof(size_t) == sizeof(unsigned PY_LONG_LONG)) ? T_ULONGLONG : -1)))
1439 #endif
1440 #endif
1442 static INLINE Py_ssize_t __pyx_PyIndex_AsSsize_t(PyObject* b);
1443 static INLINE PyObject * __pyx_PyInt_FromSize_t(size_t);
1444 static INLINE size_t __pyx_PyInt_AsSize_t(PyObject*);
1446 #define __pyx_PyInt_AsLong(x) (PyInt_CheckExact(x) ? PyInt_AS_LONG(x) : PyInt_AsLong(x))
1447 #define __pyx_PyFloat_AsDouble(x) (PyFloat_CheckExact(x) ? PyFloat_AS_DOUBLE(x) : PyFloat_AsDouble(x))
1448 """ + type_conversion_predeclarations
1450 type_conversion_functions = """
1451 /* Type Conversion Functions */
1453 static INLINE Py_ssize_t __pyx_PyIndex_AsSsize_t(PyObject* b) {
1454 Py_ssize_t ival;
1455 PyObject* x = PyNumber_Index(b);
1456 if (!x) return -1;
1457 ival = PyInt_AsSsize_t(x);
1458 Py_DECREF(x);
1459 return ival;
1460 }
1462 static INLINE PyObject * __pyx_PyInt_FromSize_t(size_t ival) {
1463 #if PY_VERSION_HEX < 0x02050000
1464 if (ival <= LONG_MAX)
1465 return PyInt_FromLong((long)ival);
1466 else {
1467 unsigned char *bytes = (unsigned char *) &ival;
1468 int one = 1; int little = (int)*(unsigned char*)&one;
1469 return _PyLong_FromByteArray(bytes, sizeof(size_t), little, 0);
1470 }
1471 #else
1472 return PyInt_FromSize_t(ival);
1473 #endif
1474 }
1476 static INLINE size_t __pyx_PyInt_AsSize_t(PyObject* b) {
1477 unsigned PY_LONG_LONG val = __pyx_PyInt_AsUnsignedLongLong(b);
1478 if (unlikely(val == (unsigned PY_LONG_LONG)-1 && PyErr_Occurred())) {
1479 return (size_t)-1;
1480 } else if (unlikely(val != (unsigned PY_LONG_LONG)(size_t)val)) {
1481 PyErr_SetString(PyExc_OverflowError, "value too large to convert to size_t");
1482 return (size_t)-1;
1483 }
1484 return val;
1485 }
1487 static INLINE int __Pyx_PyObject_IsTrue(PyObject* x) {
1488 if (x == Py_True) return 1;
1489 else if ((x == Py_False) | (x == Py_None)) return 0;
1490 else return PyObject_IsTrue(x);
1491 }
1493 static INLINE PY_LONG_LONG __pyx_PyInt_AsLongLong(PyObject* x) {
1494 #if PY_VERSION_HEX < 0x03000000
1495 if (PyInt_CheckExact(x)) {
1496 return PyInt_AS_LONG(x);
1497 }
1498 else
1499 #endif
1500 if (PyLong_CheckExact(x)) {
1501 return PyLong_AsLongLong(x);
1502 }
1503 else {
1504 PY_LONG_LONG val;
1505 #if PY_VERSION_HEX < 0x03000000
1506 PyObject* tmp = PyNumber_Int(x); if (!tmp) return (PY_LONG_LONG)-1;
1507 val = __pyx_PyInt_AsLongLong(tmp);
1508 #else
1509 PyObject* tmp = PyNumber_Long(x); if (!tmp) return (PY_LONG_LONG)-1;
1510 val = PyLong_AsLongLong(tmp);
1511 #endif
1512 Py_DECREF(tmp);
1513 return val;
1514 }
1515 }
1517 static INLINE unsigned PY_LONG_LONG __pyx_PyInt_AsUnsignedLongLong(PyObject* x) {
1518 #if PY_VERSION_HEX < 0x03000000
1519 if (PyInt_CheckExact(x)) {
1520 long val = PyInt_AS_LONG(x);
1521 if (unlikely(val < 0)) {
1522 PyErr_SetString(PyExc_OverflowError, "can't convert negative value to unsigned long long");
1523 return (unsigned PY_LONG_LONG)-1;
1524 }
1525 return val;
1526 }
1527 else
1528 #endif
1529 if (PyLong_CheckExact(x)) {
1530 return PyLong_AsUnsignedLongLong(x);
1531 }
1532 else {
1533 unsigned PY_LONG_LONG val;
1534 #if PY_VERSION_HEX < 0x03000000
1535 PyObject* tmp = PyNumber_Int(x); if (!tmp) return (PY_LONG_LONG)-1;
1536 val = __pyx_PyInt_AsUnsignedLongLong(tmp);
1537 #else
1538 PyObject* tmp = PyNumber_Long(x); if (!tmp) return (PY_LONG_LONG)-1;
1539 val = PyLong_AsUnsignedLongLong(tmp);
1540 #endif
1541 Py_DECREF(tmp);
1542 return val;
1543 }
1544 }
1546 """ + type_conversion_functions
