Cython has moved to github.
cython-devel
view Cython/Compiler/PyrexTypes.py @ 2819:3bc6d034486a
INLINE -> CYTHON_INLINE to avoid conflicts
| author | Robert Bradshaw <robertwb@math.washington.edu> |
|---|---|
| date | Mon Jan 25 22:47:09 2010 -0800 (2 years ago) |
| parents | ed2ba011aa3c |
| children | 6fd7d210d482 |
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 CYTHON_INLINE %(type)s __Pyx_PyInt_As%(SignWord)s%(TypeName)s(PyObject *);
642 """,
643 impl="""
644 static CYTHON_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 CYTHON_INLINE %(type)s __Pyx_PyInt_As%(SignWord)s%(TypeName)s(PyObject *);
667 """,
668 impl="""
669 static CYTHON_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 CYTHON_INLINE %(type)s __Pyx_PyInt_from_py_%(TypeName)s(PyObject *);
708 """,
709 impl="""
710 static CYTHON_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 CYTHON_INLINE PyObject *__Pyx_PyInt_to_py_%(TypeName)s(%(type)s);
755 """,
756 impl="""
757 static CYTHON_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
1067 #if CYTHON_CCOMPLEX && !defined(__cplusplus) && defined(__sun__) && defined(__GNUC__)
1068 #undef _Complex_I
1069 #define _Complex_I 1.0fj
1070 #endif
1071 """)
1073 complex_real_imag_utility_code = UtilityCode(
1074 proto="""
1075 #if CYTHON_CCOMPLEX
1076 #ifdef __cplusplus
1077 #define __Pyx_CREAL(z) ((z).real())
1078 #define __Pyx_CIMAG(z) ((z).imag())
1079 #else
1080 #define __Pyx_CREAL(z) (__real__(z))
1081 #define __Pyx_CIMAG(z) (__imag__(z))
1082 #endif
1083 #else
1084 #define __Pyx_CREAL(z) ((z).real)
1085 #define __Pyx_CIMAG(z) ((z).imag)
1086 #endif
1088 #if defined(_WIN32) && defined(__cplusplus) && CYTHON_CCOMPLEX
1089 #define __Pyx_SET_CREAL(z,x) ((z).real(x))
1090 #define __Pyx_SET_CIMAG(z,y) ((z).imag(y))
1091 #else
1092 #define __Pyx_SET_CREAL(z,x) __Pyx_CREAL(z) = (x)
1093 #define __Pyx_SET_CIMAG(z,y) __Pyx_CIMAG(z) = (y)
1094 #endif
1095 """)
1097 complex_type_utility_code = UtilityCode(
1098 proto_block='complex_type_declarations',
1099 proto="""
1100 #if CYTHON_CCOMPLEX
1101 #ifdef __cplusplus
1102 typedef ::std::complex< %(real_type)s > %(type_name)s;
1103 #else
1104 typedef %(real_type)s _Complex %(type_name)s;
1105 #endif
1106 #else
1107 typedef struct { %(real_type)s real, imag; } %(type_name)s;
1108 #endif
1109 """)
1111 complex_from_parts_utility_code = UtilityCode(
1112 proto_block='utility_code_proto',
1113 proto="""
1114 static CYTHON_INLINE %(type)s %(type_name)s_from_parts(%(real_type)s, %(real_type)s);
1115 """,
1116 impl="""
1117 #if CYTHON_CCOMPLEX
1118 #ifdef __cplusplus
1119 static CYTHON_INLINE %(type)s %(type_name)s_from_parts(%(real_type)s x, %(real_type)s y) {
1120 return ::std::complex< %(real_type)s >(x, y);
1121 }
1122 #else
1123 static CYTHON_INLINE %(type)s %(type_name)s_from_parts(%(real_type)s x, %(real_type)s y) {
1124 return x + y*(%(type)s)_Complex_I;
1125 }
1126 #endif
1127 #else
1128 static CYTHON_INLINE %(type)s %(type_name)s_from_parts(%(real_type)s x, %(real_type)s y) {
1129 %(type)s z;
1130 z.real = x;
1131 z.imag = y;
1132 return z;
1133 }
1134 #endif
1135 """)
1137 complex_to_py_utility_code = UtilityCode(
1138 proto="""
1139 #define __pyx_PyComplex_FromComplex(z) \\
1140 PyComplex_FromDoubles((double)__Pyx_CREAL(z), \\
1141 (double)__Pyx_CIMAG(z))
1142 """)
1144 complex_from_py_utility_code = UtilityCode(
1145 proto="""
1146 static %(type)s __Pyx_PyComplex_As_%(type_name)s(PyObject*);
1147 """,
1148 impl="""
1149 static %(type)s __Pyx_PyComplex_As_%(type_name)s(PyObject* o) {
1150 Py_complex cval;
1151 if (PyComplex_CheckExact(o))
1152 cval = ((PyComplexObject *)o)->cval;
1153 else
1154 cval = PyComplex_AsCComplex(o);
1155 return %(type_name)s_from_parts(
1156 (%(real_type)s)cval.real,
1157 (%(real_type)s)cval.imag);
1158 }
1159 """)
1161 complex_arithmatic_utility_code = UtilityCode(
1162 proto="""
1163 #if CYTHON_CCOMPLEX
1164 #define __Pyx_c_eq%(m)s(a, b) ((a)==(b))
1165 #define __Pyx_c_sum%(m)s(a, b) ((a)+(b))
1166 #define __Pyx_c_diff%(m)s(a, b) ((a)-(b))
1167 #define __Pyx_c_prod%(m)s(a, b) ((a)*(b))
1168 #define __Pyx_c_quot%(m)s(a, b) ((a)/(b))
1169 #define __Pyx_c_neg%(m)s(a) (-(a))
1170 #ifdef __cplusplus
1171 #define __Pyx_c_is_zero%(m)s(z) ((z)==(%(real_type)s)0)
1172 #define __Pyx_c_conj%(m)s(z) (::std::conj(z))
1173 /*#define __Pyx_c_abs%(m)s(z) (::std::abs(z))*/
1174 #else
1175 #define __Pyx_c_is_zero%(m)s(z) ((z)==0)
1176 #define __Pyx_c_conj%(m)s(z) (conj%(m)s(z))
1177 /*#define __Pyx_c_abs%(m)s(z) (cabs%(m)s(z))*/
1178 #endif
1179 #else
1180 static CYTHON_INLINE int __Pyx_c_eq%(m)s(%(type)s, %(type)s);
1181 static CYTHON_INLINE %(type)s __Pyx_c_sum%(m)s(%(type)s, %(type)s);
1182 static CYTHON_INLINE %(type)s __Pyx_c_diff%(m)s(%(type)s, %(type)s);
1183 static CYTHON_INLINE %(type)s __Pyx_c_prod%(m)s(%(type)s, %(type)s);
1184 static CYTHON_INLINE %(type)s __Pyx_c_quot%(m)s(%(type)s, %(type)s);
1185 static CYTHON_INLINE %(type)s __Pyx_c_neg%(m)s(%(type)s);
1186 static CYTHON_INLINE int __Pyx_c_is_zero%(m)s(%(type)s);
1187 static CYTHON_INLINE %(type)s __Pyx_c_conj%(m)s(%(type)s);
1188 /*static CYTHON_INLINE %(real_type)s __Pyx_c_abs%(m)s(%(type)s);*/
1189 #endif
1190 """,
1191 impl="""
1192 #if CYTHON_CCOMPLEX
1193 #else
1194 static CYTHON_INLINE int __Pyx_c_eq%(m)s(%(type)s a, %(type)s b) {
1195 return (a.real == b.real) && (a.imag == b.imag);
1196 }
1197 static CYTHON_INLINE %(type)s __Pyx_c_sum%(m)s(%(type)s a, %(type)s b) {
1198 %(type)s z;
1199 z.real = a.real + b.real;
1200 z.imag = a.imag + b.imag;
1201 return z;
1202 }
1203 static CYTHON_INLINE %(type)s __Pyx_c_diff%(m)s(%(type)s a, %(type)s b) {
1204 %(type)s z;
1205 z.real = a.real - b.real;
1206 z.imag = a.imag - b.imag;
1207 return z;
1208 }
1209 static CYTHON_INLINE %(type)s __Pyx_c_prod%(m)s(%(type)s a, %(type)s b) {
1210 %(type)s z;
1211 z.real = a.real * b.real - a.imag * b.imag;
1212 z.imag = a.real * b.imag + a.imag * b.real;
1213 return z;
1214 }
1215 static CYTHON_INLINE %(type)s __Pyx_c_quot%(m)s(%(type)s a, %(type)s b) {
1216 %(type)s z;
1217 %(real_type)s denom = b.real * b.real + b.imag * b.imag;
1218 z.real = (a.real * b.real + a.imag * b.imag) / denom;
1219 z.imag = (a.imag * b.real - a.real * b.imag) / denom;
1220 return z;
1221 }
1222 static CYTHON_INLINE %(type)s __Pyx_c_neg%(m)s(%(type)s a) {
1223 %(type)s z;
1224 z.real = -a.real;
1225 z.imag = -a.imag;
1226 return z;
1227 }
1228 static CYTHON_INLINE int __Pyx_c_is_zero%(m)s(%(type)s a) {
1229 return (a.real == 0) && (a.imag == 0);
1230 }
1231 static CYTHON_INLINE %(type)s __Pyx_c_conj%(m)s(%(type)s a) {
1232 %(type)s z;
1233 z.real = a.real;
1234 z.imag = -a.imag;
1235 return z;
1236 }
1237 /*
1238 static CYTHON_INLINE %(real_type)s __Pyx_c_abs%(m)s(%(type)s z) {
1239 #if HAVE_HYPOT
1240 return hypot%(m)s(z.real, z.imag);
1241 #else
1242 return sqrt%(m)s(z.real*z.real + z.imag*z.imag);
1243 #endif
1244 }
1245 */
1246 #endif
1247 """)
1249 class CArrayType(CType):
1250 # base_type CType Element type
1251 # size integer or None Number of elements
1253 is_array = 1
1255 def __init__(self, base_type, size):
1256 self.base_type = base_type
1257 self.size = size
1258 if base_type is c_char_type:
1259 self.is_string = 1
1261 def __repr__(self):
1262 return "<CArrayType %s %s>" % (self.size, repr(self.base_type))
1264 def same_as_resolved_type(self, other_type):
1265 return ((other_type.is_array and
1266 self.base_type.same_as(other_type.base_type))
1267 or other_type is error_type)
1269 def assignable_from_resolved_type(self, src_type):
1270 # Can't assign to a variable of an array type
1271 return 0
1273 def element_ptr_type(self):
1274 return c_ptr_type(self.base_type)
1276 def declaration_code(self, entity_code,
1277 for_display = 0, dll_linkage = None, pyrex = 0):
1278 if self.size is not None:
1279 dimension_code = self.size
1280 else:
1281 dimension_code = ""
1282 if entity_code.startswith("*"):
1283 entity_code = "(%s)" % entity_code
1284 return self.base_type.declaration_code(
1285 "%s[%s]" % (entity_code, dimension_code),
1286 for_display, dll_linkage, pyrex)
1288 def as_argument_type(self):
1289 return c_ptr_type(self.base_type)
1291 def is_complete(self):
1292 return self.size is not None
1295 class CPtrType(CType):
1296 # base_type CType Referenced type
1298 is_ptr = 1
1299 default_value = "0"
1301 def __init__(self, base_type):
1302 self.base_type = base_type
1304 def __repr__(self):
1305 return "<CPtrType %s>" % repr(self.base_type)
1307 def same_as_resolved_type(self, other_type):
1308 return ((other_type.is_ptr and
1309 self.base_type.same_as(other_type.base_type))
1310 or other_type is error_type)
1312 def declaration_code(self, entity_code,
1313 for_display = 0, dll_linkage = None, pyrex = 0):
1314 #print "CPtrType.declaration_code: pointer to", self.base_type ###
1315 return self.base_type.declaration_code(
1316 "*%s" % entity_code,
1317 for_display, dll_linkage, pyrex)
1319 def assignable_from_resolved_type(self, other_type):
1320 if other_type is error_type:
1321 return 1
1322 if other_type.is_null_ptr:
1323 return 1
1324 if self.base_type.is_cfunction:
1325 if other_type.is_ptr:
1326 other_type = other_type.base_type.resolve()
1327 if other_type.is_cfunction:
1328 return self.base_type.pointer_assignable_from_resolved_type(other_type)
1329 else:
1330 return 0
1331 if other_type.is_array or other_type.is_ptr:
1332 return self.base_type.is_void or self.base_type.same_as(other_type.base_type)
1333 return 0
1336 class CNullPtrType(CPtrType):
1338 is_null_ptr = 1
1341 class CFuncType(CType):
1342 # return_type CType
1343 # args [CFuncTypeArg]
1344 # has_varargs boolean
1345 # exception_value string
1346 # exception_check boolean True if PyErr_Occurred check needed
1347 # calling_convention string Function calling convention
1348 # nogil boolean Can be called without gil
1349 # with_gil boolean Acquire gil around function body
1351 is_cfunction = 1
1352 original_sig = None
1354 def __init__(self, return_type, args, has_varargs = 0,
1355 exception_value = None, exception_check = 0, calling_convention = "",
1356 nogil = 0, with_gil = 0, is_overridable = 0, optional_arg_count = 0):
1357 self.return_type = return_type
1358 self.args = args
1359 self.has_varargs = has_varargs
1360 self.optional_arg_count = optional_arg_count
1361 self.exception_value = exception_value
1362 self.exception_check = exception_check
1363 self.calling_convention = calling_convention
1364 self.nogil = nogil
1365 self.with_gil = with_gil
1366 self.is_overridable = is_overridable
1368 def __repr__(self):
1369 arg_reprs = map(repr, self.args)
1370 if self.has_varargs:
1371 arg_reprs.append("...")
1372 if self.exception_value:
1373 except_clause = " %r" % self.exception_value
1374 else:
1375 except_clause = ""
1376 if self.exception_check:
1377 except_clause += "?"
1378 return "<CFuncType %s %s[%s]%s>" % (
1379 repr(self.return_type),
1380 self.calling_convention_prefix(),
1381 ",".join(arg_reprs),
1382 except_clause)
1384 def calling_convention_prefix(self):
1385 cc = self.calling_convention
1386 if cc:
1387 return cc + " "
1388 else:
1389 return ""
1391 def same_c_signature_as(self, other_type, as_cmethod = 0):
1392 return self.same_c_signature_as_resolved_type(
1393 other_type.resolve(), as_cmethod)
1395 def same_c_signature_as_resolved_type(self, other_type, as_cmethod = 0):
1396 #print "CFuncType.same_c_signature_as_resolved_type:", \
1397 # self, other_type, "as_cmethod =", as_cmethod ###
1398 if other_type is error_type:
1399 return 1
1400 if not other_type.is_cfunction:
1401 return 0
1402 if self.is_overridable != other_type.is_overridable:
1403 return 0
1404 nargs = len(self.args)
1405 if nargs != len(other_type.args):
1406 return 0
1407 # When comparing C method signatures, the first argument
1408 # is exempt from compatibility checking (the proper check
1409 # is performed elsewhere).
1410 for i in range(as_cmethod, nargs):
1411 if not self.args[i].type.same_as(
1412 other_type.args[i].type):
1413 return 0
1414 if self.has_varargs != other_type.has_varargs:
1415 return 0
1416 if self.optional_arg_count != other_type.optional_arg_count:
1417 return 0
1418 if not self.return_type.same_as(other_type.return_type):
1419 return 0
1420 if not self.same_calling_convention_as(other_type):
1421 return 0
1422 return 1
1424 def compatible_signature_with(self, other_type, as_cmethod = 0):
1425 return self.compatible_signature_with_resolved_type(other_type.resolve(), as_cmethod)
1427 def compatible_signature_with_resolved_type(self, other_type, as_cmethod):
1428 #print "CFuncType.same_c_signature_as_resolved_type:", \
1429 # self, other_type, "as_cmethod =", as_cmethod ###
1430 if other_type is error_type:
1431 return 1
1432 if not other_type.is_cfunction:
1433 return 0
1434 if not self.is_overridable and other_type.is_overridable:
1435 return 0
1436 nargs = len(self.args)
1437 if nargs - self.optional_arg_count != len(other_type.args) - other_type.optional_arg_count:
1438 return 0
1439 if self.optional_arg_count < other_type.optional_arg_count:
1440 return 0
1441 # When comparing C method signatures, the first argument
1442 # is exempt from compatibility checking (the proper check
1443 # is performed elsewhere).
1444 for i in range(as_cmethod, len(other_type.args)):
1445 if not self.args[i].type.same_as(
1446 other_type.args[i].type):
1447 return 0
1448 if self.has_varargs != other_type.has_varargs:
1449 return 0
1450 if not self.return_type.subtype_of_resolved_type(other_type.return_type):
1451 return 0
1452 if not self.same_calling_convention_as(other_type):
1453 return 0
1454 if self.nogil != other_type.nogil:
1455 return 0
1456 self.original_sig = other_type.original_sig or other_type
1457 if as_cmethod:
1458 self.args[0] = other_type.args[0]
1459 return 1
1462 def narrower_c_signature_than(self, other_type, as_cmethod = 0):
1463 return self.narrower_c_signature_than_resolved_type(other_type.resolve(), as_cmethod)
1465 def narrower_c_signature_than_resolved_type(self, other_type, as_cmethod):
1466 if other_type is error_type:
1467 return 1
1468 if not other_type.is_cfunction:
1469 return 0
1470 nargs = len(self.args)
1471 if nargs != len(other_type.args):
1472 return 0
1473 for i in range(as_cmethod, nargs):
1474 if not self.args[i].type.subtype_of_resolved_type(other_type.args[i].type):
1475 return 0
1476 else:
1477 self.args[i].needs_type_test = other_type.args[i].needs_type_test \
1478 or not self.args[i].type.same_as(other_type.args[i].type)
1479 if self.has_varargs != other_type.has_varargs:
1480 return 0
1481 if self.optional_arg_count != other_type.optional_arg_count:
1482 return 0
1483 if not self.return_type.subtype_of_resolved_type(other_type.return_type):
1484 return 0
1485 return 1
1487 def same_calling_convention_as(self, other):
1488 ## XXX Under discussion ...
1489 ## callspec_words = ("__stdcall", "__cdecl", "__fastcall")
1490 ## cs1 = self.calling_convention
1491 ## cs2 = other.calling_convention
1492 ## if (cs1 in callspec_words or
1493 ## cs2 in callspec_words):
1494 ## return cs1 == cs2
1495 ## else:
1496 ## return True
1497 sc1 = self.calling_convention == '__stdcall'
1498 sc2 = other.calling_convention == '__stdcall'
1499 return sc1 == sc2
1501 def same_exception_signature_as(self, other_type):
1502 return self.same_exception_signature_as_resolved_type(
1503 other_type.resolve())
1505 def same_exception_signature_as_resolved_type(self, other_type):
1506 return self.exception_value == other_type.exception_value \
1507 and self.exception_check == other_type.exception_check
1509 def same_as_resolved_type(self, other_type, as_cmethod = 0):
1510 return self.same_c_signature_as_resolved_type(other_type, as_cmethod) \
1511 and self.same_exception_signature_as_resolved_type(other_type) \
1512 and self.nogil == other_type.nogil
1514 def pointer_assignable_from_resolved_type(self, other_type):
1515 return self.same_c_signature_as_resolved_type(other_type) \
1516 and self.same_exception_signature_as_resolved_type(other_type) \
1517 and not (self.nogil and not other_type.nogil)
1519 def declaration_code(self, entity_code,
1520 for_display = 0, dll_linkage = None, pyrex = 0,
1521 with_calling_convention = 1):
1522 arg_decl_list = []
1523 for arg in self.args[:len(self.args)-self.optional_arg_count]:
1524 arg_decl_list.append(
1525 arg.type.declaration_code("", for_display, pyrex = pyrex))
1526 if self.is_overridable:
1527 arg_decl_list.append("int %s" % Naming.skip_dispatch_cname)
1528 if self.optional_arg_count:
1529 arg_decl_list.append(self.op_arg_struct.declaration_code(Naming.optional_args_cname))
1530 if self.has_varargs:
1531 arg_decl_list.append("...")
1532 arg_decl_code = ", ".join(arg_decl_list)
1533 if not arg_decl_code and not pyrex:
1534 arg_decl_code = "void"
1535 trailer = ""
1536 if (pyrex or for_display) and not self.return_type.is_pyobject:
1537 if self.exception_value and self.exception_check:
1538 trailer = " except? %s" % self.exception_value
1539 elif self.exception_value:
1540 trailer = " except %s" % self.exception_value
1541 elif self.exception_check == '+':
1542 trailer = " except +"
1543 else:
1544 " except *" # ignored
1545 if self.nogil:
1546 trailer += " nogil"
1547 if not with_calling_convention:
1548 cc = ''
1549 else:
1550 cc = self.calling_convention_prefix()
1551 if (not entity_code and cc) or entity_code.startswith("*"):
1552 entity_code = "(%s%s)" % (cc, entity_code)
1553 cc = ""
1554 return self.return_type.declaration_code(
1555 "%s%s(%s)%s" % (cc, entity_code, arg_decl_code, trailer),
1556 for_display, dll_linkage, pyrex)
1558 def function_header_code(self, func_name, arg_code):
1559 return "%s%s(%s)" % (self.calling_convention_prefix(),
1560 func_name, arg_code)
1562 def signature_string(self):
1563 s = self.declaration_code("")
1564 return s
1566 def signature_cast_string(self):
1567 s = self.declaration_code("(*)", with_calling_convention=False)
1568 return '(%s)' % s
1570 def opt_arg_cname(self, arg_name):
1571 return self.op_arg_struct.base_type.scope.lookup(arg_name).cname
1574 class CFuncTypeArg(object):
1575 # name string
1576 # cname string
1577 # type PyrexType
1578 # pos source file position
1580 def __init__(self, name, type, pos, cname=None):
1581 self.name = name
1582 if cname is not None:
1583 self.cname = cname
1584 else:
1585 self.cname = Naming.var_prefix + name
1586 self.type = type
1587 self.pos = pos
1588 self.not_none = False
1589 self.needs_type_test = False # TODO: should these defaults be set in analyse_types()?
1591 def __repr__(self):
1592 return "%s:%s" % (self.name, repr(self.type))
1594 def declaration_code(self, for_display = 0):
1595 return self.type.declaration_code(self.cname, for_display)
1597 class StructUtilityCode(object):
1598 def __init__(self, type, forward_decl):
1599 self.type = type
1600 self.header = "static PyObject* %s(%s)" % (type.to_py_function, type.declaration_code('s'))
1601 self.forward_decl = forward_decl
1603 def __eq__(self, other):
1604 return isinstance(other, StructUtilityCode) and self.header == other.header
1605 def __hash__(self):
1606 return hash(self.header)
1608 def put_code(self, output):
1609 code = output['utility_code_def']
1610 proto = output['utility_code_proto']
1612 code.putln("%s {" % self.header)
1613 code.putln("PyObject* res;")
1614 code.putln("PyObject* member;")
1615 code.putln("res = PyDict_New(); if (res == NULL) return NULL;")
1616 for member in self.type.scope.var_entries:
1617 nameconst_cname = code.get_py_string_const(member.name, identifier=True)
1618 code.putln("member = %s(s.%s); if (member == NULL) goto bad;" % (
1619 member.type.to_py_function, member.cname))
1620 code.putln("if (PyDict_SetItem(res, %s, member) < 0) goto bad;" % nameconst_cname)
1621 code.putln("Py_DECREF(member);")
1622 code.putln("return res;")
1623 code.putln("bad:")
1624 code.putln("Py_XDECREF(member);")
1625 code.putln("Py_DECREF(res);")
1626 code.putln("return NULL;")
1627 code.putln("}")
1629 # This is a bit of a hack, we need a forward declaration
1630 # due to the way things are ordered in the module...
1631 if self.forward_decl:
1632 proto.putln(self.type.declaration_code('') + ';')
1633 proto.putln(self.header + ";")
1636 class CStructOrUnionType(CType):
1637 # name string
1638 # cname string
1639 # kind string "struct" or "union"
1640 # scope StructOrUnionScope, or None if incomplete
1641 # typedef_flag boolean
1642 # packed boolean
1644 # entry Entry
1646 is_struct_or_union = 1
1647 has_attributes = 1
1649 def __init__(self, name, kind, scope, typedef_flag, cname, packed=False):
1650 self.name = name
1651 self.cname = cname
1652 self.kind = kind
1653 self.scope = scope
1654 self.typedef_flag = typedef_flag
1655 self.is_struct = kind == 'struct'
1656 if self.is_struct:
1657 self.to_py_function = "%s_to_py_%s" % (Naming.convert_func_prefix, self.cname)
1658 self.exception_check = True
1659 self._convert_code = None
1660 self.packed = packed
1662 def create_to_py_utility_code(self, env):
1663 if env.outer_scope is None:
1664 return False
1666 if self._convert_code is False: return # tri-state-ish
1668 if self._convert_code is None:
1669 for member in self.scope.var_entries:
1670 if not member.type.to_py_function or not member.type.create_to_py_utility_code(env):
1671 self.to_py_function = None
1672 self._convert_code = False
1673 return False
1674 forward_decl = (self.entry.visibility != 'extern')
1675 self._convert_code = StructUtilityCode(self, forward_decl)
1677 env.use_utility_code(self._convert_code)
1678 return True
1680 def __repr__(self):
1681 return "<CStructOrUnionType %s %s%s>" % (self.name, self.cname,
1682 ("", " typedef")[self.typedef_flag])
1684 def declaration_code(self, entity_code,
1685 for_display = 0, dll_linkage = None, pyrex = 0):
1686 if pyrex:
1687 return self.base_declaration_code(self.name, entity_code)
1688 else:
1689 if for_display:
1690 base = self.name
1691 elif self.typedef_flag:
1692 base = self.cname
1693 else:
1694 base = "%s %s" % (self.kind, self.cname)
1695 return self.base_declaration_code(public_decl(base, dll_linkage), entity_code)
1697 def __eq__(self, other):
1698 try:
1699 return (isinstance(other, CStructOrUnionType) and
1700 self.name == other.name)
1701 except AttributeError:
1702 return False
1704 def __lt__(self, other):
1705 try:
1706 return self.name < other.name
1707 except AttributeError:
1708 # this is arbitrary, but it makes sure we always have
1709 # *some* kind of order
1710 return False
1712 def __hash__(self):
1713 return hash(self.cname) ^ hash(self.kind)
1715 def is_complete(self):
1716 return self.scope is not None
1718 def attributes_known(self):
1719 return self.is_complete()
1721 def can_be_complex(self):
1722 # Does the struct consist of exactly two identical floats?
1723 fields = self.scope.var_entries
1724 if len(fields) != 2: return False
1725 a, b = fields
1726 return (a.type.is_float and b.type.is_float and
1727 a.type.declaration_code("") ==
1728 b.type.declaration_code(""))
1730 def struct_nesting_depth(self):
1731 child_depths = [x.type.struct_nesting_depth()
1732 for x in self.scope.var_entries]
1733 return max(child_depths) + 1
1735 class CEnumType(CType):
1736 # name string
1737 # cname string or None
1738 # typedef_flag boolean
1740 is_enum = 1
1741 signed = 1
1742 rank = -1 # Ranks below any integer type
1743 to_py_function = "PyInt_FromLong"
1744 from_py_function = "PyInt_AsLong"
1746 def __init__(self, name, cname, typedef_flag):
1747 self.name = name
1748 self.cname = cname
1749 self.values = []
1750 self.typedef_flag = typedef_flag
1752 def __str__(self):
1753 return self.name
1755 def __repr__(self):
1756 return "<CEnumType %s %s%s>" % (self.name, self.cname,
1757 ("", " typedef")[self.typedef_flag])
1759 def declaration_code(self, entity_code,
1760 for_display = 0, dll_linkage = None, pyrex = 0):
1761 if pyrex:
1762 return self.base_declaration_code(self.cname, entity_code)
1763 else:
1764 if self.typedef_flag:
1765 base = self.cname
1766 else:
1767 base = "enum %s" % self.cname
1768 return self.base_declaration_code(public_decl(base, dll_linkage), entity_code)
1771 class CStringType(object):
1772 # Mixin class for C string types.
1774 is_string = 1
1775 is_unicode = 0
1777 to_py_function = "__Pyx_PyBytes_FromString"
1778 from_py_function = "__Pyx_PyBytes_AsString"
1779 exception_value = "NULL"
1781 def literal_code(self, value):
1782 assert isinstance(value, str)
1783 return '"%s"' % StringEncoding.escape_byte_string(value)
1786 class CUTF8CharArrayType(CStringType, CArrayType):
1787 # C 'char []' type.
1789 pymemberdef_typecode = "T_STRING_INPLACE"
1790 is_unicode = 1
1792 to_py_function = "PyUnicode_DecodeUTF8"
1793 exception_value = "NULL"
1795 def __init__(self, size):
1796 CArrayType.__init__(self, c_char_type, size)
1798 class CCharArrayType(CStringType, CArrayType):
1799 # C 'char []' type.
1801 pymemberdef_typecode = "T_STRING_INPLACE"
1803 def __init__(self, size):
1804 CArrayType.__init__(self, c_char_type, size)
1807 class CCharPtrType(CStringType, CPtrType):
1808 # C 'char *' type.
1810 pymemberdef_typecode = "T_STRING"
1812 def __init__(self):
1813 CPtrType.__init__(self, c_char_type)
1816 class CUCharPtrType(CStringType, CPtrType):
1817 # C 'unsigned char *' type.
1819 pymemberdef_typecode = "T_STRING"
1821 to_py_function = "__Pyx_PyBytes_FromUString"
1822 from_py_function = "__Pyx_PyBytes_AsUString"
1824 def __init__(self):
1825 CPtrType.__init__(self, c_uchar_type)
1828 class UnspecifiedType(PyrexType):
1829 # Used as a placeholder until the type can be determined.
1831 is_unspecified = 1
1833 def declaration_code(self, entity_code,
1834 for_display = 0, dll_linkage = None, pyrex = 0):
1835 return "<unspecified>"
1837 def same_as_resolved_type(self, other_type):
1838 return False
1841 class ErrorType(PyrexType):
1842 # Used to prevent propagation of error messages.
1844 is_error = 1
1845 exception_value = "0"
1846 exception_check = 0
1847 to_py_function = "dummy"
1848 from_py_function = "dummy"
1850 def create_to_py_utility_code(self, env):
1851 return True
1853 def create_from_py_utility_code(self, env):
1854 return True
1856 def declaration_code(self, entity_code,
1857 for_display = 0, dll_linkage = None, pyrex = 0):
1858 return "<error>"
1860 def same_as_resolved_type(self, other_type):
1861 return 1
1863 def error_condition(self, result_code):
1864 return "dummy"
1867 rank_to_type_name = (
1868 "char", # 0
1869 "short", # 1
1870 "int", # 2
1871 "long", # 3
1872 "Py_ssize_t", # 4
1873 "size_t", # 5
1874 "PY_LONG_LONG", # 6
1875 "float", # 7
1876 "double", # 8
1877 "long double", # 9
1878 )
1880 py_object_type = PyObjectType()
1882 c_void_type = CVoidType()
1883 c_void_ptr_type = CPtrType(c_void_type)
1884 c_void_ptr_ptr_type = CPtrType(c_void_ptr_type)
1886 c_uchar_type = CIntType(0, 0, "T_UBYTE")
1887 c_ushort_type = CIntType(1, 0, "T_USHORT")
1888 c_uint_type = CUIntType(2, 0, "T_UINT")
1889 c_ulong_type = CULongType(3, 0, "T_ULONG")
1890 c_ulonglong_type = CULongLongType(6, 0, "T_ULONGLONG")
1892 c_char_type = CIntType(0, 1, "T_CHAR")
1893 c_short_type = CIntType(1, 1, "T_SHORT")
1894 c_int_type = CIntType(2, 1, "T_INT")
1895 c_long_type = CLongType(3, 1, "T_LONG")
1896 c_longlong_type = CLongLongType(6, 1, "T_LONGLONG")
1897 c_bint_type = CBIntType(2, 1, "T_INT")
1899 c_schar_type = CIntType(0, 2, "T_CHAR")
1900 c_sshort_type = CIntType(1, 2, "T_SHORT")
1901 c_sint_type = CIntType(2, 2, "T_INT")
1902 c_slong_type = CLongType(3, 2, "T_LONG")
1903 c_slonglong_type = CLongLongType(6, 2, "T_LONGLONG")
1905 c_py_ssize_t_type = CPySSizeTType(4, 2, "T_PYSSIZET")
1906 c_size_t_type = CSizeTType(5, 0, "T_SIZET")
1908 c_float_type = CFloatType(7, "T_FLOAT", math_h_modifier='f')
1909 c_double_type = CFloatType(8, "T_DOUBLE")
1910 c_longdouble_type = CFloatType(9, math_h_modifier='l')
1912 c_double_complex_type = CComplexType(c_double_type)
1914 c_null_ptr_type = CNullPtrType(c_void_type)
1915 c_char_array_type = CCharArrayType(None)
1916 c_char_ptr_type = CCharPtrType()
1917 c_uchar_ptr_type = CUCharPtrType()
1918 c_utf8_char_array_type = CUTF8CharArrayType(None)
1919 c_char_ptr_ptr_type = CPtrType(c_char_ptr_type)
1920 c_int_ptr_type = CPtrType(c_int_type)
1921 c_py_ssize_t_ptr_type = CPtrType(c_py_ssize_t_type)
1922 c_size_t_ptr_type = CPtrType(c_size_t_type)
1924 c_returncode_type = CIntType(2, 1, "T_INT", is_returncode = 1)
1926 c_anon_enum_type = CAnonEnumType(-1, 1)
1928 # the Py_buffer type is defined in Builtin.py
1929 c_py_buffer_type = CStructOrUnionType("Py_buffer", "struct", None, 1, "Py_buffer")
1930 c_py_buffer_ptr_type = CPtrType(c_py_buffer_type)
1932 error_type = ErrorType()
1933 unspecified_type = UnspecifiedType()
1935 sign_and_rank_to_type = {
1936 #(signed, rank)
1937 (0, 0): c_uchar_type,
1938 (0, 1): c_ushort_type,
1939 (0, 2): c_uint_type,
1940 (0, 3): c_ulong_type,
1941 (0, 6): c_ulonglong_type,
1943 (1, 0): c_char_type,
1944 (1, 1): c_short_type,
1945 (1, 2): c_int_type,
1946 (1, 3): c_long_type,
1947 (1, 6): c_longlong_type,
1949 (2, 0): c_schar_type,
1950 (2, 1): c_sshort_type,
1951 (2, 2): c_sint_type,
1952 (2, 3): c_slong_type,
1953 (2, 6): c_slonglong_type,
1955 (0, 4): c_py_ssize_t_type,
1956 (1, 4): c_py_ssize_t_type,
1957 (2, 4): c_py_ssize_t_type,
1958 (0, 5): c_size_t_type,
1959 (1, 5): c_size_t_type,
1960 (2, 5): c_size_t_type,
1962 (1, 7): c_float_type,
1963 (1, 8): c_double_type,
1964 (1, 9): c_longdouble_type,
1965 # In case we're mixing unsigned ints and floats...
1966 (0, 7): c_float_type,
1967 (0, 8): c_double_type,
1968 (0, 9): c_longdouble_type,
1969 }
1971 modifiers_and_name_to_type = {
1972 #(signed, longness, name)
1973 (0, 0, "char"): c_uchar_type,
1974 (0, -1, "int"): c_ushort_type,
1975 (0, 0, "int"): c_uint_type,
1976 (0, 1, "int"): c_ulong_type,
1977 (0, 2, "int"): c_ulonglong_type,
1978 (1, 0, "void"): c_void_type,
1979 (1, 0, "char"): c_char_type,
1980 (1, -1, "int"): c_short_type,
1981 (1, 0, "int"): c_int_type,
1982 (1, 1, "int"): c_long_type,
1983 (1, 2, "int"): c_longlong_type,
1984 (1, 0, "float"): c_float_type,
1985 (1, 0, "double"): c_double_type,
1986 (1, 1, "double"): c_longdouble_type,
1987 (1, 0, "object"): py_object_type,
1988 (1, 0, "bint"): c_bint_type,
1989 (2, 0, "char"): c_schar_type,
1990 (2, -1, "int"): c_sshort_type,
1991 (2, 0, "int"): c_sint_type,
1992 (2, 1, "int"): c_slong_type,
1993 (2, 2, "int"): c_slonglong_type,
1995 (2, 0, "Py_ssize_t"): c_py_ssize_t_type,
1996 (0, 0, "size_t") : c_size_t_type,
1998 (1, 0, "long"): c_long_type,
1999 (1, 0, "short"): c_short_type,
2000 (1, 0, "longlong"): c_longlong_type,
2001 (1, 0, "bint"): c_bint_type,
2002 }
2004 def widest_numeric_type(type1, type2):
2005 # Given two numeric types, return the narrowest type
2006 # encompassing both of them.
2007 if type1 == type2:
2008 return type1
2009 if type1.is_complex:
2010 if type2.is_complex:
2011 return CComplexType(widest_numeric_type(type1.real_type, type2.real_type))
2012 else:
2013 return CComplexType(widest_numeric_type(type1.real_type, type2))
2014 elif type2.is_complex:
2015 return CComplexType(widest_numeric_type(type1, type2.real_type))
2016 if type1.is_enum and type2.is_enum:
2017 return c_int_type
2018 elif type1 is type2:
2019 return type1
2020 elif (type1.signed and type2.signed) or (not type1.signed and not type2.signed):
2021 if type2.rank > type1.rank:
2022 return type2
2023 else:
2024 return type1
2025 else:
2026 return sign_and_rank_to_type[min(type1.signed, type2.signed), max(type1.rank, type2.rank)]
2028 def spanning_type(type1, type2):
2029 # Return a type assignable from both type1 and type2.
2030 if type1 is py_object_type or type2 is py_object_type:
2031 return py_object_type
2032 elif type1 == type2:
2033 return type1
2034 elif type1.is_numeric and type2.is_numeric:
2035 return widest_numeric_type(type1, type2)
2036 elif type1.is_builtin_type and type1.name == 'float' and type2.is_numeric:
2037 return widest_numeric_type(c_double_type, type2)
2038 elif type2.is_builtin_type and type2.name == 'float' and type1.is_numeric:
2039 return widest_numeric_type(type1, c_double_type)
2040 elif type1.is_pyobject ^ type2.is_pyobject:
2041 return py_object_type
2042 elif type1.assignable_from(type2):
2043 if type1.is_extension_type and type1.typeobj_is_imported():
2044 # external types are unsafe, so we use PyObject instead
2045 return py_object_type
2046 return type1
2047 elif type2.assignable_from(type1):
2048 if type2.is_extension_type and type2.typeobj_is_imported():
2049 # external types are unsafe, so we use PyObject instead
2050 return py_object_type
2051 return type2
2052 else:
2053 return py_object_type
2055 def simple_c_type(signed, longness, name):
2056 # Find type descriptor for simple type given name and modifiers.
2057 # Returns None if arguments don't make sense.
2058 return modifiers_and_name_to_type.get((signed, longness, name))
2060 def parse_basic_type(name):
2061 base = None
2062 if name.startswith('p_'):
2063 base = parse_basic_type(name[2:])
2064 elif name.startswith('p'):
2065 base = parse_basic_type(name[1:])
2066 elif name.endswith('*'):
2067 base = parse_basic_type(name[:-1])
2068 if base:
2069 return CPtrType(base)
2070 elif name.startswith('u'):
2071 return simple_c_type(0, 0, name[1:])
2072 else:
2073 return simple_c_type(1, 0, name)
2075 def c_array_type(base_type, size):
2076 # Construct a C array type.
2077 if base_type is c_char_type:
2078 return CCharArrayType(size)
2079 elif base_type is error_type:
2080 return error_type
2081 else:
2082 return CArrayType(base_type, size)
2084 def c_ptr_type(base_type):
2085 # Construct a C pointer type.
2086 if base_type is c_char_type:
2087 return c_char_ptr_type
2088 elif base_type is c_uchar_type:
2089 return c_uchar_ptr_type
2090 elif base_type is error_type:
2091 return error_type
2092 else:
2093 return CPtrType(base_type)
2095 def same_type(type1, type2):
2096 return type1.same_as(type2)
2098 def assignable_from(type1, type2):
2099 return type1.assignable_from(type2)
2101 def typecast(to_type, from_type, expr_code):
2102 # Return expr_code cast to a C type which can be
2103 # assigned to to_type, assuming its existing C type
2104 # is from_type.
2105 if to_type is from_type or \
2106 (not to_type.is_pyobject and assignable_from(to_type, from_type)):
2107 return expr_code
2108 else:
2109 #print "typecast: to", to_type, "from", from_type ###
2110 return to_type.cast_code(expr_code)
2113 type_conversion_predeclarations = """
2114 /* Type Conversion Predeclarations */
2116 #if PY_MAJOR_VERSION < 3
2117 #define __Pyx_PyBytes_FromString PyString_FromString
2118 #define __Pyx_PyBytes_FromStringAndSize PyString_FromStringAndSize
2119 #define __Pyx_PyBytes_AsString PyString_AsString
2120 #else
2121 #define __Pyx_PyBytes_FromString PyBytes_FromString
2122 #define __Pyx_PyBytes_FromStringAndSize PyBytes_FromStringAndSize
2123 #define __Pyx_PyBytes_AsString PyBytes_AsString
2124 #endif
2126 #define __Pyx_PyBytes_FromUString(s) __Pyx_PyBytes_FromString((char*)s)
2127 #define __Pyx_PyBytes_AsUString(s) ((unsigned char*) __Pyx_PyBytes_AsString(s))
2129 #define __Pyx_PyBool_FromLong(b) ((b) ? (Py_INCREF(Py_True), Py_True) : (Py_INCREF(Py_False), Py_False))
2130 static CYTHON_INLINE int __Pyx_PyObject_IsTrue(PyObject*);
2131 static CYTHON_INLINE PyObject* __Pyx_PyNumber_Int(PyObject* x);
2133 #if !defined(T_PYSSIZET)
2134 #if PY_VERSION_HEX < 0x02050000
2135 #define T_PYSSIZET T_INT
2136 #elif !defined(T_LONGLONG)
2137 #define T_PYSSIZET \\
2138 ((sizeof(Py_ssize_t) == sizeof(int)) ? T_INT : \\
2139 ((sizeof(Py_ssize_t) == sizeof(long)) ? T_LONG : -1))
2140 #else
2141 #define T_PYSSIZET \\
2142 ((sizeof(Py_ssize_t) == sizeof(int)) ? T_INT : \\
2143 ((sizeof(Py_ssize_t) == sizeof(long)) ? T_LONG : \\
2144 ((sizeof(Py_ssize_t) == sizeof(PY_LONG_LONG)) ? T_LONGLONG : -1)))
2145 #endif
2146 #endif
2149 #if !defined(T_ULONGLONG)
2150 #define __Pyx_T_UNSIGNED_INT(x) \\
2151 ((sizeof(x) == sizeof(unsigned char)) ? T_UBYTE : \\
2152 ((sizeof(x) == sizeof(unsigned short)) ? T_USHORT : \\
2153 ((sizeof(x) == sizeof(unsigned int)) ? T_UINT : \\
2154 ((sizeof(x) == sizeof(unsigned long)) ? T_ULONG : -1))))
2155 #else
2156 #define __Pyx_T_UNSIGNED_INT(x) \\
2157 ((sizeof(x) == sizeof(unsigned char)) ? T_UBYTE : \\
2158 ((sizeof(x) == sizeof(unsigned short)) ? T_USHORT : \\
2159 ((sizeof(x) == sizeof(unsigned int)) ? T_UINT : \\
2160 ((sizeof(x) == sizeof(unsigned long)) ? T_ULONG : \\
2161 ((sizeof(x) == sizeof(unsigned PY_LONG_LONG)) ? T_ULONGLONG : -1)))))
2162 #endif
2163 #if !defined(T_LONGLONG)
2164 #define __Pyx_T_SIGNED_INT(x) \\
2165 ((sizeof(x) == sizeof(char)) ? T_BYTE : \\
2166 ((sizeof(x) == sizeof(short)) ? T_SHORT : \\
2167 ((sizeof(x) == sizeof(int)) ? T_INT : \\
2168 ((sizeof(x) == sizeof(long)) ? T_LONG : -1))))
2169 #else
2170 #define __Pyx_T_SIGNED_INT(x) \\
2171 ((sizeof(x) == sizeof(char)) ? T_BYTE : \\
2172 ((sizeof(x) == sizeof(short)) ? T_SHORT : \\
2173 ((sizeof(x) == sizeof(int)) ? T_INT : \\
2174 ((sizeof(x) == sizeof(long)) ? T_LONG : \\
2175 ((sizeof(x) == sizeof(PY_LONG_LONG)) ? T_LONGLONG : -1)))))
2176 #endif
2178 #define __Pyx_T_FLOATING(x) \\
2179 ((sizeof(x) == sizeof(float)) ? T_FLOAT : \\
2180 ((sizeof(x) == sizeof(double)) ? T_DOUBLE : -1))
2182 #if !defined(T_SIZET)
2183 #if !defined(T_ULONGLONG)
2184 #define T_SIZET \\
2185 ((sizeof(size_t) == sizeof(unsigned int)) ? T_UINT : \\
2186 ((sizeof(size_t) == sizeof(unsigned long)) ? T_ULONG : -1))
2187 #else
2188 #define T_SIZET \\
2189 ((sizeof(size_t) == sizeof(unsigned int)) ? T_UINT : \\
2190 ((sizeof(size_t) == sizeof(unsigned long)) ? T_ULONG : \\
2191 ((sizeof(size_t) == sizeof(unsigned PY_LONG_LONG)) ? T_ULONGLONG : -1)))
2192 #endif
2193 #endif
2195 static CYTHON_INLINE Py_ssize_t __Pyx_PyIndex_AsSsize_t(PyObject*);
2196 static CYTHON_INLINE PyObject * __Pyx_PyInt_FromSize_t(size_t);
2197 static CYTHON_INLINE size_t __Pyx_PyInt_AsSize_t(PyObject*);
2199 #define __pyx_PyFloat_AsDouble(x) (PyFloat_CheckExact(x) ? PyFloat_AS_DOUBLE(x) : PyFloat_AsDouble(x))
2201 """ + type_conversion_predeclarations
2203 type_conversion_functions = """
2204 /* Type Conversion Functions */
2206 static CYTHON_INLINE int __Pyx_PyObject_IsTrue(PyObject* x) {
2207 if (x == Py_True) return 1;
2208 else if ((x == Py_False) | (x == Py_None)) return 0;
2209 else return PyObject_IsTrue(x);
2210 }
2212 static CYTHON_INLINE PyObject* __Pyx_PyNumber_Int(PyObject* x) {
2213 PyNumberMethods *m;
2214 const char *name = NULL;
2215 PyObject *res = NULL;
2216 #if PY_VERSION_HEX < 0x03000000
2217 if (PyInt_Check(x) || PyLong_Check(x))
2218 #else
2219 if (PyLong_Check(x))
2220 #endif
2221 return Py_INCREF(x), x;
2222 m = Py_TYPE(x)->tp_as_number;
2223 #if PY_VERSION_HEX < 0x03000000
2224 if (m && m->nb_int) {
2225 name = "int";
2226 res = PyNumber_Int(x);
2227 }
2228 else if (m && m->nb_long) {
2229 name = "long";
2230 res = PyNumber_Long(x);
2231 }
2232 #else
2233 if (m && m->nb_int) {
2234 name = "int";
2235 res = PyNumber_Long(x);
2236 }
2237 #endif
2238 if (res) {
2239 #if PY_VERSION_HEX < 0x03000000
2240 if (!PyInt_Check(res) && !PyLong_Check(res)) {
2241 #else
2242 if (!PyLong_Check(res)) {
2243 #endif
2244 PyErr_Format(PyExc_TypeError,
2245 "__%s__ returned non-%s (type %.200s)",
2246 name, name, Py_TYPE(res)->tp_name);
2247 Py_DECREF(res);
2248 return NULL;
2249 }
2250 }
2251 else if (!PyErr_Occurred()) {
2252 PyErr_SetString(PyExc_TypeError,
2253 "an integer is required");
2254 }
2255 return res;
2256 }
2258 static CYTHON_INLINE Py_ssize_t __Pyx_PyIndex_AsSsize_t(PyObject* b) {
2259 Py_ssize_t ival;
2260 PyObject* x = PyNumber_Index(b);
2261 if (!x) return -1;
2262 ival = PyInt_AsSsize_t(x);
2263 Py_DECREF(x);
2264 return ival;
2265 }
2267 static CYTHON_INLINE PyObject * __Pyx_PyInt_FromSize_t(size_t ival) {
2268 #if PY_VERSION_HEX < 0x02050000
2269 if (ival <= LONG_MAX)
2270 return PyInt_FromLong((long)ival);
2271 else {
2272 unsigned char *bytes = (unsigned char *) &ival;
2273 int one = 1; int little = (int)*(unsigned char*)&one;
2274 return _PyLong_FromByteArray(bytes, sizeof(size_t), little, 0);
2275 }
2276 #else
2277 return PyInt_FromSize_t(ival);
2278 #endif
2279 }
2281 static CYTHON_INLINE size_t __Pyx_PyInt_AsSize_t(PyObject* x) {
2282 unsigned PY_LONG_LONG val = __Pyx_PyInt_AsUnsignedLongLong(x);
2283 if (unlikely(val == (unsigned PY_LONG_LONG)-1 && PyErr_Occurred())) {
2284 return (size_t)-1;
2285 } else if (unlikely(val != (unsigned PY_LONG_LONG)(size_t)val)) {
2286 PyErr_SetString(PyExc_OverflowError,
2287 "value too large to convert to size_t");
2288 return (size_t)-1;
2289 }
2290 return (size_t)val;
2291 }
2293 """ + type_conversion_functions
