Cython has moved to github.
cython-devel
view Cython/Compiler/PyrexTypes.py @ 2654:76e7121cbdc7
Fix #441
| author | Dag Sverre Seljebotn <dagss@student.matnat.uio.no> |
|---|---|
| date | Tue Nov 03 16:35:19 2009 +0100 (2 years ago) |
| parents | c6a27fd42d87 |
| children | baf3248439b3 |
line source
1 #
2 # Pyrex - Types
3 #
5 from Code 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 specalization_name(self):
18 return self.declaration_code("").replace(" ", "__")
20 def base_declaration_code(self, base_code, entity_code):
21 if entity_code:
22 return "%s %s" % (base_code, entity_code)
23 else:
24 return base_code
26 class PyrexType(BaseType):
27 #
28 # Base class for all Pyrex types.
29 #
30 # is_pyobject boolean Is a Python object type
31 # is_extension_type boolean Is a Python extension type
32 # is_numeric boolean Is a C numeric type
33 # is_int boolean Is a C integer type
34 # is_float boolean Is a C floating point type
35 # is_complex boolean Is a C complex type
36 # is_void boolean Is the C void type
37 # is_array boolean Is a C array type
38 # is_ptr boolean Is a C pointer type
39 # is_null_ptr boolean Is the type of NULL
40 # is_cfunction boolean Is a C function type
41 # is_struct_or_union boolean Is a C struct or union type
42 # is_struct boolean Is a C struct type
43 # is_enum boolean Is a C enum type
44 # is_typedef boolean Is a typedef type
45 # is_string boolean Is a C char * type
46 # is_unicode boolean Is a UTF-8 encoded C char * type
47 # is_returncode boolean Is used only to signal exceptions
48 # is_error boolean Is the dummy error type
49 # is_buffer boolean Is buffer access type
50 # has_attributes boolean Has C dot-selectable attributes
51 # default_value string Initial value
52 # pymemberdef_typecode string Type code for PyMemberDef struct
53 #
54 # declaration_code(entity_code,
55 # for_display = 0, dll_linkage = None, pyrex = 0)
56 # Returns a code fragment for the declaration of an entity
57 # of this type, given a code fragment for the entity.
58 # * If for_display, this is for reading by a human in an error
59 # message; otherwise it must be valid C code.
60 # * If dll_linkage is not None, it must be 'DL_EXPORT' or
61 # 'DL_IMPORT', and will be added to the base type part of
62 # the declaration.
63 # * If pyrex = 1, this is for use in a 'cdef extern'
64 # statement of a Pyrex include file.
65 #
66 # assignable_from(src_type)
67 # Tests whether a variable of this type can be
68 # assigned a value of type src_type.
69 #
70 # same_as(other_type)
71 # Tests whether this type represents the same type
72 # as other_type.
73 #
74 # as_argument_type():
75 # Coerces array type into pointer type for use as
76 # a formal argument type.
77 #
79 is_pyobject = 0
80 is_unspecified = 0
81 is_extension_type = 0
82 is_builtin_type = 0
83 is_numeric = 0
84 is_int = 0
85 is_float = 0
86 is_complex = 0
87 is_void = 0
88 is_array = 0
89 is_ptr = 0
90 is_null_ptr = 0
91 is_cfunction = 0
92 is_struct_or_union = 0
93 is_struct = 0
94 is_enum = 0
95 is_typedef = 0
96 is_string = 0
97 is_unicode = 0
98 is_returncode = 0
99 is_error = 0
100 is_buffer = 0
101 has_attributes = 0
102 default_value = ""
103 pymemberdef_typecode = None
105 def resolve(self):
106 # If a typedef, returns the base type.
107 return self
109 def literal_code(self, value):
110 # Returns a C code fragment representing a literal
111 # value of this type.
112 return str(value)
114 def __str__(self):
115 return self.declaration_code("", for_display = 1).strip()
117 def same_as(self, other_type, **kwds):
118 return self.same_as_resolved_type(other_type.resolve(), **kwds)
120 def same_as_resolved_type(self, other_type):
121 return self == other_type or other_type is error_type
123 def subtype_of(self, other_type):
124 return self.subtype_of_resolved_type(other_type.resolve())
126 def subtype_of_resolved_type(self, other_type):
127 return self.same_as(other_type)
129 def assignable_from(self, src_type):
130 return self.assignable_from_resolved_type(src_type.resolve())
132 def assignable_from_resolved_type(self, src_type):
133 return self.same_as(src_type)
135 def as_argument_type(self):
136 return self
138 def is_complete(self):
139 # A type is incomplete if it is an unsized array,
140 # a struct whose attributes are not defined, etc.
141 return 1
143 def is_simple_buffer_dtype(self):
144 return (self.is_int or self.is_float or self.is_complex or self.is_pyobject or
145 self.is_extension_type or self.is_ptr)
147 def struct_nesting_depth(self):
148 # Returns the number levels of nested structs. This is
149 # used for constructing a stack for walking the run-time
150 # type information of the struct.
151 return 1
154 def create_typedef_type(cname, base_type, is_external=0):
155 if base_type.is_complex:
156 if is_external:
157 raise ValueError("Complex external typedefs not supported")
158 return base_type
159 else:
160 return CTypedefType(cname, base_type, is_external)
162 class CTypedefType(BaseType):
163 #
164 # Pseudo-type defined with a ctypedef statement in a
165 # 'cdef extern from' block. Delegates most attribute
166 # lookups to the base type. ANYTHING NOT DEFINED
167 # HERE IS DELEGATED!
168 #
169 # qualified_name string
170 # typedef_cname string
171 # typedef_base_type PyrexType
172 # typedef_is_external bool
174 is_typedef = 1
175 typedef_is_external = 0
177 to_py_utility_code = None
178 from_py_utility_code = None
181 def __init__(self, cname, base_type, is_external=0):
182 assert not base_type.is_complex
183 self.typedef_cname = cname
184 self.typedef_base_type = base_type
185 self.typedef_is_external = is_external
186 # Make typecodes in external typedefs use typesize-neutral macros
187 if is_external:
188 typecode = None
189 if base_type.is_int:
190 if base_type.signed == 0:
191 typecode = "__Pyx_T_UNSIGNED_INT"
192 else:
193 typecode = "__Pyx_T_SIGNED_INT"
194 elif base_type.is_float and not rank_to_type_name[base_type.rank] == "long double":
195 typecode = "__Pyx_T_FLOATING"
196 if typecode:
197 self.pymemberdef_typecode = "%s(%s)" % (typecode, cname)
199 def resolve(self):
200 return self.typedef_base_type.resolve()
202 def declaration_code(self, entity_code,
203 for_display = 0, dll_linkage = None, pyrex = 0):
204 name = self.declaration_name(for_display, pyrex)
205 return self.base_declaration_code(name, entity_code)
207 def declaration_name(self, for_display = 0, pyrex = 0):
208 if pyrex or for_display:
209 return self.qualified_name
210 else:
211 return self.typedef_cname
213 def as_argument_type(self):
214 return self
216 def cast_code(self, expr_code):
217 # If self is really an array (rather than pointer), we can't cast.
218 # For example, the gmp mpz_t.
219 if self.typedef_base_type.is_ptr:
220 return self.typedef_base_type.cast_code(expr_code)
221 else:
222 return BaseType.cast_code(self, expr_code)
224 def __repr__(self):
225 return "<CTypedefType %s>" % self.typedef_cname
227 def __str__(self):
228 return self.declaration_name(for_display = 1)
230 def _create_utility_code(self, template_utility_code,
231 template_function_name):
232 type_name = self.typedef_cname.replace(" ","_")
233 utility_code = template_utility_code.specialize(
234 type = self.typedef_cname,
235 TypeName = type_name)
236 function_name = template_function_name % type_name
237 return utility_code, function_name
239 def create_to_py_utility_code(self, env):
240 if self.typedef_is_external:
241 if not self.to_py_utility_code:
242 base_type = self.typedef_base_type
243 if base_type.is_int:
244 self.to_py_utility_code, self.to_py_function = \
245 self._create_utility_code(c_typedef_int_to_py_function,
246 '__Pyx_PyInt_to_py_%s')
247 elif base_type.is_float:
248 pass # XXX implement!
249 elif base_type.is_complex:
250 pass # XXX implement!
251 pass
252 if self.to_py_utility_code:
253 env.use_utility_code(self.to_py_utility_code)
254 return True
255 # delegation
256 return self.typedef_base_type.create_to_py_utility_code(env)
258 def create_from_py_utility_code(self, env):
259 if self.typedef_is_external:
260 if not self.from_py_utility_code:
261 base_type = self.typedef_base_type
262 if base_type.is_int:
263 self.from_py_utility_code, self.from_py_function = \
264 self._create_utility_code(c_typedef_int_from_py_function,
265 '__Pyx_PyInt_from_py_%s')
266 elif base_type.is_float:
267 pass # XXX implement!
268 elif base_type.is_complex:
269 pass # XXX implement!
270 if self.from_py_utility_code:
271 env.use_utility_code(self.from_py_utility_code)
272 return True
273 # delegation
274 return self.typedef_base_type.create_from_py_utility_code(env)
276 def error_condition(self, result_code):
277 if self.typedef_is_external:
278 if self.exception_value:
279 condition = "(%s == (%s)%s)" % (
280 result_code, self.typedef_cname, self.exception_value)
281 if self.exception_check:
282 condition += " && PyErr_Occurred()"
283 return condition
284 # delegation
285 return self.typedef_base_type.error_condition(result_code)
287 def __getattr__(self, name):
288 return getattr(self.typedef_base_type, name)
290 class BufferType(BaseType):
291 #
292 # Delegates most attribute
293 # lookups to the base type. ANYTHING NOT DEFINED
294 # HERE IS DELEGATED!
296 # dtype PyrexType
297 # ndim int
298 # mode str
299 # negative_indices bool
300 # cast bool
301 # is_buffer bool
302 # writable bool
304 is_buffer = 1
305 writable = True
306 def __init__(self, base, dtype, ndim, mode, negative_indices, cast):
307 self.base = base
308 self.dtype = dtype
309 self.ndim = ndim
310 self.buffer_ptr_type = CPtrType(dtype)
311 self.mode = mode
312 self.negative_indices = negative_indices
313 self.cast = cast
315 def as_argument_type(self):
316 return self
318 def __getattr__(self, name):
319 return getattr(self.base, name)
321 def __repr__(self):
322 return "<BufferType %r>" % self.base
324 def public_decl(base, dll_linkage):
325 if dll_linkage:
326 return "%s(%s)" % (dll_linkage, base)
327 else:
328 return base
330 class PyObjectType(PyrexType):
331 #
332 # Base class for all Python object types (reference-counted).
333 #
334 # buffer_defaults dict or None Default options for bu
336 name = "object"
337 is_pyobject = 1
338 default_value = "0"
339 pymemberdef_typecode = "T_OBJECT"
340 buffer_defaults = None
342 def __str__(self):
343 return "Python object"
345 def __repr__(self):
346 return "<PyObjectType>"
348 def assignable_from(self, src_type):
349 # except for pointers, conversion will be attempted
350 return not src_type.is_ptr or src_type.is_string
352 def declaration_code(self, entity_code,
353 for_display = 0, dll_linkage = None, pyrex = 0):
354 if pyrex or for_display:
355 return self.base_declaration_code("object", entity_code)
356 else:
357 return "%s *%s" % (public_decl("PyObject", dll_linkage), entity_code)
359 def as_pyobject(self, cname):
360 if (not self.is_complete()) or self.is_extension_type:
361 return "(PyObject *)" + cname
362 else:
363 return cname
365 class BuiltinObjectType(PyObjectType):
367 is_builtin_type = 1
368 has_attributes = 1
369 base_type = None
370 module_name = '__builtin__'
372 alternative_name = None # used for str/bytes duality
374 def __init__(self, name, cname):
375 self.name = name
376 if name == 'str':
377 self.alternative_name = 'bytes'
378 elif name == 'bytes':
379 self.alternative_name = 'str'
380 self.cname = cname
381 self.typeptr_cname = "&" + cname
383 def set_scope(self, scope):
384 self.scope = scope
385 if scope:
386 scope.parent_type = self
388 def __str__(self):
389 return "%s object" % self.name
391 def __repr__(self):
392 return "<%s>"% self.cname
394 def assignable_from(self, src_type):
395 if isinstance(src_type, BuiltinObjectType):
396 return src_type.name == self.name or (
397 src_type.name == self.alternative_name and
398 src_type.name is not None)
399 else:
400 return not src_type.is_extension_type
402 def typeobj_is_available(self):
403 return True
405 def attributes_known(self):
406 return True
408 def subtype_of(self, type):
409 return type.is_pyobject and self.assignable_from(type)
411 def type_test_code(self, arg, notnone=False):
412 type_name = self.name
413 if type_name == 'str':
414 type_check = 'PyString_CheckExact'
415 elif type_name == 'set':
416 type_check = 'PyAnySet_CheckExact'
417 elif type_name == 'frozenset':
418 type_check = 'PyFrozenSet_CheckExact'
419 elif type_name == 'bool':
420 type_check = 'PyBool_Check'
421 else:
422 type_check = 'Py%s_CheckExact' % type_name.capitalize()
424 check = 'likely(%s(%s))' % (type_check, arg)
425 if not notnone:
426 check = check + ('||((%s) == Py_None)' % arg)
427 error = '(PyErr_Format(PyExc_TypeError, "Expected %s, got %%.200s", Py_TYPE(%s)->tp_name), 0)' % (self.name, arg)
428 return check + '||' + error
430 def declaration_code(self, entity_code,
431 for_display = 0, dll_linkage = None, pyrex = 0):
432 if pyrex or for_display:
433 return self.base_declaration_code(self.name, entity_code)
434 else:
435 return "%s *%s" % (public_decl("PyObject", dll_linkage), entity_code)
438 class PyExtensionType(PyObjectType):
439 #
440 # A Python extension type.
441 #
442 # name string
443 # scope CClassScope Attribute namespace
444 # visibility string
445 # typedef_flag boolean
446 # base_type PyExtensionType or None
447 # module_name string or None Qualified name of defining module
448 # objstruct_cname string Name of PyObject struct
449 # objtypedef_cname string Name of PyObject struct typedef
450 # typeobj_cname string or None C code fragment referring to type object
451 # typeptr_cname string or None Name of pointer to external type object
452 # vtabslot_cname string Name of C method table member
453 # vtabstruct_cname string Name of C method table struct
454 # vtabptr_cname string Name of pointer to C method table
455 # vtable_cname string Name of C method table definition
457 is_extension_type = 1
458 has_attributes = 1
460 objtypedef_cname = None
462 def __init__(self, name, typedef_flag, base_type):
463 self.name = name
464 self.scope = None
465 self.typedef_flag = typedef_flag
466 self.base_type = base_type
467 self.module_name = None
468 self.objstruct_cname = None
469 self.typeobj_cname = None
470 self.typeptr_cname = None
471 self.vtabslot_cname = None
472 self.vtabstruct_cname = None
473 self.vtabptr_cname = None
474 self.vtable_cname = None
476 def set_scope(self, scope):
477 self.scope = scope
478 if scope:
479 scope.parent_type = self
481 def subtype_of_resolved_type(self, other_type):
482 if other_type.is_extension_type:
483 return self is other_type or (
484 self.base_type and self.base_type.subtype_of(other_type))
485 else:
486 return other_type is py_object_type
488 def typeobj_is_available(self):
489 # Do we have a pointer to the type object?
490 return self.typeptr_cname
492 def typeobj_is_imported(self):
493 # If we don't know the C name of the type object but we do
494 # know which module it's defined in, it will be imported.
495 return self.typeobj_cname is None and self.module_name is not None
497 def declaration_code(self, entity_code,
498 for_display = 0, dll_linkage = None, pyrex = 0, deref = 0):
499 if pyrex or for_display:
500 return self.base_declaration_code(self.name, entity_code)
501 else:
502 if self.typedef_flag:
503 base_format = "%s"
504 else:
505 base_format = "struct %s"
506 base = public_decl(base_format % self.objstruct_cname, dll_linkage)
507 if deref:
508 return "%s %s" % (base, entity_code)
509 else:
510 return "%s *%s" % (base, entity_code)
512 def type_test_code(self, py_arg, notnone=False):
514 none_check = "((%s) == Py_None)" % py_arg
515 type_check = "likely(__Pyx_TypeTest(%s, %s))" % (
516 py_arg, self.typeptr_cname)
517 if notnone:
518 return type_check
519 else:
520 return "likely(%s || %s)" % (none_check, type_check)
522 def attributes_known(self):
523 return self.scope is not None
525 def __str__(self):
526 return self.name
528 def __repr__(self):
529 return "<PyExtensionType %s%s>" % (self.scope.class_name,
530 ("", " typedef")[self.typedef_flag])
533 class CType(PyrexType):
534 #
535 # Base class for all C types (non-reference-counted).
536 #
537 # to_py_function string C function for converting to Python object
538 # from_py_function string C function for constructing from Python object
539 #
541 to_py_function = None
542 from_py_function = None
543 exception_value = None
544 exception_check = 1
546 def create_to_py_utility_code(self, env):
547 return self.to_py_function is not None
549 def create_from_py_utility_code(self, env):
550 return self.from_py_function is not None
552 def error_condition(self, result_code):
553 conds = []
554 if self.is_string:
555 conds.append("(!%s)" % result_code)
556 elif self.exception_value is not None:
557 conds.append("(%s == (%s)%s)" % (result_code, self.sign_and_name(), self.exception_value))
558 if self.exception_check:
559 conds.append("PyErr_Occurred()")
560 if len(conds) > 0:
561 return " && ".join(conds)
562 else:
563 return 0
566 class CVoidType(CType):
567 is_void = 1
569 def __repr__(self):
570 return "<CVoidType>"
572 def declaration_code(self, entity_code,
573 for_display = 0, dll_linkage = None, pyrex = 0):
574 base = public_decl("void", dll_linkage)
575 return self.base_declaration_code(base, entity_code)
577 def is_complete(self):
578 return 0
581 class CNumericType(CType):
582 #
583 # Base class for all C numeric types.
584 #
585 # rank integer Relative size
586 # signed integer 0 = unsigned, 1 = unspecified, 2 = explicitly signed
587 #
589 is_numeric = 1
590 default_value = "0"
592 sign_words = ("unsigned ", "", "signed ")
594 def __init__(self, rank, signed = 1, pymemberdef_typecode = None):
595 self.rank = rank
596 self.signed = signed
597 self.pymemberdef_typecode = pymemberdef_typecode
599 def sign_and_name(self):
600 s = self.sign_words[self.signed]
601 n = rank_to_type_name[self.rank]
602 return s + n
604 def __repr__(self):
605 return "<CNumericType %s>" % self.sign_and_name()
607 def declaration_code(self, entity_code,
608 for_display = 0, dll_linkage = None, pyrex = 0):
609 base = public_decl(self.sign_and_name(), dll_linkage)
610 if for_display:
611 base = base.replace('PY_LONG_LONG', 'long long')
612 return self.base_declaration_code(base, entity_code)
615 type_conversion_predeclarations = ""
616 type_conversion_functions = ""
618 c_int_from_py_function = UtilityCode(
619 proto="""
620 static INLINE %(type)s __Pyx_PyInt_As%(SignWord)s%(TypeName)s(PyObject *);
621 """,
622 impl="""
623 static INLINE %(type)s __Pyx_PyInt_As%(SignWord)s%(TypeName)s(PyObject* x) {
624 const %(type)s neg_one = (%(type)s)-1, const_zero = 0;
625 const int is_unsigned = neg_one > const_zero;
626 if (sizeof(%(type)s) < sizeof(long)) {
627 long val = __Pyx_PyInt_AsLong(x);
628 if (unlikely(val != (long)(%(type)s)val)) {
629 if (!unlikely(val == -1 && PyErr_Occurred())) {
630 PyErr_SetString(PyExc_OverflowError,
631 (is_unsigned && unlikely(val < 0)) ?
632 "can't convert negative value to %(type)s" :
633 "value too large to convert to %(type)s");
634 }
635 return (%(type)s)-1;
636 }
637 return (%(type)s)val;
638 }
639 return (%(type)s)__Pyx_PyInt_As%(SignWord)sLong(x);
640 }
641 """) #fool emacs: '
643 c_long_from_py_function = UtilityCode(
644 proto="""
645 static INLINE %(type)s __Pyx_PyInt_As%(SignWord)s%(TypeName)s(PyObject *);
646 """,
647 impl="""
648 static INLINE %(type)s __Pyx_PyInt_As%(SignWord)s%(TypeName)s(PyObject* x) {
649 const %(type)s neg_one = (%(type)s)-1, const_zero = 0;
650 const int is_unsigned = neg_one > const_zero;
651 #if PY_VERSION_HEX < 0x03000000
652 if (likely(PyInt_Check(x))) {
653 long val = PyInt_AS_LONG(x);
654 if (is_unsigned && unlikely(val < 0)) {
655 PyErr_SetString(PyExc_OverflowError,
656 "can't convert negative value to %(type)s");
657 return (%(type)s)-1;
658 }
659 return (%(type)s)val;
660 } else
661 #endif
662 if (likely(PyLong_Check(x))) {
663 if (is_unsigned) {
664 if (unlikely(Py_SIZE(x) < 0)) {
665 PyErr_SetString(PyExc_OverflowError,
666 "can't convert negative value to %(type)s");
667 return (%(type)s)-1;
668 }
669 return PyLong_AsUnsigned%(TypeName)s(x);
670 } else {
671 return PyLong_As%(TypeName)s(x);
672 }
673 } else {
674 %(type)s val;
675 PyObject *tmp = __Pyx_PyNumber_Int(x);
676 if (!tmp) return (%(type)s)-1;
677 val = __Pyx_PyInt_As%(SignWord)s%(TypeName)s(tmp);
678 Py_DECREF(tmp);
679 return val;
680 }
681 }
682 """)
684 c_typedef_int_from_py_function = UtilityCode(
685 proto="""
686 static INLINE %(type)s __Pyx_PyInt_from_py_%(TypeName)s(PyObject *);
687 """,
688 impl="""
689 static INLINE %(type)s __Pyx_PyInt_from_py_%(TypeName)s(PyObject* x) {
690 const %(type)s neg_one = (%(type)s)-1, const_zero = 0;
691 const int is_unsigned = neg_one > const_zero;
692 if (sizeof(%(type)s) == sizeof(char)) {
693 if (is_unsigned)
694 return (%(type)s)__Pyx_PyInt_AsUnsignedChar(x);
695 else
696 return (%(type)s)__Pyx_PyInt_AsSignedChar(x);
697 } else if (sizeof(%(type)s) == sizeof(short)) {
698 if (is_unsigned)
699 return (%(type)s)__Pyx_PyInt_AsUnsignedShort(x);
700 else
701 return (%(type)s)__Pyx_PyInt_AsSignedShort(x);
702 } else if (sizeof(%(type)s) == sizeof(int)) {
703 if (is_unsigned)
704 return (%(type)s)__Pyx_PyInt_AsUnsignedInt(x);
705 else
706 return (%(type)s)__Pyx_PyInt_AsSignedInt(x);
707 } else if (sizeof(%(type)s) == sizeof(long)) {
708 if (is_unsigned)
709 return (%(type)s)__Pyx_PyInt_AsUnsignedLong(x);
710 else
711 return (%(type)s)__Pyx_PyInt_AsSignedLong(x);
712 } else if (sizeof(%(type)s) == sizeof(PY_LONG_LONG)) {
713 if (is_unsigned)
714 return (%(type)s)__Pyx_PyInt_AsUnsignedLongLong(x);
715 else
716 return (%(type)s)__Pyx_PyInt_AsSignedLongLong(x);
717 #if 0
718 } else if (sizeof(%(type)s) > sizeof(short) &&
719 sizeof(%(type)s) < sizeof(int)) { /* __int32 ILP64 ? */
720 if (is_unsigned)
721 return (%(type)s)__Pyx_PyInt_AsUnsignedInt(x);
722 else
723 return (%(type)s)__Pyx_PyInt_AsSignedInt(x);
724 #endif
725 }
726 PyErr_SetString(PyExc_TypeError, "%(TypeName)s");
727 return (%(type)s)-1;
728 }
729 """)
731 c_typedef_int_to_py_function = UtilityCode(
732 proto="""
733 static INLINE PyObject *__Pyx_PyInt_to_py_%(TypeName)s(%(type)s);
734 """,
735 impl="""
736 static INLINE PyObject *__Pyx_PyInt_to_py_%(TypeName)s(%(type)s val) {
737 const %(type)s neg_one = (%(type)s)-1, const_zero = 0;
738 const int is_unsigned = neg_one > const_zero;
739 if (sizeof(%(type)s) < sizeof(long)) {
740 return PyInt_FromLong((long)val);
741 } else if (sizeof(%(type)s) == sizeof(long)) {
742 if (is_unsigned)
743 return PyLong_FromUnsignedLong((unsigned long)val);
744 else
745 return PyInt_FromLong((long)val);
746 } else { /* (sizeof(%(type)s) > sizeof(long)) */
747 if (is_unsigned)
748 return PyLong_FromUnsignedLongLong((unsigned PY_LONG_LONG)val);
749 else
750 return PyLong_FromLongLong((PY_LONG_LONG)val);
751 }
752 }
753 """)
755 class CIntType(CNumericType):
757 is_int = 1
758 typedef_flag = 0
759 to_py_function = "PyInt_FromLong"
760 from_py_function = "__Pyx_PyInt_AsInt"
761 exception_value = -1
763 def __init__(self, rank, signed, pymemberdef_typecode = None, is_returncode = 0):
764 CNumericType.__init__(self, rank, signed, pymemberdef_typecode)
765 self.is_returncode = is_returncode
766 if self.from_py_function == "__Pyx_PyInt_AsInt":
767 self.from_py_function = self.get_type_conversion()
769 def get_type_conversion(self):
770 ctype = self.declaration_code('')
771 bits = ctype.split(" ", 1)
772 if len(bits) == 1:
773 sign_word, type_name = "", bits[0]
774 else:
775 sign_word, type_name = bits
776 type_name = type_name.replace("PY_LONG_LONG","long long")
777 SignWord = sign_word.title()
778 TypeName = type_name.title().replace(" ", "")
779 if "Long" in TypeName:
780 utility_code = c_long_from_py_function
781 else:
782 utility_code = c_int_from_py_function
783 utility_code.specialize(self,
784 SignWord=SignWord,
785 TypeName=TypeName)
786 func_name = "__Pyx_PyInt_As%s%s" % (SignWord, TypeName)
787 return func_name
789 def assignable_from_resolved_type(self, src_type):
790 return src_type.is_int or src_type.is_enum or src_type is error_type
793 class CBIntType(CIntType):
795 to_py_function = "__Pyx_PyBool_FromLong"
796 from_py_function = "__Pyx_PyObject_IsTrue"
797 exception_check = 0
800 class CAnonEnumType(CIntType):
802 is_enum = 1
804 def sign_and_name(self):
805 return 'int'
808 class CUIntType(CIntType):
810 to_py_function = "PyLong_FromUnsignedLong"
811 exception_value = -1
814 class CLongType(CIntType):
816 to_py_function = "PyInt_FromLong"
819 class CULongType(CUIntType):
821 to_py_function = "PyLong_FromUnsignedLong"
824 class CLongLongType(CIntType):
826 to_py_function = "PyLong_FromLongLong"
829 class CULongLongType(CUIntType):
831 to_py_function = "PyLong_FromUnsignedLongLong"
834 class CPySSizeTType(CIntType):
836 to_py_function = "PyInt_FromSsize_t"
837 from_py_function = "__Pyx_PyIndex_AsSsize_t"
839 def sign_and_name(self):
840 return rank_to_type_name[self.rank]
843 class CSizeTType(CUIntType):
845 to_py_function = "__Pyx_PyInt_FromSize_t"
846 from_py_function = "__Pyx_PyInt_AsSize_t"
848 def sign_and_name(self):
849 return rank_to_type_name[self.rank]
852 class CFloatType(CNumericType):
854 is_float = 1
855 to_py_function = "PyFloat_FromDouble"
856 from_py_function = "__pyx_PyFloat_AsDouble"
858 def __init__(self, rank, pymemberdef_typecode = None, math_h_modifier = ''):
859 CNumericType.__init__(self, rank, 1, pymemberdef_typecode)
860 self.math_h_modifier = math_h_modifier
862 def assignable_from_resolved_type(self, src_type):
863 return (src_type.is_numeric and not src_type.is_complex) or src_type is error_type
866 class CComplexType(CNumericType):
868 is_complex = 1
869 to_py_function = "__pyx_PyComplex_FromComplex"
870 has_attributes = 1
871 scope = None
873 def __init__(self, real_type):
874 while real_type.is_typedef and not real_type.typedef_is_external:
875 real_type = real_type.typedef_base_type
876 if real_type.is_typedef and real_type.typedef_is_external:
877 # The below is not actually used: Coercions are currently disabled
878 # so that complex types of external types can not be created
879 self.funcsuffix = "_%s" % real_type.specalization_name()
880 else:
881 self.funcsuffix = real_type.math_h_modifier
883 self.real_type = real_type
884 CNumericType.__init__(self, real_type.rank + 0.5, real_type.signed)
885 self.binops = {}
886 self.from_parts = "%s_from_parts" % self.specalization_name()
887 self.default_value = "%s(0, 0)" % self.from_parts
889 def __eq__(self, other):
890 if isinstance(self, CComplexType) and isinstance(other, CComplexType):
891 return self.real_type == other.real_type
892 else:
893 return False
895 def __ne__(self, other):
896 if isinstance(self, CComplexType) and isinstance(other, CComplexType):
897 return self.real_type != other.real_type
898 else:
899 return True
901 def __lt__(self, other):
902 if isinstance(self, CComplexType) and isinstance(other, CComplexType):
903 return self.real_type < other.real_type
904 else:
905 # this is arbitrary, but it makes sure we always have
906 # *some* kind of order
907 return False
909 def __hash__(self):
910 return ~hash(self.real_type)
912 def declaration_code(self, entity_code,
913 for_display = 0, dll_linkage = None, pyrex = 0):
914 if for_display:
915 base = public_decl(self.real_type.sign_and_name() + " complex", dll_linkage)
916 else:
917 base = public_decl(self.sign_and_name(), dll_linkage)
918 return self.base_declaration_code(base, entity_code)
920 def sign_and_name(self):
921 real_type_name = self.real_type.specalization_name()
922 real_type_name = real_type_name.replace('long__double','long_double')
923 return Naming.type_prefix + real_type_name + "_complex"
925 def assignable_from(self, src_type):
926 # Temporary hack/feature disabling, see #441
927 if (not src_type.is_complex and src_type.is_numeric and src_type.is_typedef
928 and src_type.typedef_is_external):
929 return False
930 else:
931 return super(CComplexType, self).assignable_from(src_type)
933 def assignable_from_resolved_type(self, src_type):
934 return (src_type.is_complex and self.real_type.assignable_from_resolved_type(src_type.real_type)
935 or src_type.is_numeric and self.real_type.assignable_from_resolved_type(src_type)
936 or src_type is error_type)
938 def attributes_known(self):
939 if self.scope is None:
940 import Symtab
941 self.scope = scope = Symtab.CClassScope(
942 '',
943 None,
944 visibility="extern")
945 scope.parent_type = self
946 scope.declare_var("real", self.real_type, None, "real", is_cdef=True)
947 scope.declare_var("imag", self.real_type, None, "imag", is_cdef=True)
948 entry = scope.declare_cfunction(
949 "conjugate",
950 CFuncType(self, [CFuncTypeArg("self", self, None)]),
951 pos=None,
952 defining=1,
953 cname="__Pyx_c_conj%s" % self.funcsuffix)
955 return True
957 def create_declaration_utility_code(self, env):
958 # This must always be run, because a single CComplexType instance can be shared
959 # across multiple compilations (the one created in the module scope)
960 env.use_utility_code(complex_header_utility_code)
961 env.use_utility_code(complex_real_imag_utility_code)
962 for utility_code in (complex_type_utility_code,
963 complex_from_parts_utility_code,
964 complex_arithmatic_utility_code):
965 env.use_utility_code(
966 utility_code.specialize(
967 self,
968 real_type = self.real_type.declaration_code(''),
969 m = self.funcsuffix))
970 return True
972 def create_to_py_utility_code(self, env):
973 env.use_utility_code(complex_real_imag_utility_code)
974 env.use_utility_code(complex_to_py_utility_code)
975 return True
977 def create_from_py_utility_code(self, env):
978 self.real_type.create_from_py_utility_code(env)
980 for utility_code in (complex_from_parts_utility_code,
981 complex_from_py_utility_code):
982 env.use_utility_code(
983 utility_code.specialize(
984 self,
985 real_type = self.real_type.declaration_code(''),
986 m = self.funcsuffix))
987 self.from_py_function = "__Pyx_PyComplex_As_" + self.specalization_name()
988 return True
990 def lookup_op(self, nargs, op):
991 try:
992 return self.binops[nargs, op]
993 except KeyError:
994 pass
995 try:
996 op_name = complex_ops[nargs, op]
997 self.binops[nargs, op] = func_name = "__Pyx_c_%s%s" % (op_name, self.funcsuffix)
998 return func_name
999 except KeyError:
1000 return None
1002 def unary_op(self, op):
1003 return self.lookup_op(1, op)
1005 def binary_op(self, op):
1006 return self.lookup_op(2, op)
1008 complex_ops = {
1009 (1, '-'): 'neg',
1010 (1, 'zero'): 'is_zero',
1011 (2, '+'): 'sum',
1012 (2, '-'): 'diff',
1013 (2, '*'): 'prod',
1014 (2, '/'): 'quot',
1015 (2, '=='): 'eq',
1016 }
1018 complex_header_utility_code = UtilityCode(
1019 proto_block='h_code',
1020 proto="""
1021 #if !defined(CYTHON_CCOMPLEX)
1022 #if defined(__cplusplus)
1023 #define CYTHON_CCOMPLEX 1
1024 #elif defined(_Complex_I)
1025 #define CYTHON_CCOMPLEX 1
1026 #else
1027 #define CYTHON_CCOMPLEX 0
1028 #endif
1029 #endif
1031 #if CYTHON_CCOMPLEX
1032 #ifdef __cplusplus
1033 #include <complex>
1034 #else
1035 #include <complex.h>
1036 #endif
1037 #endif
1038 """)
1040 complex_real_imag_utility_code = UtilityCode(
1041 proto="""
1042 #if CYTHON_CCOMPLEX
1043 #ifdef __cplusplus
1044 #define __Pyx_CREAL(z) ((z).real())
1045 #define __Pyx_CIMAG(z) ((z).imag())
1046 #else
1047 #define __Pyx_CREAL(z) (__real__(z))
1048 #define __Pyx_CIMAG(z) (__imag__(z))
1049 #endif
1050 #else
1051 #define __Pyx_CREAL(z) ((z).real)
1052 #define __Pyx_CIMAG(z) ((z).imag)
1053 #endif
1054 """)
1056 complex_type_utility_code = UtilityCode(
1057 proto_block='complex_type_declarations',
1058 proto="""
1059 #if CYTHON_CCOMPLEX
1060 #ifdef __cplusplus
1061 typedef ::std::complex< %(real_type)s > %(type_name)s;
1062 #else
1063 typedef %(real_type)s _Complex %(type_name)s;
1064 #endif
1065 #else
1066 typedef struct { %(real_type)s real, imag; } %(type_name)s;
1067 #endif
1068 """)
1070 complex_from_parts_utility_code = UtilityCode(
1071 proto_block='utility_code_proto',
1072 proto="""
1073 #if CYTHON_CCOMPLEX
1074 #ifdef __cplusplus
1075 static INLINE %(type)s %(type_name)s_from_parts(%(real_type)s, %(real_type)s);
1076 #else
1077 static INLINE %(type)s %(type_name)s_from_parts(%(real_type)s, %(real_type)s);
1078 #endif
1079 #else
1080 static INLINE %(type)s %(type_name)s_from_parts(%(real_type)s, %(real_type)s);
1081 #endif
1082 """,
1083 impl="""
1084 #if CYTHON_CCOMPLEX
1085 #ifdef __cplusplus
1086 static INLINE %(type)s %(type_name)s_from_parts(%(real_type)s x, %(real_type)s y) {
1087 return ::std::complex< %(real_type)s >(x, y);
1088 }
1089 #else
1090 static INLINE %(type)s %(type_name)s_from_parts(%(real_type)s x, %(real_type)s y) {
1091 return x + y*(%(type)s)_Complex_I;
1092 }
1093 #endif
1094 #else
1095 static INLINE %(type)s %(type_name)s_from_parts(%(real_type)s x, %(real_type)s y) {
1096 %(type)s z;
1097 z.real = x;
1098 z.imag = y;
1099 return z;
1100 }
1101 #endif
1102 """)
1104 complex_to_py_utility_code = UtilityCode(
1105 proto="""
1106 #define __pyx_PyComplex_FromComplex(z) \\
1107 PyComplex_FromDoubles((double)__Pyx_CREAL(z), \\
1108 (double)__Pyx_CIMAG(z))
1109 """)
1111 complex_from_py_utility_code = UtilityCode(
1112 proto="""
1113 static %(type)s __Pyx_PyComplex_As_%(type_name)s(PyObject*);
1114 """,
1115 impl="""
1116 static %(type)s __Pyx_PyComplex_As_%(type_name)s(PyObject* o) {
1117 Py_complex cval;
1118 if (PyComplex_CheckExact(o))
1119 cval = ((PyComplexObject *)o)->cval;
1120 else
1121 cval = PyComplex_AsCComplex(o);
1122 return %(type_name)s_from_parts(
1123 (%(real_type)s)cval.real,
1124 (%(real_type)s)cval.imag);
1125 }
1126 """)
1128 complex_arithmatic_utility_code = UtilityCode(
1129 proto="""
1130 #if CYTHON_CCOMPLEX
1131 #define __Pyx_c_eq%(m)s(a, b) ((a)==(b))
1132 #define __Pyx_c_sum%(m)s(a, b) ((a)+(b))
1133 #define __Pyx_c_diff%(m)s(a, b) ((a)-(b))
1134 #define __Pyx_c_prod%(m)s(a, b) ((a)*(b))
1135 #define __Pyx_c_quot%(m)s(a, b) ((a)/(b))
1136 #define __Pyx_c_neg%(m)s(a) (-(a))
1137 #ifdef __cplusplus
1138 #define __Pyx_c_is_zero%(m)s(z) ((z)==0.0)
1139 #define __Pyx_c_conj%(m)s(z) (::std::conj(z))
1140 /*#define __Pyx_c_abs%(m)s(z) (::std::abs(z))*/
1141 #else
1142 #define __Pyx_c_is_zero%(m)s(z) ((z)==0)
1143 #define __Pyx_c_conj%(m)s(z) (conj%(m)s(z))
1144 /*#define __Pyx_c_abs%(m)s(z) (cabs%(m)s(z))*/
1145 #endif
1146 #else
1147 static INLINE int __Pyx_c_eq%(m)s(%(type)s, %(type)s);
1148 static INLINE %(type)s __Pyx_c_sum%(m)s(%(type)s, %(type)s);
1149 static INLINE %(type)s __Pyx_c_diff%(m)s(%(type)s, %(type)s);
1150 static INLINE %(type)s __Pyx_c_prod%(m)s(%(type)s, %(type)s);
1151 static INLINE %(type)s __Pyx_c_quot%(m)s(%(type)s, %(type)s);
1152 static INLINE %(type)s __Pyx_c_neg%(m)s(%(type)s);
1153 static INLINE int __Pyx_c_is_zero%(m)s(%(type)s);
1154 static INLINE %(type)s __Pyx_c_conj%(m)s(%(type)s);
1155 /*static INLINE %(real_type)s __Pyx_c_abs%(m)s(%(type)s);*/
1156 #endif
1157 """,
1158 impl="""
1159 #if CYTHON_CCOMPLEX
1160 #else
1161 static INLINE int __Pyx_c_eq%(m)s(%(type)s a, %(type)s b) {
1162 return (a.real == b.real) && (a.imag == b.imag);
1163 }
1164 static INLINE %(type)s __Pyx_c_sum%(m)s(%(type)s a, %(type)s b) {
1165 %(type)s z;
1166 z.real = a.real + b.real;
1167 z.imag = a.imag + b.imag;
1168 return z;
1169 }
1170 static INLINE %(type)s __Pyx_c_diff%(m)s(%(type)s a, %(type)s b) {
1171 %(type)s z;
1172 z.real = a.real - b.real;
1173 z.imag = a.imag - b.imag;
1174 return z;
1175 }
1176 static INLINE %(type)s __Pyx_c_prod%(m)s(%(type)s a, %(type)s b) {
1177 %(type)s z;
1178 z.real = a.real * b.real - a.imag * b.imag;
1179 z.imag = a.real * b.imag + a.imag * b.real;
1180 return z;
1181 }
1182 static INLINE %(type)s __Pyx_c_quot%(m)s(%(type)s a, %(type)s b) {
1183 %(type)s z;
1184 %(real_type)s denom = b.real * b.real + b.imag * b.imag;
1185 z.real = (a.real * b.real + a.imag * b.imag) / denom;
1186 z.imag = (a.imag * b.real - a.real * b.imag) / denom;
1187 return z;
1188 }
1189 static INLINE %(type)s __Pyx_c_neg%(m)s(%(type)s a) {
1190 %(type)s z;
1191 z.real = -a.real;
1192 z.imag = -a.imag;
1193 return z;
1194 }
1195 static INLINE int __Pyx_c_is_zero%(m)s(%(type)s a) {
1196 return (a.real == 0) && (a.imag == 0);
1197 }
1198 static INLINE %(type)s __Pyx_c_conj%(m)s(%(type)s a) {
1199 %(type)s z;
1200 z.real = a.real;
1201 z.imag = -a.imag;
1202 return z;
1203 }
1204 /*
1205 static INLINE %(real_type)s __Pyx_c_abs%(m)s(%(type)s z) {
1206 #if HAVE_HYPOT
1207 return hypot%(m)s(z.real, z.imag);
1208 #else
1209 return sqrt%(m)s(z.real*z.real + z.imag*z.imag);
1210 #endif
1211 }
1212 */
1213 #endif
1214 """)
1216 class CArrayType(CType):
1217 # base_type CType Element type
1218 # size integer or None Number of elements
1220 is_array = 1
1222 def __init__(self, base_type, size):
1223 self.base_type = base_type
1224 self.size = size
1225 if base_type is c_char_type:
1226 self.is_string = 1
1228 def __repr__(self):
1229 return "<CArrayType %s %s>" % (self.size, repr(self.base_type))
1231 def same_as_resolved_type(self, other_type):
1232 return ((other_type.is_array and
1233 self.base_type.same_as(other_type.base_type))
1234 or other_type is error_type)
1236 def assignable_from_resolved_type(self, src_type):
1237 # Can't assign to a variable of an array type
1238 return 0
1240 def element_ptr_type(self):
1241 return c_ptr_type(self.base_type)
1243 def declaration_code(self, entity_code,
1244 for_display = 0, dll_linkage = None, pyrex = 0):
1245 if self.size is not None:
1246 dimension_code = self.size
1247 else:
1248 dimension_code = ""
1249 if entity_code.startswith("*"):
1250 entity_code = "(%s)" % entity_code
1251 return self.base_type.declaration_code(
1252 "%s[%s]" % (entity_code, dimension_code),
1253 for_display, dll_linkage, pyrex)
1255 def as_argument_type(self):
1256 return c_ptr_type(self.base_type)
1258 def is_complete(self):
1259 return self.size is not None
1262 class CPtrType(CType):
1263 # base_type CType Referenced type
1265 is_ptr = 1
1266 default_value = "0"
1268 def __init__(self, base_type):
1269 self.base_type = base_type
1271 def __repr__(self):
1272 return "<CPtrType %s>" % repr(self.base_type)
1274 def same_as_resolved_type(self, other_type):
1275 return ((other_type.is_ptr and
1276 self.base_type.same_as(other_type.base_type))
1277 or other_type is error_type)
1279 def declaration_code(self, entity_code,
1280 for_display = 0, dll_linkage = None, pyrex = 0):
1281 #print "CPtrType.declaration_code: pointer to", self.base_type ###
1282 return self.base_type.declaration_code(
1283 "*%s" % entity_code,
1284 for_display, dll_linkage, pyrex)
1286 def assignable_from_resolved_type(self, other_type):
1287 if other_type is error_type:
1288 return 1
1289 if other_type.is_null_ptr:
1290 return 1
1291 if self.base_type.is_cfunction:
1292 if other_type.is_ptr:
1293 other_type = other_type.base_type.resolve()
1294 if other_type.is_cfunction:
1295 return self.base_type.pointer_assignable_from_resolved_type(other_type)
1296 else:
1297 return 0
1298 if other_type.is_array or other_type.is_ptr:
1299 return self.base_type.is_void or self.base_type.same_as(other_type.base_type)
1300 return 0
1303 class CNullPtrType(CPtrType):
1305 is_null_ptr = 1
1308 class CFuncType(CType):
1309 # return_type CType
1310 # args [CFuncTypeArg]
1311 # has_varargs boolean
1312 # exception_value string
1313 # exception_check boolean True if PyErr_Occurred check needed
1314 # calling_convention string Function calling convention
1315 # nogil boolean Can be called without gil
1316 # with_gil boolean Acquire gil around function body
1318 is_cfunction = 1
1319 original_sig = None
1321 def __init__(self, return_type, args, has_varargs = 0,
1322 exception_value = None, exception_check = 0, calling_convention = "",
1323 nogil = 0, with_gil = 0, is_overridable = 0, optional_arg_count = 0):
1324 self.return_type = return_type
1325 self.args = args
1326 self.has_varargs = has_varargs
1327 self.optional_arg_count = optional_arg_count
1328 self.exception_value = exception_value
1329 self.exception_check = exception_check
1330 self.calling_convention = calling_convention
1331 self.nogil = nogil
1332 self.with_gil = with_gil
1333 self.is_overridable = is_overridable
1335 def __repr__(self):
1336 arg_reprs = map(repr, self.args)
1337 if self.has_varargs:
1338 arg_reprs.append("...")
1339 if self.exception_value:
1340 except_clause = " %r" % self.exception_value
1341 else:
1342 except_clause = ""
1343 if self.exception_check:
1344 except_clause += "?"
1345 return "<CFuncType %s %s[%s]%s>" % (
1346 repr(self.return_type),
1347 self.calling_convention_prefix(),
1348 ",".join(arg_reprs),
1349 except_clause)
1351 def calling_convention_prefix(self):
1352 cc = self.calling_convention
1353 if cc:
1354 return cc + " "
1355 else:
1356 return ""
1358 def same_c_signature_as(self, other_type, as_cmethod = 0):
1359 return self.same_c_signature_as_resolved_type(
1360 other_type.resolve(), as_cmethod)
1362 def same_c_signature_as_resolved_type(self, other_type, as_cmethod = 0):
1363 #print "CFuncType.same_c_signature_as_resolved_type:", \
1364 # self, other_type, "as_cmethod =", as_cmethod ###
1365 if other_type is error_type:
1366 return 1
1367 if not other_type.is_cfunction:
1368 return 0
1369 if self.is_overridable != other_type.is_overridable:
1370 return 0
1371 nargs = len(self.args)
1372 if nargs != len(other_type.args):
1373 return 0
1374 # When comparing C method signatures, the first argument
1375 # is exempt from compatibility checking (the proper check
1376 # is performed elsewhere).
1377 for i in range(as_cmethod, nargs):
1378 if not self.args[i].type.same_as(
1379 other_type.args[i].type):
1380 return 0
1381 if self.has_varargs != other_type.has_varargs:
1382 return 0
1383 if self.optional_arg_count != other_type.optional_arg_count:
1384 return 0
1385 if not self.return_type.same_as(other_type.return_type):
1386 return 0
1387 if not self.same_calling_convention_as(other_type):
1388 return 0
1389 return 1
1391 def compatible_signature_with(self, other_type, as_cmethod = 0):
1392 return self.compatible_signature_with_resolved_type(other_type.resolve(), as_cmethod)
1394 def compatible_signature_with_resolved_type(self, other_type, as_cmethod):
1395 #print "CFuncType.same_c_signature_as_resolved_type:", \
1396 # self, other_type, "as_cmethod =", as_cmethod ###
1397 if other_type is error_type:
1398 return 1
1399 if not other_type.is_cfunction:
1400 return 0
1401 if not self.is_overridable and other_type.is_overridable:
1402 return 0
1403 nargs = len(self.args)
1404 if nargs - self.optional_arg_count != len(other_type.args) - other_type.optional_arg_count:
1405 return 0
1406 if self.optional_arg_count < other_type.optional_arg_count:
1407 return 0
1408 # When comparing C method signatures, the first argument
1409 # is exempt from compatibility checking (the proper check
1410 # is performed elsewhere).
1411 for i in range(as_cmethod, len(other_type.args)):
1412 if not self.args[i].type.same_as(
1413 other_type.args[i].type):
1414 return 0
1415 if self.has_varargs != other_type.has_varargs:
1416 return 0
1417 if not self.return_type.subtype_of_resolved_type(other_type.return_type):
1418 return 0
1419 if not self.same_calling_convention_as(other_type):
1420 return 0
1421 if self.nogil != other_type.nogil:
1422 return 0
1423 self.original_sig = other_type.original_sig or other_type
1424 if as_cmethod:
1425 self.args[0] = other_type.args[0]
1426 return 1
1429 def narrower_c_signature_than(self, other_type, as_cmethod = 0):
1430 return self.narrower_c_signature_than_resolved_type(other_type.resolve(), as_cmethod)
1432 def narrower_c_signature_than_resolved_type(self, other_type, as_cmethod):
1433 if other_type is error_type:
1434 return 1
1435 if not other_type.is_cfunction:
1436 return 0
1437 nargs = len(self.args)
1438 if nargs != len(other_type.args):
1439 return 0
1440 for i in range(as_cmethod, nargs):
1441 if not self.args[i].type.subtype_of_resolved_type(other_type.args[i].type):
1442 return 0
1443 else:
1444 self.args[i].needs_type_test = other_type.args[i].needs_type_test \
1445 or not self.args[i].type.same_as(other_type.args[i].type)
1446 if self.has_varargs != other_type.has_varargs:
1447 return 0
1448 if self.optional_arg_count != other_type.optional_arg_count:
1449 return 0
1450 if not self.return_type.subtype_of_resolved_type(other_type.return_type):
1451 return 0
1452 return 1
1454 def same_calling_convention_as(self, other):
1455 ## XXX Under discussion ...
1456 ## callspec_words = ("__stdcall", "__cdecl", "__fastcall")
1457 ## cs1 = self.calling_convention
1458 ## cs2 = other.calling_convention
1459 ## if (cs1 in callspec_words or
1460 ## cs2 in callspec_words):
1461 ## return cs1 == cs2
1462 ## else:
1463 ## return True
1464 sc1 = self.calling_convention == '__stdcall'
1465 sc2 = other.calling_convention == '__stdcall'
1466 return sc1 == sc2
1468 def same_exception_signature_as(self, other_type):
1469 return self.same_exception_signature_as_resolved_type(
1470 other_type.resolve())
1472 def same_exception_signature_as_resolved_type(self, other_type):
1473 return self.exception_value == other_type.exception_value \
1474 and self.exception_check == other_type.exception_check
1476 def same_as_resolved_type(self, other_type, as_cmethod = 0):
1477 return self.same_c_signature_as_resolved_type(other_type, as_cmethod) \
1478 and self.same_exception_signature_as_resolved_type(other_type) \
1479 and self.nogil == other_type.nogil
1481 def pointer_assignable_from_resolved_type(self, other_type):
1482 return self.same_c_signature_as_resolved_type(other_type) \
1483 and self.same_exception_signature_as_resolved_type(other_type) \
1484 and not (self.nogil and not other_type.nogil)
1486 def declaration_code(self, entity_code,
1487 for_display = 0, dll_linkage = None, pyrex = 0,
1488 with_calling_convention = 1):
1489 arg_decl_list = []
1490 for arg in self.args[:len(self.args)-self.optional_arg_count]:
1491 arg_decl_list.append(
1492 arg.type.declaration_code("", for_display, pyrex = pyrex))
1493 if self.is_overridable:
1494 arg_decl_list.append("int %s" % Naming.skip_dispatch_cname)
1495 if self.optional_arg_count:
1496 arg_decl_list.append(self.op_arg_struct.declaration_code(Naming.optional_args_cname))
1497 if self.has_varargs:
1498 arg_decl_list.append("...")
1499 arg_decl_code = ", ".join(arg_decl_list)
1500 if not arg_decl_code and not pyrex:
1501 arg_decl_code = "void"
1502 trailer = ""
1503 if (pyrex or for_display) and not self.return_type.is_pyobject:
1504 if self.exception_value and self.exception_check:
1505 trailer = " except? %s" % self.exception_value
1506 elif self.exception_value:
1507 trailer = " except %s" % self.exception_value
1508 elif self.exception_check == '+':
1509 trailer = " except +"
1510 else:
1511 " except *" # ignored
1512 if self.nogil:
1513 trailer += " nogil"
1514 if not with_calling_convention:
1515 cc = ''
1516 else:
1517 cc = self.calling_convention_prefix()
1518 if (not entity_code and cc) or entity_code.startswith("*"):
1519 entity_code = "(%s%s)" % (cc, entity_code)
1520 cc = ""
1521 return self.return_type.declaration_code(
1522 "%s%s(%s)%s" % (cc, entity_code, arg_decl_code, trailer),
1523 for_display, dll_linkage, pyrex)
1525 def function_header_code(self, func_name, arg_code):
1526 return "%s%s(%s)" % (self.calling_convention_prefix(),
1527 func_name, arg_code)
1529 def signature_string(self):
1530 s = self.declaration_code("")
1531 return s
1533 def signature_cast_string(self):
1534 s = self.declaration_code("(*)", with_calling_convention=False)
1535 return '(%s)' % s
1538 class CFuncTypeArg(object):
1539 # name string
1540 # cname string
1541 # type PyrexType
1542 # pos source file position
1544 def __init__(self, name, type, pos, cname=None):
1545 self.name = name
1546 if cname is not None:
1547 self.cname = cname
1548 else:
1549 self.cname = Naming.var_prefix + name
1550 self.type = type
1551 self.pos = pos
1552 self.not_none = False
1553 self.needs_type_test = False # TODO: should these defaults be set in analyse_types()?
1555 def __repr__(self):
1556 return "%s:%s" % (self.name, repr(self.type))
1558 def declaration_code(self, for_display = 0):
1559 return self.type.declaration_code(self.cname, for_display)
1561 class StructUtilityCode(object):
1562 def __init__(self, type, forward_decl):
1563 self.type = type
1564 self.header = "static PyObject* %s(%s)" % (type.to_py_function, type.declaration_code('s'))
1565 self.forward_decl = forward_decl
1567 def __eq__(self, other):
1568 return isinstance(other, StructUtilityCode) and self.header == other.header
1569 def __hash__(self):
1570 return hash(self.header)
1572 def put_code(self, output):
1573 code = output['utility_code_def']
1574 proto = output['utility_code_proto']
1576 code.putln("%s {" % self.header)
1577 code.putln("PyObject* res;")
1578 code.putln("PyObject* member;")
1579 code.putln("res = PyDict_New(); if (res == NULL) return NULL;")
1580 for member in self.type.scope.var_entries:
1581 nameconst_cname = code.get_py_string_const(member.name, identifier=True)
1582 code.putln("member = %s(s.%s); if (member == NULL) goto bad;" % (
1583 member.type.to_py_function, member.cname))
1584 code.putln("if (PyDict_SetItem(res, %s, member) < 0) goto bad;" % nameconst_cname)
1585 code.putln("Py_DECREF(member);")
1586 code.putln("return res;")
1587 code.putln("bad:")
1588 code.putln("Py_XDECREF(member);")
1589 code.putln("Py_DECREF(res);")
1590 code.putln("return NULL;")
1591 code.putln("}")
1593 # This is a bit of a hack, we need a forward declaration
1594 # due to the way things are ordered in the module...
1595 if self.forward_decl:
1596 proto.putln(self.type.declaration_code('') + ';')
1597 proto.putln(self.header + ";")
1600 class CStructOrUnionType(CType):
1601 # name string
1602 # cname string
1603 # kind string "struct" or "union"
1604 # scope StructOrUnionScope, or None if incomplete
1605 # typedef_flag boolean
1606 # packed boolean
1608 # entry Entry
1610 is_struct_or_union = 1
1611 has_attributes = 1
1613 def __init__(self, name, kind, scope, typedef_flag, cname, packed=False):
1614 self.name = name
1615 self.cname = cname
1616 self.kind = kind
1617 self.scope = scope
1618 self.typedef_flag = typedef_flag
1619 self.is_struct = kind == 'struct'
1620 if self.is_struct:
1621 self.to_py_function = "%s_to_py_%s" % (Naming.convert_func_prefix, self.cname)
1622 self.exception_check = True
1623 self._convert_code = None
1624 self.packed = packed
1626 def create_to_py_utility_code(self, env):
1627 if env.outer_scope is None:
1628 return False
1630 if self._convert_code is False: return # tri-state-ish
1632 if self._convert_code is None:
1633 for member in self.scope.var_entries:
1634 if not member.type.to_py_function or not member.type.create_to_py_utility_code(env):
1635 self.to_py_function = None
1636 self._convert_code = False
1637 return False
1638 forward_decl = (self.entry.visibility != 'extern')
1639 self._convert_code = StructUtilityCode(self, forward_decl)
1641 env.use_utility_code(self._convert_code)
1642 return True
1644 def __repr__(self):
1645 return "<CStructOrUnionType %s %s%s>" % (self.name, self.cname,
1646 ("", " typedef")[self.typedef_flag])
1648 def declaration_code(self, entity_code,
1649 for_display = 0, dll_linkage = None, pyrex = 0):
1650 if pyrex:
1651 return self.base_declaration_code(self.name, entity_code)
1652 else:
1653 if for_display:
1654 base = self.name
1655 elif self.typedef_flag:
1656 base = self.cname
1657 else:
1658 base = "%s %s" % (self.kind, self.cname)
1659 return self.base_declaration_code(public_decl(base, dll_linkage), entity_code)
1661 def __eq__(self, other):
1662 try:
1663 return (isinstance(other, CStructOrUnionType) and
1664 self.name == other.name)
1665 except AttributeError:
1666 return False
1668 def __lt__(self, other):
1669 try:
1670 return self.name < other.name
1671 except AttributeError:
1672 # this is arbitrary, but it makes sure we always have
1673 # *some* kind of order
1674 return False
1676 def __hash__(self):
1677 return hash(self.cname) ^ hash(self.kind)
1679 def is_complete(self):
1680 return self.scope is not None
1682 def attributes_known(self):
1683 return self.is_complete()
1685 def can_be_complex(self):
1686 # Does the struct consist of exactly two identical floats?
1687 fields = self.scope.var_entries
1688 if len(fields) != 2: return False
1689 a, b = fields
1690 return (a.type.is_float and b.type.is_float and
1691 a.type.declaration_code("") ==
1692 b.type.declaration_code(""))
1694 def struct_nesting_depth(self):
1695 child_depths = [x.type.struct_nesting_depth()
1696 for x in self.scope.var_entries]
1697 return max(child_depths) + 1
1699 class CEnumType(CType):
1700 # name string
1701 # cname string or None
1702 # typedef_flag boolean
1704 is_enum = 1
1705 signed = 1
1706 rank = -1 # Ranks below any integer type
1707 to_py_function = "PyInt_FromLong"
1708 from_py_function = "PyInt_AsLong"
1710 def __init__(self, name, cname, typedef_flag):
1711 self.name = name
1712 self.cname = cname
1713 self.values = []
1714 self.typedef_flag = typedef_flag
1716 def __str__(self):
1717 return self.name
1719 def __repr__(self):
1720 return "<CEnumType %s %s%s>" % (self.name, self.cname,
1721 ("", " typedef")[self.typedef_flag])
1723 def declaration_code(self, entity_code,
1724 for_display = 0, dll_linkage = None, pyrex = 0):
1725 if pyrex:
1726 return self.base_declaration_code(self.cname, entity_code)
1727 else:
1728 if self.typedef_flag:
1729 base = self.cname
1730 else:
1731 base = "enum %s" % self.cname
1732 return self.base_declaration_code(public_decl(base, dll_linkage), entity_code)
1735 class CStringType(object):
1736 # Mixin class for C string types.
1738 is_string = 1
1739 is_unicode = 0
1741 to_py_function = "__Pyx_PyBytes_FromString"
1742 from_py_function = "__Pyx_PyBytes_AsString"
1743 exception_value = "NULL"
1745 def literal_code(self, value):
1746 assert isinstance(value, str)
1747 return '"%s"' % StringEncoding.escape_byte_string(value)
1750 class CUTF8CharArrayType(CStringType, CArrayType):
1751 # C 'char []' type.
1753 pymemberdef_typecode = "T_STRING_INPLACE"
1754 is_unicode = 1
1756 to_py_function = "PyUnicode_DecodeUTF8"
1757 exception_value = "NULL"
1759 def __init__(self, size):
1760 CArrayType.__init__(self, c_char_type, size)
1762 class CCharArrayType(CStringType, CArrayType):
1763 # C 'char []' type.
1765 pymemberdef_typecode = "T_STRING_INPLACE"
1767 def __init__(self, size):
1768 CArrayType.__init__(self, c_char_type, size)
1771 class CCharPtrType(CStringType, CPtrType):
1772 # C 'char *' type.
1774 pymemberdef_typecode = "T_STRING"
1776 def __init__(self):
1777 CPtrType.__init__(self, c_char_type)
1780 class CUCharPtrType(CStringType, CPtrType):
1781 # C 'unsigned char *' type.
1783 pymemberdef_typecode = "T_STRING"
1785 to_py_function = "__Pyx_PyBytes_FromUString"
1786 from_py_function = "__Pyx_PyBytes_AsUString"
1788 def __init__(self):
1789 CPtrType.__init__(self, c_uchar_type)
1792 class UnspecifiedType(PyrexType):
1793 # Used as a placeholder until the type can be determined.
1795 is_unspecified = 1
1797 def declaration_code(self, entity_code,
1798 for_display = 0, dll_linkage = None, pyrex = 0):
1799 return "<unspecified>"
1801 def same_as_resolved_type(self, other_type):
1802 return False
1805 class ErrorType(PyrexType):
1806 # Used to prevent propagation of error messages.
1808 is_error = 1
1809 exception_value = "0"
1810 exception_check = 0
1811 to_py_function = "dummy"
1812 from_py_function = "dummy"
1814 def create_to_py_utility_code(self, env):
1815 return True
1817 def create_from_py_utility_code(self, env):
1818 return True
1820 def declaration_code(self, entity_code,
1821 for_display = 0, dll_linkage = None, pyrex = 0):
1822 return "<error>"
1824 def same_as_resolved_type(self, other_type):
1825 return 1
1827 def error_condition(self, result_code):
1828 return "dummy"
1831 rank_to_type_name = (
1832 "char", # 0
1833 "short", # 1
1834 "int", # 2
1835 "long", # 3
1836 "Py_ssize_t", # 4
1837 "size_t", # 5
1838 "PY_LONG_LONG", # 6
1839 "float", # 7
1840 "double", # 8
1841 "long double", # 9
1842 )
1844 py_object_type = PyObjectType()
1846 c_void_type = CVoidType()
1847 c_void_ptr_type = CPtrType(c_void_type)
1848 c_void_ptr_ptr_type = CPtrType(c_void_ptr_type)
1850 c_uchar_type = CIntType(0, 0, "T_UBYTE")
1851 c_ushort_type = CIntType(1, 0, "T_USHORT")
1852 c_uint_type = CUIntType(2, 0, "T_UINT")
1853 c_ulong_type = CULongType(3, 0, "T_ULONG")
1854 c_ulonglong_type = CULongLongType(6, 0, "T_ULONGLONG")
1856 c_char_type = CIntType(0, 1, "T_CHAR")
1857 c_short_type = CIntType(1, 1, "T_SHORT")
1858 c_int_type = CIntType(2, 1, "T_INT")
1859 c_long_type = CLongType(3, 1, "T_LONG")
1860 c_longlong_type = CLongLongType(6, 1, "T_LONGLONG")
1861 c_bint_type = CBIntType(2, 1, "T_INT")
1863 c_schar_type = CIntType(0, 2, "T_CHAR")
1864 c_sshort_type = CIntType(1, 2, "T_SHORT")
1865 c_sint_type = CIntType(2, 2, "T_INT")
1866 c_slong_type = CLongType(3, 2, "T_LONG")
1867 c_slonglong_type = CLongLongType(6, 2, "T_LONGLONG")
1869 c_py_ssize_t_type = CPySSizeTType(4, 2, "T_PYSSIZET")
1870 c_size_t_type = CSizeTType(5, 0, "T_SIZET")
1872 c_float_type = CFloatType(7, "T_FLOAT", math_h_modifier='f')
1873 c_double_type = CFloatType(8, "T_DOUBLE")
1874 c_longdouble_type = CFloatType(9, math_h_modifier='l')
1876 c_double_complex_type = CComplexType(c_double_type)
1878 c_null_ptr_type = CNullPtrType(c_void_type)
1879 c_char_array_type = CCharArrayType(None)
1880 c_char_ptr_type = CCharPtrType()
1881 c_uchar_ptr_type = CUCharPtrType()
1882 c_utf8_char_array_type = CUTF8CharArrayType(None)
1883 c_char_ptr_ptr_type = CPtrType(c_char_ptr_type)
1884 c_int_ptr_type = CPtrType(c_int_type)
1885 c_py_ssize_t_ptr_type = CPtrType(c_py_ssize_t_type)
1886 c_size_t_ptr_type = CPtrType(c_size_t_type)
1888 c_returncode_type = CIntType(2, 1, "T_INT", is_returncode = 1)
1890 c_anon_enum_type = CAnonEnumType(-1, 1)
1892 # the Py_buffer type is defined in Builtin.py
1893 c_py_buffer_type = CStructOrUnionType("Py_buffer", "struct", None, 1, "Py_buffer")
1894 c_py_buffer_ptr_type = CPtrType(c_py_buffer_type)
1896 error_type = ErrorType()
1897 unspecified_type = UnspecifiedType()
1899 sign_and_rank_to_type = {
1900 #(signed, rank)
1901 (0, 0): c_uchar_type,
1902 (0, 1): c_ushort_type,
1903 (0, 2): c_uint_type,
1904 (0, 3): c_ulong_type,
1905 (0, 6): c_ulonglong_type,
1907 (1, 0): c_char_type,
1908 (1, 1): c_short_type,
1909 (1, 2): c_int_type,
1910 (1, 3): c_long_type,
1911 (1, 6): c_longlong_type,
1913 (2, 0): c_schar_type,
1914 (2, 1): c_sshort_type,
1915 (2, 2): c_sint_type,
1916 (2, 3): c_slong_type,
1917 (2, 6): c_slonglong_type,
1919 (0, 4): c_py_ssize_t_type,
1920 (1, 4): c_py_ssize_t_type,
1921 (2, 4): c_py_ssize_t_type,
1922 (0, 5): c_size_t_type,
1923 (1, 5): c_size_t_type,
1924 (2, 5): c_size_t_type,
1926 (1, 7): c_float_type,
1927 (1, 8): c_double_type,
1928 (1, 9): c_longdouble_type,
1929 # In case we're mixing unsigned ints and floats...
1930 (0, 7): c_float_type,
1931 (0, 8): c_double_type,
1932 (0, 9): c_longdouble_type,
1933 }
1935 modifiers_and_name_to_type = {
1936 #(signed, longness, name)
1937 (0, 0, "char"): c_uchar_type,
1938 (0, -1, "int"): c_ushort_type,
1939 (0, 0, "int"): c_uint_type,
1940 (0, 1, "int"): c_ulong_type,
1941 (0, 2, "int"): c_ulonglong_type,
1942 (1, 0, "void"): c_void_type,
1943 (1, 0, "char"): c_char_type,
1944 (1, -1, "int"): c_short_type,
1945 (1, 0, "int"): c_int_type,
1946 (1, 1, "int"): c_long_type,
1947 (1, 2, "int"): c_longlong_type,
1948 (1, 0, "float"): c_float_type,
1949 (1, 0, "double"): c_double_type,
1950 (1, 1, "double"): c_longdouble_type,
1951 (1, 0, "object"): py_object_type,
1952 (1, 0, "bint"): c_bint_type,
1953 (2, 0, "char"): c_schar_type,
1954 (2, -1, "int"): c_sshort_type,
1955 (2, 0, "int"): c_sint_type,
1956 (2, 1, "int"): c_slong_type,
1957 (2, 2, "int"): c_slonglong_type,
1959 (2, 0, "Py_ssize_t"): c_py_ssize_t_type,
1960 (0, 0, "size_t") : c_size_t_type,
1962 (1, 0, "long"): c_long_type,
1963 (1, 0, "short"): c_short_type,
1964 (1, 0, "longlong"): c_longlong_type,
1965 (1, 0, "bint"): c_bint_type,
1966 }
1968 def widest_numeric_type(type1, type2):
1969 # Given two numeric types, return the narrowest type
1970 # encompassing both of them.
1971 if type1 == type2:
1972 return type1
1973 if type1.is_complex:
1974 if type2.is_complex:
1975 return CComplexType(widest_numeric_type(type1.real_type, type2.real_type))
1976 else:
1977 return CComplexType(widest_numeric_type(type1.real_type, type2))
1978 elif type2.is_complex:
1979 return CComplexType(widest_numeric_type(type1, type2.real_type))
1980 if type1.is_enum and type2.is_enum:
1981 return c_int_type
1982 elif type1 is type2:
1983 return type1
1984 elif (type1.signed and type2.signed) or (not type1.signed and not type2.signed):
1985 if type2.rank > type1.rank:
1986 return type2
1987 else:
1988 return type1
1989 else:
1990 return sign_and_rank_to_type[min(type1.signed, type2.signed), max(type1.rank, type2.rank)]
1991 return widest_type
1993 def spanning_type(type1, type2):
1994 # Return a type assignable from both type1 and type2.
1995 if type1 is py_object_type or type2 is py_object_type:
1996 return py_object_type
1997 elif type1 == type2:
1998 return type1
1999 elif type1.is_numeric and type2.is_numeric:
2000 return widest_numeric_type(type1, type2)
2001 elif type1.is_pyobject ^ type2.is_pyobject:
2002 return py_object_type
2003 elif type1.assignable_from(type2):
2004 return type1
2005 elif type2.assignable_from(type1):
2006 return type2
2007 else:
2008 return py_object_type
2010 def simple_c_type(signed, longness, name):
2011 # Find type descriptor for simple type given name and modifiers.
2012 # Returns None if arguments don't make sense.
2013 return modifiers_and_name_to_type.get((signed, longness, name))
2015 def parse_basic_type(name):
2016 base = None
2017 if name.startswith('p_'):
2018 base = parse_basic_type(name[2:])
2019 elif name.startswith('p'):
2020 base = parse_basic_type(name[1:])
2021 elif name.endswith('*'):
2022 base = parse_basic_type(name[:-1])
2023 if base:
2024 return CPtrType(base)
2025 elif name.startswith('u'):
2026 return simple_c_type(0, 0, name[1:])
2027 else:
2028 return simple_c_type(1, 0, name)
2030 def c_array_type(base_type, size):
2031 # Construct a C array type.
2032 if base_type is c_char_type:
2033 return CCharArrayType(size)
2034 elif base_type is error_type:
2035 return error_type
2036 else:
2037 return CArrayType(base_type, size)
2039 def c_ptr_type(base_type):
2040 # Construct a C pointer type.
2041 if base_type is c_char_type:
2042 return c_char_ptr_type
2043 elif base_type is c_uchar_type:
2044 return c_uchar_ptr_type
2045 elif base_type is error_type:
2046 return error_type
2047 else:
2048 return CPtrType(base_type)
2050 def same_type(type1, type2):
2051 return type1.same_as(type2)
2053 def assignable_from(type1, type2):
2054 return type1.assignable_from(type2)
2056 def typecast(to_type, from_type, expr_code):
2057 # Return expr_code cast to a C type which can be
2058 # assigned to to_type, assuming its existing C type
2059 # is from_type.
2060 if to_type is from_type or \
2061 (not to_type.is_pyobject and assignable_from(to_type, from_type)):
2062 return expr_code
2063 else:
2064 #print "typecast: to", to_type, "from", from_type ###
2065 return to_type.cast_code(expr_code)
2068 type_conversion_predeclarations = """
2069 /* Type Conversion Predeclarations */
2071 #if PY_MAJOR_VERSION < 3
2072 #define __Pyx_PyBytes_FromString PyString_FromString
2073 #define __Pyx_PyBytes_FromStringAndSize PyString_FromStringAndSize
2074 #define __Pyx_PyBytes_AsString PyString_AsString
2075 #else
2076 #define __Pyx_PyBytes_FromString PyBytes_FromString
2077 #define __Pyx_PyBytes_FromStringAndSize PyBytes_FromStringAndSize
2078 #define __Pyx_PyBytes_AsString PyBytes_AsString
2079 #endif
2081 #define __Pyx_PyBytes_FromUString(s) __Pyx_PyBytes_FromString((char*)s)
2082 #define __Pyx_PyBytes_AsUString(s) ((unsigned char*) __Pyx_PyBytes_AsString(s))
2084 #define __Pyx_PyBool_FromLong(b) ((b) ? (Py_INCREF(Py_True), Py_True) : (Py_INCREF(Py_False), Py_False))
2085 static INLINE int __Pyx_PyObject_IsTrue(PyObject*);
2086 static INLINE PyObject* __Pyx_PyNumber_Int(PyObject* x);
2088 #if !defined(T_PYSSIZET)
2089 #if PY_VERSION_HEX < 0x02050000
2090 #define T_PYSSIZET T_INT
2091 #elif !defined(T_LONGLONG)
2092 #define T_PYSSIZET \\
2093 ((sizeof(Py_ssize_t) == sizeof(int)) ? T_INT : \\
2094 ((sizeof(Py_ssize_t) == sizeof(long)) ? T_LONG : -1))
2095 #else
2096 #define T_PYSSIZET \\
2097 ((sizeof(Py_ssize_t) == sizeof(int)) ? T_INT : \\
2098 ((sizeof(Py_ssize_t) == sizeof(long)) ? T_LONG : \\
2099 ((sizeof(Py_ssize_t) == sizeof(PY_LONG_LONG)) ? T_LONGLONG : -1)))
2100 #endif
2101 #endif
2104 #if !defined(T_ULONGLONG)
2105 #define __Pyx_T_UNSIGNED_INT(x) \\
2106 ((sizeof(x) == sizeof(unsigned char)) ? T_UBYTE : \\
2107 ((sizeof(x) == sizeof(unsigned short)) ? T_USHORT : \\
2108 ((sizeof(x) == sizeof(unsigned int)) ? T_UINT : \\
2109 ((sizeof(x) == sizeof(unsigned long)) ? T_ULONG : -1))))
2110 #else
2111 #define __Pyx_T_UNSIGNED_INT(x) \\
2112 ((sizeof(x) == sizeof(unsigned char)) ? T_UBYTE : \\
2113 ((sizeof(x) == sizeof(unsigned short)) ? T_USHORT : \\
2114 ((sizeof(x) == sizeof(unsigned int)) ? T_UINT : \\
2115 ((sizeof(x) == sizeof(unsigned long)) ? T_ULONG : \\
2116 ((sizeof(x) == sizeof(unsigned PY_LONG_LONG)) ? T_ULONGLONG : -1)))))
2117 #endif
2118 #if !defined(T_LONGLONG)
2119 #define __Pyx_T_SIGNED_INT(x) \\
2120 ((sizeof(x) == sizeof(char)) ? T_BYTE : \\
2121 ((sizeof(x) == sizeof(short)) ? T_SHORT : \\
2122 ((sizeof(x) == sizeof(int)) ? T_INT : \\
2123 ((sizeof(x) == sizeof(long)) ? T_LONG : -1))))
2124 #else
2125 #define __Pyx_T_SIGNED_INT(x) \\
2126 ((sizeof(x) == sizeof(char)) ? T_BYTE : \\
2127 ((sizeof(x) == sizeof(short)) ? T_SHORT : \\
2128 ((sizeof(x) == sizeof(int)) ? T_INT : \\
2129 ((sizeof(x) == sizeof(long)) ? T_LONG : \\
2130 ((sizeof(x) == sizeof(PY_LONG_LONG)) ? T_LONGLONG : -1)))))
2131 #endif
2133 #define __Pyx_T_FLOATING(x) \\
2134 ((sizeof(x) == sizeof(float)) ? T_FLOAT : \\
2135 ((sizeof(x) == sizeof(double)) ? T_DOUBLE : -1))
2137 #if !defined(T_SIZET)
2138 #if !defined(T_ULONGLONG)
2139 #define T_SIZET \\
2140 ((sizeof(size_t) == sizeof(unsigned int)) ? T_UINT : \\
2141 ((sizeof(size_t) == sizeof(unsigned long)) ? T_ULONG : -1))
2142 #else
2143 #define T_SIZET \\
2144 ((sizeof(size_t) == sizeof(unsigned int)) ? T_UINT : \\
2145 ((sizeof(size_t) == sizeof(unsigned long)) ? T_ULONG : \\
2146 ((sizeof(size_t) == sizeof(unsigned PY_LONG_LONG)) ? T_ULONGLONG : -1)))
2147 #endif
2148 #endif
2150 static INLINE Py_ssize_t __Pyx_PyIndex_AsSsize_t(PyObject*);
2151 static INLINE PyObject * __Pyx_PyInt_FromSize_t(size_t);
2152 static INLINE size_t __Pyx_PyInt_AsSize_t(PyObject*);
2154 #define __pyx_PyFloat_AsDouble(x) (PyFloat_CheckExact(x) ? PyFloat_AS_DOUBLE(x) : PyFloat_AsDouble(x))
2156 """ + type_conversion_predeclarations
2158 type_conversion_functions = """
2159 /* Type Conversion Functions */
2161 static INLINE int __Pyx_PyObject_IsTrue(PyObject* x) {
2162 if (x == Py_True) return 1;
2163 else if ((x == Py_False) | (x == Py_None)) return 0;
2164 else return PyObject_IsTrue(x);
2165 }
2167 static INLINE PyObject* __Pyx_PyNumber_Int(PyObject* x) {
2168 PyNumberMethods *m;
2169 const char *name = NULL;
2170 PyObject *res = NULL;
2171 #if PY_VERSION_HEX < 0x03000000
2172 if (PyInt_Check(x) || PyLong_Check(x))
2173 #else
2174 if (PyLong_Check(x))
2175 #endif
2176 return Py_INCREF(x), x;
2177 m = Py_TYPE(x)->tp_as_number;
2178 #if PY_VERSION_HEX < 0x03000000
2179 if (m && m->nb_int) {
2180 name = "int";
2181 res = PyNumber_Int(x);
2182 }
2183 else if (m && m->nb_long) {
2184 name = "long";
2185 res = PyNumber_Long(x);
2186 }
2187 #else
2188 if (m && m->nb_int) {
2189 name = "int";
2190 res = PyNumber_Long(x);
2191 }
2192 #endif
2193 if (res) {
2194 #if PY_VERSION_HEX < 0x03000000
2195 if (!PyInt_Check(res) && !PyLong_Check(res)) {
2196 #else
2197 if (!PyLong_Check(res)) {
2198 #endif
2199 PyErr_Format(PyExc_TypeError,
2200 "__%s__ returned non-%s (type %.200s)",
2201 name, name, Py_TYPE(res)->tp_name);
2202 Py_DECREF(res);
2203 return NULL;
2204 }
2205 }
2206 else if (!PyErr_Occurred()) {
2207 PyErr_SetString(PyExc_TypeError,
2208 "an integer is required");
2209 }
2210 return res;
2211 }
2213 static INLINE Py_ssize_t __Pyx_PyIndex_AsSsize_t(PyObject* b) {
2214 Py_ssize_t ival;
2215 PyObject* x = PyNumber_Index(b);
2216 if (!x) return -1;
2217 ival = PyInt_AsSsize_t(x);
2218 Py_DECREF(x);
2219 return ival;
2220 }
2222 static INLINE PyObject * __Pyx_PyInt_FromSize_t(size_t ival) {
2223 #if PY_VERSION_HEX < 0x02050000
2224 if (ival <= LONG_MAX)
2225 return PyInt_FromLong((long)ival);
2226 else {
2227 unsigned char *bytes = (unsigned char *) &ival;
2228 int one = 1; int little = (int)*(unsigned char*)&one;
2229 return _PyLong_FromByteArray(bytes, sizeof(size_t), little, 0);
2230 }
2231 #else
2232 return PyInt_FromSize_t(ival);
2233 #endif
2234 }
2236 static INLINE size_t __Pyx_PyInt_AsSize_t(PyObject* x) {
2237 unsigned PY_LONG_LONG val = __Pyx_PyInt_AsUnsignedLongLong(x);
2238 if (unlikely(val == (unsigned PY_LONG_LONG)-1 && PyErr_Occurred())) {
2239 return (size_t)-1;
2240 } else if (unlikely(val != (unsigned PY_LONG_LONG)(size_t)val)) {
2241 PyErr_SetString(PyExc_OverflowError,
2242 "value too large to convert to size_t");
2243 return (size_t)-1;
2244 }
2245 return (size_t)val;
2246 }
2248 """ + type_conversion_functions
