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):
919 class CBIntType(CIntType):
921 to_py_function = "__Pyx_PyBool_FromLong"
922 from_py_function = "__Pyx_PyObject_IsTrue"
923 exception_check = 1 # for C++ bool
926 return "<CNumericType bint>"
929 class CPyUCS4IntType(CIntType):
932 is_unicode_char = True
934 # Py_UCS4 coerces from and to single character unicode strings (or
935 # at most two characters on 16bit Unicode builds), but we also
936 # allow Python integers as input. The value range for Py_UCS4
937 # is 0..1114111, which is checked when converting from an integer
940 to_py_function = "PyUnicode_FromOrdinal"
941 from_py_function = "__Pyx_PyObject_AsPy_UCS4"
943 def create_from_py_utility_code(self, env):
944 env.use_utility_code(pyobject_as_py_ucs4_utility_code)
947 def sign_and_name(self):
951 pyobject_as_py_ucs4_utility_code = UtilityCode(
953 static CYTHON_INLINE Py_UCS4 __Pyx_PyObject_AsPy_UCS4(PyObject*);
956 static CYTHON_INLINE Py_UCS4 __Pyx_PyObject_AsPy_UCS4(PyObject* x) {
958 if (PyUnicode_Check(x)) {
959 if (likely(PyUnicode_GET_SIZE(x) == 1)) {
960 return PyUnicode_AS_UNICODE(x)[0];
961 } else if (PyUnicode_GET_SIZE(x) == 2) {
962 Py_UCS4 high_val = PyUnicode_AS_UNICODE(x)[0];
963 if (high_val >= 0xD800 && high_val <= 0xDBFF) {
964 Py_UCS4 low_val = PyUnicode_AS_UNICODE(x)[1];
965 if (low_val >= 0xDC00 && low_val <= 0xDFFF) {
966 return 0x10000 | ((high_val & ((1<<10)-1)) << 10) | (low_val & ((1<<10)-1));
970 PyErr_Format(PyExc_ValueError,
971 "only single character unicode strings or surrogate pairs can be converted to Py_UCS4, got length "
972 #if PY_VERSION_HEX < 0x02050000
977 PyUnicode_GET_SIZE(x));
980 ival = __Pyx_PyInt_AsLong(x);
981 if (unlikely(ival < 0)) {
982 if (!PyErr_Occurred())
983 PyErr_SetString(PyExc_OverflowError,
984 "cannot convert negative value to Py_UCS4");
986 } else if (unlikely(ival > 1114111)) {
987 PyErr_SetString(PyExc_OverflowError,
988 "value too large to convert to Py_UCS4");
991 return (Py_UCS4)ival;
996 class CPyUnicodeIntType(CIntType):
999 is_unicode_char = True
1001 # Py_UNICODE coerces from and to single character unicode strings,
1002 # but we also allow Python integers as input. The value range for
1003 # Py_UNICODE is 0..1114111, which is checked when converting from
1006 to_py_function = "PyUnicode_FromOrdinal"
1007 from_py_function = "__Pyx_PyObject_AsPy_UNICODE"
1009 def create_from_py_utility_code(self, env):
1010 env.use_utility_code(pyobject_as_py_unicode_utility_code)
1013 def sign_and_name(self):
1016 pyobject_as_py_unicode_utility_code = UtilityCode(
1018 static CYTHON_INLINE Py_UNICODE __Pyx_PyObject_AsPy_UNICODE(PyObject*);
1021 static CYTHON_INLINE Py_UNICODE __Pyx_PyObject_AsPy_UNICODE(PyObject* x) {
1022 static long maxval = 0;
1024 if (PyUnicode_Check(x)) {
1025 if (unlikely(PyUnicode_GET_SIZE(x) != 1)) {
1026 PyErr_Format(PyExc_ValueError,
1027 "only single character unicode strings can be converted to Py_UNICODE, got length "
1028 #if PY_VERSION_HEX < 0x02050000
1033 PyUnicode_GET_SIZE(x));
1034 return (Py_UNICODE)-1;
1036 return PyUnicode_AS_UNICODE(x)[0];
1038 if (unlikely(!maxval))
1039 maxval = (long)PyUnicode_GetMax();
1040 ival = __Pyx_PyInt_AsLong(x);
1041 if (unlikely(ival < 0)) {
1042 if (!PyErr_Occurred())
1043 PyErr_SetString(PyExc_OverflowError,
1044 "cannot convert negative value to Py_UNICODE");
1045 return (Py_UNICODE)-1;
1046 } else if (unlikely(ival > maxval)) {
1047 PyErr_SetString(PyExc_OverflowError,
1048 "value too large to convert to Py_UNICODE");
1049 return (Py_UNICODE)-1;
1051 return (Py_UNICODE)ival;
1056 class CPySSizeTType(CIntType):
1058 to_py_function = "PyInt_FromSsize_t"
1059 from_py_function = "__Pyx_PyIndex_AsSsize_t"
1061 def sign_and_name(self):
1064 class CSSizeTType(CIntType):
1066 to_py_function = "PyInt_FromSsize_t"
1067 from_py_function = "PyInt_AsSsize_t"
1069 def sign_and_name(self):
1072 class CSizeTType(CIntType):
1074 to_py_function = "__Pyx_PyInt_FromSize_t"
1075 from_py_function = "__Pyx_PyInt_AsSize_t"
1077 def sign_and_name(self):
1081 class CFloatType(CNumericType):
1084 to_py_function = "PyFloat_FromDouble"
1085 from_py_function = "__pyx_PyFloat_AsDouble"
1087 exception_value = -1
1089 def __init__(self, rank, math_h_modifier = ''):
1090 CNumericType.__init__(self, rank, 1)
1091 self.math_h_modifier = math_h_modifier
1093 def assignable_from_resolved_type(self, src_type):
1094 return (src_type.is_numeric and not src_type.is_complex) or src_type is error_type
1097 class CComplexType(CNumericType):
1100 to_py_function = "__pyx_PyComplex_FromComplex"
1104 def __init__(self, real_type):
1105 while real_type.is_typedef and not real_type.typedef_is_external:
1106 real_type = real_type.typedef_base_type
1107 if real_type.is_typedef and real_type.typedef_is_external:
1108 # The below is not actually used: Coercions are currently disabled
1109 # so that complex types of external types can not be created
1110 self.funcsuffix = "_%s" % real_type.specialization_name()
1111 elif hasattr(real_type, 'math_h_modifier'):
1112 self.funcsuffix = real_type.math_h_modifier
1114 self.funcsuffix = "_%s" % real_type.specialization_name()
1116 self.real_type = real_type
1117 CNumericType.__init__(self, real_type.rank + 0.5, real_type.signed)
1119 self.from_parts = "%s_from_parts" % self.specialization_name()
1120 self.default_value = "%s(0, 0)" % self.from_parts
1122 def __eq__(self, other):
1123 if isinstance(self, CComplexType) and isinstance(other, CComplexType):
1124 return self.real_type == other.real_type
1128 def __ne__(self, other):
1129 if isinstance(self, CComplexType) and isinstance(other, CComplexType):
1130 return self.real_type != other.real_type
1134 def __lt__(self, other):
1135 if isinstance(self, CComplexType) and isinstance(other, CComplexType):
1136 return self.real_type < other.real_type
1138 # this is arbitrary, but it makes sure we always have
1139 # *some* kind of order
1143 return ~hash(self.real_type)
1145 def declaration_code(self, entity_code,
1146 for_display = 0, dll_linkage = None, pyrex = 0):
1147 if pyrex or for_display:
1148 real_code = self.real_type.declaration_code("", for_display, dll_linkage, pyrex)
1149 base_code = "%s complex" % real_code
1151 base_code = public_decl(self.sign_and_name(), dll_linkage)
1152 return self.base_declaration_code(base_code, entity_code)
1154 def sign_and_name(self):
1155 real_type_name = self.real_type.specialization_name()
1156 real_type_name = real_type_name.replace('long__double','long_double')
1157 real_type_name = real_type_name.replace('PY_LONG_LONG','long_long')
1158 return Naming.type_prefix + real_type_name + "_complex"
1160 def assignable_from(self, src_type):
1161 # Temporary hack/feature disabling, see #441
1162 if (not src_type.is_complex and src_type.is_numeric and src_type.is_typedef
1163 and src_type.typedef_is_external):
1166 return super(CComplexType, self).assignable_from(src_type)
1168 def assignable_from_resolved_type(self, src_type):
1169 return (src_type.is_complex and self.real_type.assignable_from_resolved_type(src_type.real_type)
1170 or src_type.is_numeric and self.real_type.assignable_from_resolved_type(src_type)
1171 or src_type is error_type)
1173 def attributes_known(self):
1174 if self.scope is None:
1176 self.scope = scope = Symtab.CClassScope(
1179 visibility="extern")
1180 scope.parent_type = self
1181 scope.directives = {}
1182 scope.declare_var("real", self.real_type, None, "real", is_cdef=True)
1183 scope.declare_var("imag", self.real_type, None, "imag", is_cdef=True)
1184 entry = scope.declare_cfunction(
1186 CFuncType(self, [CFuncTypeArg("self", self, None)], nogil=True),
1189 cname="__Pyx_c_conj%s" % self.funcsuffix)
1193 def create_declaration_utility_code(self, env):
1194 # This must always be run, because a single CComplexType instance can be shared
1195 # across multiple compilations (the one created in the module scope)
1196 env.use_utility_code(complex_header_utility_code)
1197 env.use_utility_code(complex_real_imag_utility_code)
1198 for utility_code in (complex_type_utility_code,
1199 complex_from_parts_utility_code,
1200 complex_arithmetic_utility_code):
1201 env.use_utility_code(
1202 utility_code.specialize(
1204 real_type = self.real_type.declaration_code(''),
1205 m = self.funcsuffix,
1206 is_float = self.real_type.is_float))
1209 def create_to_py_utility_code(self, env):
1210 env.use_utility_code(complex_real_imag_utility_code)
1211 env.use_utility_code(complex_to_py_utility_code)
1214 def create_from_py_utility_code(self, env):
1215 self.real_type.create_from_py_utility_code(env)
1217 for utility_code in (complex_from_parts_utility_code,
1218 complex_from_py_utility_code):
1219 env.use_utility_code(
1220 utility_code.specialize(
1222 real_type = self.real_type.declaration_code(''),
1223 m = self.funcsuffix,
1224 is_float = self.real_type.is_float))
1225 self.from_py_function = "__Pyx_PyComplex_As_" + self.specialization_name()
1228 def lookup_op(self, nargs, op):
1230 return self.binops[nargs, op]
1234 op_name = complex_ops[nargs, op]
1235 self.binops[nargs, op] = func_name = "__Pyx_c_%s%s" % (op_name, self.funcsuffix)
1240 def unary_op(self, op):
1241 return self.lookup_op(1, op)
1243 def binary_op(self, op):
1244 return self.lookup_op(2, op)
1248 (1, 'zero'): 'is_zero',
1256 complex_header_utility_code = UtilityCode(
1257 proto_block='h_code',
1259 #if !defined(CYTHON_CCOMPLEX)
1260 #if defined(__cplusplus)
1261 #define CYTHON_CCOMPLEX 1
1262 #elif defined(_Complex_I)
1263 #define CYTHON_CCOMPLEX 1
1265 #define CYTHON_CCOMPLEX 0
1273 #include <complex.h>
1277 #if CYTHON_CCOMPLEX && !defined(__cplusplus) && defined(__sun__) && defined(__GNUC__)
1279 #define _Complex_I 1.0fj
1283 complex_real_imag_utility_code = UtilityCode(
1287 #define __Pyx_CREAL(z) ((z).real())
1288 #define __Pyx_CIMAG(z) ((z).imag())
1290 #define __Pyx_CREAL(z) (__real__(z))
1291 #define __Pyx_CIMAG(z) (__imag__(z))
1294 #define __Pyx_CREAL(z) ((z).real)
1295 #define __Pyx_CIMAG(z) ((z).imag)
1298 #if defined(_WIN32) && defined(__cplusplus) && CYTHON_CCOMPLEX
1299 #define __Pyx_SET_CREAL(z,x) ((z).real(x))
1300 #define __Pyx_SET_CIMAG(z,y) ((z).imag(y))
1302 #define __Pyx_SET_CREAL(z,x) __Pyx_CREAL(z) = (x)
1303 #define __Pyx_SET_CIMAG(z,y) __Pyx_CIMAG(z) = (y)
1307 complex_type_utility_code = UtilityCode(
1308 proto_block='complex_type_declarations',
1312 typedef ::std::complex< %(real_type)s > %(type_name)s;
1314 typedef %(real_type)s _Complex %(type_name)s;
1317 typedef struct { %(real_type)s real, imag; } %(type_name)s;
1321 complex_from_parts_utility_code = UtilityCode(
1322 proto_block='utility_code_proto',
1324 static CYTHON_INLINE %(type)s %(type_name)s_from_parts(%(real_type)s, %(real_type)s);
1329 static CYTHON_INLINE %(type)s %(type_name)s_from_parts(%(real_type)s x, %(real_type)s y) {
1330 return ::std::complex< %(real_type)s >(x, y);
1333 static CYTHON_INLINE %(type)s %(type_name)s_from_parts(%(real_type)s x, %(real_type)s y) {
1334 return x + y*(%(type)s)_Complex_I;
1338 static CYTHON_INLINE %(type)s %(type_name)s_from_parts(%(real_type)s x, %(real_type)s y) {
1347 complex_to_py_utility_code = UtilityCode(
1349 #define __pyx_PyComplex_FromComplex(z) \\
1350 PyComplex_FromDoubles((double)__Pyx_CREAL(z), \\
1351 (double)__Pyx_CIMAG(z))
1354 complex_from_py_utility_code = UtilityCode(
1356 static %(type)s __Pyx_PyComplex_As_%(type_name)s(PyObject*);
1359 static %(type)s __Pyx_PyComplex_As_%(type_name)s(PyObject* o) {
1361 if (PyComplex_CheckExact(o))
1362 cval = ((PyComplexObject *)o)->cval;
1364 cval = PyComplex_AsCComplex(o);
1365 return %(type_name)s_from_parts(
1366 (%(real_type)s)cval.real,
1367 (%(real_type)s)cval.imag);
1371 complex_arithmetic_utility_code = UtilityCode(
1374 #define __Pyx_c_eq%(m)s(a, b) ((a)==(b))
1375 #define __Pyx_c_sum%(m)s(a, b) ((a)+(b))
1376 #define __Pyx_c_diff%(m)s(a, b) ((a)-(b))
1377 #define __Pyx_c_prod%(m)s(a, b) ((a)*(b))
1378 #define __Pyx_c_quot%(m)s(a, b) ((a)/(b))
1379 #define __Pyx_c_neg%(m)s(a) (-(a))
1381 #define __Pyx_c_is_zero%(m)s(z) ((z)==(%(real_type)s)0)
1382 #define __Pyx_c_conj%(m)s(z) (::std::conj(z))
1384 #define __Pyx_c_abs%(m)s(z) (::std::abs(z))
1385 #define __Pyx_c_pow%(m)s(a, b) (::std::pow(a, b))
1388 #define __Pyx_c_is_zero%(m)s(z) ((z)==0)
1389 #define __Pyx_c_conj%(m)s(z) (conj%(m)s(z))
1391 #define __Pyx_c_abs%(m)s(z) (cabs%(m)s(z))
1392 #define __Pyx_c_pow%(m)s(a, b) (cpow%(m)s(a, b))
1396 static CYTHON_INLINE int __Pyx_c_eq%(m)s(%(type)s, %(type)s);
1397 static CYTHON_INLINE %(type)s __Pyx_c_sum%(m)s(%(type)s, %(type)s);
1398 static CYTHON_INLINE %(type)s __Pyx_c_diff%(m)s(%(type)s, %(type)s);
1399 static CYTHON_INLINE %(type)s __Pyx_c_prod%(m)s(%(type)s, %(type)s);
1400 static CYTHON_INLINE %(type)s __Pyx_c_quot%(m)s(%(type)s, %(type)s);
1401 static CYTHON_INLINE %(type)s __Pyx_c_neg%(m)s(%(type)s);
1402 static CYTHON_INLINE int __Pyx_c_is_zero%(m)s(%(type)s);
1403 static CYTHON_INLINE %(type)s __Pyx_c_conj%(m)s(%(type)s);
1405 static CYTHON_INLINE %(real_type)s __Pyx_c_abs%(m)s(%(type)s);
1406 static CYTHON_INLINE %(type)s __Pyx_c_pow%(m)s(%(type)s, %(type)s);
1413 static CYTHON_INLINE int __Pyx_c_eq%(m)s(%(type)s a, %(type)s b) {
1414 return (a.real == b.real) && (a.imag == b.imag);
1416 static CYTHON_INLINE %(type)s __Pyx_c_sum%(m)s(%(type)s a, %(type)s b) {
1418 z.real = a.real + b.real;
1419 z.imag = a.imag + b.imag;
1422 static CYTHON_INLINE %(type)s __Pyx_c_diff%(m)s(%(type)s a, %(type)s b) {
1424 z.real = a.real - b.real;
1425 z.imag = a.imag - b.imag;
1428 static CYTHON_INLINE %(type)s __Pyx_c_prod%(m)s(%(type)s a, %(type)s b) {
1430 z.real = a.real * b.real - a.imag * b.imag;
1431 z.imag = a.real * b.imag + a.imag * b.real;
1434 static CYTHON_INLINE %(type)s __Pyx_c_quot%(m)s(%(type)s a, %(type)s b) {
1436 %(real_type)s denom = b.real * b.real + b.imag * b.imag;
1437 z.real = (a.real * b.real + a.imag * b.imag) / denom;
1438 z.imag = (a.imag * b.real - a.real * b.imag) / denom;
1441 static CYTHON_INLINE %(type)s __Pyx_c_neg%(m)s(%(type)s a) {
1447 static CYTHON_INLINE int __Pyx_c_is_zero%(m)s(%(type)s a) {
1448 return (a.real == 0) && (a.imag == 0);
1450 static CYTHON_INLINE %(type)s __Pyx_c_conj%(m)s(%(type)s a) {
1457 static CYTHON_INLINE %(real_type)s __Pyx_c_abs%(m)s(%(type)s z) {
1458 #if !defined(HAVE_HYPOT) || defined(_MSC_VER)
1459 return sqrt%(m)s(z.real*z.real + z.imag*z.imag);
1461 return hypot%(m)s(z.real, z.imag);
1464 static CYTHON_INLINE %(type)s __Pyx_c_pow%(m)s(%(type)s a, %(type)s b) {
1466 %(real_type)s r, lnr, theta, z_r, z_theta;
1467 if (b.imag == 0 && b.real == (int)b.real) {
1469 %(real_type)s denom = a.real * a.real + a.imag * a.imag;
1470 a.real = a.real / denom;
1471 a.imag = -a.imag / denom;
1474 switch ((int)b.real) {
1482 z = __Pyx_c_prod%(m)s(a, a);
1483 return __Pyx_c_prod%(m)s(a, a);
1485 z = __Pyx_c_prod%(m)s(a, a);
1486 return __Pyx_c_prod%(m)s(z, a);
1488 z = __Pyx_c_prod%(m)s(a, a);
1489 return __Pyx_c_prod%(m)s(z, z);
1499 r = __Pyx_c_abs%(m)s(a);
1500 theta = atan2%(m)s(a.imag, a.real);
1503 z_r = exp%(m)s(lnr * b.real - theta * b.imag);
1504 z_theta = theta * b.real + lnr * b.imag;
1505 z.real = z_r * cos%(m)s(z_theta);
1506 z.imag = z_r * sin%(m)s(z_theta);
1513 class CArrayType(CType):
1514 # base_type CType Element type
1515 # size integer or None Number of elements
1519 def __init__(self, base_type, size):
1520 self.base_type = base_type
1522 if base_type is c_char_type:
1526 return "<CArrayType %s %s>" % (self.size, repr(self.base_type))
1528 def same_as_resolved_type(self, other_type):
1529 return ((other_type.is_array and
1530 self.base_type.same_as(other_type.base_type))
1531 or other_type is error_type)
1533 def assignable_from_resolved_type(self, src_type):
1534 # Can't assign to a variable of an array type
1537 def element_ptr_type(self):
1538 return c_ptr_type(self.base_type)
1540 def declaration_code(self, entity_code,
1541 for_display = 0, dll_linkage = None, pyrex = 0):
1542 if self.size is not None:
1543 dimension_code = self.size
1546 if entity_code.startswith("*"):
1547 entity_code = "(%s)" % entity_code
1548 return self.base_type.declaration_code(
1549 "%s[%s]" % (entity_code, dimension_code),
1550 for_display, dll_linkage, pyrex)
1552 def as_argument_type(self):
1553 return c_ptr_type(self.base_type)
1555 def is_complete(self):
1556 return self.size is not None
1559 class CPtrType(CType):
1560 # base_type CType Referenced type
1565 def __init__(self, base_type):
1566 self.base_type = base_type
1569 return "<CPtrType %s>" % repr(self.base_type)
1571 def same_as_resolved_type(self, other_type):
1572 return ((other_type.is_ptr and
1573 self.base_type.same_as(other_type.base_type))
1574 or other_type is error_type)
1576 def declaration_code(self, entity_code,
1577 for_display = 0, dll_linkage = None, pyrex = 0):
1578 #print "CPtrType.declaration_code: pointer to", self.base_type ###
1579 return self.base_type.declaration_code(
1580 "*%s" % entity_code,
1581 for_display, dll_linkage, pyrex)
1583 def assignable_from_resolved_type(self, other_type):
1584 if other_type is error_type:
1586 if other_type.is_null_ptr:
1588 if self.base_type.is_cfunction:
1589 if other_type.is_ptr:
1590 other_type = other_type.base_type.resolve()
1591 if other_type.is_cfunction:
1592 return self.base_type.pointer_assignable_from_resolved_type(other_type)
1595 if (self.base_type.is_cpp_class and other_type.is_ptr
1596 and other_type.base_type.is_cpp_class and other_type.base_type.is_subclass(self.base_type)):
1598 if other_type.is_array or other_type.is_ptr:
1599 return self.base_type.is_void or self.base_type.same_as(other_type.base_type)
1602 def specialize(self, values):
1603 base_type = self.base_type.specialize(values)
1604 if base_type == self.base_type:
1607 return CPtrType(base_type)
1610 class CNullPtrType(CPtrType):
1615 class CReferenceType(BaseType):
1619 def __init__(self, base_type):
1620 self.ref_base_type = base_type
1623 return "<CReferenceType %s>" % repr(self.ref_base_type)
1626 return "%s &" % self.ref_base_type
1628 def as_argument_type(self):
1631 def declaration_code(self, entity_code,
1632 for_display = 0, dll_linkage = None, pyrex = 0):
1633 #print "CReferenceType.declaration_code: pointer to", self.base_type ###
1634 return self.ref_base_type.declaration_code(
1635 "&%s" % entity_code,
1636 for_display, dll_linkage, pyrex)
1638 def specialize(self, values):
1639 base_type = self.ref_base_type.specialize(values)
1640 if base_type == self.ref_base_type:
1643 return CReferenceType(base_type)
1645 def __getattr__(self, name):
1646 return getattr(self.ref_base_type, name)
1649 class CFuncType(CType):
1651 # args [CFuncTypeArg]
1652 # has_varargs boolean
1653 # exception_value string
1654 # exception_check boolean True if PyErr_Occurred check needed
1655 # calling_convention string Function calling convention
1656 # nogil boolean Can be called without gil
1657 # with_gil boolean Acquire gil around function body
1658 # templates [string] or None
1663 def __init__(self, return_type, args, has_varargs = 0,
1664 exception_value = None, exception_check = 0, calling_convention = "",
1665 nogil = 0, with_gil = 0, is_overridable = 0, optional_arg_count = 0,
1667 self.return_type = return_type
1669 self.has_varargs = has_varargs
1670 self.optional_arg_count = optional_arg_count
1671 self.exception_value = exception_value
1672 self.exception_check = exception_check
1673 self.calling_convention = calling_convention
1675 self.with_gil = with_gil
1676 self.is_overridable = is_overridable
1677 self.templates = templates
1680 arg_reprs = map(repr, self.args)
1681 if self.has_varargs:
1682 arg_reprs.append("...")
1683 if self.exception_value:
1684 except_clause = " %r" % self.exception_value
1687 if self.exception_check:
1688 except_clause += "?"
1689 return "<CFuncType %s %s[%s]%s>" % (
1690 repr(self.return_type),
1691 self.calling_convention_prefix(),
1692 ",".join(arg_reprs),
1695 def calling_convention_prefix(self):
1696 cc = self.calling_convention
1702 def same_c_signature_as(self, other_type, as_cmethod = 0):
1703 return self.same_c_signature_as_resolved_type(
1704 other_type.resolve(), as_cmethod)
1706 def same_c_signature_as_resolved_type(self, other_type, as_cmethod = 0):
1707 #print "CFuncType.same_c_signature_as_resolved_type:", \
1708 # self, other_type, "as_cmethod =", as_cmethod ###
1709 if other_type is error_type:
1711 if not other_type.is_cfunction:
1713 if self.is_overridable != other_type.is_overridable:
1715 nargs = len(self.args)
1716 if nargs != len(other_type.args):
1718 # When comparing C method signatures, the first argument
1719 # is exempt from compatibility checking (the proper check
1720 # is performed elsewhere).
1721 for i in range(as_cmethod, nargs):
1722 if not self.args[i].type.same_as(
1723 other_type.args[i].type):
1725 if self.has_varargs != other_type.has_varargs:
1727 if self.optional_arg_count != other_type.optional_arg_count:
1729 if not self.return_type.same_as(other_type.return_type):
1731 if not self.same_calling_convention_as(other_type):
1735 def compatible_signature_with(self, other_type, as_cmethod = 0):
1736 return self.compatible_signature_with_resolved_type(other_type.resolve(), as_cmethod)
1738 def compatible_signature_with_resolved_type(self, other_type, as_cmethod):
1739 #print "CFuncType.same_c_signature_as_resolved_type:", \
1740 # self, other_type, "as_cmethod =", as_cmethod ###
1741 if other_type is error_type:
1743 if not other_type.is_cfunction:
1745 if not self.is_overridable and other_type.is_overridable:
1747 nargs = len(self.args)
1748 if nargs - self.optional_arg_count != len(other_type.args) - other_type.optional_arg_count:
1750 if self.optional_arg_count < other_type.optional_arg_count:
1752 # When comparing C method signatures, the first argument
1753 # is exempt from compatibility checking (the proper check
1754 # is performed elsewhere).
1755 for i in range(as_cmethod, len(other_type.args)):
1756 if not self.args[i].type.same_as(
1757 other_type.args[i].type):
1759 if self.has_varargs != other_type.has_varargs:
1761 if not self.return_type.subtype_of_resolved_type(other_type.return_type):
1763 if not self.same_calling_convention_as(other_type):
1765 if self.nogil != other_type.nogil:
1767 self.original_sig = other_type.original_sig or other_type
1769 self.args[0] = other_type.args[0]
1773 def narrower_c_signature_than(self, other_type, as_cmethod = 0):
1774 return self.narrower_c_signature_than_resolved_type(other_type.resolve(), as_cmethod)
1776 def narrower_c_signature_than_resolved_type(self, other_type, as_cmethod):
1777 if other_type is error_type:
1779 if not other_type.is_cfunction:
1781 nargs = len(self.args)
1782 if nargs != len(other_type.args):
1784 for i in range(as_cmethod, nargs):
1785 if not self.args[i].type.subtype_of_resolved_type(other_type.args[i].type):
1788 self.args[i].needs_type_test = other_type.args[i].needs_type_test \
1789 or not self.args[i].type.same_as(other_type.args[i].type)
1790 if self.has_varargs != other_type.has_varargs:
1792 if self.optional_arg_count != other_type.optional_arg_count:
1794 if not self.return_type.subtype_of_resolved_type(other_type.return_type):
1798 def same_calling_convention_as(self, other):
1799 ## XXX Under discussion ...
1800 ## callspec_words = ("__stdcall", "__cdecl", "__fastcall")
1801 ## cs1 = self.calling_convention
1802 ## cs2 = other.calling_convention
1803 ## if (cs1 in callspec_words or
1804 ## cs2 in callspec_words):
1805 ## return cs1 == cs2
1808 sc1 = self.calling_convention == '__stdcall'
1809 sc2 = other.calling_convention == '__stdcall'
1812 def same_exception_signature_as(self, other_type):
1813 return self.same_exception_signature_as_resolved_type(
1814 other_type.resolve())
1816 def same_exception_signature_as_resolved_type(self, other_type):
1817 return self.exception_value == other_type.exception_value \
1818 and self.exception_check == other_type.exception_check
1820 def same_as_resolved_type(self, other_type, as_cmethod = 0):
1821 return self.same_c_signature_as_resolved_type(other_type, as_cmethod) \
1822 and self.same_exception_signature_as_resolved_type(other_type) \
1823 and self.nogil == other_type.nogil
1825 def pointer_assignable_from_resolved_type(self, other_type):
1826 return self.same_c_signature_as_resolved_type(other_type) \
1827 and self.same_exception_signature_as_resolved_type(other_type) \
1828 and not (self.nogil and not other_type.nogil)
1830 def declaration_code(self, entity_code,
1831 for_display = 0, dll_linkage = None, pyrex = 0,
1832 with_calling_convention = 1):
1834 for arg in self.args[:len(self.args)-self.optional_arg_count]:
1835 arg_decl_list.append(
1836 arg.type.declaration_code("", for_display, pyrex = pyrex))
1837 if self.is_overridable:
1838 arg_decl_list.append("int %s" % Naming.skip_dispatch_cname)
1839 if self.optional_arg_count:
1840 arg_decl_list.append(self.op_arg_struct.declaration_code(Naming.optional_args_cname))
1841 if self.has_varargs:
1842 arg_decl_list.append("...")
1843 arg_decl_code = ", ".join(arg_decl_list)
1844 if not arg_decl_code and not pyrex:
1845 arg_decl_code = "void"
1847 if (pyrex or for_display) and not self.return_type.is_pyobject:
1848 if self.exception_value and self.exception_check:
1849 trailer = " except? %s" % self.exception_value
1850 elif self.exception_value:
1851 trailer = " except %s" % self.exception_value
1852 elif self.exception_check == '+':
1853 trailer = " except +"
1855 " except *" # ignored
1858 if not with_calling_convention:
1861 cc = self.calling_convention_prefix()
1862 if (not entity_code and cc) or entity_code.startswith("*"):
1863 entity_code = "(%s%s)" % (cc, entity_code)
1865 return self.return_type.declaration_code(
1866 "%s%s(%s)%s" % (cc, entity_code, arg_decl_code, trailer),
1867 for_display, dll_linkage, pyrex)
1869 def function_header_code(self, func_name, arg_code):
1870 return "%s%s(%s)" % (self.calling_convention_prefix(),
1871 func_name, arg_code)
1873 def signature_string(self):
1874 s = self.declaration_code("")
1877 def signature_cast_string(self):
1878 s = self.declaration_code("(*)", with_calling_convention=False)
1881 def specialize(self, values):
1882 if self.templates is None:
1883 new_templates = None
1885 new_templates = [v.specialize(values) for v in self.templates]
1886 return CFuncType(self.return_type.specialize(values),
1887 [arg.specialize(values) for arg in self.args],
1889 exception_value = self.exception_value,
1890 exception_check = self.exception_check,
1891 calling_convention = self.calling_convention,
1893 with_gil = self.with_gil,
1894 is_overridable = self.is_overridable,
1895 optional_arg_count = self.optional_arg_count,
1896 templates = new_templates)
1898 def opt_arg_cname(self, arg_name):
1899 return self.op_arg_struct.base_type.scope.lookup(arg_name).cname
1902 class CFuncTypeArg(object):
1906 # pos source file position
1908 # FIXME: is this the right setup? should None be allowed here?
1913 def __init__(self, name, type, pos, cname=None):
1915 if cname is not None:
1918 self.cname = Naming.var_prefix + name
1921 self.needs_type_test = False # TODO: should these defaults be set in analyse_types()?
1924 return "%s:%s" % (self.name, repr(self.type))
1926 def declaration_code(self, for_display = 0):
1927 return self.type.declaration_code(self.cname, for_display)
1929 def specialize(self, values):
1930 return CFuncTypeArg(self.name, self.type.specialize(values), self.pos, self.cname)
1932 class StructUtilityCode(object):
1933 def __init__(self, type, forward_decl):
1935 self.header = "static PyObject* %s(%s)" % (type.to_py_function, type.declaration_code('s'))
1936 self.forward_decl = forward_decl
1938 def __eq__(self, other):
1939 return isinstance(other, StructUtilityCode) and self.header == other.header
1941 return hash(self.header)
1943 def put_code(self, output):
1944 code = output['utility_code_def']
1945 proto = output['utility_code_proto']
1947 code.putln("%s {" % self.header)
1948 code.putln("PyObject* res;")
1949 code.putln("PyObject* member;")
1950 code.putln("res = PyDict_New(); if (res == NULL) return NULL;")
1951 for member in self.type.scope.var_entries:
1952 nameconst_cname = code.get_py_string_const(member.name, identifier=True)
1953 code.putln("member = %s(s.%s); if (member == NULL) goto bad;" % (
1954 member.type.to_py_function, member.cname))
1955 code.putln("if (PyDict_SetItem(res, %s, member) < 0) goto bad;" % nameconst_cname)
1956 code.putln("Py_DECREF(member);")
1957 code.putln("return res;")
1959 code.putln("Py_XDECREF(member);")
1960 code.putln("Py_DECREF(res);")
1961 code.putln("return NULL;")
1964 # This is a bit of a hack, we need a forward declaration
1965 # due to the way things are ordered in the module...
1966 if self.forward_decl:
1967 proto.putln(self.type.declaration_code('') + ';')
1968 proto.putln(self.header + ";")
1971 class CStructOrUnionType(CType):
1974 # kind string "struct" or "union"
1975 # scope StructOrUnionScope, or None if incomplete
1976 # typedef_flag boolean
1981 is_struct_or_union = 1
1984 def __init__(self, name, kind, scope, typedef_flag, cname, packed=False):
1989 self.typedef_flag = typedef_flag
1990 self.is_struct = kind == 'struct'
1992 self.to_py_function = "%s_to_py_%s" % (Naming.convert_func_prefix, self.cname)
1993 self.exception_check = True
1994 self._convert_code = None
1995 self.packed = packed
1997 def create_to_py_utility_code(self, env):
1998 if env.outer_scope is None:
2001 if self._convert_code is False: return # tri-state-ish
2003 if self._convert_code is None:
2004 for member in self.scope.var_entries:
2005 if not member.type.to_py_function or not member.type.create_to_py_utility_code(env):
2006 self.to_py_function = None
2007 self._convert_code = False
2009 forward_decl = (self.entry.visibility != 'extern')
2010 self._convert_code = StructUtilityCode(self, forward_decl)
2012 env.use_utility_code(self._convert_code)
2016 return "<CStructOrUnionType %s %s%s>" % (self.name, self.cname,
2017 ("", " typedef")[self.typedef_flag])
2019 def declaration_code(self, entity_code,
2020 for_display = 0, dll_linkage = None, pyrex = 0):
2021 if pyrex or for_display:
2022 base_code = self.name
2024 if self.typedef_flag:
2025 base_code = self.cname
2027 base_code = "%s %s" % (self.kind, self.cname)
2028 base_code = public_decl(base_code, dll_linkage)
2029 return self.base_declaration_code(base_code, entity_code)
2031 def __eq__(self, other):
2033 return (isinstance(other, CStructOrUnionType) and
2034 self.name == other.name)
2035 except AttributeError:
2038 def __lt__(self, other):
2040 return self.name < other.name
2041 except AttributeError:
2042 # this is arbitrary, but it makes sure we always have
2043 # *some* kind of order
2047 return hash(self.cname) ^ hash(self.kind)
2049 def is_complete(self):
2050 return self.scope is not None
2052 def attributes_known(self):
2053 return self.is_complete()
2055 def can_be_complex(self):
2056 # Does the struct consist of exactly two identical floats?
2057 fields = self.scope.var_entries
2058 if len(fields) != 2: return False
2060 return (a.type.is_float and b.type.is_float and
2061 a.type.declaration_code("") ==
2062 b.type.declaration_code(""))
2064 def struct_nesting_depth(self):
2065 child_depths = [x.type.struct_nesting_depth()
2066 for x in self.scope.var_entries]
2067 return max(child_depths) + 1
2069 class CppClassType(CType):
2072 # scope CppClassScope
2073 # templates [string] or None
2077 exception_check = True
2080 def __init__(self, name, scope, cname, base_classes, templates = None, template_type = None):
2084 self.base_classes = base_classes
2086 self.templates = templates
2087 self.template_type = template_type
2088 self.specializations = {}
2090 def specialize_here(self, pos, template_values = None):
2091 if self.templates is None:
2092 error(pos, "'%s' type is not a template" % self);
2093 return PyrexTypes.error_type
2094 if len(self.templates) != len(template_values):
2095 error(pos, "%s templated type receives %d arguments, got %d" %
2096 (self.name, len(self.templates), len(template_values)))
2098 return self.specialize(dict(zip(self.templates, template_values)))
2100 def specialize(self, values):
2101 if not self.templates and not self.namespace:
2103 if self.templates is None:
2105 key = tuple(values.items())
2106 if key in self.specializations:
2107 return self.specializations[key]
2108 template_values = [t.specialize(values) for t in self.templates]
2109 specialized = self.specializations[key] = \
2110 CppClassType(self.name, None, self.cname, [], template_values, template_type=self)
2111 # Need to do these *after* self.specializations[key] is set
2112 # to avoid infinite recursion on circular references.
2113 specialized.base_classes = [b.specialize(values) for b in self.base_classes]
2114 specialized.scope = self.scope.specialize(values)
2115 if self.namespace is not None:
2116 specialized.namespace = self.namespace.specialize(values)
2119 def declaration_code(self, entity_code,
2120 for_display = 0, dll_linkage = None, pyrex = 0):
2122 template_strings = [param.declaration_code('', for_display, None, pyrex)
2123 for param in self.templates]
2124 templates = "<%s>" % ",".join(template_strings)
2125 if templates[-2:] == ">>":
2126 templates = templates[:-2] + "> >"
2129 if pyrex or for_display:
2130 base_code = "%s%s" % (self.name, templates)
2132 base_code = "%s%s" % (self.cname, templates)
2133 if self.namespace is not None:
2134 base_code = "%s::%s" % (self.namespace.declaration_code(''), base_code)
2135 base_code = public_decl(base_code, dll_linkage)
2136 return self.base_declaration_code(base_code, entity_code)
2138 def is_subclass(self, other_type):
2139 # TODO(danilo): Handle templates.
2140 if self.same_as_resolved_type(other_type):
2142 for base_class in self.base_classes:
2143 if base_class.is_subclass(other_type):
2147 def same_as_resolved_type(self, other_type):
2148 if other_type.is_cpp_class:
2149 if self == other_type:
2151 elif self.template_type and self.template_type == other_type.template_type:
2152 if self.templates == other_type.templates:
2154 for t1, t2 in zip(self.templates, other_type.templates):
2155 if not t1.same_as_resolved_type(t2):
2160 def assignable_from_resolved_type(self, other_type):
2161 # TODO: handle operator=(...) here?
2162 if other_type is error_type:
2164 return other_type.is_cpp_class and other_type.is_subclass(self)
2166 def attributes_known(self):
2167 return self.scope is not None
2170 class TemplatePlaceholderType(CType):
2172 def __init__(self, name):
2175 def declaration_code(self, entity_code,
2176 for_display = 0, dll_linkage = None, pyrex = 0):
2178 return self.name + " " + entity_code
2182 def specialize(self, values):
2188 def same_as_resolved_type(self, other_type):
2189 if isinstance(other_type, TemplatePlaceholderType):
2190 return self.name == other_type.name
2195 return hash(self.name)
2197 def __cmp__(self, other):
2198 if isinstance(other, TemplatePlaceholderType):
2199 return cmp(self.name, other.name)
2201 return cmp(type(self), type(other))
2203 class CEnumType(CType):
2205 # cname string or None
2206 # typedef_flag boolean
2210 rank = -1 # Ranks below any integer type
2211 to_py_function = "PyInt_FromLong"
2212 from_py_function = "PyInt_AsLong"
2214 def __init__(self, name, cname, typedef_flag):
2218 self.typedef_flag = typedef_flag
2224 return "<CEnumType %s %s%s>" % (self.name, self.cname,
2225 ("", " typedef")[self.typedef_flag])
2227 def declaration_code(self, entity_code,
2228 for_display = 0, dll_linkage = None, pyrex = 0):
2229 if pyrex or for_display:
2230 base_code = self.name
2232 if self.typedef_flag:
2233 base_code = self.cname
2235 base_code = "enum %s" % self.cname
2236 base_code = public_decl(base_code, dll_linkage)
2237 return self.base_declaration_code(base_code, entity_code)
2240 class CStringType(object):
2241 # Mixin class for C string types.
2246 to_py_function = "PyBytes_FromString"
2247 from_py_function = "PyBytes_AsString"
2248 exception_value = "NULL"
2250 def literal_code(self, value):
2251 assert isinstance(value, str)
2252 return '"%s"' % StringEncoding.escape_byte_string(value)
2255 class CUTF8CharArrayType(CStringType, CArrayType):
2260 to_py_function = "PyUnicode_DecodeUTF8"
2261 exception_value = "NULL"
2263 def __init__(self, size):
2264 CArrayType.__init__(self, c_char_type, size)
2266 class CCharArrayType(CStringType, CArrayType):
2269 def __init__(self, size):
2270 CArrayType.__init__(self, c_char_type, size)
2273 class CCharPtrType(CStringType, CPtrType):
2277 CPtrType.__init__(self, c_char_type)
2280 class CUCharPtrType(CStringType, CPtrType):
2281 # C 'unsigned char *' type.
2283 to_py_function = "__Pyx_PyBytes_FromUString"
2284 from_py_function = "__Pyx_PyBytes_AsUString"
2287 CPtrType.__init__(self, c_uchar_type)
2290 class UnspecifiedType(PyrexType):
2291 # Used as a placeholder until the type can be determined.
2295 def declaration_code(self, entity_code,
2296 for_display = 0, dll_linkage = None, pyrex = 0):
2297 return "<unspecified>"
2299 def same_as_resolved_type(self, other_type):
2303 class ErrorType(PyrexType):
2304 # Used to prevent propagation of error messages.
2307 exception_value = "0"
2309 to_py_function = "dummy"
2310 from_py_function = "dummy"
2312 def create_to_py_utility_code(self, env):
2315 def create_from_py_utility_code(self, env):
2318 def declaration_code(self, entity_code,
2319 for_display = 0, dll_linkage = None, pyrex = 0):
2322 def same_as_resolved_type(self, other_type):
2325 def error_condition(self, result_code):
2329 rank_to_type_name = (
2340 RANK_INT = list(rank_to_type_name).index('int')
2341 RANK_LONG = list(rank_to_type_name).index('long')
2346 py_object_type = PyObjectType()
2348 c_void_type = CVoidType()
2350 c_uchar_type = CIntType(0, UNSIGNED)
2351 c_ushort_type = CIntType(1, UNSIGNED)
2352 c_uint_type = CIntType(2, UNSIGNED)
2353 c_ulong_type = CIntType(3, UNSIGNED)
2354 c_ulonglong_type = CIntType(4, UNSIGNED)
2356 c_char_type = CIntType(0)
2357 c_short_type = CIntType(1)
2358 c_int_type = CIntType(2)
2359 c_long_type = CIntType(3)
2360 c_longlong_type = CIntType(4)
2362 c_schar_type = CIntType(0, SIGNED)
2363 c_sshort_type = CIntType(1, SIGNED)
2364 c_sint_type = CIntType(2, SIGNED)
2365 c_slong_type = CIntType(3, SIGNED)
2366 c_slonglong_type = CIntType(4, SIGNED)
2368 c_float_type = CFloatType(5, math_h_modifier='f')
2369 c_double_type = CFloatType(6)
2370 c_longdouble_type = CFloatType(7, math_h_modifier='l')
2372 c_float_complex_type = CComplexType(c_float_type)
2373 c_double_complex_type = CComplexType(c_double_type)
2374 c_longdouble_complex_type = CComplexType(c_longdouble_type)
2376 c_anon_enum_type = CAnonEnumType(-1)
2377 c_returncode_type = CReturnCodeType(RANK_INT)
2378 c_bint_type = CBIntType(RANK_INT)
2379 c_py_unicode_type = CPyUnicodeIntType(RANK_INT-0.5, UNSIGNED)
2380 c_py_ucs4_type = CPyUCS4IntType(RANK_LONG-0.5, UNSIGNED)
2381 c_py_ssize_t_type = CPySSizeTType(RANK_LONG+0.5, SIGNED)
2382 c_ssize_t_type = CSSizeTType(RANK_LONG+0.5, SIGNED)
2383 c_size_t_type = CSizeTType(RANK_LONG+0.5, UNSIGNED)
2385 c_null_ptr_type = CNullPtrType(c_void_type)
2386 c_void_ptr_type = CPtrType(c_void_type)
2387 c_void_ptr_ptr_type = CPtrType(c_void_ptr_type)
2388 c_char_array_type = CCharArrayType(None)
2389 c_char_ptr_type = CCharPtrType()
2390 c_uchar_ptr_type = CUCharPtrType()
2391 c_utf8_char_array_type = CUTF8CharArrayType(None)
2392 c_char_ptr_ptr_type = CPtrType(c_char_ptr_type)
2393 c_int_ptr_type = CPtrType(c_int_type)
2394 c_py_unicode_ptr_type = CPtrType(c_py_unicode_type)
2395 c_py_ssize_t_ptr_type = CPtrType(c_py_ssize_t_type)
2396 c_ssize_t_ptr_type = CPtrType(c_ssize_t_type)
2397 c_size_t_ptr_type = CPtrType(c_size_t_type)
2400 # the Py_buffer type is defined in Builtin.py
2401 c_py_buffer_type = CStructOrUnionType("Py_buffer", "struct", None, 1, "Py_buffer")
2402 c_py_buffer_ptr_type = CPtrType(c_py_buffer_type)
2404 error_type = ErrorType()
2405 unspecified_type = UnspecifiedType()
2407 modifiers_and_name_to_type = {
2408 #(signed, longness, name) : type
2409 (0, 0, "char"): c_uchar_type,
2410 (1, 0, "char"): c_char_type,
2411 (2, 0, "char"): c_schar_type,
2413 (0, -1, "int"): c_ushort_type,
2414 (0, 0, "int"): c_uint_type,
2415 (0, 1, "int"): c_ulong_type,
2416 (0, 2, "int"): c_ulonglong_type,
2418 (1, -1, "int"): c_short_type,
2419 (1, 0, "int"): c_int_type,
2420 (1, 1, "int"): c_long_type,
2421 (1, 2, "int"): c_longlong_type,
2423 (2, -1, "int"): c_sshort_type,
2424 (2, 0, "int"): c_sint_type,
2425 (2, 1, "int"): c_slong_type,
2426 (2, 2, "int"): c_slonglong_type,
2428 (1, 0, "float"): c_float_type,
2429 (1, 0, "double"): c_double_type,
2430 (1, 1, "double"): c_longdouble_type,
2432 (1, 0, "complex"): c_double_complex_type, # C: float, Python: double => Python wins
2433 (1, 0, "floatcomplex"): c_float_complex_type,
2434 (1, 0, "doublecomplex"): c_double_complex_type,
2435 (1, 1, "doublecomplex"): c_longdouble_complex_type,
2438 (1, 0, "void"): c_void_type,
2440 (1, 0, "bint"): c_bint_type,
2441 (0, 0, "Py_UNICODE"): c_py_unicode_type,
2442 (0, 0, "Py_UCS4"): c_py_ucs4_type,
2443 (2, 0, "Py_ssize_t"): c_py_ssize_t_type,
2444 (2, 0, "ssize_t") : c_ssize_t_type,
2445 (0, 0, "size_t") : c_size_t_type,
2447 (1, 0, "object"): py_object_type,
2450 def is_promotion(src_type, dst_type):
2451 # It's hard to find a hard definition of promotion, but empirical
2452 # evidence suggests that the below is all that's allowed.
2453 if src_type.is_numeric:
2454 if dst_type.same_as(c_int_type):
2455 unsigned = (not src_type.signed)
2456 return (src_type.is_enum or
2457 (src_type.is_int and
2458 unsigned + src_type.rank < dst_type.rank))
2459 elif dst_type.same_as(c_double_type):
2460 return src_type.is_float and src_type.rank <= dst_type.rank
2463 def best_match(args, functions, pos=None):
2465 Given a list args of arguments and a list of functions, choose one
2466 to call which seems to be the "best" fit for this list of arguments.
2467 This function is used, e.g., when deciding which overloaded method
2468 to dispatch for C++ classes.
2470 We first eliminate functions based on arity, and if only one
2471 function has the correct arity, we return it. Otherwise, we weight
2472 functions based on how much work must be done to convert the
2473 arguments, with the following priorities:
2474 * identical types or pointers to identical types
2477 That is, we prefer functions where no arguments need converted,
2478 and failing that, functions where only promotions are required, and
2481 If no function is deemed a good fit, or if two or more functions have
2482 the same weight, we return None (as there is no best match). If pos
2483 is not None, we also generate an error.
2485 # TODO: args should be a list of types, not a list of Nodes.
2486 actual_nargs = len(args)
2490 for func in functions:
2492 func_type = func.type
2493 if func_type.is_ptr:
2494 func_type = func_type.base_type
2495 # Check function type
2496 if not func_type.is_cfunction:
2497 if not func_type.is_error and pos is not None:
2498 error_mesg = "Calling non-function type '%s'" % func_type
2499 errors.append((func, error_mesg))
2502 max_nargs = len(func_type.args)
2503 min_nargs = max_nargs - func_type.optional_arg_count
2504 if actual_nargs < min_nargs or \
2505 (not func_type.has_varargs and actual_nargs > max_nargs):
2506 if max_nargs == min_nargs and not func_type.has_varargs:
2507 expectation = max_nargs
2508 elif actual_nargs < min_nargs:
2509 expectation = "at least %s" % min_nargs
2511 expectation = "at most %s" % max_nargs
2512 error_mesg = "Call with wrong number of arguments (expected %s, got %s)" \
2513 % (expectation, actual_nargs)
2514 errors.append((func, error_mesg))
2516 candidates.append((func, func_type))
2518 # Optimize the most common case of no overloading...
2519 if len(candidates) == 1:
2520 return candidates[0][0]
2521 elif len(candidates) == 0:
2523 if len(errors) == 1:
2524 error(pos, errors[0][1])
2526 error(pos, "no suitable method found")
2531 for func, func_type in candidates:
2533 for i in range(min(len(args), len(func_type.args))):
2534 src_type = args[i].type
2535 dst_type = func_type.args[i].type
2536 if dst_type.assignable_from(src_type):
2537 if src_type == dst_type or dst_type.same_as(src_type):
2539 elif is_promotion(src_type, dst_type):
2541 elif not src_type.is_pyobject:
2546 error_mesg = "Invalid conversion from '%s' to '%s'"%(src_type,
2548 bad_types.append((func, error_mesg))
2551 possibilities.append((score, func)) # so we can sort it
2553 possibilities.sort()
2554 if len(possibilities) > 1 and possibilities[0][0] == possibilities[1][0]:
2556 error(pos, "ambiguous overloaded method")
2558 return possibilities[0][1]
2560 if len(bad_types) == 1:
2561 error(pos, bad_types[0][1])
2563 error(pos, "no suitable method found")
2566 def widest_numeric_type(type1, type2):
2567 # Given two numeric types, return the narrowest type
2568 # encompassing both of them.
2571 elif type1.is_complex or type2.is_complex:
2572 def real_type(ntype):
2573 if ntype.is_complex:
2574 return ntype.real_type
2576 widest_type = CComplexType(
2577 widest_numeric_type(
2580 elif type1.is_enum and type2.is_enum:
2581 widest_type = c_int_type
2582 elif type1.rank < type2.rank:
2584 elif type1.rank > type2.rank:
2586 elif type1.signed < type2.signed:
2592 def independent_spanning_type(type1, type2):
2593 # Return a type assignable independently from both type1 and
2594 # type2, but do not require any interoperability between the two.
2595 # For example, in "True * 2", it is safe to assume an integer
2596 # result type (so spanning_type() will do the right thing),
2597 # whereas "x = True or 2" must evaluate to a type that can hold
2598 # both a boolean value and an integer, so this function works
2602 elif (type1 is c_bint_type or type2 is c_bint_type) and (type1.is_numeric and type2.is_numeric):
2603 # special case: if one of the results is a bint and the other
2604 # is another C integer, we must prevent returning a numeric
2605 # type so that we do not lose the ability to coerce to a
2606 # Python bool if we have to.
2607 return py_object_type
2608 span_type = _spanning_type(type1, type2)
2609 if span_type is None:
2613 def spanning_type(type1, type2):
2614 # Return a type assignable from both type1 and type2, or
2615 # py_object_type if no better type is found. Assumes that the
2616 # code that calls this will try a coercion afterwards, which will
2617 # fail if the types cannot actually coerce to a py_object_type.
2620 elif type1 is py_object_type or type2 is py_object_type:
2621 return py_object_type
2622 elif type1 is c_py_unicode_type or type2 is c_py_unicode_type:
2623 # Py_UNICODE behaves more like a string than an int
2624 return py_object_type
2625 span_type = _spanning_type(type1, type2)
2626 if span_type is None:
2627 return py_object_type
2630 def _spanning_type(type1, type2):
2631 if type1.is_numeric and type2.is_numeric:
2632 return widest_numeric_type(type1, type2)
2633 elif type1.is_builtin_type and type1.name == 'float' and type2.is_numeric:
2634 return widest_numeric_type(c_double_type, type2)
2635 elif type2.is_builtin_type and type2.name == 'float' and type1.is_numeric:
2636 return widest_numeric_type(type1, c_double_type)
2637 elif type1.is_extension_type and type2.is_extension_type:
2638 return widest_extension_type(type1, type2)
2639 elif type1.is_pyobject or type2.is_pyobject:
2640 return py_object_type
2641 elif type1.assignable_from(type2):
2642 if type1.is_extension_type and type1.typeobj_is_imported():
2643 # external types are unsafe, so we use PyObject instead
2644 return py_object_type
2646 elif type2.assignable_from(type1):
2647 if type2.is_extension_type and type2.typeobj_is_imported():
2648 # external types are unsafe, so we use PyObject instead
2649 return py_object_type
2654 def widest_extension_type(type1, type2):
2655 if type1.typeobj_is_imported() or type2.typeobj_is_imported():
2656 return py_object_type
2658 if type1.subtype_of(type2):
2660 elif type2.subtype_of(type1):
2662 type1, type2 = type1.base_type, type2.base_type
2663 if type1 is None or type2 is None:
2664 return py_object_type
2666 def simple_c_type(signed, longness, name):
2667 # Find type descriptor for simple type given name and modifiers.
2668 # Returns None if arguments don't make sense.
2669 return modifiers_and_name_to_type.get((signed, longness, name))
2671 def parse_basic_type(name):
2673 if name.startswith('p_'):
2674 base = parse_basic_type(name[2:])
2675 elif name.startswith('p'):
2676 base = parse_basic_type(name[1:])
2677 elif name.endswith('*'):
2678 base = parse_basic_type(name[:-1])
2680 return CPtrType(base)
2682 basic_type = simple_c_type(1, 0, name)
2688 if name == 'Py_UNICODE':
2690 elif name == 'Py_UCS4':
2692 elif name == 'Py_ssize_t':
2694 elif name == 'ssize_t':
2696 elif name == 'size_t':
2699 if name.startswith('u'):
2702 elif (name.startswith('s') and
2703 not name.startswith('short')):
2707 while name.startswith('short'):
2708 name = name.replace('short', '', 1).strip()
2710 while name.startswith('long'):
2711 name = name.replace('long', '', 1).strip()
2713 if longness != 0 and not name:
2715 return simple_c_type(signed, longness, name)
2717 def c_array_type(base_type, size):
2718 # Construct a C array type.
2719 if base_type is c_char_type:
2720 return CCharArrayType(size)
2721 elif base_type is error_type:
2724 return CArrayType(base_type, size)
2726 def c_ptr_type(base_type):
2727 # Construct a C pointer type.
2728 if base_type is c_char_type:
2729 return c_char_ptr_type
2730 elif base_type is c_uchar_type:
2731 return c_uchar_ptr_type
2732 elif base_type is error_type:
2735 return CPtrType(base_type)
2737 def c_ref_type(base_type):
2738 # Construct a C reference type
2739 if base_type is error_type:
2742 return CReferenceType(base_type)
2744 def same_type(type1, type2):
2745 return type1.same_as(type2)
2747 def assignable_from(type1, type2):
2748 return type1.assignable_from(type2)
2750 def typecast(to_type, from_type, expr_code):
2751 # Return expr_code cast to a C type which can be
2752 # assigned to to_type, assuming its existing C type
2754 if to_type is from_type or \
2755 (not to_type.is_pyobject and assignable_from(to_type, from_type)):
2758 #print "typecast: to", to_type, "from", from_type ###
2759 return to_type.cast_code(expr_code)
2762 type_conversion_predeclarations = """
2763 /* Type Conversion Predeclarations */
2765 #define __Pyx_PyBytes_FromUString(s) PyBytes_FromString((char*)s)
2766 #define __Pyx_PyBytes_AsUString(s) ((unsigned char*) PyBytes_AsString(s))
2768 #define __Pyx_PyBool_FromLong(b) ((b) ? (Py_INCREF(Py_True), Py_True) : (Py_INCREF(Py_False), Py_False))
2769 static CYTHON_INLINE int __Pyx_PyObject_IsTrue(PyObject*);
2770 static CYTHON_INLINE PyObject* __Pyx_PyNumber_Int(PyObject* x);
2772 static CYTHON_INLINE Py_ssize_t __Pyx_PyIndex_AsSsize_t(PyObject*);
2773 static CYTHON_INLINE PyObject * __Pyx_PyInt_FromSize_t(size_t);
2774 static CYTHON_INLINE size_t __Pyx_PyInt_AsSize_t(PyObject*);
2776 #define __pyx_PyFloat_AsDouble(x) (PyFloat_CheckExact(x) ? PyFloat_AS_DOUBLE(x) : PyFloat_AsDouble(x))
2778 """ + type_conversion_predeclarations
2780 # Note: __Pyx_PyObject_IsTrue is written to minimize branching.
2781 type_conversion_functions = """
2782 /* Type Conversion Functions */
2784 static CYTHON_INLINE int __Pyx_PyObject_IsTrue(PyObject* x) {
2785 int is_true = x == Py_True;
2786 if (is_true | (x == Py_False) | (x == Py_None)) return is_true;
2787 else return PyObject_IsTrue(x);
2790 static CYTHON_INLINE PyObject* __Pyx_PyNumber_Int(PyObject* x) {
2792 const char *name = NULL;
2793 PyObject *res = NULL;
2794 #if PY_VERSION_HEX < 0x03000000
2795 if (PyInt_Check(x) || PyLong_Check(x))
2797 if (PyLong_Check(x))
2799 return Py_INCREF(x), x;
2800 m = Py_TYPE(x)->tp_as_number;
2801 #if PY_VERSION_HEX < 0x03000000
2802 if (m && m->nb_int) {
2804 res = PyNumber_Int(x);
2806 else if (m && m->nb_long) {
2808 res = PyNumber_Long(x);
2811 if (m && m->nb_int) {
2813 res = PyNumber_Long(x);
2817 #if PY_VERSION_HEX < 0x03000000
2818 if (!PyInt_Check(res) && !PyLong_Check(res)) {
2820 if (!PyLong_Check(res)) {
2822 PyErr_Format(PyExc_TypeError,
2823 "__%s__ returned non-%s (type %.200s)",
2824 name, name, Py_TYPE(res)->tp_name);
2829 else if (!PyErr_Occurred()) {
2830 PyErr_SetString(PyExc_TypeError,
2831 "an integer is required");
2836 static CYTHON_INLINE Py_ssize_t __Pyx_PyIndex_AsSsize_t(PyObject* b) {
2838 PyObject* x = PyNumber_Index(b);
2840 ival = PyInt_AsSsize_t(x);
2845 static CYTHON_INLINE PyObject * __Pyx_PyInt_FromSize_t(size_t ival) {
2846 #if PY_VERSION_HEX < 0x02050000
2847 if (ival <= LONG_MAX)
2848 return PyInt_FromLong((long)ival);
2850 unsigned char *bytes = (unsigned char *) &ival;
2851 int one = 1; int little = (int)*(unsigned char*)&one;
2852 return _PyLong_FromByteArray(bytes, sizeof(size_t), little, 0);
2855 return PyInt_FromSize_t(ival);
2859 static CYTHON_INLINE size_t __Pyx_PyInt_AsSize_t(PyObject* x) {
2860 unsigned PY_LONG_LONG val = __Pyx_PyInt_AsUnsignedLongLong(x);
2861 if (unlikely(val == (unsigned PY_LONG_LONG)-1 && PyErr_Occurred())) {
2863 } else if (unlikely(val != (unsigned PY_LONG_LONG)(size_t)val)) {
2864 PyErr_SetString(PyExc_OverflowError,
2865 "value too large to convert to size_t");
2871 """ + type_conversion_functions