5 from Code import UtilityCode
9 from Errors import error
11 class BaseType(object):
13 # Base class for all Pyrex types including pseudo-types.
15 def can_coerce_to_pyobject(self, env):
18 def cast_code(self, expr_code):
19 return "((%s)%s)" % (self.declaration_code(""), expr_code)
21 def specialization_name(self):
22 return self.declaration_code("").replace(" ", "__")
24 def base_declaration_code(self, base_code, entity_code):
26 return "%s %s" % (base_code, entity_code)
30 class PyrexType(BaseType):
32 # Base class for all Pyrex types.
34 # is_pyobject boolean Is a Python object type
35 # is_extension_type boolean Is a Python extension type
36 # is_numeric boolean Is a C numeric type
37 # is_int boolean Is a C integer type
38 # is_float boolean Is a C floating point type
39 # is_complex boolean Is a C complex type
40 # is_void boolean Is the C void type
41 # is_array boolean Is a C array type
42 # is_ptr boolean Is a C pointer type
43 # is_null_ptr boolean Is the type of NULL
44 # is_reference boolean Is a C reference type
45 # is_cfunction boolean Is a C function type
46 # is_struct_or_union boolean Is a C struct or union type
47 # is_struct boolean Is a C struct type
48 # is_enum boolean Is a C enum type
49 # is_typedef boolean Is a typedef type
50 # is_string boolean Is a C char * type
51 # is_unicode boolean Is a UTF-8 encoded C char * type
52 # is_unicode_char boolean Is either Py_UCS4 or Py_UNICODE
53 # is_returncode boolean Is used only to signal exceptions
54 # is_error boolean Is the dummy error type
55 # is_buffer boolean Is buffer access type
56 # has_attributes boolean Has C dot-selectable attributes
57 # default_value string Initial value
59 # declaration_code(entity_code,
60 # for_display = 0, dll_linkage = None, pyrex = 0)
61 # Returns a code fragment for the declaration of an entity
62 # of this type, given a code fragment for the entity.
63 # * If for_display, this is for reading by a human in an error
64 # message; otherwise it must be valid C code.
65 # * If dll_linkage is not None, it must be 'DL_EXPORT' or
66 # 'DL_IMPORT', and will be added to the base type part of
68 # * If pyrex = 1, this is for use in a 'cdef extern'
69 # statement of a Pyrex include file.
71 # assignable_from(src_type)
72 # Tests whether a variable of this type can be
73 # assigned a value of type src_type.
76 # Tests whether this type represents the same type
80 # Coerces array type into pointer type for use as
81 # a formal argument type.
98 is_struct_or_union = 0
113 # If a typedef, returns the base type.
116 def specialize(self, values):
117 # TODO(danilo): Override wherever it makes sense.
120 def literal_code(self, value):
121 # Returns a C code fragment representing a literal
122 # value of this type.
126 return self.declaration_code("", for_display = 1).strip()
128 def same_as(self, other_type, **kwds):
129 return self.same_as_resolved_type(other_type.resolve(), **kwds)
131 def same_as_resolved_type(self, other_type):
132 return self == other_type or other_type is error_type
134 def subtype_of(self, other_type):
135 return self.subtype_of_resolved_type(other_type.resolve())
137 def subtype_of_resolved_type(self, other_type):
138 return self.same_as(other_type)
140 def assignable_from(self, src_type):
141 return self.assignable_from_resolved_type(src_type.resolve())
143 def assignable_from_resolved_type(self, src_type):
144 return self.same_as(src_type)
146 def as_argument_type(self):
149 def is_complete(self):
150 # A type is incomplete if it is an unsized array,
151 # a struct whose attributes are not defined, etc.
154 def is_simple_buffer_dtype(self):
155 return (self.is_int or self.is_float or self.is_complex or self.is_pyobject or
156 self.is_extension_type or self.is_ptr)
158 def struct_nesting_depth(self):
159 # Returns the number levels of nested structs. This is
160 # used for constructing a stack for walking the run-time
161 # type information of the struct.
165 def public_decl(base_code, dll_linkage):
167 return "%s(%s)" % (dll_linkage, base_code)
171 def create_typedef_type(name, base_type, cname, is_external=0):
172 if base_type.is_complex:
174 raise ValueError("Complex external typedefs not supported")
177 return CTypedefType(name, base_type, cname, is_external)
180 class CTypedefType(BaseType):
182 # Pseudo-type defined with a ctypedef statement in a
183 # 'cdef extern from' block. Delegates most attribute
184 # lookups to the base type. ANYTHING NOT DEFINED
187 # qualified_name string
188 # typedef_name string
189 # typedef_cname string
190 # typedef_base_type PyrexType
191 # typedef_is_external bool
194 typedef_is_external = 0
196 to_py_utility_code = None
197 from_py_utility_code = None
200 def __init__(self, name, base_type, cname, is_external=0):
201 assert not base_type.is_complex
202 self.typedef_name = name
203 self.typedef_cname = cname
204 self.typedef_base_type = base_type
205 self.typedef_is_external = is_external
208 return self.typedef_base_type.resolve()
210 def declaration_code(self, entity_code,
211 for_display = 0, dll_linkage = None, pyrex = 0):
212 if pyrex or for_display:
213 base_code = self.typedef_name
215 base_code = public_decl(self.typedef_cname, dll_linkage)
216 return self.base_declaration_code(base_code, entity_code)
218 def as_argument_type(self):
221 def cast_code(self, expr_code):
222 # If self is really an array (rather than pointer), we can't cast.
223 # For example, the gmp mpz_t.
224 if self.typedef_base_type.is_array:
225 base_type = self.typedef_base_type.base_type
226 return CPtrType(base_type).cast_code(expr_code)
228 return BaseType.cast_code(self, expr_code)
231 return "<CTypedefType %s>" % self.typedef_cname
234 return self.typedef_name
236 def _create_utility_code(self, template_utility_code,
237 template_function_name):
238 type_name = self.typedef_cname.replace(" ","_").replace("::","__")
239 utility_code = template_utility_code.specialize(
240 type = self.typedef_cname,
241 TypeName = type_name)
242 function_name = template_function_name % type_name
243 return utility_code, function_name
245 def create_to_py_utility_code(self, env):
246 if self.typedef_is_external:
247 if not self.to_py_utility_code:
248 base_type = self.typedef_base_type
249 if type(base_type) is CIntType:
250 # Various subclasses have special methods
251 # that should be inherited.
252 self.to_py_utility_code, self.to_py_function = \
253 self._create_utility_code(c_typedef_int_to_py_function,
254 '__Pyx_PyInt_to_py_%s')
255 elif base_type.is_float:
256 pass # XXX implement!
257 elif base_type.is_complex:
258 pass # XXX implement!
260 if self.to_py_utility_code:
261 env.use_utility_code(self.to_py_utility_code)
264 return self.typedef_base_type.create_to_py_utility_code(env)
266 def create_from_py_utility_code(self, env):
267 if self.typedef_is_external:
268 if not self.from_py_utility_code:
269 base_type = self.typedef_base_type
270 if type(base_type) is CIntType:
271 # Various subclasses have special methods
272 # that should be inherited.
273 self.from_py_utility_code, self.from_py_function = \
274 self._create_utility_code(c_typedef_int_from_py_function,
275 '__Pyx_PyInt_from_py_%s')
276 elif base_type.is_float:
277 pass # XXX implement!
278 elif base_type.is_complex:
279 pass # XXX implement!
280 if self.from_py_utility_code:
281 env.use_utility_code(self.from_py_utility_code)
284 return self.typedef_base_type.create_from_py_utility_code(env)
286 def error_condition(self, result_code):
287 if self.typedef_is_external:
288 if self.exception_value:
289 condition = "(%s == (%s)%s)" % (
290 result_code, self.typedef_cname, self.exception_value)
291 if self.exception_check:
292 condition += " && PyErr_Occurred()"
295 return self.typedef_base_type.error_condition(result_code)
297 def __getattr__(self, name):
298 return getattr(self.typedef_base_type, name)
301 class BufferType(BaseType):
303 # Delegates most attribute
304 # lookups to the base type. ANYTHING NOT DEFINED
310 # negative_indices bool
317 def __init__(self, base, dtype, ndim, mode, negative_indices, cast):
321 self.buffer_ptr_type = CPtrType(dtype)
323 self.negative_indices = negative_indices
326 def as_argument_type(self):
329 def __getattr__(self, name):
330 return getattr(self.base, name)
333 return "<BufferType %r>" % self.base
336 class PyObjectType(PyrexType):
338 # Base class for all Python object types (reference-counted).
340 # buffer_defaults dict or None Default options for bu
345 buffer_defaults = None
347 is_subclassed = False
350 return "Python object"
353 return "<PyObjectType>"
355 def can_coerce_to_pyobject(self, env):
358 def default_coerced_ctype(self):
359 "The default C type that this Python type coerces to, or None."
362 def assignable_from(self, src_type):
363 # except for pointers, conversion will be attempted
364 return not src_type.is_ptr or src_type.is_string
366 def declaration_code(self, entity_code,
367 for_display = 0, dll_linkage = None, pyrex = 0):
368 if pyrex or for_display:
371 base_code = public_decl("PyObject", dll_linkage)
372 entity_code = "*%s" % entity_code
373 return self.base_declaration_code(base_code, entity_code)
375 def as_pyobject(self, cname):
376 if (not self.is_complete()) or self.is_extension_type:
377 return "(PyObject *)" + cname
381 class BuiltinObjectType(PyObjectType):
382 # objstruct_cname string Name of PyObject struct
387 module_name = '__builtin__'
389 # fields that let it look like an extension type
390 vtabslot_cname = None
391 vtabstruct_cname = None
396 def __init__(self, name, cname, objstruct_cname=None):
399 self.typeptr_cname = "(&%s)" % cname
400 self.objstruct_cname = objstruct_cname
402 def set_scope(self, scope):
405 scope.parent_type = self
408 return "%s object" % self.name
411 return "<%s>"% self.cname
413 def default_coerced_ctype(self):
414 if self.name == 'bytes':
415 return c_char_ptr_type
416 elif self.name == 'bool':
418 elif self.name == 'float':
422 def assignable_from(self, src_type):
423 if isinstance(src_type, BuiltinObjectType):
424 return src_type.name == self.name
425 elif src_type.is_extension_type:
426 return (src_type.module_name == '__builtin__' and
427 src_type.name == self.name)
431 def typeobj_is_available(self):
434 def attributes_known(self):
437 def subtype_of(self, type):
438 return type.is_pyobject and self.assignable_from(type)
440 def type_check_function(self, exact=True):
441 type_name = self.name
442 if type_name == 'str':
443 type_check = 'PyString_Check'
444 elif type_name == 'frozenset':
445 type_check = 'PyFrozenSet_Check'
447 type_check = 'Py%s_Check' % type_name.capitalize()
448 if exact and type_name not in ('bool', 'slice'):
449 type_check += 'Exact'
452 def isinstance_code(self, arg):
453 return '%s(%s)' % (self.type_check_function(exact=False), arg)
455 def type_test_code(self, arg, notnone=False):
456 type_check = self.type_check_function(exact=True)
457 check = 'likely(%s(%s))' % (type_check, arg)
459 check = check + ('||((%s) == Py_None)' % arg)
460 error = '(PyErr_Format(PyExc_TypeError, "Expected %s, got %%.200s", Py_TYPE(%s)->tp_name), 0)' % (self.name, arg)
461 return check + '||' + error
463 def declaration_code(self, entity_code,
464 for_display = 0, dll_linkage = None, pyrex = 0):
465 if pyrex or for_display:
466 base_code = self.name
468 base_code = public_decl("PyObject", dll_linkage)
469 entity_code = "*%s" % entity_code
470 return self.base_declaration_code(base_code, entity_code)
472 def cast_code(self, expr_code, to_object_struct = False):
473 return "((%s*)%s)" % (
474 to_object_struct and self.objstruct_cname or "PyObject", # self.objstruct_cname may be None
478 class PyExtensionType(PyObjectType):
480 # A Python extension type.
483 # scope CClassScope Attribute namespace
485 # typedef_flag boolean
486 # base_type PyExtensionType or None
487 # module_name string or None Qualified name of defining module
488 # objstruct_cname string Name of PyObject struct
489 # objtypedef_cname string Name of PyObject struct typedef
490 # typeobj_cname string or None C code fragment referring to type object
491 # typeptr_cname string or None Name of pointer to external type object
492 # vtabslot_cname string Name of C method table member
493 # vtabstruct_cname string Name of C method table struct
494 # vtabptr_cname string Name of pointer to C method table
495 # vtable_cname string Name of C method table definition
497 is_extension_type = 1
500 objtypedef_cname = None
502 def __init__(self, name, typedef_flag, base_type, is_external=0):
505 self.typedef_flag = typedef_flag
506 if base_type is not None:
507 base_type.is_subclassed = True
508 self.base_type = base_type
509 self.module_name = None
510 self.objstruct_cname = None
511 self.typeobj_cname = None
512 self.typeptr_cname = None
513 self.vtabslot_cname = None
514 self.vtabstruct_cname = None
515 self.vtabptr_cname = None
516 self.vtable_cname = None
517 self.is_external = is_external
519 def set_scope(self, scope):
522 scope.parent_type = self
524 def subtype_of_resolved_type(self, other_type):
525 if other_type.is_extension_type:
526 return self is other_type or (
527 self.base_type and self.base_type.subtype_of(other_type))
529 return other_type is py_object_type
531 def typeobj_is_available(self):
532 # Do we have a pointer to the type object?
533 return self.typeptr_cname
535 def typeobj_is_imported(self):
536 # If we don't know the C name of the type object but we do
537 # know which module it's defined in, it will be imported.
538 return self.typeobj_cname is None and self.module_name is not None
540 def assignable_from(self, src_type):
543 if isinstance(src_type, PyExtensionType):
544 if src_type.base_type is not None:
545 return self.assignable_from(src_type.base_type)
548 def declaration_code(self, entity_code,
549 for_display = 0, dll_linkage = None, pyrex = 0, deref = 0):
550 if pyrex or for_display:
551 base_code = self.name
553 if self.typedef_flag:
554 objstruct = self.objstruct_cname
556 objstruct = "struct %s" % self.objstruct_cname
557 base_code = public_decl(objstruct, dll_linkage)
559 assert not entity_code
561 entity_code = "*%s" % entity_code
562 return self.base_declaration_code(base_code, entity_code)
564 def type_test_code(self, py_arg, notnone=False):
566 none_check = "((%s) == Py_None)" % py_arg
567 type_check = "likely(__Pyx_TypeTest(%s, %s))" % (
568 py_arg, self.typeptr_cname)
572 return "likely(%s || %s)" % (none_check, type_check)
574 def attributes_known(self):
575 return self.scope is not None
581 return "<PyExtensionType %s%s>" % (self.scope.class_name,
582 ("", " typedef")[self.typedef_flag])
585 class CType(PyrexType):
587 # Base class for all C types (non-reference-counted).
589 # to_py_function string C function for converting to Python object
590 # from_py_function string C function for constructing from Python object
593 to_py_function = None
594 from_py_function = None
595 exception_value = None
598 def create_to_py_utility_code(self, env):
599 return self.to_py_function is not None
601 def create_from_py_utility_code(self, env):
602 return self.from_py_function is not None
604 def can_coerce_to_pyobject(self, env):
605 return self.create_to_py_utility_code(env)
607 def error_condition(self, result_code):
610 conds.append("(!%s)" % result_code)
611 elif self.exception_value is not None:
612 conds.append("(%s == (%s)%s)" % (result_code, self.sign_and_name(), self.exception_value))
613 if self.exception_check:
614 conds.append("PyErr_Occurred()")
616 return " && ".join(conds)
621 class CVoidType(CType):
631 def declaration_code(self, entity_code,
632 for_display = 0, dll_linkage = None, pyrex = 0):
633 if pyrex or for_display:
636 base_code = public_decl("void", dll_linkage)
637 return self.base_declaration_code(base_code, entity_code)
639 def is_complete(self):
643 class CNumericType(CType):
645 # Base class for all C numeric types.
647 # rank integer Relative size
648 # signed integer 0 = unsigned, 1 = unspecified, 2 = explicitly signed
653 has_attributes = True
656 sign_words = ("unsigned ", "", "signed ")
658 def __init__(self, rank, signed = 1):
662 def sign_and_name(self):
663 s = self.sign_words[self.signed]
664 n = rank_to_type_name[self.rank]
668 return "<CNumericType %s>" % self.sign_and_name()
670 def declaration_code(self, entity_code,
671 for_display = 0, dll_linkage = None, pyrex = 0):
672 type_name = self.sign_and_name()
673 if pyrex or for_display:
674 base_code = type_name.replace('PY_LONG_LONG', 'long long')
676 base_code = public_decl(type_name, dll_linkage)
677 return self.base_declaration_code(base_code, entity_code)
679 def attributes_known(self):
680 if self.scope is None:
682 self.scope = scope = Symtab.CClassScope(
686 scope.parent_type = self
687 scope.directives = {}
688 entry = scope.declare_cfunction(
690 CFuncType(self, [CFuncTypeArg("self", self, None)], nogil=True),
697 type_conversion_predeclarations = ""
698 type_conversion_functions = ""
700 c_int_from_py_function = UtilityCode(
702 static CYTHON_INLINE %(type)s __Pyx_PyInt_As%(SignWord)s%(TypeName)s(PyObject *);
705 static CYTHON_INLINE %(type)s __Pyx_PyInt_As%(SignWord)s%(TypeName)s(PyObject* x) {
706 const %(type)s neg_one = (%(type)s)-1, const_zero = 0;
707 const int is_unsigned = neg_one > const_zero;
708 if (sizeof(%(type)s) < sizeof(long)) {
709 long val = __Pyx_PyInt_AsLong(x);
710 if (unlikely(val != (long)(%(type)s)val)) {
711 if (!unlikely(val == -1 && PyErr_Occurred())) {
712 PyErr_SetString(PyExc_OverflowError,
713 (is_unsigned && unlikely(val < 0)) ?
714 "can't convert negative value to %(type)s" :
715 "value too large to convert to %(type)s");
719 return (%(type)s)val;
721 return (%(type)s)__Pyx_PyInt_As%(SignWord)sLong(x);
725 c_long_from_py_function = UtilityCode(
727 static CYTHON_INLINE %(type)s __Pyx_PyInt_As%(SignWord)s%(TypeName)s(PyObject *);
730 static CYTHON_INLINE %(type)s __Pyx_PyInt_As%(SignWord)s%(TypeName)s(PyObject* x) {
731 const %(type)s neg_one = (%(type)s)-1, const_zero = 0;
732 const int is_unsigned = neg_one > const_zero;
733 #if PY_VERSION_HEX < 0x03000000
734 if (likely(PyInt_Check(x))) {
735 long val = PyInt_AS_LONG(x);
736 if (is_unsigned && unlikely(val < 0)) {
737 PyErr_SetString(PyExc_OverflowError,
738 "can't convert negative value to %(type)s");
741 return (%(type)s)val;
744 if (likely(PyLong_Check(x))) {
746 if (unlikely(Py_SIZE(x) < 0)) {
747 PyErr_SetString(PyExc_OverflowError,
748 "can't convert negative value to %(type)s");
751 return PyLong_AsUnsigned%(TypeName)s(x);
753 return PyLong_As%(TypeName)s(x);
757 PyObject *tmp = __Pyx_PyNumber_Int(x);
758 if (!tmp) return (%(type)s)-1;
759 val = __Pyx_PyInt_As%(SignWord)s%(TypeName)s(tmp);
766 c_typedef_int_from_py_function = UtilityCode(
768 static CYTHON_INLINE %(type)s __Pyx_PyInt_from_py_%(TypeName)s(PyObject *);
771 static CYTHON_INLINE %(type)s __Pyx_PyInt_from_py_%(TypeName)s(PyObject* x) {
772 const %(type)s neg_one = (%(type)s)-1, const_zero = (%(type)s)0;
773 const int is_unsigned = const_zero < neg_one;
774 if (sizeof(%(type)s) == sizeof(char)) {
776 return (%(type)s)__Pyx_PyInt_AsUnsignedChar(x);
778 return (%(type)s)__Pyx_PyInt_AsSignedChar(x);
779 } else if (sizeof(%(type)s) == sizeof(short)) {
781 return (%(type)s)__Pyx_PyInt_AsUnsignedShort(x);
783 return (%(type)s)__Pyx_PyInt_AsSignedShort(x);
784 } else if (sizeof(%(type)s) == sizeof(int)) {
786 return (%(type)s)__Pyx_PyInt_AsUnsignedInt(x);
788 return (%(type)s)__Pyx_PyInt_AsSignedInt(x);
789 } else if (sizeof(%(type)s) == sizeof(long)) {
791 return (%(type)s)__Pyx_PyInt_AsUnsignedLong(x);
793 return (%(type)s)__Pyx_PyInt_AsSignedLong(x);
794 } else if (sizeof(%(type)s) == sizeof(PY_LONG_LONG)) {
796 return (%(type)s)__Pyx_PyInt_AsUnsignedLongLong(x);
798 return (%(type)s)__Pyx_PyInt_AsSignedLongLong(x);
801 PyObject *v = __Pyx_PyNumber_Int(x);
802 #if PY_VERSION_HEX < 0x03000000
803 if (likely(v) && !PyLong_Check(v)) {
805 v = PyNumber_Long(tmp);
810 int one = 1; int is_little = (int)*(unsigned char *)&one;
811 unsigned char *bytes = (unsigned char *)&val;
812 int ret = _PyLong_AsByteArray((PyLongObject *)v,
814 is_little, !is_unsigned);
824 c_typedef_int_to_py_function = UtilityCode(
826 static CYTHON_INLINE PyObject *__Pyx_PyInt_to_py_%(TypeName)s(%(type)s);
829 static CYTHON_INLINE PyObject *__Pyx_PyInt_to_py_%(TypeName)s(%(type)s val) {
830 const %(type)s neg_one = (%(type)s)-1, const_zero = (%(type)s)0;
831 const int is_unsigned = const_zero < neg_one;
832 if ((sizeof(%(type)s) == sizeof(char)) ||
833 (sizeof(%(type)s) == sizeof(short))) {
834 return PyInt_FromLong((long)val);
835 } else if ((sizeof(%(type)s) == sizeof(int)) ||
836 (sizeof(%(type)s) == sizeof(long))) {
838 return PyLong_FromUnsignedLong((unsigned long)val);
840 return PyInt_FromLong((long)val);
841 } else if (sizeof(%(type)s) == sizeof(PY_LONG_LONG)) {
843 return PyLong_FromUnsignedLongLong((unsigned PY_LONG_LONG)val);
845 return PyLong_FromLongLong((PY_LONG_LONG)val);
847 int one = 1; int little = (int)*(unsigned char *)&one;
848 unsigned char *bytes = (unsigned char *)&val;
849 return _PyLong_FromByteArray(bytes, sizeof(%(type)s),
850 little, !is_unsigned);
855 class CIntType(CNumericType):
859 to_py_function = None
860 from_py_function = None
863 def __init__(self, rank, signed = 1):
864 CNumericType.__init__(self, rank, signed)
865 if self.to_py_function is None:
866 self.to_py_function = self.get_to_py_type_conversion()
867 if self.from_py_function is None:
868 self.from_py_function = self.get_from_py_type_conversion()
870 def get_to_py_type_conversion(self):
871 if self.rank < list(rank_to_type_name).index('int'):
872 # This assumes sizeof(short) < sizeof(int)
873 return "PyInt_FromLong"
875 # Py{Int|Long}_From[Unsigned]Long[Long]
881 SignWord = "Unsigned"
882 if self.rank >= list(rank_to_type_name).index('PY_LONG_LONG'):
884 TypeName = "LongLong"
885 return "Py%s_From%s%s" % (Prefix, SignWord, TypeName)
887 def get_from_py_type_conversion(self):
888 type_name = rank_to_type_name[self.rank]
889 type_name = type_name.replace("PY_LONG_LONG", "long long")
890 TypeName = type_name.title().replace(" ", "")
891 SignWord = self.sign_words[self.signed].strip().title()
892 if self.rank >= list(rank_to_type_name).index('long'):
893 utility_code = c_long_from_py_function
895 utility_code = c_int_from_py_function
896 utility_code.specialize(self,
899 func_name = "__Pyx_PyInt_As%s%s" % (SignWord, TypeName)
902 def assignable_from_resolved_type(self, src_type):
903 return src_type.is_int or src_type.is_enum or src_type is error_type
906 class CAnonEnumType(CIntType):
910 def sign_and_name(self):
914 class CReturnCodeType(CIntType):
916 to_py_function = "__Pyx_Owned_Py_None"
921 class CBIntType(CIntType):
923 to_py_function = "__Pyx_PyBool_FromLong"
924 from_py_function = "__Pyx_PyObject_IsTrue"
925 exception_check = 1 # for C++ bool
928 return "<CNumericType bint>"
934 class CPyUCS4IntType(CIntType):
937 is_unicode_char = True
939 # Py_UCS4 coerces from and to single character unicode strings (or
940 # at most two characters on 16bit Unicode builds), but we also
941 # allow Python integers as input. The value range for Py_UCS4
942 # is 0..1114111, which is checked when converting from an integer
945 to_py_function = "PyUnicode_FromOrdinal"
946 from_py_function = "__Pyx_PyObject_AsPy_UCS4"
948 def create_from_py_utility_code(self, env):
949 env.use_utility_code(pyobject_as_py_ucs4_utility_code)
952 def sign_and_name(self):
956 pyobject_as_py_ucs4_utility_code = UtilityCode(
958 static CYTHON_INLINE Py_UCS4 __Pyx_PyObject_AsPy_UCS4(PyObject*);
961 static CYTHON_INLINE Py_UCS4 __Pyx_PyObject_AsPy_UCS4(PyObject* x) {
963 if (PyUnicode_Check(x)) {
964 if (likely(PyUnicode_GET_SIZE(x) == 1)) {
965 return PyUnicode_AS_UNICODE(x)[0];
967 #if Py_UNICODE_SIZE == 2
968 else if (PyUnicode_GET_SIZE(x) == 2) {
969 Py_UCS4 high_val = PyUnicode_AS_UNICODE(x)[0];
970 if (high_val >= 0xD800 && high_val <= 0xDBFF) {
971 Py_UCS4 low_val = PyUnicode_AS_UNICODE(x)[1];
972 if (low_val >= 0xDC00 && low_val <= 0xDFFF) {
973 return 0x10000 + (((high_val & ((1<<10)-1)) << 10) | (low_val & ((1<<10)-1)));
978 PyErr_Format(PyExc_ValueError,
979 "only single character unicode strings can be converted to Py_UCS4, got length "
980 #if PY_VERSION_HEX < 0x02050000
985 PyUnicode_GET_SIZE(x));
988 ival = __Pyx_PyInt_AsLong(x);
989 if (unlikely(ival < 0)) {
990 if (!PyErr_Occurred())
991 PyErr_SetString(PyExc_OverflowError,
992 "cannot convert negative value to Py_UCS4");
994 } else if (unlikely(ival > 1114111)) {
995 PyErr_SetString(PyExc_OverflowError,
996 "value too large to convert to Py_UCS4");
999 return (Py_UCS4)ival;
1004 class CPyUnicodeIntType(CIntType):
1007 is_unicode_char = True
1009 # Py_UNICODE coerces from and to single character unicode strings,
1010 # but we also allow Python integers as input. The value range for
1011 # Py_UNICODE is 0..1114111, which is checked when converting from
1014 to_py_function = "PyUnicode_FromOrdinal"
1015 from_py_function = "__Pyx_PyObject_AsPy_UNICODE"
1017 def create_from_py_utility_code(self, env):
1018 env.use_utility_code(pyobject_as_py_unicode_utility_code)
1021 def sign_and_name(self):
1024 pyobject_as_py_unicode_utility_code = UtilityCode(
1026 static CYTHON_INLINE Py_UNICODE __Pyx_PyObject_AsPy_UNICODE(PyObject*);
1029 static CYTHON_INLINE Py_UNICODE __Pyx_PyObject_AsPy_UNICODE(PyObject* x) {
1030 static long maxval = 0;
1032 if (PyUnicode_Check(x)) {
1033 if (unlikely(PyUnicode_GET_SIZE(x) != 1)) {
1034 PyErr_Format(PyExc_ValueError,
1035 "only single character unicode strings can be converted to Py_UNICODE, got length "
1036 #if PY_VERSION_HEX < 0x02050000
1041 PyUnicode_GET_SIZE(x));
1042 return (Py_UNICODE)-1;
1044 return PyUnicode_AS_UNICODE(x)[0];
1046 if (unlikely(!maxval))
1047 maxval = (long)PyUnicode_GetMax();
1048 ival = __Pyx_PyInt_AsLong(x);
1049 if (unlikely(ival < 0)) {
1050 if (!PyErr_Occurred())
1051 PyErr_SetString(PyExc_OverflowError,
1052 "cannot convert negative value to Py_UNICODE");
1053 return (Py_UNICODE)-1;
1054 } else if (unlikely(ival > maxval)) {
1055 PyErr_SetString(PyExc_OverflowError,
1056 "value too large to convert to Py_UNICODE");
1057 return (Py_UNICODE)-1;
1059 return (Py_UNICODE)ival;
1064 class CPyHashTType(CIntType):
1066 to_py_function = "__Pyx_PyInt_FromHash_t"
1067 from_py_function = "__Pyx_PyInt_AsHash_t"
1069 def sign_and_name(self):
1072 class CPySSizeTType(CIntType):
1074 to_py_function = "PyInt_FromSsize_t"
1075 from_py_function = "__Pyx_PyIndex_AsSsize_t"
1077 def sign_and_name(self):
1080 class CSSizeTType(CIntType):
1082 to_py_function = "PyInt_FromSsize_t"
1083 from_py_function = "PyInt_AsSsize_t"
1085 def sign_and_name(self):
1088 class CSizeTType(CIntType):
1090 to_py_function = "__Pyx_PyInt_FromSize_t"
1091 from_py_function = "__Pyx_PyInt_AsSize_t"
1093 def sign_and_name(self):
1097 class CFloatType(CNumericType):
1100 to_py_function = "PyFloat_FromDouble"
1101 from_py_function = "__pyx_PyFloat_AsDouble"
1103 exception_value = -1
1105 def __init__(self, rank, math_h_modifier = ''):
1106 CNumericType.__init__(self, rank, 1)
1107 self.math_h_modifier = math_h_modifier
1109 def assignable_from_resolved_type(self, src_type):
1110 return (src_type.is_numeric and not src_type.is_complex) or src_type is error_type
1113 class CComplexType(CNumericType):
1116 to_py_function = "__pyx_PyComplex_FromComplex"
1120 def __init__(self, real_type):
1121 while real_type.is_typedef and not real_type.typedef_is_external:
1122 real_type = real_type.typedef_base_type
1123 if real_type.is_typedef and real_type.typedef_is_external:
1124 # The below is not actually used: Coercions are currently disabled
1125 # so that complex types of external types can not be created
1126 self.funcsuffix = "_%s" % real_type.specialization_name()
1127 elif hasattr(real_type, 'math_h_modifier'):
1128 self.funcsuffix = real_type.math_h_modifier
1130 self.funcsuffix = "_%s" % real_type.specialization_name()
1132 self.real_type = real_type
1133 CNumericType.__init__(self, real_type.rank + 0.5, real_type.signed)
1135 self.from_parts = "%s_from_parts" % self.specialization_name()
1136 self.default_value = "%s(0, 0)" % self.from_parts
1138 def __eq__(self, other):
1139 if isinstance(self, CComplexType) and isinstance(other, CComplexType):
1140 return self.real_type == other.real_type
1144 def __ne__(self, other):
1145 if isinstance(self, CComplexType) and isinstance(other, CComplexType):
1146 return self.real_type != other.real_type
1150 def __lt__(self, other):
1151 if isinstance(self, CComplexType) and isinstance(other, CComplexType):
1152 return self.real_type < other.real_type
1154 # this is arbitrary, but it makes sure we always have
1155 # *some* kind of order
1159 return ~hash(self.real_type)
1161 def declaration_code(self, entity_code,
1162 for_display = 0, dll_linkage = None, pyrex = 0):
1163 if pyrex or for_display:
1164 real_code = self.real_type.declaration_code("", for_display, dll_linkage, pyrex)
1165 base_code = "%s complex" % real_code
1167 base_code = public_decl(self.sign_and_name(), dll_linkage)
1168 return self.base_declaration_code(base_code, entity_code)
1170 def sign_and_name(self):
1171 real_type_name = self.real_type.specialization_name()
1172 real_type_name = real_type_name.replace('long__double','long_double')
1173 real_type_name = real_type_name.replace('PY_LONG_LONG','long_long')
1174 return Naming.type_prefix + real_type_name + "_complex"
1176 def assignable_from(self, src_type):
1177 # Temporary hack/feature disabling, see #441
1178 if (not src_type.is_complex and src_type.is_numeric and src_type.is_typedef
1179 and src_type.typedef_is_external):
1182 return super(CComplexType, self).assignable_from(src_type)
1184 def assignable_from_resolved_type(self, src_type):
1185 return (src_type.is_complex and self.real_type.assignable_from_resolved_type(src_type.real_type)
1186 or src_type.is_numeric and self.real_type.assignable_from_resolved_type(src_type)
1187 or src_type is error_type)
1189 def attributes_known(self):
1190 if self.scope is None:
1192 self.scope = scope = Symtab.CClassScope(
1195 visibility="extern")
1196 scope.parent_type = self
1197 scope.directives = {}
1198 scope.declare_var("real", self.real_type, None, cname="real", is_cdef=True)
1199 scope.declare_var("imag", self.real_type, None, cname="imag", is_cdef=True)
1200 entry = scope.declare_cfunction(
1202 CFuncType(self, [CFuncTypeArg("self", self, None)], nogil=True),
1205 cname="__Pyx_c_conj%s" % self.funcsuffix)
1209 def create_declaration_utility_code(self, env):
1210 # This must always be run, because a single CComplexType instance can be shared
1211 # across multiple compilations (the one created in the module scope)
1212 env.use_utility_code(complex_header_utility_code)
1213 env.use_utility_code(complex_real_imag_utility_code)
1214 for utility_code in (complex_type_utility_code,
1215 complex_from_parts_utility_code,
1216 complex_arithmetic_utility_code):
1217 env.use_utility_code(
1218 utility_code.specialize(
1220 real_type = self.real_type.declaration_code(''),
1221 m = self.funcsuffix,
1222 is_float = self.real_type.is_float))
1225 def create_to_py_utility_code(self, env):
1226 env.use_utility_code(complex_real_imag_utility_code)
1227 env.use_utility_code(complex_to_py_utility_code)
1230 def create_from_py_utility_code(self, env):
1231 self.real_type.create_from_py_utility_code(env)
1233 for utility_code in (complex_from_parts_utility_code,
1234 complex_from_py_utility_code):
1235 env.use_utility_code(
1236 utility_code.specialize(
1238 real_type = self.real_type.declaration_code(''),
1239 m = self.funcsuffix,
1240 is_float = self.real_type.is_float))
1241 self.from_py_function = "__Pyx_PyComplex_As_" + self.specialization_name()
1244 def lookup_op(self, nargs, op):
1246 return self.binops[nargs, op]
1250 op_name = complex_ops[nargs, op]
1251 self.binops[nargs, op] = func_name = "__Pyx_c_%s%s" % (op_name, self.funcsuffix)
1256 def unary_op(self, op):
1257 return self.lookup_op(1, op)
1259 def binary_op(self, op):
1260 return self.lookup_op(2, op)
1264 (1, 'zero'): 'is_zero',
1272 complex_header_utility_code = UtilityCode(
1273 proto_block='h_code',
1275 #if !defined(CYTHON_CCOMPLEX)
1276 #if defined(__cplusplus)
1277 #define CYTHON_CCOMPLEX 1
1278 #elif defined(_Complex_I)
1279 #define CYTHON_CCOMPLEX 1
1281 #define CYTHON_CCOMPLEX 0
1289 #include <complex.h>
1293 #if CYTHON_CCOMPLEX && !defined(__cplusplus) && defined(__sun__) && defined(__GNUC__)
1295 #define _Complex_I 1.0fj
1299 complex_real_imag_utility_code = UtilityCode(
1303 #define __Pyx_CREAL(z) ((z).real())
1304 #define __Pyx_CIMAG(z) ((z).imag())
1306 #define __Pyx_CREAL(z) (__real__(z))
1307 #define __Pyx_CIMAG(z) (__imag__(z))
1310 #define __Pyx_CREAL(z) ((z).real)
1311 #define __Pyx_CIMAG(z) ((z).imag)
1314 #if defined(_WIN32) && defined(__cplusplus) && CYTHON_CCOMPLEX
1315 #define __Pyx_SET_CREAL(z,x) ((z).real(x))
1316 #define __Pyx_SET_CIMAG(z,y) ((z).imag(y))
1318 #define __Pyx_SET_CREAL(z,x) __Pyx_CREAL(z) = (x)
1319 #define __Pyx_SET_CIMAG(z,y) __Pyx_CIMAG(z) = (y)
1323 complex_type_utility_code = UtilityCode(
1324 proto_block='complex_type_declarations',
1328 typedef ::std::complex< %(real_type)s > %(type_name)s;
1330 typedef %(real_type)s _Complex %(type_name)s;
1333 typedef struct { %(real_type)s real, imag; } %(type_name)s;
1337 complex_from_parts_utility_code = UtilityCode(
1338 proto_block='utility_code_proto',
1340 static CYTHON_INLINE %(type)s %(type_name)s_from_parts(%(real_type)s, %(real_type)s);
1345 static CYTHON_INLINE %(type)s %(type_name)s_from_parts(%(real_type)s x, %(real_type)s y) {
1346 return ::std::complex< %(real_type)s >(x, y);
1349 static CYTHON_INLINE %(type)s %(type_name)s_from_parts(%(real_type)s x, %(real_type)s y) {
1350 return x + y*(%(type)s)_Complex_I;
1354 static CYTHON_INLINE %(type)s %(type_name)s_from_parts(%(real_type)s x, %(real_type)s y) {
1363 complex_to_py_utility_code = UtilityCode(
1365 #define __pyx_PyComplex_FromComplex(z) \\
1366 PyComplex_FromDoubles((double)__Pyx_CREAL(z), \\
1367 (double)__Pyx_CIMAG(z))
1370 complex_from_py_utility_code = UtilityCode(
1372 static %(type)s __Pyx_PyComplex_As_%(type_name)s(PyObject*);
1375 static %(type)s __Pyx_PyComplex_As_%(type_name)s(PyObject* o) {
1377 if (PyComplex_CheckExact(o))
1378 cval = ((PyComplexObject *)o)->cval;
1380 cval = PyComplex_AsCComplex(o);
1381 return %(type_name)s_from_parts(
1382 (%(real_type)s)cval.real,
1383 (%(real_type)s)cval.imag);
1387 complex_arithmetic_utility_code = UtilityCode(
1390 #define __Pyx_c_eq%(m)s(a, b) ((a)==(b))
1391 #define __Pyx_c_sum%(m)s(a, b) ((a)+(b))
1392 #define __Pyx_c_diff%(m)s(a, b) ((a)-(b))
1393 #define __Pyx_c_prod%(m)s(a, b) ((a)*(b))
1394 #define __Pyx_c_quot%(m)s(a, b) ((a)/(b))
1395 #define __Pyx_c_neg%(m)s(a) (-(a))
1397 #define __Pyx_c_is_zero%(m)s(z) ((z)==(%(real_type)s)0)
1398 #define __Pyx_c_conj%(m)s(z) (::std::conj(z))
1400 #define __Pyx_c_abs%(m)s(z) (::std::abs(z))
1401 #define __Pyx_c_pow%(m)s(a, b) (::std::pow(a, b))
1404 #define __Pyx_c_is_zero%(m)s(z) ((z)==0)
1405 #define __Pyx_c_conj%(m)s(z) (conj%(m)s(z))
1407 #define __Pyx_c_abs%(m)s(z) (cabs%(m)s(z))
1408 #define __Pyx_c_pow%(m)s(a, b) (cpow%(m)s(a, b))
1412 static CYTHON_INLINE int __Pyx_c_eq%(m)s(%(type)s, %(type)s);
1413 static CYTHON_INLINE %(type)s __Pyx_c_sum%(m)s(%(type)s, %(type)s);
1414 static CYTHON_INLINE %(type)s __Pyx_c_diff%(m)s(%(type)s, %(type)s);
1415 static CYTHON_INLINE %(type)s __Pyx_c_prod%(m)s(%(type)s, %(type)s);
1416 static CYTHON_INLINE %(type)s __Pyx_c_quot%(m)s(%(type)s, %(type)s);
1417 static CYTHON_INLINE %(type)s __Pyx_c_neg%(m)s(%(type)s);
1418 static CYTHON_INLINE int __Pyx_c_is_zero%(m)s(%(type)s);
1419 static CYTHON_INLINE %(type)s __Pyx_c_conj%(m)s(%(type)s);
1421 static CYTHON_INLINE %(real_type)s __Pyx_c_abs%(m)s(%(type)s);
1422 static CYTHON_INLINE %(type)s __Pyx_c_pow%(m)s(%(type)s, %(type)s);
1429 static CYTHON_INLINE int __Pyx_c_eq%(m)s(%(type)s a, %(type)s b) {
1430 return (a.real == b.real) && (a.imag == b.imag);
1432 static CYTHON_INLINE %(type)s __Pyx_c_sum%(m)s(%(type)s a, %(type)s b) {
1434 z.real = a.real + b.real;
1435 z.imag = a.imag + b.imag;
1438 static CYTHON_INLINE %(type)s __Pyx_c_diff%(m)s(%(type)s a, %(type)s b) {
1440 z.real = a.real - b.real;
1441 z.imag = a.imag - b.imag;
1444 static CYTHON_INLINE %(type)s __Pyx_c_prod%(m)s(%(type)s a, %(type)s b) {
1446 z.real = a.real * b.real - a.imag * b.imag;
1447 z.imag = a.real * b.imag + a.imag * b.real;
1450 static CYTHON_INLINE %(type)s __Pyx_c_quot%(m)s(%(type)s a, %(type)s b) {
1452 %(real_type)s denom = b.real * b.real + b.imag * b.imag;
1453 z.real = (a.real * b.real + a.imag * b.imag) / denom;
1454 z.imag = (a.imag * b.real - a.real * b.imag) / denom;
1457 static CYTHON_INLINE %(type)s __Pyx_c_neg%(m)s(%(type)s a) {
1463 static CYTHON_INLINE int __Pyx_c_is_zero%(m)s(%(type)s a) {
1464 return (a.real == 0) && (a.imag == 0);
1466 static CYTHON_INLINE %(type)s __Pyx_c_conj%(m)s(%(type)s a) {
1473 static CYTHON_INLINE %(real_type)s __Pyx_c_abs%(m)s(%(type)s z) {
1474 #if !defined(HAVE_HYPOT) || defined(_MSC_VER)
1475 return sqrt%(m)s(z.real*z.real + z.imag*z.imag);
1477 return hypot%(m)s(z.real, z.imag);
1480 static CYTHON_INLINE %(type)s __Pyx_c_pow%(m)s(%(type)s a, %(type)s b) {
1482 %(real_type)s r, lnr, theta, z_r, z_theta;
1483 if (b.imag == 0 && b.real == (int)b.real) {
1485 %(real_type)s denom = a.real * a.real + a.imag * a.imag;
1486 a.real = a.real / denom;
1487 a.imag = -a.imag / denom;
1490 switch ((int)b.real) {
1498 z = __Pyx_c_prod%(m)s(a, a);
1499 return __Pyx_c_prod%(m)s(a, a);
1501 z = __Pyx_c_prod%(m)s(a, a);
1502 return __Pyx_c_prod%(m)s(z, a);
1504 z = __Pyx_c_prod%(m)s(a, a);
1505 return __Pyx_c_prod%(m)s(z, z);
1515 r = __Pyx_c_abs%(m)s(a);
1516 theta = atan2%(m)s(a.imag, a.real);
1519 z_r = exp%(m)s(lnr * b.real - theta * b.imag);
1520 z_theta = theta * b.real + lnr * b.imag;
1521 z.real = z_r * cos%(m)s(z_theta);
1522 z.imag = z_r * sin%(m)s(z_theta);
1529 class CArrayType(CType):
1530 # base_type CType Element type
1531 # size integer or None Number of elements
1535 def __init__(self, base_type, size):
1536 self.base_type = base_type
1538 if base_type in (c_char_type, c_uchar_type, c_schar_type):
1542 return "<CArrayType %s %s>" % (self.size, repr(self.base_type))
1544 def same_as_resolved_type(self, other_type):
1545 return ((other_type.is_array and
1546 self.base_type.same_as(other_type.base_type))
1547 or other_type is error_type)
1549 def assignable_from_resolved_type(self, src_type):
1550 # Can't assign to a variable of an array type
1553 def element_ptr_type(self):
1554 return c_ptr_type(self.base_type)
1556 def declaration_code(self, entity_code,
1557 for_display = 0, dll_linkage = None, pyrex = 0):
1558 if self.size is not None:
1559 dimension_code = self.size
1562 if entity_code.startswith("*"):
1563 entity_code = "(%s)" % entity_code
1564 return self.base_type.declaration_code(
1565 "%s[%s]" % (entity_code, dimension_code),
1566 for_display, dll_linkage, pyrex)
1568 def as_argument_type(self):
1569 return c_ptr_type(self.base_type)
1571 def is_complete(self):
1572 return self.size is not None
1575 class CPtrType(CType):
1576 # base_type CType Referenced type
1581 def __init__(self, base_type):
1582 self.base_type = base_type
1585 return "<CPtrType %s>" % repr(self.base_type)
1587 def same_as_resolved_type(self, other_type):
1588 return ((other_type.is_ptr and
1589 self.base_type.same_as(other_type.base_type))
1590 or other_type is error_type)
1592 def declaration_code(self, entity_code,
1593 for_display = 0, dll_linkage = None, pyrex = 0):
1594 #print "CPtrType.declaration_code: pointer to", self.base_type ###
1595 return self.base_type.declaration_code(
1596 "*%s" % entity_code,
1597 for_display, dll_linkage, pyrex)
1599 def assignable_from_resolved_type(self, other_type):
1600 if other_type is error_type:
1602 if other_type.is_null_ptr:
1604 if self.base_type.is_cfunction:
1605 if other_type.is_ptr:
1606 other_type = other_type.base_type.resolve()
1607 if other_type.is_cfunction:
1608 return self.base_type.pointer_assignable_from_resolved_type(other_type)
1611 if (self.base_type.is_cpp_class and other_type.is_ptr
1612 and other_type.base_type.is_cpp_class and other_type.base_type.is_subclass(self.base_type)):
1614 if other_type.is_array or other_type.is_ptr:
1615 return self.base_type.is_void or self.base_type.same_as(other_type.base_type)
1618 def specialize(self, values):
1619 base_type = self.base_type.specialize(values)
1620 if base_type == self.base_type:
1623 return CPtrType(base_type)
1626 class CNullPtrType(CPtrType):
1631 class CReferenceType(BaseType):
1635 def __init__(self, base_type):
1636 self.ref_base_type = base_type
1639 return "<CReferenceType %s>" % repr(self.ref_base_type)
1642 return "%s &" % self.ref_base_type
1644 def as_argument_type(self):
1647 def declaration_code(self, entity_code,
1648 for_display = 0, dll_linkage = None, pyrex = 0):
1649 #print "CReferenceType.declaration_code: pointer to", self.base_type ###
1650 return self.ref_base_type.declaration_code(
1651 "&%s" % entity_code,
1652 for_display, dll_linkage, pyrex)
1654 def specialize(self, values):
1655 base_type = self.ref_base_type.specialize(values)
1656 if base_type == self.ref_base_type:
1659 return CReferenceType(base_type)
1661 def __getattr__(self, name):
1662 return getattr(self.ref_base_type, name)
1665 class CFuncType(CType):
1667 # args [CFuncTypeArg]
1668 # has_varargs boolean
1669 # exception_value string
1670 # exception_check boolean True if PyErr_Occurred check needed
1671 # calling_convention string Function calling convention
1672 # nogil boolean Can be called without gil
1673 # with_gil boolean Acquire gil around function body
1674 # templates [string] or None
1679 def __init__(self, return_type, args, has_varargs = 0,
1680 exception_value = None, exception_check = 0, calling_convention = "",
1681 nogil = 0, with_gil = 0, is_overridable = 0, optional_arg_count = 0,
1683 self.return_type = return_type
1685 self.has_varargs = has_varargs
1686 self.optional_arg_count = optional_arg_count
1687 self.exception_value = exception_value
1688 self.exception_check = exception_check
1689 self.calling_convention = calling_convention
1691 self.with_gil = with_gil
1692 self.is_overridable = is_overridable
1693 self.templates = templates
1696 arg_reprs = map(repr, self.args)
1697 if self.has_varargs:
1698 arg_reprs.append("...")
1699 if self.exception_value:
1700 except_clause = " %r" % self.exception_value
1703 if self.exception_check:
1704 except_clause += "?"
1705 return "<CFuncType %s %s[%s]%s>" % (
1706 repr(self.return_type),
1707 self.calling_convention_prefix(),
1708 ",".join(arg_reprs),
1711 def calling_convention_prefix(self):
1712 cc = self.calling_convention
1718 def same_c_signature_as(self, other_type, as_cmethod = 0):
1719 return self.same_c_signature_as_resolved_type(
1720 other_type.resolve(), as_cmethod)
1722 def same_c_signature_as_resolved_type(self, other_type, as_cmethod = 0):
1723 #print "CFuncType.same_c_signature_as_resolved_type:", \
1724 # self, other_type, "as_cmethod =", as_cmethod ###
1725 if other_type is error_type:
1727 if not other_type.is_cfunction:
1729 if self.is_overridable != other_type.is_overridable:
1731 nargs = len(self.args)
1732 if nargs != len(other_type.args):
1734 # When comparing C method signatures, the first argument
1735 # is exempt from compatibility checking (the proper check
1736 # is performed elsewhere).
1737 for i in range(as_cmethod, nargs):
1738 if not self.args[i].type.same_as(
1739 other_type.args[i].type):
1741 if self.has_varargs != other_type.has_varargs:
1743 if self.optional_arg_count != other_type.optional_arg_count:
1745 if not self.return_type.same_as(other_type.return_type):
1747 if not self.same_calling_convention_as(other_type):
1751 def compatible_signature_with(self, other_type, as_cmethod = 0):
1752 return self.compatible_signature_with_resolved_type(other_type.resolve(), as_cmethod)
1754 def compatible_signature_with_resolved_type(self, other_type, as_cmethod):
1755 #print "CFuncType.same_c_signature_as_resolved_type:", \
1756 # self, other_type, "as_cmethod =", as_cmethod ###
1757 if other_type is error_type:
1759 if not other_type.is_cfunction:
1761 if not self.is_overridable and other_type.is_overridable:
1763 nargs = len(self.args)
1764 if nargs - self.optional_arg_count != len(other_type.args) - other_type.optional_arg_count:
1766 if self.optional_arg_count < other_type.optional_arg_count:
1768 # When comparing C method signatures, the first argument
1769 # is exempt from compatibility checking (the proper check
1770 # is performed elsewhere).
1771 for i in range(as_cmethod, len(other_type.args)):
1772 if not self.args[i].type.same_as(
1773 other_type.args[i].type):
1775 if self.has_varargs != other_type.has_varargs:
1777 if not self.return_type.subtype_of_resolved_type(other_type.return_type):
1779 if not self.same_calling_convention_as(other_type):
1781 if self.nogil != other_type.nogil:
1783 self.original_sig = other_type.original_sig or other_type
1785 self.args[0] = other_type.args[0]
1789 def narrower_c_signature_than(self, other_type, as_cmethod = 0):
1790 return self.narrower_c_signature_than_resolved_type(other_type.resolve(), as_cmethod)
1792 def narrower_c_signature_than_resolved_type(self, other_type, as_cmethod):
1793 if other_type is error_type:
1795 if not other_type.is_cfunction:
1797 nargs = len(self.args)
1798 if nargs != len(other_type.args):
1800 for i in range(as_cmethod, nargs):
1801 if not self.args[i].type.subtype_of_resolved_type(other_type.args[i].type):
1804 self.args[i].needs_type_test = other_type.args[i].needs_type_test \
1805 or not self.args[i].type.same_as(other_type.args[i].type)
1806 if self.has_varargs != other_type.has_varargs:
1808 if self.optional_arg_count != other_type.optional_arg_count:
1810 if not self.return_type.subtype_of_resolved_type(other_type.return_type):
1814 def same_calling_convention_as(self, other):
1815 ## XXX Under discussion ...
1816 ## callspec_words = ("__stdcall", "__cdecl", "__fastcall")
1817 ## cs1 = self.calling_convention
1818 ## cs2 = other.calling_convention
1819 ## if (cs1 in callspec_words or
1820 ## cs2 in callspec_words):
1821 ## return cs1 == cs2
1824 sc1 = self.calling_convention == '__stdcall'
1825 sc2 = other.calling_convention == '__stdcall'
1828 def same_exception_signature_as(self, other_type):
1829 return self.same_exception_signature_as_resolved_type(
1830 other_type.resolve())
1832 def same_exception_signature_as_resolved_type(self, other_type):
1833 return self.exception_value == other_type.exception_value \
1834 and self.exception_check == other_type.exception_check
1836 def same_as_resolved_type(self, other_type, as_cmethod = 0):
1837 return self.same_c_signature_as_resolved_type(other_type, as_cmethod) \
1838 and self.same_exception_signature_as_resolved_type(other_type) \
1839 and self.nogil == other_type.nogil
1841 def pointer_assignable_from_resolved_type(self, other_type):
1842 return self.same_c_signature_as_resolved_type(other_type) \
1843 and self.same_exception_signature_as_resolved_type(other_type) \
1844 and not (self.nogil and not other_type.nogil)
1846 def declaration_code(self, entity_code,
1847 for_display = 0, dll_linkage = None, pyrex = 0,
1848 with_calling_convention = 1):
1850 for arg in self.args[:len(self.args)-self.optional_arg_count]:
1851 arg_decl_list.append(
1852 arg.type.declaration_code("", for_display, pyrex = pyrex))
1853 if self.is_overridable:
1854 arg_decl_list.append("int %s" % Naming.skip_dispatch_cname)
1855 if self.optional_arg_count:
1856 arg_decl_list.append(self.op_arg_struct.declaration_code(Naming.optional_args_cname))
1857 if self.has_varargs:
1858 arg_decl_list.append("...")
1859 arg_decl_code = ", ".join(arg_decl_list)
1860 if not arg_decl_code and not pyrex:
1861 arg_decl_code = "void"
1863 if (pyrex or for_display) and not self.return_type.is_pyobject:
1864 if self.exception_value and self.exception_check:
1865 trailer = " except? %s" % self.exception_value
1866 elif self.exception_value:
1867 trailer = " except %s" % self.exception_value
1868 elif self.exception_check == '+':
1869 trailer = " except +"
1871 " except *" # ignored
1874 if not with_calling_convention:
1877 cc = self.calling_convention_prefix()
1878 if (not entity_code and cc) or entity_code.startswith("*"):
1879 entity_code = "(%s%s)" % (cc, entity_code)
1881 return self.return_type.declaration_code(
1882 "%s%s(%s)%s" % (cc, entity_code, arg_decl_code, trailer),
1883 for_display, dll_linkage, pyrex)
1885 def function_header_code(self, func_name, arg_code):
1886 return "%s%s(%s)" % (self.calling_convention_prefix(),
1887 func_name, arg_code)
1889 def signature_string(self):
1890 s = self.declaration_code("")
1893 def signature_cast_string(self):
1894 s = self.declaration_code("(*)", with_calling_convention=False)
1897 def specialize(self, values):
1898 if self.templates is None:
1899 new_templates = None
1901 new_templates = [v.specialize(values) for v in self.templates]
1902 return CFuncType(self.return_type.specialize(values),
1903 [arg.specialize(values) for arg in self.args],
1905 exception_value = self.exception_value,
1906 exception_check = self.exception_check,
1907 calling_convention = self.calling_convention,
1909 with_gil = self.with_gil,
1910 is_overridable = self.is_overridable,
1911 optional_arg_count = self.optional_arg_count,
1912 templates = new_templates)
1914 def opt_arg_cname(self, arg_name):
1915 return self.op_arg_struct.base_type.scope.lookup(arg_name).cname
1918 class CFuncTypeArg(object):
1922 # pos source file position
1924 # FIXME: is this the right setup? should None be allowed here?
1929 def __init__(self, name, type, pos, cname=None):
1931 if cname is not None:
1934 self.cname = Naming.var_prefix + name
1937 self.needs_type_test = False # TODO: should these defaults be set in analyse_types()?
1940 return "%s:%s" % (self.name, repr(self.type))
1942 def declaration_code(self, for_display = 0):
1943 return self.type.declaration_code(self.cname, for_display)
1945 def specialize(self, values):
1946 return CFuncTypeArg(self.name, self.type.specialize(values), self.pos, self.cname)
1948 class StructUtilityCode(object):
1949 def __init__(self, type, forward_decl):
1951 self.header = "static PyObject* %s(%s)" % (type.to_py_function, type.declaration_code('s'))
1952 self.forward_decl = forward_decl
1954 def __eq__(self, other):
1955 return isinstance(other, StructUtilityCode) and self.header == other.header
1957 return hash(self.header)
1959 def put_code(self, output):
1960 code = output['utility_code_def']
1961 proto = output['utility_code_proto']
1963 code.putln("%s {" % self.header)
1964 code.putln("PyObject* res;")
1965 code.putln("PyObject* member;")
1966 code.putln("res = PyDict_New(); if (res == NULL) return NULL;")
1967 for member in self.type.scope.var_entries:
1968 nameconst_cname = code.get_py_string_const(member.name, identifier=True)
1969 code.putln("member = %s(s.%s); if (member == NULL) goto bad;" % (
1970 member.type.to_py_function, member.cname))
1971 code.putln("if (PyDict_SetItem(res, %s, member) < 0) goto bad;" % nameconst_cname)
1972 code.putln("Py_DECREF(member);")
1973 code.putln("return res;")
1975 code.putln("Py_XDECREF(member);")
1976 code.putln("Py_DECREF(res);")
1977 code.putln("return NULL;")
1980 # This is a bit of a hack, we need a forward declaration
1981 # due to the way things are ordered in the module...
1982 if self.forward_decl:
1983 proto.putln(self.type.declaration_code('') + ';')
1984 proto.putln(self.header + ";")
1987 class CStructOrUnionType(CType):
1990 # kind string "struct" or "union"
1991 # scope StructOrUnionScope, or None if incomplete
1992 # typedef_flag boolean
1997 is_struct_or_union = 1
2000 def __init__(self, name, kind, scope, typedef_flag, cname, packed=False):
2005 self.typedef_flag = typedef_flag
2006 self.is_struct = kind == 'struct'
2008 self.to_py_function = "%s_to_py_%s" % (Naming.convert_func_prefix, self.cname)
2009 self.exception_check = True
2010 self._convert_code = None
2011 self.packed = packed
2013 def create_to_py_utility_code(self, env):
2014 if env.outer_scope is None:
2017 if self._convert_code is False: return # tri-state-ish
2019 if self._convert_code is None:
2020 for member in self.scope.var_entries:
2021 if not member.type.to_py_function or not member.type.create_to_py_utility_code(env):
2022 self.to_py_function = None
2023 self._convert_code = False
2025 forward_decl = (self.entry.visibility != 'extern')
2026 self._convert_code = StructUtilityCode(self, forward_decl)
2028 env.use_utility_code(self._convert_code)
2032 return "<CStructOrUnionType %s %s%s>" % (self.name, self.cname,
2033 ("", " typedef")[self.typedef_flag])
2035 def declaration_code(self, entity_code,
2036 for_display = 0, dll_linkage = None, pyrex = 0):
2037 if pyrex or for_display:
2038 base_code = self.name
2040 if self.typedef_flag:
2041 base_code = self.cname
2043 base_code = "%s %s" % (self.kind, self.cname)
2044 base_code = public_decl(base_code, dll_linkage)
2045 return self.base_declaration_code(base_code, entity_code)
2047 def __eq__(self, other):
2049 return (isinstance(other, CStructOrUnionType) and
2050 self.name == other.name)
2051 except AttributeError:
2054 def __lt__(self, other):
2056 return self.name < other.name
2057 except AttributeError:
2058 # this is arbitrary, but it makes sure we always have
2059 # *some* kind of order
2063 return hash(self.cname) ^ hash(self.kind)
2065 def is_complete(self):
2066 return self.scope is not None
2068 def attributes_known(self):
2069 return self.is_complete()
2071 def can_be_complex(self):
2072 # Does the struct consist of exactly two identical floats?
2073 fields = self.scope.var_entries
2074 if len(fields) != 2: return False
2076 return (a.type.is_float and b.type.is_float and
2077 a.type.declaration_code("") ==
2078 b.type.declaration_code(""))
2080 def struct_nesting_depth(self):
2081 child_depths = [x.type.struct_nesting_depth()
2082 for x in self.scope.var_entries]
2083 return max(child_depths) + 1
2085 class CppClassType(CType):
2088 # scope CppClassScope
2089 # templates [string] or None
2093 exception_check = True
2096 def __init__(self, name, scope, cname, base_classes, templates = None, template_type = None):
2100 self.base_classes = base_classes
2102 self.templates = templates
2103 self.template_type = template_type
2104 self.specializations = {}
2106 def specialize_here(self, pos, template_values = None):
2107 if self.templates is None:
2108 error(pos, "'%s' type is not a template" % self);
2109 return PyrexTypes.error_type
2110 if len(self.templates) != len(template_values):
2111 error(pos, "%s templated type receives %d arguments, got %d" %
2112 (self.name, len(self.templates), len(template_values)))
2114 return self.specialize(dict(zip(self.templates, template_values)))
2116 def specialize(self, values):
2117 if not self.templates and not self.namespace:
2119 if self.templates is None:
2121 key = tuple(values.items())
2122 if key in self.specializations:
2123 return self.specializations[key]
2124 template_values = [t.specialize(values) for t in self.templates]
2125 specialized = self.specializations[key] = \
2126 CppClassType(self.name, None, self.cname, [], template_values, template_type=self)
2127 # Need to do these *after* self.specializations[key] is set
2128 # to avoid infinite recursion on circular references.
2129 specialized.base_classes = [b.specialize(values) for b in self.base_classes]
2130 specialized.scope = self.scope.specialize(values)
2131 if self.namespace is not None:
2132 specialized.namespace = self.namespace.specialize(values)
2135 def declaration_code(self, entity_code,
2136 for_display = 0, dll_linkage = None, pyrex = 0):
2138 template_strings = [param.declaration_code('', for_display, None, pyrex)
2139 for param in self.templates]
2140 templates = "<%s>" % ",".join(template_strings)
2141 if templates[-2:] == ">>":
2142 templates = templates[:-2] + "> >"
2145 if pyrex or for_display:
2146 base_code = "%s%s" % (self.name, templates)
2148 base_code = "%s%s" % (self.cname, templates)
2149 if self.namespace is not None:
2150 base_code = "%s::%s" % (self.namespace.declaration_code(''), base_code)
2151 base_code = public_decl(base_code, dll_linkage)
2152 return self.base_declaration_code(base_code, entity_code)
2154 def is_subclass(self, other_type):
2155 # TODO(danilo): Handle templates.
2156 if self.same_as_resolved_type(other_type):
2158 for base_class in self.base_classes:
2159 if base_class.is_subclass(other_type):
2163 def same_as_resolved_type(self, other_type):
2164 if other_type.is_cpp_class:
2165 if self == other_type:
2167 elif self.template_type and self.template_type == other_type.template_type:
2168 if self.templates == other_type.templates:
2170 for t1, t2 in zip(self.templates, other_type.templates):
2171 if not t1.same_as_resolved_type(t2):
2176 def assignable_from_resolved_type(self, other_type):
2177 # TODO: handle operator=(...) here?
2178 if other_type is error_type:
2180 return other_type.is_cpp_class and other_type.is_subclass(self)
2182 def attributes_known(self):
2183 return self.scope is not None
2186 class TemplatePlaceholderType(CType):
2188 def __init__(self, name):
2191 def declaration_code(self, entity_code,
2192 for_display = 0, dll_linkage = None, pyrex = 0):
2194 return self.name + " " + entity_code
2198 def specialize(self, values):
2204 def same_as_resolved_type(self, other_type):
2205 if isinstance(other_type, TemplatePlaceholderType):
2206 return self.name == other_type.name
2211 return hash(self.name)
2213 def __cmp__(self, other):
2214 if isinstance(other, TemplatePlaceholderType):
2215 return cmp(self.name, other.name)
2217 return cmp(type(self), type(other))
2219 class CEnumType(CType):
2221 # cname string or None
2222 # typedef_flag boolean
2226 rank = -1 # Ranks below any integer type
2227 to_py_function = "PyInt_FromLong"
2228 from_py_function = "PyInt_AsLong"
2230 def __init__(self, name, cname, typedef_flag):
2234 self.typedef_flag = typedef_flag
2240 return "<CEnumType %s %s%s>" % (self.name, self.cname,
2241 ("", " typedef")[self.typedef_flag])
2243 def declaration_code(self, entity_code,
2244 for_display = 0, dll_linkage = None, pyrex = 0):
2245 if pyrex or for_display:
2246 base_code = self.name
2248 if self.typedef_flag:
2249 base_code = self.cname
2251 base_code = "enum %s" % self.cname
2252 base_code = public_decl(base_code, dll_linkage)
2253 return self.base_declaration_code(base_code, entity_code)
2256 class CStringType(object):
2257 # Mixin class for C string types.
2262 to_py_function = "PyBytes_FromString"
2263 from_py_function = "PyBytes_AsString"
2264 exception_value = "NULL"
2266 def literal_code(self, value):
2267 assert isinstance(value, str)
2268 return '"%s"' % StringEncoding.escape_byte_string(value)
2271 class CUTF8CharArrayType(CStringType, CArrayType):
2276 to_py_function = "PyUnicode_DecodeUTF8"
2277 exception_value = "NULL"
2279 def __init__(self, size):
2280 CArrayType.__init__(self, c_char_type, size)
2282 class CCharArrayType(CStringType, CArrayType):
2285 def __init__(self, size):
2286 CArrayType.__init__(self, c_char_type, size)
2289 class CCharPtrType(CStringType, CPtrType):
2293 CPtrType.__init__(self, c_char_type)
2296 class CUCharPtrType(CStringType, CPtrType):
2297 # C 'unsigned char *' type.
2299 to_py_function = "__Pyx_PyBytes_FromUString"
2300 from_py_function = "__Pyx_PyBytes_AsUString"
2303 CPtrType.__init__(self, c_uchar_type)
2306 class UnspecifiedType(PyrexType):
2307 # Used as a placeholder until the type can be determined.
2311 def declaration_code(self, entity_code,
2312 for_display = 0, dll_linkage = None, pyrex = 0):
2313 return "<unspecified>"
2315 def same_as_resolved_type(self, other_type):
2319 class ErrorType(PyrexType):
2320 # Used to prevent propagation of error messages.
2323 exception_value = "0"
2325 to_py_function = "dummy"
2326 from_py_function = "dummy"
2328 def create_to_py_utility_code(self, env):
2331 def create_from_py_utility_code(self, env):
2334 def declaration_code(self, entity_code,
2335 for_display = 0, dll_linkage = None, pyrex = 0):
2338 def same_as_resolved_type(self, other_type):
2341 def error_condition(self, result_code):
2345 rank_to_type_name = (
2356 RANK_INT = list(rank_to_type_name).index('int')
2357 RANK_LONG = list(rank_to_type_name).index('long')
2362 py_object_type = PyObjectType()
2364 c_void_type = CVoidType()
2366 c_uchar_type = CIntType(0, UNSIGNED)
2367 c_ushort_type = CIntType(1, UNSIGNED)
2368 c_uint_type = CIntType(2, UNSIGNED)
2369 c_ulong_type = CIntType(3, UNSIGNED)
2370 c_ulonglong_type = CIntType(4, UNSIGNED)
2372 c_char_type = CIntType(0)
2373 c_short_type = CIntType(1)
2374 c_int_type = CIntType(2)
2375 c_long_type = CIntType(3)
2376 c_longlong_type = CIntType(4)
2378 c_schar_type = CIntType(0, SIGNED)
2379 c_sshort_type = CIntType(1, SIGNED)
2380 c_sint_type = CIntType(2, SIGNED)
2381 c_slong_type = CIntType(3, SIGNED)
2382 c_slonglong_type = CIntType(4, SIGNED)
2384 c_float_type = CFloatType(5, math_h_modifier='f')
2385 c_double_type = CFloatType(6)
2386 c_longdouble_type = CFloatType(7, math_h_modifier='l')
2388 c_float_complex_type = CComplexType(c_float_type)
2389 c_double_complex_type = CComplexType(c_double_type)
2390 c_longdouble_complex_type = CComplexType(c_longdouble_type)
2392 c_anon_enum_type = CAnonEnumType(-1)
2393 c_returncode_type = CReturnCodeType(RANK_INT)
2394 c_bint_type = CBIntType(RANK_INT)
2395 c_py_unicode_type = CPyUnicodeIntType(RANK_INT-0.5, UNSIGNED)
2396 c_py_ucs4_type = CPyUCS4IntType(RANK_LONG-0.5, UNSIGNED)
2397 c_py_hash_t_type = CPyHashTType(RANK_LONG+0.5, SIGNED)
2398 c_py_ssize_t_type = CPySSizeTType(RANK_LONG+0.5, SIGNED)
2399 c_ssize_t_type = CSSizeTType(RANK_LONG+0.5, SIGNED)
2400 c_size_t_type = CSizeTType(RANK_LONG+0.5, UNSIGNED)
2402 c_null_ptr_type = CNullPtrType(c_void_type)
2403 c_void_ptr_type = CPtrType(c_void_type)
2404 c_void_ptr_ptr_type = CPtrType(c_void_ptr_type)
2405 c_char_array_type = CCharArrayType(None)
2406 c_char_ptr_type = CCharPtrType()
2407 c_uchar_ptr_type = CUCharPtrType()
2408 c_utf8_char_array_type = CUTF8CharArrayType(None)
2409 c_char_ptr_ptr_type = CPtrType(c_char_ptr_type)
2410 c_int_ptr_type = CPtrType(c_int_type)
2411 c_py_unicode_ptr_type = CPtrType(c_py_unicode_type)
2412 c_py_ssize_t_ptr_type = CPtrType(c_py_ssize_t_type)
2413 c_ssize_t_ptr_type = CPtrType(c_ssize_t_type)
2414 c_size_t_ptr_type = CPtrType(c_size_t_type)
2417 # the Py_buffer type is defined in Builtin.py
2418 c_py_buffer_type = CStructOrUnionType("Py_buffer", "struct", None, 1, "Py_buffer")
2419 c_py_buffer_ptr_type = CPtrType(c_py_buffer_type)
2421 error_type = ErrorType()
2422 unspecified_type = UnspecifiedType()
2424 modifiers_and_name_to_type = {
2425 #(signed, longness, name) : type
2426 (0, 0, "char"): c_uchar_type,
2427 (1, 0, "char"): c_char_type,
2428 (2, 0, "char"): c_schar_type,
2430 (0, -1, "int"): c_ushort_type,
2431 (0, 0, "int"): c_uint_type,
2432 (0, 1, "int"): c_ulong_type,
2433 (0, 2, "int"): c_ulonglong_type,
2435 (1, -1, "int"): c_short_type,
2436 (1, 0, "int"): c_int_type,
2437 (1, 1, "int"): c_long_type,
2438 (1, 2, "int"): c_longlong_type,
2440 (2, -1, "int"): c_sshort_type,
2441 (2, 0, "int"): c_sint_type,
2442 (2, 1, "int"): c_slong_type,
2443 (2, 2, "int"): c_slonglong_type,
2445 (1, 0, "float"): c_float_type,
2446 (1, 0, "double"): c_double_type,
2447 (1, 1, "double"): c_longdouble_type,
2449 (1, 0, "complex"): c_double_complex_type, # C: float, Python: double => Python wins
2450 (1, 0, "floatcomplex"): c_float_complex_type,
2451 (1, 0, "doublecomplex"): c_double_complex_type,
2452 (1, 1, "doublecomplex"): c_longdouble_complex_type,
2455 (1, 0, "void"): c_void_type,
2457 (1, 0, "bint"): c_bint_type,
2458 (0, 0, "Py_UNICODE"): c_py_unicode_type,
2459 (0, 0, "Py_UCS4"): c_py_ucs4_type,
2460 (2, 0, "Py_hash_t"): c_py_hash_t_type,
2461 (2, 0, "Py_ssize_t"): c_py_ssize_t_type,
2462 (2, 0, "ssize_t") : c_ssize_t_type,
2463 (0, 0, "size_t") : c_size_t_type,
2465 (1, 0, "object"): py_object_type,
2468 def is_promotion(src_type, dst_type):
2469 # It's hard to find a hard definition of promotion, but empirical
2470 # evidence suggests that the below is all that's allowed.
2471 if src_type.is_numeric:
2472 if dst_type.same_as(c_int_type):
2473 unsigned = (not src_type.signed)
2474 return (src_type.is_enum or
2475 (src_type.is_int and
2476 unsigned + src_type.rank < dst_type.rank))
2477 elif dst_type.same_as(c_double_type):
2478 return src_type.is_float and src_type.rank <= dst_type.rank
2481 def best_match(args, functions, pos=None):
2483 Given a list args of arguments and a list of functions, choose one
2484 to call which seems to be the "best" fit for this list of arguments.
2485 This function is used, e.g., when deciding which overloaded method
2486 to dispatch for C++ classes.
2488 We first eliminate functions based on arity, and if only one
2489 function has the correct arity, we return it. Otherwise, we weight
2490 functions based on how much work must be done to convert the
2491 arguments, with the following priorities:
2492 * identical types or pointers to identical types
2495 That is, we prefer functions where no arguments need converted,
2496 and failing that, functions where only promotions are required, and
2499 If no function is deemed a good fit, or if two or more functions have
2500 the same weight, we return None (as there is no best match). If pos
2501 is not None, we also generate an error.
2503 # TODO: args should be a list of types, not a list of Nodes.
2504 actual_nargs = len(args)
2508 for func in functions:
2510 func_type = func.type
2511 if func_type.is_ptr:
2512 func_type = func_type.base_type
2513 # Check function type
2514 if not func_type.is_cfunction:
2515 if not func_type.is_error and pos is not None:
2516 error_mesg = "Calling non-function type '%s'" % func_type
2517 errors.append((func, error_mesg))
2520 max_nargs = len(func_type.args)
2521 min_nargs = max_nargs - func_type.optional_arg_count
2522 if actual_nargs < min_nargs or \
2523 (not func_type.has_varargs and actual_nargs > max_nargs):
2524 if max_nargs == min_nargs and not func_type.has_varargs:
2525 expectation = max_nargs
2526 elif actual_nargs < min_nargs:
2527 expectation = "at least %s" % min_nargs
2529 expectation = "at most %s" % max_nargs
2530 error_mesg = "Call with wrong number of arguments (expected %s, got %s)" \
2531 % (expectation, actual_nargs)
2532 errors.append((func, error_mesg))
2534 candidates.append((func, func_type))
2536 # Optimize the most common case of no overloading...
2537 if len(candidates) == 1:
2538 return candidates[0][0]
2539 elif len(candidates) == 0:
2541 if len(errors) == 1:
2542 error(pos, errors[0][1])
2544 error(pos, "no suitable method found")
2549 for func, func_type in candidates:
2551 for i in range(min(len(args), len(func_type.args))):
2552 src_type = args[i].type
2553 dst_type = func_type.args[i].type
2554 if dst_type.assignable_from(src_type):
2555 if src_type == dst_type or dst_type.same_as(src_type):
2557 elif is_promotion(src_type, dst_type):
2559 elif not src_type.is_pyobject:
2564 error_mesg = "Invalid conversion from '%s' to '%s'"%(src_type,
2566 bad_types.append((func, error_mesg))
2569 possibilities.append((score, func)) # so we can sort it
2571 possibilities.sort()
2572 if len(possibilities) > 1 and possibilities[0][0] == possibilities[1][0]:
2574 error(pos, "ambiguous overloaded method")
2576 return possibilities[0][1]
2578 if len(bad_types) == 1:
2579 error(pos, bad_types[0][1])
2581 error(pos, "no suitable method found")
2584 def widest_numeric_type(type1, type2):
2585 # Given two numeric types, return the narrowest type
2586 # encompassing both of them.
2589 elif type1.is_complex or type2.is_complex:
2590 def real_type(ntype):
2591 if ntype.is_complex:
2592 return ntype.real_type
2594 widest_type = CComplexType(
2595 widest_numeric_type(
2598 elif type1.is_enum and type2.is_enum:
2599 widest_type = c_int_type
2600 elif type1.rank < type2.rank:
2602 elif type1.rank > type2.rank:
2604 elif type1.signed < type2.signed:
2610 def independent_spanning_type(type1, type2):
2611 # Return a type assignable independently from both type1 and
2612 # type2, but do not require any interoperability between the two.
2613 # For example, in "True * 2", it is safe to assume an integer
2614 # result type (so spanning_type() will do the right thing),
2615 # whereas "x = True or 2" must evaluate to a type that can hold
2616 # both a boolean value and an integer, so this function works
2620 elif (type1 is c_bint_type or type2 is c_bint_type) and (type1.is_numeric and type2.is_numeric):
2621 # special case: if one of the results is a bint and the other
2622 # is another C integer, we must prevent returning a numeric
2623 # type so that we do not lose the ability to coerce to a
2624 # Python bool if we have to.
2625 return py_object_type
2626 span_type = _spanning_type(type1, type2)
2627 if span_type is None:
2631 def spanning_type(type1, type2):
2632 # Return a type assignable from both type1 and type2, or
2633 # py_object_type if no better type is found. Assumes that the
2634 # code that calls this will try a coercion afterwards, which will
2635 # fail if the types cannot actually coerce to a py_object_type.
2638 elif type1 is py_object_type or type2 is py_object_type:
2639 return py_object_type
2640 elif type1 is c_py_unicode_type or type2 is c_py_unicode_type:
2641 # Py_UNICODE behaves more like a string than an int
2642 return py_object_type
2643 span_type = _spanning_type(type1, type2)
2644 if span_type is None:
2645 return py_object_type
2648 def _spanning_type(type1, type2):
2649 if type1.is_numeric and type2.is_numeric:
2650 return widest_numeric_type(type1, type2)
2651 elif type1.is_builtin_type and type1.name == 'float' and type2.is_numeric:
2652 return widest_numeric_type(c_double_type, type2)
2653 elif type2.is_builtin_type and type2.name == 'float' and type1.is_numeric:
2654 return widest_numeric_type(type1, c_double_type)
2655 elif type1.is_extension_type and type2.is_extension_type:
2656 return widest_extension_type(type1, type2)
2657 elif type1.is_pyobject or type2.is_pyobject:
2658 return py_object_type
2659 elif type1.assignable_from(type2):
2660 if type1.is_extension_type and type1.typeobj_is_imported():
2661 # external types are unsafe, so we use PyObject instead
2662 return py_object_type
2664 elif type2.assignable_from(type1):
2665 if type2.is_extension_type and type2.typeobj_is_imported():
2666 # external types are unsafe, so we use PyObject instead
2667 return py_object_type
2672 def widest_extension_type(type1, type2):
2673 if type1.typeobj_is_imported() or type2.typeobj_is_imported():
2674 return py_object_type
2676 if type1.subtype_of(type2):
2678 elif type2.subtype_of(type1):
2680 type1, type2 = type1.base_type, type2.base_type
2681 if type1 is None or type2 is None:
2682 return py_object_type
2684 def simple_c_type(signed, longness, name):
2685 # Find type descriptor for simple type given name and modifiers.
2686 # Returns None if arguments don't make sense.
2687 return modifiers_and_name_to_type.get((signed, longness, name))
2689 def parse_basic_type(name):
2691 if name.startswith('p_'):
2692 base = parse_basic_type(name[2:])
2693 elif name.startswith('p'):
2694 base = parse_basic_type(name[1:])
2695 elif name.endswith('*'):
2696 base = parse_basic_type(name[:-1])
2698 return CPtrType(base)
2700 basic_type = simple_c_type(1, 0, name)
2706 if name == 'Py_UNICODE':
2708 elif name == 'Py_UCS4':
2710 elif name == 'Py_hash_t':
2712 elif name == 'Py_ssize_t':
2714 elif name == 'ssize_t':
2716 elif name == 'size_t':
2719 if name.startswith('u'):
2722 elif (name.startswith('s') and
2723 not name.startswith('short')):
2727 while name.startswith('short'):
2728 name = name.replace('short', '', 1).strip()
2730 while name.startswith('long'):
2731 name = name.replace('long', '', 1).strip()
2733 if longness != 0 and not name:
2735 return simple_c_type(signed, longness, name)
2737 def c_array_type(base_type, size):
2738 # Construct a C array type.
2739 if base_type is c_char_type:
2740 return CCharArrayType(size)
2741 elif base_type is error_type:
2744 return CArrayType(base_type, size)
2746 def c_ptr_type(base_type):
2747 # Construct a C pointer type.
2748 if base_type is c_char_type:
2749 return c_char_ptr_type
2750 elif base_type is c_uchar_type:
2751 return c_uchar_ptr_type
2752 elif base_type is error_type:
2755 return CPtrType(base_type)
2757 def c_ref_type(base_type):
2758 # Construct a C reference type
2759 if base_type is error_type:
2762 return CReferenceType(base_type)
2764 def same_type(type1, type2):
2765 return type1.same_as(type2)
2767 def assignable_from(type1, type2):
2768 return type1.assignable_from(type2)
2770 def typecast(to_type, from_type, expr_code):
2771 # Return expr_code cast to a C type which can be
2772 # assigned to to_type, assuming its existing C type
2774 if to_type is from_type or \
2775 (not to_type.is_pyobject and assignable_from(to_type, from_type)):
2778 #print "typecast: to", to_type, "from", from_type ###
2779 return to_type.cast_code(expr_code)
2782 type_conversion_predeclarations = """
2783 /* Type Conversion Predeclarations */
2785 #define __Pyx_PyBytes_FromUString(s) PyBytes_FromString((char*)s)
2786 #define __Pyx_PyBytes_AsUString(s) ((unsigned char*) PyBytes_AsString(s))
2788 #define __Pyx_Owned_Py_None(b) (Py_INCREF(Py_None), Py_None)
2789 #define __Pyx_PyBool_FromLong(b) ((b) ? (Py_INCREF(Py_True), Py_True) : (Py_INCREF(Py_False), Py_False))
2790 static CYTHON_INLINE int __Pyx_PyObject_IsTrue(PyObject*);
2791 static CYTHON_INLINE PyObject* __Pyx_PyNumber_Int(PyObject* x);
2793 static CYTHON_INLINE Py_ssize_t __Pyx_PyIndex_AsSsize_t(PyObject*);
2794 static CYTHON_INLINE PyObject * __Pyx_PyInt_FromSize_t(size_t);
2795 static CYTHON_INLINE size_t __Pyx_PyInt_AsSize_t(PyObject*);
2797 #define __pyx_PyFloat_AsDouble(x) (PyFloat_CheckExact(x) ? PyFloat_AS_DOUBLE(x) : PyFloat_AsDouble(x))
2799 """ + type_conversion_predeclarations
2801 # Note: __Pyx_PyObject_IsTrue is written to minimize branching.
2802 type_conversion_functions = """
2803 /* Type Conversion Functions */
2805 static CYTHON_INLINE int __Pyx_PyObject_IsTrue(PyObject* x) {
2806 int is_true = x == Py_True;
2807 if (is_true | (x == Py_False) | (x == Py_None)) return is_true;
2808 else return PyObject_IsTrue(x);
2811 static CYTHON_INLINE PyObject* __Pyx_PyNumber_Int(PyObject* x) {
2813 const char *name = NULL;
2814 PyObject *res = NULL;
2815 #if PY_VERSION_HEX < 0x03000000
2816 if (PyInt_Check(x) || PyLong_Check(x))
2818 if (PyLong_Check(x))
2820 return Py_INCREF(x), x;
2821 m = Py_TYPE(x)->tp_as_number;
2822 #if PY_VERSION_HEX < 0x03000000
2823 if (m && m->nb_int) {
2825 res = PyNumber_Int(x);
2827 else if (m && m->nb_long) {
2829 res = PyNumber_Long(x);
2832 if (m && m->nb_int) {
2834 res = PyNumber_Long(x);
2838 #if PY_VERSION_HEX < 0x03000000
2839 if (!PyInt_Check(res) && !PyLong_Check(res)) {
2841 if (!PyLong_Check(res)) {
2843 PyErr_Format(PyExc_TypeError,
2844 "__%s__ returned non-%s (type %.200s)",
2845 name, name, Py_TYPE(res)->tp_name);
2850 else if (!PyErr_Occurred()) {
2851 PyErr_SetString(PyExc_TypeError,
2852 "an integer is required");
2857 static CYTHON_INLINE Py_ssize_t __Pyx_PyIndex_AsSsize_t(PyObject* b) {
2859 PyObject* x = PyNumber_Index(b);
2861 ival = PyInt_AsSsize_t(x);
2866 static CYTHON_INLINE PyObject * __Pyx_PyInt_FromSize_t(size_t ival) {
2867 #if PY_VERSION_HEX < 0x02050000
2868 if (ival <= LONG_MAX)
2869 return PyInt_FromLong((long)ival);
2871 unsigned char *bytes = (unsigned char *) &ival;
2872 int one = 1; int little = (int)*(unsigned char*)&one;
2873 return _PyLong_FromByteArray(bytes, sizeof(size_t), little, 0);
2876 return PyInt_FromSize_t(ival);
2880 static CYTHON_INLINE size_t __Pyx_PyInt_AsSize_t(PyObject* x) {
2881 unsigned PY_LONG_LONG val = __Pyx_PyInt_AsUnsignedLongLong(x);
2882 if (unlikely(val == (unsigned PY_LONG_LONG)-1 && PyErr_Occurred())) {
2884 } else if (unlikely(val != (unsigned PY_LONG_LONG)(size_t)val)) {
2885 PyErr_SetString(PyExc_OverflowError,
2886 "value too large to convert to size_t");
2892 """ + type_conversion_functions