Cython has moved to github.
cython-devel
view Cython/Compiler/PyrexTypes.py @ 2771:8094c672a0b9
Less strict type checking on non-subclassed extern types.
| author | Robert Bradshaw <robertwb@math.washington.edu> |
|---|---|
| date | Tue Dec 08 23:10:36 2009 -0800 (2 years ago) |
| parents | 885dbfad02aa |
| children | 6a2538923399 dde8beab2d1e |
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 can_coerce_to_pyobject(self, env):
15 return False
17 def cast_code(self, expr_code):
18 return "((%s)%s)" % (self.declaration_code(""), expr_code)
20 def specalization_name(self):
21 return self.declaration_code("").replace(" ", "__")
23 def base_declaration_code(self, base_code, entity_code):
24 if entity_code:
25 return "%s %s" % (base_code, entity_code)
26 else:
27 return base_code
29 class PyrexType(BaseType):
30 #
31 # Base class for all Pyrex types.
32 #
33 # is_pyobject boolean Is a Python object type
34 # is_extension_type boolean Is a Python extension type
35 # is_numeric boolean Is a C numeric type
36 # is_int boolean Is a C integer type
37 # is_float boolean Is a C floating point type
38 # is_complex boolean Is a C complex type
39 # is_void boolean Is the C void type
40 # is_array boolean Is a C array type
41 # is_ptr boolean Is a C pointer type
42 # is_null_ptr boolean Is the type of NULL
43 # is_cfunction boolean Is a C function type
44 # is_struct_or_union boolean Is a C struct or union type
45 # is_struct boolean Is a C struct type
46 # is_enum boolean Is a C enum type
47 # is_typedef boolean Is a typedef type
48 # is_string boolean Is a C char * type
49 # is_unicode boolean Is a UTF-8 encoded C char * type
50 # is_returncode boolean Is used only to signal exceptions
51 # is_error boolean Is the dummy error type
52 # is_buffer boolean Is buffer access type
53 # has_attributes boolean Has C dot-selectable attributes
54 # default_value string Initial value
55 # pymemberdef_typecode string Type code for PyMemberDef struct
56 #
57 # declaration_code(entity_code,
58 # for_display = 0, dll_linkage = None, pyrex = 0)
59 # Returns a code fragment for the declaration of an entity
60 # of this type, given a code fragment for the entity.
61 # * If for_display, this is for reading by a human in an error
62 # message; otherwise it must be valid C code.
63 # * If dll_linkage is not None, it must be 'DL_EXPORT' or
64 # 'DL_IMPORT', and will be added to the base type part of
65 # the declaration.
66 # * If pyrex = 1, this is for use in a 'cdef extern'
67 # statement of a Pyrex include file.
68 #
69 # assignable_from(src_type)
70 # Tests whether a variable of this type can be
71 # assigned a value of type src_type.
72 #
73 # same_as(other_type)
74 # Tests whether this type represents the same type
75 # as other_type.
76 #
77 # as_argument_type():
78 # Coerces array type into pointer type for use as
79 # a formal argument type.
80 #
82 is_pyobject = 0
83 is_unspecified = 0
84 is_extension_type = 0
85 is_builtin_type = 0
86 is_numeric = 0
87 is_int = 0
88 is_float = 0
89 is_complex = 0
90 is_void = 0
91 is_array = 0
92 is_ptr = 0
93 is_null_ptr = 0
94 is_cfunction = 0
95 is_struct_or_union = 0
96 is_struct = 0
97 is_enum = 0
98 is_typedef = 0
99 is_string = 0
100 is_unicode = 0
101 is_returncode = 0
102 is_error = 0
103 is_buffer = 0
104 has_attributes = 0
105 default_value = ""
106 pymemberdef_typecode = None
108 def resolve(self):
109 # If a typedef, returns the base type.
110 return self
112 def literal_code(self, value):
113 # Returns a C code fragment representing a literal
114 # value of this type.
115 return str(value)
117 def __str__(self):
118 return self.declaration_code("", for_display = 1).strip()
120 def same_as(self, other_type, **kwds):
121 return self.same_as_resolved_type(other_type.resolve(), **kwds)
123 def same_as_resolved_type(self, other_type):
124 return self == other_type or other_type is error_type
126 def subtype_of(self, other_type):
127 return self.subtype_of_resolved_type(other_type.resolve())
129 def subtype_of_resolved_type(self, other_type):
130 return self.same_as(other_type)
132 def assignable_from(self, src_type):
133 return self.assignable_from_resolved_type(src_type.resolve())
135 def assignable_from_resolved_type(self, src_type):
136 return self.same_as(src_type)
138 def as_argument_type(self):
139 return self
141 def is_complete(self):
142 # A type is incomplete if it is an unsized array,
143 # a struct whose attributes are not defined, etc.
144 return 1
146 def is_simple_buffer_dtype(self):
147 return (self.is_int or self.is_float or self.is_complex or self.is_pyobject or
148 self.is_extension_type or self.is_ptr)
150 def struct_nesting_depth(self):
151 # Returns the number levels of nested structs. This is
152 # used for constructing a stack for walking the run-time
153 # type information of the struct.
154 return 1
157 def create_typedef_type(cname, base_type, is_external=0):
158 if base_type.is_complex:
159 if is_external:
160 raise ValueError("Complex external typedefs not supported")
161 return base_type
162 else:
163 return CTypedefType(cname, base_type, is_external)
165 class CTypedefType(BaseType):
166 #
167 # Pseudo-type defined with a ctypedef statement in a
168 # 'cdef extern from' block. Delegates most attribute
169 # lookups to the base type. ANYTHING NOT DEFINED
170 # HERE IS DELEGATED!
171 #
172 # qualified_name string
173 # typedef_cname string
174 # typedef_base_type PyrexType
175 # typedef_is_external bool
177 is_typedef = 1
178 typedef_is_external = 0
180 to_py_utility_code = None
181 from_py_utility_code = None
184 def __init__(self, cname, base_type, is_external=0):
185 assert not base_type.is_complex
186 self.typedef_cname = cname
187 self.typedef_base_type = base_type
188 self.typedef_is_external = is_external
189 # Make typecodes in external typedefs use typesize-neutral macros
190 if is_external:
191 typecode = None
192 if base_type.is_int:
193 if base_type.signed == 0:
194 typecode = "__Pyx_T_UNSIGNED_INT"
195 else:
196 typecode = "__Pyx_T_SIGNED_INT"
197 elif base_type.is_float and not rank_to_type_name[base_type.rank] == "long double":
198 typecode = "__Pyx_T_FLOATING"
199 if typecode:
200 self.pymemberdef_typecode = "%s(%s)" % (typecode, cname)
202 def resolve(self):
203 return self.typedef_base_type.resolve()
205 def declaration_code(self, entity_code,
206 for_display = 0, dll_linkage = None, pyrex = 0):
207 name = self.declaration_name(for_display, pyrex)
208 if pyrex or for_display:
209 base_code = name
210 else:
211 base_code = public_decl(name, dll_linkage)
212 return self.base_declaration_code(base_code, entity_code)
214 def declaration_name(self, for_display = 0, pyrex = 0):
215 if pyrex or for_display:
216 return self.qualified_name
217 else:
218 return self.typedef_cname
220 def as_argument_type(self):
221 return self
223 def cast_code(self, expr_code):
224 # If self is really an array (rather than pointer), we can't cast.
225 # For example, the gmp mpz_t.
226 if self.typedef_base_type.is_ptr:
227 return self.typedef_base_type.cast_code(expr_code)
228 else:
229 return BaseType.cast_code(self, expr_code)
231 def __repr__(self):
232 return "<CTypedefType %s>" % self.typedef_cname
234 def __str__(self):
235 return self.declaration_name(for_display = 1)
237 def _create_utility_code(self, template_utility_code,
238 template_function_name):
239 type_name = self.typedef_cname.replace(" ","_")
240 utility_code = template_utility_code.specialize(
241 type = self.typedef_cname,
242 TypeName = type_name)
243 function_name = template_function_name % type_name
244 return utility_code, function_name
246 def create_to_py_utility_code(self, env):
247 if self.typedef_is_external:
248 if not self.to_py_utility_code:
249 base_type = self.typedef_base_type
250 if base_type.is_int:
251 self.to_py_utility_code, self.to_py_function = \
252 self._create_utility_code(c_typedef_int_to_py_function,
253 '__Pyx_PyInt_to_py_%s')
254 elif base_type.is_float:
255 pass # XXX implement!
256 elif base_type.is_complex:
257 pass # XXX implement!
258 pass
259 if self.to_py_utility_code:
260 env.use_utility_code(self.to_py_utility_code)
261 return True
262 # delegation
263 return self.typedef_base_type.create_to_py_utility_code(env)
265 def create_from_py_utility_code(self, env):
266 if self.typedef_is_external:
267 if not self.from_py_utility_code:
268 base_type = self.typedef_base_type
269 if base_type.is_int:
270 self.from_py_utility_code, self.from_py_function = \
271 self._create_utility_code(c_typedef_int_from_py_function,
272 '__Pyx_PyInt_from_py_%s')
273 elif base_type.is_float:
274 pass # XXX implement!
275 elif base_type.is_complex:
276 pass # XXX implement!
277 if self.from_py_utility_code:
278 env.use_utility_code(self.from_py_utility_code)
279 return True
280 # delegation
281 return self.typedef_base_type.create_from_py_utility_code(env)
283 def error_condition(self, result_code):
284 if self.typedef_is_external:
285 if self.exception_value:
286 condition = "(%s == (%s)%s)" % (
287 result_code, self.typedef_cname, self.exception_value)
288 if self.exception_check:
289 condition += " && PyErr_Occurred()"
290 return condition
291 # delegation
292 return self.typedef_base_type.error_condition(result_code)
294 def __getattr__(self, name):
295 return getattr(self.typedef_base_type, name)
297 class BufferType(BaseType):
298 #
299 # Delegates most attribute
300 # lookups to the base type. ANYTHING NOT DEFINED
301 # HERE IS DELEGATED!
303 # dtype PyrexType
304 # ndim int
305 # mode str
306 # negative_indices bool
307 # cast bool
308 # is_buffer bool
309 # writable bool
311 is_buffer = 1
312 writable = True
313 def __init__(self, base, dtype, ndim, mode, negative_indices, cast):
314 self.base = base
315 self.dtype = dtype
316 self.ndim = ndim
317 self.buffer_ptr_type = CPtrType(dtype)
318 self.mode = mode
319 self.negative_indices = negative_indices
320 self.cast = cast
322 def as_argument_type(self):
323 return self
325 def __getattr__(self, name):
326 return getattr(self.base, name)
328 def __repr__(self):
329 return "<BufferType %r>" % self.base
331 def public_decl(base, dll_linkage):
332 if dll_linkage:
333 return "%s(%s)" % (dll_linkage, base)
334 else:
335 return base
337 class PyObjectType(PyrexType):
338 #
339 # Base class for all Python object types (reference-counted).
340 #
341 # buffer_defaults dict or None Default options for bu
343 name = "object"
344 is_pyobject = 1
345 default_value = "0"
346 pymemberdef_typecode = "T_OBJECT"
347 buffer_defaults = None
348 is_extern = False
349 is_subclassed = False
351 def __str__(self):
352 return "Python object"
354 def __repr__(self):
355 return "<PyObjectType>"
357 def can_coerce_to_pyobject(self, env):
358 return True
360 def assignable_from(self, src_type):
361 # except for pointers, conversion will be attempted
362 return not src_type.is_ptr or src_type.is_string
364 def declaration_code(self, entity_code,
365 for_display = 0, dll_linkage = None, pyrex = 0):
366 if pyrex or for_display:
367 return self.base_declaration_code("object", entity_code)
368 else:
369 return "%s *%s" % (public_decl("PyObject", dll_linkage), entity_code)
371 def as_pyobject(self, cname):
372 if (not self.is_complete()) or self.is_extension_type:
373 return "(PyObject *)" + cname
374 else:
375 return cname
377 class BuiltinObjectType(PyObjectType):
379 is_builtin_type = 1
380 has_attributes = 1
381 base_type = None
382 module_name = '__builtin__'
384 alternative_name = None # used for str/bytes duality
386 def __init__(self, name, cname):
387 self.name = name
388 if name == 'str':
389 self.alternative_name = 'bytes'
390 elif name == 'bytes':
391 self.alternative_name = 'str'
392 self.cname = cname
393 self.typeptr_cname = "&" + cname
395 def set_scope(self, scope):
396 self.scope = scope
397 if scope:
398 scope.parent_type = self
400 def __str__(self):
401 return "%s object" % self.name
403 def __repr__(self):
404 return "<%s>"% self.cname
406 def assignable_from(self, src_type):
407 if isinstance(src_type, BuiltinObjectType):
408 return src_type.name == self.name or (
409 src_type.name == self.alternative_name and
410 src_type.name is not None)
411 elif src_type.is_extension_type:
412 return (src_type.module_name == '__builtin__' and
413 src_type.name == self.name)
414 else:
415 return True
417 def typeobj_is_available(self):
418 return True
420 def attributes_known(self):
421 return True
423 def subtype_of(self, type):
424 return type.is_pyobject and self.assignable_from(type)
426 def type_test_code(self, arg, notnone=False):
427 type_name = self.name
428 if type_name == 'str':
429 type_check = 'PyString_CheckExact'
430 elif type_name == 'set':
431 type_check = 'PyAnySet_CheckExact'
432 elif type_name == 'frozenset':
433 type_check = 'PyFrozenSet_CheckExact'
434 elif type_name == 'bool':
435 type_check = 'PyBool_Check'
436 else:
437 type_check = 'Py%s_CheckExact' % type_name.capitalize()
439 check = 'likely(%s(%s))' % (type_check, arg)
440 if not notnone:
441 check = check + ('||((%s) == Py_None)' % arg)
442 error = '(PyErr_Format(PyExc_TypeError, "Expected %s, got %%.200s", Py_TYPE(%s)->tp_name), 0)' % (self.name, arg)
443 return check + '||' + error
445 def declaration_code(self, entity_code,
446 for_display = 0, dll_linkage = None, pyrex = 0):
447 if pyrex or for_display:
448 return self.base_declaration_code(self.name, entity_code)
449 else:
450 return "%s *%s" % (public_decl("PyObject", dll_linkage), entity_code)
453 class PyExtensionType(PyObjectType):
454 #
455 # A Python extension type.
456 #
457 # name string
458 # scope CClassScope Attribute namespace
459 # visibility string
460 # typedef_flag boolean
461 # base_type PyExtensionType or None
462 # module_name string or None Qualified name of defining module
463 # objstruct_cname string Name of PyObject struct
464 # objtypedef_cname string Name of PyObject struct typedef
465 # typeobj_cname string or None C code fragment referring to type object
466 # typeptr_cname string or None Name of pointer to external type object
467 # vtabslot_cname string Name of C method table member
468 # vtabstruct_cname string Name of C method table struct
469 # vtabptr_cname string Name of pointer to C method table
470 # vtable_cname string Name of C method table definition
472 is_extension_type = 1
473 has_attributes = 1
475 objtypedef_cname = None
477 def __init__(self, name, typedef_flag, base_type, is_external=0):
478 self.name = name
479 self.scope = None
480 self.typedef_flag = typedef_flag
481 if base_type is not None:
482 base_type.is_subclassed = True
483 self.base_type = base_type
484 self.module_name = None
485 self.objstruct_cname = None
486 self.typeobj_cname = None
487 self.typeptr_cname = None
488 self.vtabslot_cname = None
489 self.vtabstruct_cname = None
490 self.vtabptr_cname = None
491 self.vtable_cname = None
492 self.is_external = is_external
494 def set_scope(self, scope):
495 self.scope = scope
496 if scope:
497 scope.parent_type = self
499 def subtype_of_resolved_type(self, other_type):
500 if other_type.is_extension_type:
501 return self is other_type or (
502 self.base_type and self.base_type.subtype_of(other_type))
503 else:
504 return other_type is py_object_type
506 def typeobj_is_available(self):
507 # Do we have a pointer to the type object?
508 return self.typeptr_cname
510 def typeobj_is_imported(self):
511 # If we don't know the C name of the type object but we do
512 # know which module it's defined in, it will be imported.
513 return self.typeobj_cname is None and self.module_name is not None
515 def declaration_code(self, entity_code,
516 for_display = 0, dll_linkage = None, pyrex = 0, deref = 0):
517 if pyrex or for_display:
518 return self.base_declaration_code(self.name, entity_code)
519 else:
520 if self.typedef_flag:
521 base_format = "%s"
522 else:
523 base_format = "struct %s"
524 base = public_decl(base_format % self.objstruct_cname, dll_linkage)
525 if deref:
526 return "%s %s" % (base, entity_code)
527 else:
528 return "%s *%s" % (base, entity_code)
530 def type_test_code(self, py_arg, notnone=False):
532 none_check = "((%s) == Py_None)" % py_arg
533 type_check = "likely(__Pyx_TypeTest(%s, %s))" % (
534 py_arg, self.typeptr_cname)
535 if notnone:
536 return type_check
537 else:
538 return "likely(%s || %s)" % (none_check, type_check)
540 def attributes_known(self):
541 return self.scope is not None
543 def __str__(self):
544 return self.name
546 def __repr__(self):
547 return "<PyExtensionType %s%s>" % (self.scope.class_name,
548 ("", " typedef")[self.typedef_flag])
551 class CType(PyrexType):
552 #
553 # Base class for all C types (non-reference-counted).
554 #
555 # to_py_function string C function for converting to Python object
556 # from_py_function string C function for constructing from Python object
557 #
559 to_py_function = None
560 from_py_function = None
561 exception_value = None
562 exception_check = 1
564 def create_to_py_utility_code(self, env):
565 return self.to_py_function is not None
567 def create_from_py_utility_code(self, env):
568 return self.from_py_function is not None
570 def can_coerce_to_pyobject(self, env):
571 return self.create_to_py_utility_code(env)
573 def error_condition(self, result_code):
574 conds = []
575 if self.is_string:
576 conds.append("(!%s)" % result_code)
577 elif self.exception_value is not None:
578 conds.append("(%s == (%s)%s)" % (result_code, self.sign_and_name(), self.exception_value))
579 if self.exception_check:
580 conds.append("PyErr_Occurred()")
581 if len(conds) > 0:
582 return " && ".join(conds)
583 else:
584 return 0
587 class CVoidType(CType):
588 is_void = 1
590 def __repr__(self):
591 return "<CVoidType>"
593 def declaration_code(self, entity_code,
594 for_display = 0, dll_linkage = None, pyrex = 0):
595 base = public_decl("void", dll_linkage)
596 return self.base_declaration_code(base, entity_code)
598 def is_complete(self):
599 return 0
602 class CNumericType(CType):
603 #
604 # Base class for all C numeric types.
605 #
606 # rank integer Relative size
607 # signed integer 0 = unsigned, 1 = unspecified, 2 = explicitly signed
608 #
610 is_numeric = 1
611 default_value = "0"
613 sign_words = ("unsigned ", "", "signed ")
615 def __init__(self, rank, signed = 1, pymemberdef_typecode = None):
616 self.rank = rank
617 self.signed = signed
618 self.pymemberdef_typecode = pymemberdef_typecode
620 def sign_and_name(self):
621 s = self.sign_words[self.signed]
622 n = rank_to_type_name[self.rank]
623 return s + n
625 def __repr__(self):
626 return "<CNumericType %s>" % self.sign_and_name()
628 def declaration_code(self, entity_code,
629 for_display = 0, dll_linkage = None, pyrex = 0):
630 base = public_decl(self.sign_and_name(), dll_linkage)
631 if for_display:
632 base = base.replace('PY_LONG_LONG', 'long long')
633 return self.base_declaration_code(base, entity_code)
636 type_conversion_predeclarations = ""
637 type_conversion_functions = ""
639 c_int_from_py_function = UtilityCode(
640 proto="""
641 static INLINE %(type)s __Pyx_PyInt_As%(SignWord)s%(TypeName)s(PyObject *);
642 """,
643 impl="""
644 static INLINE %(type)s __Pyx_PyInt_As%(SignWord)s%(TypeName)s(PyObject* x) {
645 const %(type)s neg_one = (%(type)s)-1, const_zero = 0;
646 const int is_unsigned = neg_one > const_zero;
647 if (sizeof(%(type)s) < sizeof(long)) {
648 long val = __Pyx_PyInt_AsLong(x);
649 if (unlikely(val != (long)(%(type)s)val)) {
650 if (!unlikely(val == -1 && PyErr_Occurred())) {
651 PyErr_SetString(PyExc_OverflowError,
652 (is_unsigned && unlikely(val < 0)) ?
653 "can't convert negative value to %(type)s" :
654 "value too large to convert to %(type)s");
655 }
656 return (%(type)s)-1;
657 }
658 return (%(type)s)val;
659 }
660 return (%(type)s)__Pyx_PyInt_As%(SignWord)sLong(x);
661 }
662 """) #fool emacs: '
664 c_long_from_py_function = UtilityCode(
665 proto="""
666 static INLINE %(type)s __Pyx_PyInt_As%(SignWord)s%(TypeName)s(PyObject *);
667 """,
668 impl="""
669 static INLINE %(type)s __Pyx_PyInt_As%(SignWord)s%(TypeName)s(PyObject* x) {
670 const %(type)s neg_one = (%(type)s)-1, const_zero = 0;
671 const int is_unsigned = neg_one > const_zero;
672 #if PY_VERSION_HEX < 0x03000000
673 if (likely(PyInt_Check(x))) {
674 long val = PyInt_AS_LONG(x);
675 if (is_unsigned && unlikely(val < 0)) {
676 PyErr_SetString(PyExc_OverflowError,
677 "can't convert negative value to %(type)s");
678 return (%(type)s)-1;
679 }
680 return (%(type)s)val;
681 } else
682 #endif
683 if (likely(PyLong_Check(x))) {
684 if (is_unsigned) {
685 if (unlikely(Py_SIZE(x) < 0)) {
686 PyErr_SetString(PyExc_OverflowError,
687 "can't convert negative value to %(type)s");
688 return (%(type)s)-1;
689 }
690 return PyLong_AsUnsigned%(TypeName)s(x);
691 } else {
692 return PyLong_As%(TypeName)s(x);
693 }
694 } else {
695 %(type)s val;
696 PyObject *tmp = __Pyx_PyNumber_Int(x);
697 if (!tmp) return (%(type)s)-1;
698 val = __Pyx_PyInt_As%(SignWord)s%(TypeName)s(tmp);
699 Py_DECREF(tmp);
700 return val;
701 }
702 }
703 """)
705 c_typedef_int_from_py_function = UtilityCode(
706 proto="""
707 static INLINE %(type)s __Pyx_PyInt_from_py_%(TypeName)s(PyObject *);
708 """,
709 impl="""
710 static INLINE %(type)s __Pyx_PyInt_from_py_%(TypeName)s(PyObject* x) {
711 const %(type)s neg_one = (%(type)s)-1, const_zero = 0;
712 const int is_unsigned = neg_one > const_zero;
713 if (sizeof(%(type)s) == sizeof(char)) {
714 if (is_unsigned)
715 return (%(type)s)__Pyx_PyInt_AsUnsignedChar(x);
716 else
717 return (%(type)s)__Pyx_PyInt_AsSignedChar(x);
718 } else if (sizeof(%(type)s) == sizeof(short)) {
719 if (is_unsigned)
720 return (%(type)s)__Pyx_PyInt_AsUnsignedShort(x);
721 else
722 return (%(type)s)__Pyx_PyInt_AsSignedShort(x);
723 } else if (sizeof(%(type)s) == sizeof(int)) {
724 if (is_unsigned)
725 return (%(type)s)__Pyx_PyInt_AsUnsignedInt(x);
726 else
727 return (%(type)s)__Pyx_PyInt_AsSignedInt(x);
728 } else if (sizeof(%(type)s) == sizeof(long)) {
729 if (is_unsigned)
730 return (%(type)s)__Pyx_PyInt_AsUnsignedLong(x);
731 else
732 return (%(type)s)__Pyx_PyInt_AsSignedLong(x);
733 } else if (sizeof(%(type)s) == sizeof(PY_LONG_LONG)) {
734 if (is_unsigned)
735 return (%(type)s)__Pyx_PyInt_AsUnsignedLongLong(x);
736 else
737 return (%(type)s)__Pyx_PyInt_AsSignedLongLong(x);
738 #if 0
739 } else if (sizeof(%(type)s) > sizeof(short) &&
740 sizeof(%(type)s) < sizeof(int)) { /* __int32 ILP64 ? */
741 if (is_unsigned)
742 return (%(type)s)__Pyx_PyInt_AsUnsignedInt(x);
743 else
744 return (%(type)s)__Pyx_PyInt_AsSignedInt(x);
745 #endif
746 }
747 PyErr_SetString(PyExc_TypeError, "%(TypeName)s");
748 return (%(type)s)-1;
749 }
750 """)
752 c_typedef_int_to_py_function = UtilityCode(
753 proto="""
754 static INLINE PyObject *__Pyx_PyInt_to_py_%(TypeName)s(%(type)s);
755 """,
756 impl="""
757 static INLINE PyObject *__Pyx_PyInt_to_py_%(TypeName)s(%(type)s val) {
758 const %(type)s neg_one = (%(type)s)-1, const_zero = 0;
759 const int is_unsigned = neg_one > const_zero;
760 if (sizeof(%(type)s) < sizeof(long)) {
761 return PyInt_FromLong((long)val);
762 } else if (sizeof(%(type)s) == sizeof(long)) {
763 if (is_unsigned)
764 return PyLong_FromUnsignedLong((unsigned long)val);
765 else
766 return PyInt_FromLong((long)val);
767 } else { /* (sizeof(%(type)s) > sizeof(long)) */
768 if (is_unsigned)
769 return PyLong_FromUnsignedLongLong((unsigned PY_LONG_LONG)val);
770 else
771 return PyLong_FromLongLong((PY_LONG_LONG)val);
772 }
773 }
774 """)
776 class CIntType(CNumericType):
778 is_int = 1
779 typedef_flag = 0
780 to_py_function = "PyInt_FromLong"
781 from_py_function = "__Pyx_PyInt_AsInt"
782 exception_value = -1
784 def __init__(self, rank, signed, pymemberdef_typecode = None, is_returncode = 0):
785 CNumericType.__init__(self, rank, signed, pymemberdef_typecode)
786 self.is_returncode = is_returncode
787 if self.from_py_function == "__Pyx_PyInt_AsInt":
788 self.from_py_function = self.get_type_conversion()
790 def get_type_conversion(self):
791 ctype = self.declaration_code('')
792 bits = ctype.split(" ", 1)
793 if len(bits) == 1:
794 sign_word, type_name = "", bits[0]
795 else:
796 sign_word, type_name = bits
797 type_name = type_name.replace("PY_LONG_LONG","long long")
798 SignWord = sign_word.title()
799 TypeName = type_name.title().replace(" ", "")
800 if "Long" in TypeName:
801 utility_code = c_long_from_py_function
802 else:
803 utility_code = c_int_from_py_function
804 utility_code.specialize(self,
805 SignWord=SignWord,
806 TypeName=TypeName)
807 func_name = "__Pyx_PyInt_As%s%s" % (SignWord, TypeName)
808 return func_name
810 def assignable_from_resolved_type(self, src_type):
811 return src_type.is_int or src_type.is_enum or src_type is error_type
814 class CBIntType(CIntType):
816 to_py_function = "__Pyx_PyBool_FromLong"
817 from_py_function = "__Pyx_PyObject_IsTrue"
818 exception_check = 0
820 def __repr__(self):
821 return "<CNumericType bint>"
824 class CAnonEnumType(CIntType):
826 is_enum = 1
828 def sign_and_name(self):
829 return 'int'
832 class CUIntType(CIntType):
834 to_py_function = "PyLong_FromUnsignedLong"
835 exception_value = -1
838 class CLongType(CIntType):
840 to_py_function = "PyInt_FromLong"
843 class CULongType(CUIntType):
845 to_py_function = "PyLong_FromUnsignedLong"
848 class CLongLongType(CIntType):
850 to_py_function = "PyLong_FromLongLong"
853 class CULongLongType(CUIntType):
855 to_py_function = "PyLong_FromUnsignedLongLong"
858 class CPySSizeTType(CIntType):
860 to_py_function = "PyInt_FromSsize_t"
861 from_py_function = "__Pyx_PyIndex_AsSsize_t"
863 def sign_and_name(self):
864 return rank_to_type_name[self.rank]
867 class CSizeTType(CUIntType):
869 to_py_function = "__Pyx_PyInt_FromSize_t"
870 from_py_function = "__Pyx_PyInt_AsSize_t"
872 def sign_and_name(self):
873 return rank_to_type_name[self.rank]
876 class CFloatType(CNumericType):
878 is_float = 1
879 to_py_function = "PyFloat_FromDouble"
880 from_py_function = "__pyx_PyFloat_AsDouble"
882 exception_value = -1
884 def __init__(self, rank, pymemberdef_typecode = None, math_h_modifier = ''):
885 CNumericType.__init__(self, rank, 1, pymemberdef_typecode)
886 self.math_h_modifier = math_h_modifier
888 def assignable_from_resolved_type(self, src_type):
889 return (src_type.is_numeric and not src_type.is_complex) or src_type is error_type
892 class CComplexType(CNumericType):
894 is_complex = 1
895 to_py_function = "__pyx_PyComplex_FromComplex"
896 has_attributes = 1
897 scope = None
899 def __init__(self, real_type):
900 while real_type.is_typedef and not real_type.typedef_is_external:
901 real_type = real_type.typedef_base_type
902 if real_type.is_typedef and real_type.typedef_is_external:
903 # The below is not actually used: Coercions are currently disabled
904 # so that complex types of external types can not be created
905 self.funcsuffix = "_%s" % real_type.specalization_name()
906 elif hasattr(real_type, 'math_h_modifier'):
907 self.funcsuffix = real_type.math_h_modifier
908 else:
909 self.funcsuffix = "_%s" % real_type.specalization_name()
911 self.real_type = real_type
912 CNumericType.__init__(self, real_type.rank + 0.5, real_type.signed)
913 self.binops = {}
914 self.from_parts = "%s_from_parts" % self.specalization_name()
915 self.default_value = "%s(0, 0)" % self.from_parts
917 def __eq__(self, other):
918 if isinstance(self, CComplexType) and isinstance(other, CComplexType):
919 return self.real_type == other.real_type
920 else:
921 return False
923 def __ne__(self, other):
924 if isinstance(self, CComplexType) and isinstance(other, CComplexType):
925 return self.real_type != other.real_type
926 else:
927 return True
929 def __lt__(self, other):
930 if isinstance(self, CComplexType) and isinstance(other, CComplexType):
931 return self.real_type < other.real_type
932 else:
933 # this is arbitrary, but it makes sure we always have
934 # *some* kind of order
935 return False
937 def __hash__(self):
938 return ~hash(self.real_type)
940 def declaration_code(self, entity_code,
941 for_display = 0, dll_linkage = None, pyrex = 0):
942 if for_display:
943 base = public_decl(self.real_type.sign_and_name() + " complex", dll_linkage)
944 else:
945 base = public_decl(self.sign_and_name(), dll_linkage)
946 return self.base_declaration_code(base, entity_code)
948 def sign_and_name(self):
949 real_type_name = self.real_type.specalization_name()
950 real_type_name = real_type_name.replace('long__double','long_double')
951 return Naming.type_prefix + real_type_name + "_complex"
953 def assignable_from(self, src_type):
954 # Temporary hack/feature disabling, see #441
955 if (not src_type.is_complex and src_type.is_numeric and src_type.is_typedef
956 and src_type.typedef_is_external):
957 return False
958 else:
959 return super(CComplexType, self).assignable_from(src_type)
961 def assignable_from_resolved_type(self, src_type):
962 return (src_type.is_complex and self.real_type.assignable_from_resolved_type(src_type.real_type)
963 or src_type.is_numeric and self.real_type.assignable_from_resolved_type(src_type)
964 or src_type is error_type)
966 def attributes_known(self):
967 if self.scope is None:
968 import Symtab
969 self.scope = scope = Symtab.CClassScope(
970 '',
971 None,
972 visibility="extern")
973 scope.parent_type = self
974 scope.declare_var("real", self.real_type, None, "real", is_cdef=True)
975 scope.declare_var("imag", self.real_type, None, "imag", is_cdef=True)
976 entry = scope.declare_cfunction(
977 "conjugate",
978 CFuncType(self, [CFuncTypeArg("self", self, None)]),
979 pos=None,
980 defining=1,
981 cname="__Pyx_c_conj%s" % self.funcsuffix)
983 return True
985 def create_declaration_utility_code(self, env):
986 # This must always be run, because a single CComplexType instance can be shared
987 # across multiple compilations (the one created in the module scope)
988 env.use_utility_code(complex_header_utility_code)
989 env.use_utility_code(complex_real_imag_utility_code)
990 for utility_code in (complex_type_utility_code,
991 complex_from_parts_utility_code,
992 complex_arithmatic_utility_code):
993 env.use_utility_code(
994 utility_code.specialize(
995 self,
996 real_type = self.real_type.declaration_code(''),
997 m = self.funcsuffix))
998 return True
1000 def create_to_py_utility_code(self, env):
1001 env.use_utility_code(complex_real_imag_utility_code)
1002 env.use_utility_code(complex_to_py_utility_code)
1003 return True
1005 def create_from_py_utility_code(self, env):
1006 self.real_type.create_from_py_utility_code(env)
1008 for utility_code in (complex_from_parts_utility_code,
1009 complex_from_py_utility_code):
1010 env.use_utility_code(
1011 utility_code.specialize(
1012 self,
1013 real_type = self.real_type.declaration_code(''),
1014 m = self.funcsuffix))
1015 self.from_py_function = "__Pyx_PyComplex_As_" + self.specalization_name()
1016 return True
1018 def lookup_op(self, nargs, op):
1019 try:
1020 return self.binops[nargs, op]
1021 except KeyError:
1022 pass
1023 try:
1024 op_name = complex_ops[nargs, op]
1025 self.binops[nargs, op] = func_name = "__Pyx_c_%s%s" % (op_name, self.funcsuffix)
1026 return func_name
1027 except KeyError:
1028 return None
1030 def unary_op(self, op):
1031 return self.lookup_op(1, op)
1033 def binary_op(self, op):
1034 return self.lookup_op(2, op)
1036 complex_ops = {
1037 (1, '-'): 'neg',
1038 (1, 'zero'): 'is_zero',
1039 (2, '+'): 'sum',
1040 (2, '-'): 'diff',
1041 (2, '*'): 'prod',
1042 (2, '/'): 'quot',
1043 (2, '=='): 'eq',
1044 }
1046 complex_header_utility_code = UtilityCode(
1047 proto_block='h_code',
1048 proto="""
1049 #if !defined(CYTHON_CCOMPLEX)
1050 #if defined(__cplusplus)
1051 #define CYTHON_CCOMPLEX 1
1052 #elif defined(_Complex_I)
1053 #define CYTHON_CCOMPLEX 1
1054 #else
1055 #define CYTHON_CCOMPLEX 0
1056 #endif
1057 #endif
1059 #if CYTHON_CCOMPLEX
1060 #ifdef __cplusplus
1061 #include <complex>
1062 #else
1063 #include <complex.h>
1064 #endif
1065 #endif
1066 """)
1068 complex_real_imag_utility_code = UtilityCode(
1069 proto="""
1070 #if CYTHON_CCOMPLEX
1071 #ifdef __cplusplus
1072 #define __Pyx_CREAL(z) ((z).real())
1073 #define __Pyx_CIMAG(z) ((z).imag())
1074 #else
1075 #define __Pyx_CREAL(z) (__real__(z))
1076 #define __Pyx_CIMAG(z) (__imag__(z))
1077 #endif
1078 #else
1079 #define __Pyx_CREAL(z) ((z).real)
1080 #define __Pyx_CIMAG(z) ((z).imag)
1081 #endif
1083 #if defined(_WIN32) && defined(__cplusplus) && CYTHON_CCOMPLEX
1084 #define __Pyx_SET_CREAL(z,x) ((z).real(x))
1085 #define __Pyx_SET_CIMAG(z,y) ((z).imag(y))
1086 #else
1087 #define __Pyx_SET_CREAL(z,x) __Pyx_CREAL(z) = (x)
1088 #define __Pyx_SET_CIMAG(z,y) __Pyx_CIMAG(z) = (y)
1089 #endif
1090 """)
1092 complex_type_utility_code = UtilityCode(
1093 proto_block='complex_type_declarations',
1094 proto="""
1095 #if CYTHON_CCOMPLEX
1096 #ifdef __cplusplus
1097 typedef ::std::complex< %(real_type)s > %(type_name)s;
1098 #else
1099 typedef %(real_type)s _Complex %(type_name)s;
1100 #endif
1101 #else
1102 typedef struct { %(real_type)s real, imag; } %(type_name)s;
1103 #endif
1104 """)
1106 complex_from_parts_utility_code = UtilityCode(
1107 proto_block='utility_code_proto',
1108 proto="""
1109 #if CYTHON_CCOMPLEX
1110 #ifdef __cplusplus
1111 static INLINE %(type)s %(type_name)s_from_parts(%(real_type)s, %(real_type)s);
1112 #else
1113 static INLINE %(type)s %(type_name)s_from_parts(%(real_type)s, %(real_type)s);
1114 #endif
1115 #else
1116 static INLINE %(type)s %(type_name)s_from_parts(%(real_type)s, %(real_type)s);
1117 #endif
1118 """,
1119 impl="""
1120 #if CYTHON_CCOMPLEX
1121 #ifdef __cplusplus
1122 static INLINE %(type)s %(type_name)s_from_parts(%(real_type)s x, %(real_type)s y) {
1123 return ::std::complex< %(real_type)s >(x, y);
1124 }
1125 #else
1126 static INLINE %(type)s %(type_name)s_from_parts(%(real_type)s x, %(real_type)s y) {
1127 return x + y*(%(type)s)_Complex_I;
1128 }
1129 #endif
1130 #else
1131 static INLINE %(type)s %(type_name)s_from_parts(%(real_type)s x, %(real_type)s y) {
1132 %(type)s z;
1133 z.real = x;
1134 z.imag = y;
1135 return z;
1136 }
1137 #endif
1138 """)
1140 complex_to_py_utility_code = UtilityCode(
1141 proto="""
1142 #define __pyx_PyComplex_FromComplex(z) \\
1143 PyComplex_FromDoubles((double)__Pyx_CREAL(z), \\
1144 (double)__Pyx_CIMAG(z))
1145 """)
1147 complex_from_py_utility_code = UtilityCode(
1148 proto="""
1149 static %(type)s __Pyx_PyComplex_As_%(type_name)s(PyObject*);
1150 """,
1151 impl="""
1152 static %(type)s __Pyx_PyComplex_As_%(type_name)s(PyObject* o) {
1153 Py_complex cval;
1154 if (PyComplex_CheckExact(o))
1155 cval = ((PyComplexObject *)o)->cval;
1156 else
1157 cval = PyComplex_AsCComplex(o);
1158 return %(type_name)s_from_parts(
1159 (%(real_type)s)cval.real,
1160 (%(real_type)s)cval.imag);
1161 }
1162 """)
1164 complex_arithmatic_utility_code = UtilityCode(
1165 proto="""
1166 #if CYTHON_CCOMPLEX
1167 #define __Pyx_c_eq%(m)s(a, b) ((a)==(b))
1168 #define __Pyx_c_sum%(m)s(a, b) ((a)+(b))
1169 #define __Pyx_c_diff%(m)s(a, b) ((a)-(b))
1170 #define __Pyx_c_prod%(m)s(a, b) ((a)*(b))
1171 #define __Pyx_c_quot%(m)s(a, b) ((a)/(b))
1172 #define __Pyx_c_neg%(m)s(a) (-(a))
1173 #ifdef __cplusplus
1174 #define __Pyx_c_is_zero%(m)s(z) ((z)==(%(real_type)s)0)
1175 #define __Pyx_c_conj%(m)s(z) (::std::conj(z))
1176 /*#define __Pyx_c_abs%(m)s(z) (::std::abs(z))*/
1177 #else
1178 #define __Pyx_c_is_zero%(m)s(z) ((z)==0)
1179 #define __Pyx_c_conj%(m)s(z) (conj%(m)s(z))
1180 /*#define __Pyx_c_abs%(m)s(z) (cabs%(m)s(z))*/
1181 #endif
1182 #else
1183 static INLINE int __Pyx_c_eq%(m)s(%(type)s, %(type)s);
1184 static INLINE %(type)s __Pyx_c_sum%(m)s(%(type)s, %(type)s);
1185 static INLINE %(type)s __Pyx_c_diff%(m)s(%(type)s, %(type)s);
1186 static INLINE %(type)s __Pyx_c_prod%(m)s(%(type)s, %(type)s);
1187 static INLINE %(type)s __Pyx_c_quot%(m)s(%(type)s, %(type)s);
1188 static INLINE %(type)s __Pyx_c_neg%(m)s(%(type)s);
1189 static INLINE int __Pyx_c_is_zero%(m)s(%(type)s);
1190 static INLINE %(type)s __Pyx_c_conj%(m)s(%(type)s);
1191 /*static INLINE %(real_type)s __Pyx_c_abs%(m)s(%(type)s);*/
1192 #endif
1193 """,
1194 impl="""
1195 #if CYTHON_CCOMPLEX
1196 #else
1197 static INLINE int __Pyx_c_eq%(m)s(%(type)s a, %(type)s b) {
1198 return (a.real == b.real) && (a.imag == b.imag);
1199 }
1200 static INLINE %(type)s __Pyx_c_sum%(m)s(%(type)s a, %(type)s b) {
1201 %(type)s z;
1202 z.real = a.real + b.real;
1203 z.imag = a.imag + b.imag;
1204 return z;
1205 }
1206 static INLINE %(type)s __Pyx_c_diff%(m)s(%(type)s a, %(type)s b) {
1207 %(type)s z;
1208 z.real = a.real - b.real;
1209 z.imag = a.imag - b.imag;
1210 return z;
1211 }
1212 static INLINE %(type)s __Pyx_c_prod%(m)s(%(type)s a, %(type)s b) {
1213 %(type)s z;
1214 z.real = a.real * b.real - a.imag * b.imag;
1215 z.imag = a.real * b.imag + a.imag * b.real;
1216 return z;
1217 }
1218 static INLINE %(type)s __Pyx_c_quot%(m)s(%(type)s a, %(type)s b) {
1219 %(type)s z;
1220 %(real_type)s denom = b.real * b.real + b.imag * b.imag;
1221 z.real = (a.real * b.real + a.imag * b.imag) / denom;
1222 z.imag = (a.imag * b.real - a.real * b.imag) / denom;
1223 return z;
1224 }
1225 static INLINE %(type)s __Pyx_c_neg%(m)s(%(type)s a) {
1226 %(type)s z;
1227 z.real = -a.real;
1228 z.imag = -a.imag;
1229 return z;
1230 }
1231 static INLINE int __Pyx_c_is_zero%(m)s(%(type)s a) {
1232 return (a.real == 0) && (a.imag == 0);
1233 }
1234 static INLINE %(type)s __Pyx_c_conj%(m)s(%(type)s a) {
1235 %(type)s z;
1236 z.real = a.real;
1237 z.imag = -a.imag;
1238 return z;
1239 }
1240 /*
1241 static INLINE %(real_type)s __Pyx_c_abs%(m)s(%(type)s z) {
1242 #if HAVE_HYPOT
1243 return hypot%(m)s(z.real, z.imag);
1244 #else
1245 return sqrt%(m)s(z.real*z.real + z.imag*z.imag);
1246 #endif
1247 }
1248 */
1249 #endif
1250 """)
1252 class CArrayType(CType):
1253 # base_type CType Element type
1254 # size integer or None Number of elements
1256 is_array = 1
1258 def __init__(self, base_type, size):
1259 self.base_type = base_type
1260 self.size = size
1261 if base_type is c_char_type:
1262 self.is_string = 1
1264 def __repr__(self):
1265 return "<CArrayType %s %s>" % (self.size, repr(self.base_type))
1267 def same_as_resolved_type(self, other_type):
1268 return ((other_type.is_array and
1269 self.base_type.same_as(other_type.base_type))
1270 or other_type is error_type)
1272 def assignable_from_resolved_type(self, src_type):
1273 # Can't assign to a variable of an array type
1274 return 0
1276 def element_ptr_type(self):
1277 return c_ptr_type(self.base_type)
1279 def declaration_code(self, entity_code,
1280 for_display = 0, dll_linkage = None, pyrex = 0):
1281 if self.size is not None:
1282 dimension_code = self.size
1283 else:
1284 dimension_code = ""
1285 if entity_code.startswith("*"):
1286 entity_code = "(%s)" % entity_code
1287 return self.base_type.declaration_code(
1288 "%s[%s]" % (entity_code, dimension_code),
1289 for_display, dll_linkage, pyrex)
1291 def as_argument_type(self):
1292 return c_ptr_type(self.base_type)
1294 def is_complete(self):
1295 return self.size is not None
1298 class CPtrType(CType):
1299 # base_type CType Referenced type
1301 is_ptr = 1
1302 default_value = "0"
1304 def __init__(self, base_type):
1305 self.base_type = base_type
1307 def __repr__(self):
1308 return "<CPtrType %s>" % repr(self.base_type)
1310 def same_as_resolved_type(self, other_type):
1311 return ((other_type.is_ptr and
1312 self.base_type.same_as(other_type.base_type))
1313 or other_type is error_type)
1315 def declaration_code(self, entity_code,
1316 for_display = 0, dll_linkage = None, pyrex = 0):
1317 #print "CPtrType.declaration_code: pointer to", self.base_type ###
1318 return self.base_type.declaration_code(
1319 "*%s" % entity_code,
1320 for_display, dll_linkage, pyrex)
1322 def assignable_from_resolved_type(self, other_type):
1323 if other_type is error_type:
1324 return 1
1325 if other_type.is_null_ptr:
1326 return 1
1327 if self.base_type.is_cfunction:
1328 if other_type.is_ptr:
1329 other_type = other_type.base_type.resolve()
1330 if other_type.is_cfunction:
1331 return self.base_type.pointer_assignable_from_resolved_type(other_type)
1332 else:
1333 return 0
1334 if other_type.is_array or other_type.is_ptr:
1335 return self.base_type.is_void or self.base_type.same_as(other_type.base_type)
1336 return 0
1339 class CNullPtrType(CPtrType):
1341 is_null_ptr = 1
1344 class CFuncType(CType):
1345 # return_type CType
1346 # args [CFuncTypeArg]
1347 # has_varargs boolean
1348 # exception_value string
1349 # exception_check boolean True if PyErr_Occurred check needed
1350 # calling_convention string Function calling convention
1351 # nogil boolean Can be called without gil
1352 # with_gil boolean Acquire gil around function body
1354 is_cfunction = 1
1355 original_sig = None
1357 def __init__(self, return_type, args, has_varargs = 0,
1358 exception_value = None, exception_check = 0, calling_convention = "",
1359 nogil = 0, with_gil = 0, is_overridable = 0, optional_arg_count = 0):
1360 self.return_type = return_type
1361 self.args = args
1362 self.has_varargs = has_varargs
1363 self.optional_arg_count = optional_arg_count
1364 self.exception_value = exception_value
1365 self.exception_check = exception_check
1366 self.calling_convention = calling_convention
1367 self.nogil = nogil
1368 self.with_gil = with_gil
1369 self.is_overridable = is_overridable
1371 def __repr__(self):
1372 arg_reprs = map(repr, self.args)
1373 if self.has_varargs:
1374 arg_reprs.append("...")
1375 if self.exception_value:
1376 except_clause = " %r" % self.exception_value
1377 else:
1378 except_clause = ""
1379 if self.exception_check:
1380 except_clause += "?"
1381 return "<CFuncType %s %s[%s]%s>" % (
1382 repr(self.return_type),
1383 self.calling_convention_prefix(),
1384 ",".join(arg_reprs),
1385 except_clause)
1387 def calling_convention_prefix(self):
1388 cc = self.calling_convention
1389 if cc:
1390 return cc + " "
1391 else:
1392 return ""
1394 def same_c_signature_as(self, other_type, as_cmethod = 0):
1395 return self.same_c_signature_as_resolved_type(
1396 other_type.resolve(), as_cmethod)
1398 def same_c_signature_as_resolved_type(self, other_type, as_cmethod = 0):
1399 #print "CFuncType.same_c_signature_as_resolved_type:", \
1400 # self, other_type, "as_cmethod =", as_cmethod ###
1401 if other_type is error_type:
1402 return 1
1403 if not other_type.is_cfunction:
1404 return 0
1405 if self.is_overridable != other_type.is_overridable:
1406 return 0
1407 nargs = len(self.args)
1408 if nargs != len(other_type.args):
1409 return 0
1410 # When comparing C method signatures, the first argument
1411 # is exempt from compatibility checking (the proper check
1412 # is performed elsewhere).
1413 for i in range(as_cmethod, nargs):
1414 if not self.args[i].type.same_as(
1415 other_type.args[i].type):
1416 return 0
1417 if self.has_varargs != other_type.has_varargs:
1418 return 0
1419 if self.optional_arg_count != other_type.optional_arg_count:
1420 return 0
1421 if not self.return_type.same_as(other_type.return_type):
1422 return 0
1423 if not self.same_calling_convention_as(other_type):
1424 return 0
1425 return 1
1427 def compatible_signature_with(self, other_type, as_cmethod = 0):
1428 return self.compatible_signature_with_resolved_type(other_type.resolve(), as_cmethod)
1430 def compatible_signature_with_resolved_type(self, other_type, as_cmethod):
1431 #print "CFuncType.same_c_signature_as_resolved_type:", \
1432 # self, other_type, "as_cmethod =", as_cmethod ###
1433 if other_type is error_type:
1434 return 1
1435 if not other_type.is_cfunction:
1436 return 0
1437 if not self.is_overridable and other_type.is_overridable:
1438 return 0
1439 nargs = len(self.args)
1440 if nargs - self.optional_arg_count != len(other_type.args) - other_type.optional_arg_count:
1441 return 0
1442 if self.optional_arg_count < other_type.optional_arg_count:
1443 return 0
1444 # When comparing C method signatures, the first argument
1445 # is exempt from compatibility checking (the proper check
1446 # is performed elsewhere).
1447 for i in range(as_cmethod, len(other_type.args)):
1448 if not self.args[i].type.same_as(
1449 other_type.args[i].type):
1450 return 0
1451 if self.has_varargs != other_type.has_varargs:
1452 return 0
1453 if not self.return_type.subtype_of_resolved_type(other_type.return_type):
1454 return 0
1455 if not self.same_calling_convention_as(other_type):
1456 return 0
1457 if self.nogil != other_type.nogil:
1458 return 0
1459 self.original_sig = other_type.original_sig or other_type
1460 if as_cmethod:
1461 self.args[0] = other_type.args[0]
1462 return 1
1465 def narrower_c_signature_than(self, other_type, as_cmethod = 0):
1466 return self.narrower_c_signature_than_resolved_type(other_type.resolve(), as_cmethod)
1468 def narrower_c_signature_than_resolved_type(self, other_type, as_cmethod):
1469 if other_type is error_type:
1470 return 1
1471 if not other_type.is_cfunction:
1472 return 0
1473 nargs = len(self.args)
1474 if nargs != len(other_type.args):
1475 return 0
1476 for i in range(as_cmethod, nargs):
1477 if not self.args[i].type.subtype_of_resolved_type(other_type.args[i].type):
1478 return 0
1479 else:
1480 self.args[i].needs_type_test = other_type.args[i].needs_type_test \
1481 or not self.args[i].type.same_as(other_type.args[i].type)
1482 if self.has_varargs != other_type.has_varargs:
1483 return 0
1484 if self.optional_arg_count != other_type.optional_arg_count:
1485 return 0
1486 if not self.return_type.subtype_of_resolved_type(other_type.return_type):
1487 return 0
1488 return 1
1490 def same_calling_convention_as(self, other):
1491 ## XXX Under discussion ...
1492 ## callspec_words = ("__stdcall", "__cdecl", "__fastcall")
1493 ## cs1 = self.calling_convention
1494 ## cs2 = other.calling_convention
1495 ## if (cs1 in callspec_words or
1496 ## cs2 in callspec_words):
1497 ## return cs1 == cs2
1498 ## else:
1499 ## return True
1500 sc1 = self.calling_convention == '__stdcall'
1501 sc2 = other.calling_convention == '__stdcall'
1502 return sc1 == sc2
1504 def same_exception_signature_as(self, other_type):
1505 return self.same_exception_signature_as_resolved_type(
1506 other_type.resolve())
1508 def same_exception_signature_as_resolved_type(self, other_type):
1509 return self.exception_value == other_type.exception_value \
1510 and self.exception_check == other_type.exception_check
1512 def same_as_resolved_type(self, other_type, as_cmethod = 0):
1513 return self.same_c_signature_as_resolved_type(other_type, as_cmethod) \
1514 and self.same_exception_signature_as_resolved_type(other_type) \
1515 and self.nogil == other_type.nogil
1517 def pointer_assignable_from_resolved_type(self, other_type):
1518 return self.same_c_signature_as_resolved_type(other_type) \
1519 and self.same_exception_signature_as_resolved_type(other_type) \
1520 and not (self.nogil and not other_type.nogil)
1522 def declaration_code(self, entity_code,
1523 for_display = 0, dll_linkage = None, pyrex = 0,
1524 with_calling_convention = 1):
1525 arg_decl_list = []
1526 for arg in self.args[:len(self.args)-self.optional_arg_count]:
1527 arg_decl_list.append(
1528 arg.type.declaration_code("", for_display, pyrex = pyrex))
1529 if self.is_overridable:
1530 arg_decl_list.append("int %s" % Naming.skip_dispatch_cname)
1531 if self.optional_arg_count:
1532 arg_decl_list.append(self.op_arg_struct.declaration_code(Naming.optional_args_cname))
1533 if self.has_varargs:
1534 arg_decl_list.append("...")
1535 arg_decl_code = ", ".join(arg_decl_list)
1536 if not arg_decl_code and not pyrex:
1537 arg_decl_code = "void"
1538 trailer = ""
1539 if (pyrex or for_display) and not self.return_type.is_pyobject:
1540 if self.exception_value and self.exception_check:
1541 trailer = " except? %s" % self.exception_value
1542 elif self.exception_value:
1543 trailer = " except %s" % self.exception_value
1544 elif self.exception_check == '+':
1545 trailer = " except +"
1546 else:
1547 " except *" # ignored
1548 if self.nogil:
1549 trailer += " nogil"
1550 if not with_calling_convention:
1551 cc = ''
1552 else:
1553 cc = self.calling_convention_prefix()
1554 if (not entity_code and cc) or entity_code.startswith("*"):
1555 entity_code = "(%s%s)" % (cc, entity_code)
1556 cc = ""
1557 return self.return_type.declaration_code(
1558 "%s%s(%s)%s" % (cc, entity_code, arg_decl_code, trailer),
1559 for_display, dll_linkage, pyrex)
1561 def function_header_code(self, func_name, arg_code):
1562 return "%s%s(%s)" % (self.calling_convention_prefix(),
1563 func_name, arg_code)
1565 def signature_string(self):
1566 s = self.declaration_code("")
1567 return s
1569 def signature_cast_string(self):
1570 s = self.declaration_code("(*)", with_calling_convention=False)
1571 return '(%s)' % s
1573 def opt_arg_cname(self, arg_name):
1574 return self.op_arg_struct.base_type.scope.lookup(arg_name).cname
1577 class CFuncTypeArg(object):
1578 # name string
1579 # cname string
1580 # type PyrexType
1581 # pos source file position
1583 def __init__(self, name, type, pos, cname=None):
1584 self.name = name
1585 if cname is not None:
1586 self.cname = cname
1587 else:
1588 self.cname = Naming.var_prefix + name
1589 self.type = type
1590 self.pos = pos
1591 self.not_none = False
1592 self.needs_type_test = False # TODO: should these defaults be set in analyse_types()?
1594 def __repr__(self):
1595 return "%s:%s" % (self.name, repr(self.type))
1597 def declaration_code(self, for_display = 0):
1598 return self.type.declaration_code(self.cname, for_display)
1600 class StructUtilityCode(object):
1601 def __init__(self, type, forward_decl):
1602 self.type = type
1603 self.header = "static PyObject* %s(%s)" % (type.to_py_function, type.declaration_code('s'))
1604 self.forward_decl = forward_decl
1606 def __eq__(self, other):
1607 return isinstance(other, StructUtilityCode) and self.header == other.header
1608 def __hash__(self):
1609 return hash(self.header)
1611 def put_code(self, output):
1612 code = output['utility_code_def']
1613 proto = output['utility_code_proto']
1615 code.putln("%s {" % self.header)
1616 code.putln("PyObject* res;")
1617 code.putln("PyObject* member;")
1618 code.putln("res = PyDict_New(); if (res == NULL) return NULL;")
1619 for member in self.type.scope.var_entries:
1620 nameconst_cname = code.get_py_string_const(member.name, identifier=True)
1621 code.putln("member = %s(s.%s); if (member == NULL) goto bad;" % (
1622 member.type.to_py_function, member.cname))
1623 code.putln("if (PyDict_SetItem(res, %s, member) < 0) goto bad;" % nameconst_cname)
1624 code.putln("Py_DECREF(member);")
1625 code.putln("return res;")
1626 code.putln("bad:")
1627 code.putln("Py_XDECREF(member);")
1628 code.putln("Py_DECREF(res);")
1629 code.putln("return NULL;")
1630 code.putln("}")
1632 # This is a bit of a hack, we need a forward declaration
1633 # due to the way things are ordered in the module...
1634 if self.forward_decl:
1635 proto.putln(self.type.declaration_code('') + ';')
1636 proto.putln(self.header + ";")
1639 class CStructOrUnionType(CType):
1640 # name string
1641 # cname string
1642 # kind string "struct" or "union"
1643 # scope StructOrUnionScope, or None if incomplete
1644 # typedef_flag boolean
1645 # packed boolean
1647 # entry Entry
1649 is_struct_or_union = 1
1650 has_attributes = 1
1652 def __init__(self, name, kind, scope, typedef_flag, cname, packed=False):
1653 self.name = name
1654 self.cname = cname
1655 self.kind = kind
1656 self.scope = scope
1657 self.typedef_flag = typedef_flag
1658 self.is_struct = kind == 'struct'
1659 if self.is_struct:
1660 self.to_py_function = "%s_to_py_%s" % (Naming.convert_func_prefix, self.cname)
1661 self.exception_check = True
1662 self._convert_code = None
1663 self.packed = packed
1665 def create_to_py_utility_code(self, env):
1666 if env.outer_scope is None:
1667 return False
1669 if self._convert_code is False: return # tri-state-ish
1671 if self._convert_code is None:
1672 for member in self.scope.var_entries:
1673 if not member.type.to_py_function or not member.type.create_to_py_utility_code(env):
1674 self.to_py_function = None
1675 self._convert_code = False
1676 return False
1677 forward_decl = (self.entry.visibility != 'extern')
1678 self._convert_code = StructUtilityCode(self, forward_decl)
1680 env.use_utility_code(self._convert_code)
1681 return True
1683 def __repr__(self):
1684 return "<CStructOrUnionType %s %s%s>" % (self.name, self.cname,
1685 ("", " typedef")[self.typedef_flag])
1687 def declaration_code(self, entity_code,
1688 for_display = 0, dll_linkage = None, pyrex = 0):
1689 if pyrex:
1690 return self.base_declaration_code(self.name, entity_code)
1691 else:
1692 if for_display:
1693 base = self.name
1694 elif self.typedef_flag:
1695 base = self.cname
1696 else:
1697 base = "%s %s" % (self.kind, self.cname)
1698 return self.base_declaration_code(public_decl(base, dll_linkage), entity_code)
1700 def __eq__(self, other):
1701 try:
1702 return (isinstance(other, CStructOrUnionType) and
1703 self.name == other.name)
1704 except AttributeError:
1705 return False
1707 def __lt__(self, other):
1708 try:
1709 return self.name < other.name
1710 except AttributeError:
1711 # this is arbitrary, but it makes sure we always have
1712 # *some* kind of order
1713 return False
1715 def __hash__(self):
1716 return hash(self.cname) ^ hash(self.kind)
1718 def is_complete(self):
1719 return self.scope is not None
1721 def attributes_known(self):
1722 return self.is_complete()
1724 def can_be_complex(self):
1725 # Does the struct consist of exactly two identical floats?
1726 fields = self.scope.var_entries
1727 if len(fields) != 2: return False
1728 a, b = fields
1729 return (a.type.is_float and b.type.is_float and
1730 a.type.declaration_code("") ==
1731 b.type.declaration_code(""))
1733 def struct_nesting_depth(self):
1734 child_depths = [x.type.struct_nesting_depth()
1735 for x in self.scope.var_entries]
1736 return max(child_depths) + 1
1738 class CEnumType(CType):
1739 # name string
1740 # cname string or None
1741 # typedef_flag boolean
1743 is_enum = 1
1744 signed = 1
1745 rank = -1 # Ranks below any integer type
1746 to_py_function = "PyInt_FromLong"
1747 from_py_function = "PyInt_AsLong"
1749 def __init__(self, name, cname, typedef_flag):
1750 self.name = name
1751 self.cname = cname
1752 self.values = []
1753 self.typedef_flag = typedef_flag
1755 def __str__(self):
1756 return self.name
1758 def __repr__(self):
1759 return "<CEnumType %s %s%s>" % (self.name, self.cname,
1760 ("", " typedef")[self.typedef_flag])
1762 def declaration_code(self, entity_code,
1763 for_display = 0, dll_linkage = None, pyrex = 0):
1764 if pyrex:
1765 return self.base_declaration_code(self.cname, entity_code)
1766 else:
1767 if self.typedef_flag:
1768 base = self.cname
1769 else:
1770 base = "enum %s" % self.cname
1771 return self.base_declaration_code(public_decl(base, dll_linkage), entity_code)
1774 class CStringType(object):
1775 # Mixin class for C string types.
1777 is_string = 1
1778 is_unicode = 0
1780 to_py_function = "__Pyx_PyBytes_FromString"
1781 from_py_function = "__Pyx_PyBytes_AsString"
1782 exception_value = "NULL"
1784 def literal_code(self, value):
1785 assert isinstance(value, str)
1786 return '"%s"' % StringEncoding.escape_byte_string(value)
1789 class CUTF8CharArrayType(CStringType, CArrayType):
1790 # C 'char []' type.
1792 pymemberdef_typecode = "T_STRING_INPLACE"
1793 is_unicode = 1
1795 to_py_function = "PyUnicode_DecodeUTF8"
1796 exception_value = "NULL"
1798 def __init__(self, size):
1799 CArrayType.__init__(self, c_char_type, size)
1801 class CCharArrayType(CStringType, CArrayType):
1802 # C 'char []' type.
1804 pymemberdef_typecode = "T_STRING_INPLACE"
1806 def __init__(self, size):
1807 CArrayType.__init__(self, c_char_type, size)
1810 class CCharPtrType(CStringType, CPtrType):
1811 # C 'char *' type.
1813 pymemberdef_typecode = "T_STRING"
1815 def __init__(self):
1816 CPtrType.__init__(self, c_char_type)
1819 class CUCharPtrType(CStringType, CPtrType):
1820 # C 'unsigned char *' type.
1822 pymemberdef_typecode = "T_STRING"
1824 to_py_function = "__Pyx_PyBytes_FromUString"
1825 from_py_function = "__Pyx_PyBytes_AsUString"
1827 def __init__(self):
1828 CPtrType.__init__(self, c_uchar_type)
1831 class UnspecifiedType(PyrexType):
1832 # Used as a placeholder until the type can be determined.
1834 is_unspecified = 1
1836 def declaration_code(self, entity_code,
1837 for_display = 0, dll_linkage = None, pyrex = 0):
1838 return "<unspecified>"
1840 def same_as_resolved_type(self, other_type):
1841 return False
1844 class ErrorType(PyrexType):
1845 # Used to prevent propagation of error messages.
1847 is_error = 1
1848 exception_value = "0"
1849 exception_check = 0
1850 to_py_function = "dummy"
1851 from_py_function = "dummy"
1853 def create_to_py_utility_code(self, env):
1854 return True
1856 def create_from_py_utility_code(self, env):
1857 return True
1859 def declaration_code(self, entity_code,
1860 for_display = 0, dll_linkage = None, pyrex = 0):
1861 return "<error>"
1863 def same_as_resolved_type(self, other_type):
1864 return 1
1866 def error_condition(self, result_code):
1867 return "dummy"
1870 rank_to_type_name = (
1871 "char", # 0
1872 "short", # 1
1873 "int", # 2
1874 "long", # 3
1875 "Py_ssize_t", # 4
1876 "size_t", # 5
1877 "PY_LONG_LONG", # 6
1878 "float", # 7
1879 "double", # 8
1880 "long double", # 9
1881 )
1883 py_object_type = PyObjectType()
1885 c_void_type = CVoidType()
1886 c_void_ptr_type = CPtrType(c_void_type)
1887 c_void_ptr_ptr_type = CPtrType(c_void_ptr_type)
1889 c_uchar_type = CIntType(0, 0, "T_UBYTE")
1890 c_ushort_type = CIntType(1, 0, "T_USHORT")
1891 c_uint_type = CUIntType(2, 0, "T_UINT")
1892 c_ulong_type = CULongType(3, 0, "T_ULONG")
1893 c_ulonglong_type = CULongLongType(6, 0, "T_ULONGLONG")
1895 c_char_type = CIntType(0, 1, "T_CHAR")
1896 c_short_type = CIntType(1, 1, "T_SHORT")
1897 c_int_type = CIntType(2, 1, "T_INT")
1898 c_long_type = CLongType(3, 1, "T_LONG")
1899 c_longlong_type = CLongLongType(6, 1, "T_LONGLONG")
1900 c_bint_type = CBIntType(2, 1, "T_INT")
1902 c_schar_type = CIntType(0, 2, "T_CHAR")
1903 c_sshort_type = CIntType(1, 2, "T_SHORT")
1904 c_sint_type = CIntType(2, 2, "T_INT")
1905 c_slong_type = CLongType(3, 2, "T_LONG")
1906 c_slonglong_type = CLongLongType(6, 2, "T_LONGLONG")
1908 c_py_ssize_t_type = CPySSizeTType(4, 2, "T_PYSSIZET")
1909 c_size_t_type = CSizeTType(5, 0, "T_SIZET")
1911 c_float_type = CFloatType(7, "T_FLOAT", math_h_modifier='f')
1912 c_double_type = CFloatType(8, "T_DOUBLE")
1913 c_longdouble_type = CFloatType(9, math_h_modifier='l')
1915 c_double_complex_type = CComplexType(c_double_type)
1917 c_null_ptr_type = CNullPtrType(c_void_type)
1918 c_char_array_type = CCharArrayType(None)
1919 c_char_ptr_type = CCharPtrType()
1920 c_uchar_ptr_type = CUCharPtrType()
1921 c_utf8_char_array_type = CUTF8CharArrayType(None)
1922 c_char_ptr_ptr_type = CPtrType(c_char_ptr_type)
1923 c_int_ptr_type = CPtrType(c_int_type)
1924 c_py_ssize_t_ptr_type = CPtrType(c_py_ssize_t_type)
1925 c_size_t_ptr_type = CPtrType(c_size_t_type)
1927 c_returncode_type = CIntType(2, 1, "T_INT", is_returncode = 1)
1929 c_anon_enum_type = CAnonEnumType(-1, 1)
1931 # the Py_buffer type is defined in Builtin.py
1932 c_py_buffer_type = CStructOrUnionType("Py_buffer", "struct", None, 1, "Py_buffer")
1933 c_py_buffer_ptr_type = CPtrType(c_py_buffer_type)
1935 error_type = ErrorType()
1936 unspecified_type = UnspecifiedType()
1938 sign_and_rank_to_type = {
1939 #(signed, rank)
1940 (0, 0): c_uchar_type,
1941 (0, 1): c_ushort_type,
1942 (0, 2): c_uint_type,
1943 (0, 3): c_ulong_type,
1944 (0, 6): c_ulonglong_type,
1946 (1, 0): c_char_type,
1947 (1, 1): c_short_type,
1948 (1, 2): c_int_type,
1949 (1, 3): c_long_type,
1950 (1, 6): c_longlong_type,
1952 (2, 0): c_schar_type,
1953 (2, 1): c_sshort_type,
1954 (2, 2): c_sint_type,
1955 (2, 3): c_slong_type,
1956 (2, 6): c_slonglong_type,
1958 (0, 4): c_py_ssize_t_type,
1959 (1, 4): c_py_ssize_t_type,
1960 (2, 4): c_py_ssize_t_type,
1961 (0, 5): c_size_t_type,
1962 (1, 5): c_size_t_type,
1963 (2, 5): c_size_t_type,
1965 (1, 7): c_float_type,
1966 (1, 8): c_double_type,
1967 (1, 9): c_longdouble_type,
1968 # In case we're mixing unsigned ints and floats...
1969 (0, 7): c_float_type,
1970 (0, 8): c_double_type,
1971 (0, 9): c_longdouble_type,
1972 }
1974 modifiers_and_name_to_type = {
1975 #(signed, longness, name)
1976 (0, 0, "char"): c_uchar_type,
1977 (0, -1, "int"): c_ushort_type,
1978 (0, 0, "int"): c_uint_type,
1979 (0, 1, "int"): c_ulong_type,
1980 (0, 2, "int"): c_ulonglong_type,
1981 (1, 0, "void"): c_void_type,
1982 (1, 0, "char"): c_char_type,
1983 (1, -1, "int"): c_short_type,
1984 (1, 0, "int"): c_int_type,
1985 (1, 1, "int"): c_long_type,
1986 (1, 2, "int"): c_longlong_type,
1987 (1, 0, "float"): c_float_type,
1988 (1, 0, "double"): c_double_type,
1989 (1, 1, "double"): c_longdouble_type,
1990 (1, 0, "object"): py_object_type,
1991 (1, 0, "bint"): c_bint_type,
1992 (2, 0, "char"): c_schar_type,
1993 (2, -1, "int"): c_sshort_type,
1994 (2, 0, "int"): c_sint_type,
1995 (2, 1, "int"): c_slong_type,
1996 (2, 2, "int"): c_slonglong_type,
1998 (2, 0, "Py_ssize_t"): c_py_ssize_t_type,
1999 (0, 0, "size_t") : c_size_t_type,
2001 (1, 0, "long"): c_long_type,
2002 (1, 0, "short"): c_short_type,
2003 (1, 0, "longlong"): c_longlong_type,
2004 (1, 0, "bint"): c_bint_type,
2005 }
2007 def widest_numeric_type(type1, type2):
2008 # Given two numeric types, return the narrowest type
2009 # encompassing both of them.
2010 if type1 == type2:
2011 return type1
2012 if type1.is_complex:
2013 if type2.is_complex:
2014 return CComplexType(widest_numeric_type(type1.real_type, type2.real_type))
2015 else:
2016 return CComplexType(widest_numeric_type(type1.real_type, type2))
2017 elif type2.is_complex:
2018 return CComplexType(widest_numeric_type(type1, type2.real_type))
2019 if type1.is_enum and type2.is_enum:
2020 return c_int_type
2021 elif type1 is type2:
2022 return type1
2023 elif (type1.signed and type2.signed) or (not type1.signed and not type2.signed):
2024 if type2.rank > type1.rank:
2025 return type2
2026 else:
2027 return type1
2028 else:
2029 return sign_and_rank_to_type[min(type1.signed, type2.signed), max(type1.rank, type2.rank)]
2031 def spanning_type(type1, type2):
2032 # Return a type assignable from both type1 and type2.
2033 if type1 is py_object_type or type2 is py_object_type:
2034 return py_object_type
2035 elif type1 == type2:
2036 return type1
2037 elif type1.is_numeric and type2.is_numeric:
2038 return widest_numeric_type(type1, type2)
2039 elif type1.is_builtin_type and type1.name == 'float' and type2.is_numeric:
2040 return widest_numeric_type(c_double_type, type2)
2041 elif type2.is_builtin_type and type2.name == 'float' and type1.is_numeric:
2042 return widest_numeric_type(type1, c_double_type)
2043 elif type1.is_pyobject ^ type2.is_pyobject:
2044 return py_object_type
2045 elif type1.assignable_from(type2):
2046 if type1.is_extension_type and type1.typeobj_is_imported():
2047 # external types are unsafe, so we use PyObject instead
2048 return py_object_type
2049 return type1
2050 elif type2.assignable_from(type1):
2051 if type2.is_extension_type and type2.typeobj_is_imported():
2052 # external types are unsafe, so we use PyObject instead
2053 return py_object_type
2054 return type2
2055 else:
2056 return py_object_type
2058 def simple_c_type(signed, longness, name):
2059 # Find type descriptor for simple type given name and modifiers.
2060 # Returns None if arguments don't make sense.
2061 return modifiers_and_name_to_type.get((signed, longness, name))
2063 def parse_basic_type(name):
2064 base = None
2065 if name.startswith('p_'):
2066 base = parse_basic_type(name[2:])
2067 elif name.startswith('p'):
2068 base = parse_basic_type(name[1:])
2069 elif name.endswith('*'):
2070 base = parse_basic_type(name[:-1])
2071 if base:
2072 return CPtrType(base)
2073 elif name.startswith('u'):
2074 return simple_c_type(0, 0, name[1:])
2075 else:
2076 return simple_c_type(1, 0, name)
2078 def c_array_type(base_type, size):
2079 # Construct a C array type.
2080 if base_type is c_char_type:
2081 return CCharArrayType(size)
2082 elif base_type is error_type:
2083 return error_type
2084 else:
2085 return CArrayType(base_type, size)
2087 def c_ptr_type(base_type):
2088 # Construct a C pointer type.
2089 if base_type is c_char_type:
2090 return c_char_ptr_type
2091 elif base_type is c_uchar_type:
2092 return c_uchar_ptr_type
2093 elif base_type is error_type:
2094 return error_type
2095 else:
2096 return CPtrType(base_type)
2098 def same_type(type1, type2):
2099 return type1.same_as(type2)
2101 def assignable_from(type1, type2):
2102 return type1.assignable_from(type2)
2104 def typecast(to_type, from_type, expr_code):
2105 # Return expr_code cast to a C type which can be
2106 # assigned to to_type, assuming its existing C type
2107 # is from_type.
2108 if to_type is from_type or \
2109 (not to_type.is_pyobject and assignable_from(to_type, from_type)):
2110 return expr_code
2111 else:
2112 #print "typecast: to", to_type, "from", from_type ###
2113 return to_type.cast_code(expr_code)
2116 type_conversion_predeclarations = """
2117 /* Type Conversion Predeclarations */
2119 #if PY_MAJOR_VERSION < 3
2120 #define __Pyx_PyBytes_FromString PyString_FromString
2121 #define __Pyx_PyBytes_FromStringAndSize PyString_FromStringAndSize
2122 #define __Pyx_PyBytes_AsString PyString_AsString
2123 #else
2124 #define __Pyx_PyBytes_FromString PyBytes_FromString
2125 #define __Pyx_PyBytes_FromStringAndSize PyBytes_FromStringAndSize
2126 #define __Pyx_PyBytes_AsString PyBytes_AsString
2127 #endif
2129 #define __Pyx_PyBytes_FromUString(s) __Pyx_PyBytes_FromString((char*)s)
2130 #define __Pyx_PyBytes_AsUString(s) ((unsigned char*) __Pyx_PyBytes_AsString(s))
2132 #define __Pyx_PyBool_FromLong(b) ((b) ? (Py_INCREF(Py_True), Py_True) : (Py_INCREF(Py_False), Py_False))
2133 static INLINE int __Pyx_PyObject_IsTrue(PyObject*);
2134 static INLINE PyObject* __Pyx_PyNumber_Int(PyObject* x);
2136 #if !defined(T_PYSSIZET)
2137 #if PY_VERSION_HEX < 0x02050000
2138 #define T_PYSSIZET T_INT
2139 #elif !defined(T_LONGLONG)
2140 #define T_PYSSIZET \\
2141 ((sizeof(Py_ssize_t) == sizeof(int)) ? T_INT : \\
2142 ((sizeof(Py_ssize_t) == sizeof(long)) ? T_LONG : -1))
2143 #else
2144 #define T_PYSSIZET \\
2145 ((sizeof(Py_ssize_t) == sizeof(int)) ? T_INT : \\
2146 ((sizeof(Py_ssize_t) == sizeof(long)) ? T_LONG : \\
2147 ((sizeof(Py_ssize_t) == sizeof(PY_LONG_LONG)) ? T_LONGLONG : -1)))
2148 #endif
2149 #endif
2152 #if !defined(T_ULONGLONG)
2153 #define __Pyx_T_UNSIGNED_INT(x) \\
2154 ((sizeof(x) == sizeof(unsigned char)) ? T_UBYTE : \\
2155 ((sizeof(x) == sizeof(unsigned short)) ? T_USHORT : \\
2156 ((sizeof(x) == sizeof(unsigned int)) ? T_UINT : \\
2157 ((sizeof(x) == sizeof(unsigned long)) ? T_ULONG : -1))))
2158 #else
2159 #define __Pyx_T_UNSIGNED_INT(x) \\
2160 ((sizeof(x) == sizeof(unsigned char)) ? T_UBYTE : \\
2161 ((sizeof(x) == sizeof(unsigned short)) ? T_USHORT : \\
2162 ((sizeof(x) == sizeof(unsigned int)) ? T_UINT : \\
2163 ((sizeof(x) == sizeof(unsigned long)) ? T_ULONG : \\
2164 ((sizeof(x) == sizeof(unsigned PY_LONG_LONG)) ? T_ULONGLONG : -1)))))
2165 #endif
2166 #if !defined(T_LONGLONG)
2167 #define __Pyx_T_SIGNED_INT(x) \\
2168 ((sizeof(x) == sizeof(char)) ? T_BYTE : \\
2169 ((sizeof(x) == sizeof(short)) ? T_SHORT : \\
2170 ((sizeof(x) == sizeof(int)) ? T_INT : \\
2171 ((sizeof(x) == sizeof(long)) ? T_LONG : -1))))
2172 #else
2173 #define __Pyx_T_SIGNED_INT(x) \\
2174 ((sizeof(x) == sizeof(char)) ? T_BYTE : \\
2175 ((sizeof(x) == sizeof(short)) ? T_SHORT : \\
2176 ((sizeof(x) == sizeof(int)) ? T_INT : \\
2177 ((sizeof(x) == sizeof(long)) ? T_LONG : \\
2178 ((sizeof(x) == sizeof(PY_LONG_LONG)) ? T_LONGLONG : -1)))))
2179 #endif
2181 #define __Pyx_T_FLOATING(x) \\
2182 ((sizeof(x) == sizeof(float)) ? T_FLOAT : \\
2183 ((sizeof(x) == sizeof(double)) ? T_DOUBLE : -1))
2185 #if !defined(T_SIZET)
2186 #if !defined(T_ULONGLONG)
2187 #define T_SIZET \\
2188 ((sizeof(size_t) == sizeof(unsigned int)) ? T_UINT : \\
2189 ((sizeof(size_t) == sizeof(unsigned long)) ? T_ULONG : -1))
2190 #else
2191 #define T_SIZET \\
2192 ((sizeof(size_t) == sizeof(unsigned int)) ? T_UINT : \\
2193 ((sizeof(size_t) == sizeof(unsigned long)) ? T_ULONG : \\
2194 ((sizeof(size_t) == sizeof(unsigned PY_LONG_LONG)) ? T_ULONGLONG : -1)))
2195 #endif
2196 #endif
2198 static INLINE Py_ssize_t __Pyx_PyIndex_AsSsize_t(PyObject*);
2199 static INLINE PyObject * __Pyx_PyInt_FromSize_t(size_t);
2200 static INLINE size_t __Pyx_PyInt_AsSize_t(PyObject*);
2202 #define __pyx_PyFloat_AsDouble(x) (PyFloat_CheckExact(x) ? PyFloat_AS_DOUBLE(x) : PyFloat_AsDouble(x))
2204 """ + type_conversion_predeclarations
2206 type_conversion_functions = """
2207 /* Type Conversion Functions */
2209 static INLINE int __Pyx_PyObject_IsTrue(PyObject* x) {
2210 if (x == Py_True) return 1;
2211 else if ((x == Py_False) | (x == Py_None)) return 0;
2212 else return PyObject_IsTrue(x);
2213 }
2215 static INLINE PyObject* __Pyx_PyNumber_Int(PyObject* x) {
2216 PyNumberMethods *m;
2217 const char *name = NULL;
2218 PyObject *res = NULL;
2219 #if PY_VERSION_HEX < 0x03000000
2220 if (PyInt_Check(x) || PyLong_Check(x))
2221 #else
2222 if (PyLong_Check(x))
2223 #endif
2224 return Py_INCREF(x), x;
2225 m = Py_TYPE(x)->tp_as_number;
2226 #if PY_VERSION_HEX < 0x03000000
2227 if (m && m->nb_int) {
2228 name = "int";
2229 res = PyNumber_Int(x);
2230 }
2231 else if (m && m->nb_long) {
2232 name = "long";
2233 res = PyNumber_Long(x);
2234 }
2235 #else
2236 if (m && m->nb_int) {
2237 name = "int";
2238 res = PyNumber_Long(x);
2239 }
2240 #endif
2241 if (res) {
2242 #if PY_VERSION_HEX < 0x03000000
2243 if (!PyInt_Check(res) && !PyLong_Check(res)) {
2244 #else
2245 if (!PyLong_Check(res)) {
2246 #endif
2247 PyErr_Format(PyExc_TypeError,
2248 "__%s__ returned non-%s (type %.200s)",
2249 name, name, Py_TYPE(res)->tp_name);
2250 Py_DECREF(res);
2251 return NULL;
2252 }
2253 }
2254 else if (!PyErr_Occurred()) {
2255 PyErr_SetString(PyExc_TypeError,
2256 "an integer is required");
2257 }
2258 return res;
2259 }
2261 static INLINE Py_ssize_t __Pyx_PyIndex_AsSsize_t(PyObject* b) {
2262 Py_ssize_t ival;
2263 PyObject* x = PyNumber_Index(b);
2264 if (!x) return -1;
2265 ival = PyInt_AsSsize_t(x);
2266 Py_DECREF(x);
2267 return ival;
2268 }
2270 static INLINE PyObject * __Pyx_PyInt_FromSize_t(size_t ival) {
2271 #if PY_VERSION_HEX < 0x02050000
2272 if (ival <= LONG_MAX)
2273 return PyInt_FromLong((long)ival);
2274 else {
2275 unsigned char *bytes = (unsigned char *) &ival;
2276 int one = 1; int little = (int)*(unsigned char*)&one;
2277 return _PyLong_FromByteArray(bytes, sizeof(size_t), little, 0);
2278 }
2279 #else
2280 return PyInt_FromSize_t(ival);
2281 #endif
2282 }
2284 static INLINE size_t __Pyx_PyInt_AsSize_t(PyObject* x) {
2285 unsigned PY_LONG_LONG val = __Pyx_PyInt_AsUnsignedLongLong(x);
2286 if (unlikely(val == (unsigned PY_LONG_LONG)-1 && PyErr_Occurred())) {
2287 return (size_t)-1;
2288 } else if (unlikely(val != (unsigned PY_LONG_LONG)(size_t)val)) {
2289 PyErr_SetString(PyExc_OverflowError,
2290 "value too large to convert to size_t");
2291 return (size_t)-1;
2292 }
2293 return (size_t)val;
2294 }
2296 """ + type_conversion_functions
