2 # Cython/Python language types
5 from Code import UtilityCode, LazyUtilityCode, TempitaUtilityCode
9 from Errors import error
11 class BaseType(object):
13 # Base class for all Cython types including pseudo-types.
15 # List of attribute names of any subtypes
18 def can_coerce_to_pyobject(self, env):
21 def cast_code(self, expr_code):
22 return "((%s)%s)" % (self.declaration_code(""), expr_code)
24 def specialization_name(self):
25 # This is not entirely robust.
26 safe = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz_0123456789'
28 for c in self.declaration_code("").replace("unsigned ", "unsigned_").replace("long long", "long_long").replace(" ", "__"):
32 all.append('_%x_' % ord(c))
35 def base_declaration_code(self, base_code, entity_code):
37 return "%s %s" % (base_code, entity_code)
41 def __deepcopy__(self, memo):
43 Types never need to be copied, if we do copy, Unfortunate Things
48 def get_fused_types(self, result=None, seen=None, subtypes=None):
49 subtypes = subtypes or self.subtypes
56 list_or_subtype = getattr(self, attr)
58 if isinstance(list_or_subtype, BaseType):
59 list_or_subtype.get_fused_types(result, seen)
61 for subtype in list_or_subtype:
62 subtype.get_fused_types(result, seen)
68 def specialize_fused(self, env):
69 if env.fused_to_specific:
70 return self.specialize(env.fused_to_specific)
74 def _get_fused_types(self):
76 Add this indirection for the is_fused property to allow overriding
77 get_fused_types in subclasses.
79 return self.get_fused_types()
81 is_fused = property(_get_fused_types, doc="Whether this type or any of its "
82 "subtypes is a fused type")
84 def deduce_template_params(self, actual):
86 Deduce any template params in this (argument) type given the actual
89 http://en.cppreference.com/w/cpp/language/function_template#Template_argument_deduction
96 def __lt__(self, other):
98 For sorting. The sorting order should correspond to the preference of
99 conversion from Python types.
101 Override to provide something sensible. This is only implemented so that
102 python 3 doesn't trip
104 return id(type(self)) < id(type(other))
106 def py_type_name(self):
108 Return the name of the Python type that can coerce to this type.
111 def typeof_name(self):
113 Return the string with which fused python functions can be indexed.
115 if self.is_builtin_type or self.py_type_name() == 'object':
116 index_name = self.py_type_name()
118 index_name = str(self)
122 def check_for_null_code(self, cname):
124 Return the code for a NULL-check in case an UnboundLocalError should
125 be raised if an entry of this type is referenced before assignment.
126 Returns None if no check should be performed.
130 def invalid_value(self):
132 Returns the most invalid value an object of this type can assume as a
133 C expression string. Returns None if no such value exists.
137 class PyrexType(BaseType):
139 # Base class for all Cython types
141 # is_pyobject boolean Is a Python object type
142 # is_extension_type boolean Is a Python extension type
143 # is_final_type boolean Is a final extension type
144 # is_numeric boolean Is a C numeric type
145 # is_int boolean Is a C integer type
146 # is_float boolean Is a C floating point type
147 # is_complex boolean Is a C complex type
148 # is_void boolean Is the C void type
149 # is_array boolean Is a C array type
150 # is_ptr boolean Is a C pointer type
151 # is_null_ptr boolean Is the type of NULL
152 # is_reference boolean Is a C reference type
153 # is_const boolean Is a C const type.
154 # is_cfunction boolean Is a C function type
155 # is_struct_or_union boolean Is a C struct or union type
156 # is_struct boolean Is a C struct type
157 # is_enum boolean Is a C enum type
158 # is_typedef boolean Is a typedef type
159 # is_string boolean Is a C char * type
160 # is_pyunicode_ptr boolean Is a C PyUNICODE * type
161 # is_cpp_string boolean Is a C++ std::string type
162 # is_unicode_char boolean Is either Py_UCS4 or Py_UNICODE
163 # is_returncode boolean Is used only to signal exceptions
164 # is_error boolean Is the dummy error type
165 # is_buffer boolean Is buffer access type
166 # has_attributes boolean Has C dot-selectable attributes
167 # default_value string Initial value
168 # entry Entry The Entry for this type
170 # declaration_code(entity_code,
171 # for_display = 0, dll_linkage = None, pyrex = 0)
172 # Returns a code fragment for the declaration of an entity
173 # of this type, given a code fragment for the entity.
174 # * If for_display, this is for reading by a human in an error
175 # message; otherwise it must be valid C code.
176 # * If dll_linkage is not None, it must be 'DL_EXPORT' or
177 # 'DL_IMPORT', and will be added to the base type part of
179 # * If pyrex = 1, this is for use in a 'cdef extern'
180 # statement of a Cython include file.
182 # assignable_from(src_type)
183 # Tests whether a variable of this type can be
184 # assigned a value of type src_type.
186 # same_as(other_type)
187 # Tests whether this type represents the same type
190 # as_argument_type():
191 # Coerces array and C function types into pointer type for use as
192 # a formal argument type.
197 is_extension_type = 0
211 is_struct_or_union = 0
223 is_memoryviewslice = 0
228 # If a typedef, returns the base type.
231 def specialize(self, values):
232 # TODO(danilo): Override wherever it makes sense.
235 def literal_code(self, value):
236 # Returns a C code fragment representing a literal
237 # value of this type.
241 return self.declaration_code("", for_display = 1).strip()
243 def same_as(self, other_type, **kwds):
244 return self.same_as_resolved_type(other_type.resolve(), **kwds)
246 def same_as_resolved_type(self, other_type):
247 return self == other_type or other_type is error_type
249 def subtype_of(self, other_type):
250 return self.subtype_of_resolved_type(other_type.resolve())
252 def subtype_of_resolved_type(self, other_type):
253 return self.same_as(other_type)
255 def assignable_from(self, src_type):
256 return self.assignable_from_resolved_type(src_type.resolve())
258 def assignable_from_resolved_type(self, src_type):
259 return self.same_as(src_type)
261 def as_argument_type(self):
264 def is_complete(self):
265 # A type is incomplete if it is an unsized array,
266 # a struct whose attributes are not defined, etc.
269 def is_simple_buffer_dtype(self):
270 return (self.is_int or self.is_float or self.is_complex or self.is_pyobject or
271 self.is_extension_type or self.is_ptr)
273 def struct_nesting_depth(self):
274 # Returns the number levels of nested structs. This is
275 # used for constructing a stack for walking the run-time
276 # type information of the struct.
279 def global_init_code(self, entry, code):
283 def needs_nonecheck(self):
287 def public_decl(base_code, dll_linkage):
289 return "%s(%s)" % (dll_linkage, base_code)
293 def create_typedef_type(name, base_type, cname, is_external=0):
294 is_fused = base_type.is_fused
295 if base_type.is_complex or is_fused:
302 raise ValueError("%s external typedefs not supported" % msg)
306 return CTypedefType(name, base_type, cname, is_external)
309 class CTypedefType(BaseType):
311 # Pseudo-type defined with a ctypedef statement in a
312 # 'cdef extern from' block.
313 # Delegates most attribute lookups to the base type.
314 # (Anything not defined here or in the BaseType is delegated.)
316 # qualified_name string
317 # typedef_name string
318 # typedef_cname string
319 # typedef_base_type PyrexType
320 # typedef_is_external bool
323 typedef_is_external = 0
325 to_py_utility_code = None
326 from_py_utility_code = None
328 subtypes = ['typedef_base_type']
330 def __init__(self, name, base_type, cname, is_external=0):
331 assert not base_type.is_complex
332 self.typedef_name = name
333 self.typedef_cname = cname
334 self.typedef_base_type = base_type
335 self.typedef_is_external = is_external
337 def invalid_value(self):
338 return self.typedef_base_type.invalid_value()
341 return self.typedef_base_type.resolve()
343 def declaration_code(self, entity_code,
344 for_display = 0, dll_linkage = None, pyrex = 0):
345 if pyrex or for_display:
346 base_code = self.typedef_name
348 base_code = public_decl(self.typedef_cname, dll_linkage)
349 return self.base_declaration_code(base_code, entity_code)
351 def as_argument_type(self):
354 def cast_code(self, expr_code):
355 # If self is really an array (rather than pointer), we can't cast.
356 # For example, the gmp mpz_t.
357 if self.typedef_base_type.is_array:
358 base_type = self.typedef_base_type.base_type
359 return CPtrType(base_type).cast_code(expr_code)
361 return BaseType.cast_code(self, expr_code)
364 return "<CTypedefType %s>" % self.typedef_cname
367 return self.typedef_name
369 def _create_utility_code(self, template_utility_code,
370 template_function_name):
371 type_name = self.typedef_cname.replace(" ","_").replace("::","__")
372 utility_code = template_utility_code.specialize(
373 type = self.typedef_cname,
374 TypeName = type_name)
375 function_name = template_function_name % type_name
376 return utility_code, function_name
378 def create_to_py_utility_code(self, env):
379 if self.typedef_is_external:
380 if not self.to_py_utility_code:
381 base_type = self.typedef_base_type
382 if type(base_type) is CIntType:
383 self.to_py_function = "__Pyx_PyInt_From_" + self.specialization_name()
384 env.use_utility_code(TempitaUtilityCode.load(
385 "CIntToPy", "TypeConversion.c",
386 context={"TYPE": self.declaration_code(''),
387 "TO_PY_FUNCTION": self.to_py_function}))
389 elif base_type.is_float:
390 pass # XXX implement!
391 elif base_type.is_complex:
392 pass # XXX implement!
394 if self.to_py_utility_code:
395 env.use_utility_code(self.to_py_utility_code)
398 return self.typedef_base_type.create_to_py_utility_code(env)
400 def create_from_py_utility_code(self, env):
401 if self.typedef_is_external:
402 if not self.from_py_utility_code:
403 base_type = self.typedef_base_type
404 if type(base_type) is CIntType:
405 self.from_py_function = "__Pyx_PyInt_As_" + self.specialization_name()
406 env.use_utility_code(TempitaUtilityCode.load(
407 "CIntFromPy", "TypeConversion.c",
408 context={"TYPE": self.declaration_code(''),
409 "FROM_PY_FUNCTION": self.from_py_function}))
411 elif base_type.is_float:
412 pass # XXX implement!
413 elif base_type.is_complex:
414 pass # XXX implement!
415 if self.from_py_utility_code:
416 env.use_utility_code(self.from_py_utility_code)
419 return self.typedef_base_type.create_from_py_utility_code(env)
421 def overflow_check_binop(self, binop, env, const_rhs=False):
422 env.use_utility_code(UtilityCode.load("Common", "Overflow.c"))
423 type = self.declaration_code("")
424 name = self.specialization_name()
425 if binop == "lshift":
426 env.use_utility_code(TempitaUtilityCode.load(
427 "LeftShift", "Overflow.c",
428 context={'TYPE': type, 'NAME': name, 'SIGNED': self.signed}))
432 _load_overflow_base(env)
433 env.use_utility_code(TempitaUtilityCode.load(
434 "SizeCheck", "Overflow.c",
435 context={'TYPE': type, 'NAME': name}))
436 env.use_utility_code(TempitaUtilityCode.load(
437 "Binop", "Overflow.c",
438 context={'TYPE': type, 'NAME': name, 'BINOP': binop}))
439 return "__Pyx_%s_%s_checking_overflow" % (binop, name)
441 def error_condition(self, result_code):
442 if self.typedef_is_external:
443 if self.exception_value:
444 condition = "(%s == (%s)%s)" % (
445 result_code, self.typedef_cname, self.exception_value)
446 if self.exception_check:
447 condition += " && PyErr_Occurred()"
450 return self.typedef_base_type.error_condition(result_code)
452 def __getattr__(self, name):
453 return getattr(self.typedef_base_type, name)
455 def py_type_name(self):
456 return self.typedef_base_type.py_type_name()
458 def can_coerce_to_pyobject(self, env):
459 return self.typedef_base_type.can_coerce_to_pyobject(env)
462 class MemoryViewSliceType(PyrexType):
464 is_memoryviewslice = 1
469 # These are special cased in Defnode
470 from_py_function = None
471 to_py_function = None
473 exception_value = None
474 exception_check = True
478 def __init__(self, base_dtype, axes):
480 MemoryViewSliceType(base, axes)
482 Base is the C base type; axes is a list of (access, packing) strings,
483 where access is one of 'full', 'direct' or 'ptr' and packing is one of
484 'contig', 'strided' or 'follow'. There is one (access, packing) tuple
487 the access specifiers determine whether the array data contains
488 pointers that need to be dereferenced along that axis when
491 'direct' -- No pointers stored in this dimension.
492 'ptr' -- Pointer stored in this dimension.
493 'full' -- Check along this dimension, don't assume either.
495 the packing specifiers specify how the array elements are layed-out
498 'contig' -- The data are contiguous in memory along this dimension.
499 At most one dimension may be specified as 'contig'.
500 'strided' -- The data aren't contiguous along this dimenison.
501 'follow' -- Used for C/Fortran contiguous arrays, a 'follow' dimension
502 has its stride automatically computed from extents of the other
503 dimensions to ensure C or Fortran memory layout.
505 C-contiguous memory has 'direct' as the access spec, 'contig' as the
506 *last* axis' packing spec and 'follow' for all other packing specs.
508 Fortran-contiguous memory has 'direct' as the access spec, 'contig' as
509 the *first* axis' packing spec and 'follow' for all other packing
514 self.dtype = base_dtype
516 self.ndim = len(axes)
517 self.flags = MemoryView.get_buf_flags(self.axes)
519 self.is_c_contig, self.is_f_contig = MemoryView.is_cf_contig(self.axes)
520 assert not (self.is_c_contig and self.is_f_contig)
522 self.mode = MemoryView.get_mode(axes)
523 self.writable_needed = False
525 if not self.dtype.is_fused:
526 self.dtype_name = MemoryView.mangle_dtype_name(self.dtype)
528 def same_as_resolved_type(self, other_type):
529 return ((other_type.is_memoryviewslice and
530 self.dtype.same_as(other_type.dtype) and
531 self.axes == other_type.axes) or
532 other_type is error_type)
534 def needs_nonecheck(self):
537 def is_complete(self):
538 # incomplete since the underlying struct doesn't have a cython.memoryview object.
541 def declaration_code(self, entity_code,
542 for_display = 0, dll_linkage = None, pyrex = 0):
543 # XXX: we put these guards in for now...
545 assert not dll_linkage
547 return self.base_declaration_code(
548 MemoryView.memviewslice_cname,
551 def attributes_known(self):
552 if self.scope is None:
555 self.scope = scope = Symtab.CClassScope(
556 'mvs_class_'+self.specialization_suffix(),
560 scope.parent_type = self
561 scope.directives = {}
563 scope.declare_var('_data', c_char_ptr_type, None,
564 cname='data', is_cdef=1)
568 def declare_attribute(self, attribute, env, pos):
569 import MemoryView, Options
573 if attribute == 'shape':
574 scope.declare_var('shape',
575 c_array_type(c_py_ssize_t_type,
576 Options.buffer_max_dims),
581 elif attribute == 'strides':
582 scope.declare_var('strides',
583 c_array_type(c_py_ssize_t_type,
584 Options.buffer_max_dims),
589 elif attribute == 'suboffsets':
590 scope.declare_var('suboffsets',
591 c_array_type(c_py_ssize_t_type,
592 Options.buffer_max_dims),
597 elif attribute in ("copy", "copy_fortran"):
598 ndim = len(self.axes)
600 to_axes_c = [('direct', 'contig')]
601 to_axes_f = [('direct', 'contig')]
603 to_axes_c = [('direct', 'follow')]*(ndim-1) + to_axes_c
604 to_axes_f = to_axes_f + [('direct', 'follow')]*(ndim-1)
606 to_memview_c = MemoryViewSliceType(self.dtype, to_axes_c)
607 to_memview_f = MemoryViewSliceType(self.dtype, to_axes_f)
609 for to_memview, cython_name in [(to_memview_c, "copy"),
610 (to_memview_f, "copy_fortran")]:
611 entry = scope.declare_cfunction(cython_name,
612 CFuncType(self, [CFuncTypeArg("memviewslice", self, None)]),
615 cname=MemoryView.copy_c_or_fortran_cname(to_memview))
617 #entry.utility_code_definition = \
618 env.use_utility_code(MemoryView.get_copy_new_utility(pos, self, to_memview))
620 MemoryView.use_cython_array_utility_code(env)
622 elif attribute in ("is_c_contig", "is_f_contig"):
623 # is_c_contig and is_f_contig functions
624 for (c_or_f, cython_name) in (('c', 'is_c_contig'), ('f', 'is_f_contig')):
627 MemoryView.get_is_contig_func_name(c_or_f, self.ndim)
629 cfunctype = CFuncType(
630 return_type=c_bint_type,
631 args=[CFuncTypeArg("memviewslice", self, None)],
632 exception_value="-1",
635 entry = scope.declare_cfunction(cython_name,
639 cname=is_contig_name)
641 entry.utility_code_definition = MemoryView.get_is_contig_utility(
642 attribute == 'is_c_contig', self.ndim)
646 def specialization_suffix(self):
647 return "%s_%s" % (self.axes_to_name(), self.dtype_name)
649 def can_coerce_to_pyobject(self, env):
652 def check_for_null_code(self, cname):
653 return cname + '.memview'
655 def create_from_py_utility_code(self, env):
656 import MemoryView, Buffer
658 # We don't have 'code', so use a LazyUtilityCode with a callback.
659 def lazy_utility_callback(code):
660 context['dtype_typeinfo'] = Buffer.get_type_information_cname(
662 return TempitaUtilityCode.load(
663 "ObjectToMemviewSlice", "MemoryView_C.c", context=context)
665 env.use_utility_code(Buffer.acquire_utility_code)
666 env.use_utility_code(MemoryView.memviewslice_init_code)
667 env.use_utility_code(LazyUtilityCode(lazy_utility_callback))
670 c_or_f_flag = "__Pyx_IS_C_CONTIG"
671 elif self.is_f_contig:
672 c_or_f_flag = "__Pyx_IS_F_CONTIG"
676 suffix = self.specialization_suffix()
677 funcname = "__Pyx_PyObject_to_MemoryviewSlice_" + suffix
681 buf_flag = self.flags,
683 axes_specs = ', '.join(self.axes_to_code()),
684 dtype_typedecl = self.dtype.declaration_code(""),
685 struct_nesting_depth = self.dtype.struct_nesting_depth(),
686 c_or_f_flag = c_or_f_flag,
690 self.from_py_function = funcname
693 def create_to_py_utility_code(self, env):
696 def get_to_py_function(self, env, obj):
697 to_py_func, from_py_func = self.dtype_object_conversion_funcs(env)
698 to_py_func = "(PyObject *(*)(char *)) " + to_py_func
699 from_py_func = "(int (*)(char *, PyObject *)) " + from_py_func
701 tup = (obj.result(), self.ndim, to_py_func, from_py_func,
702 self.dtype.is_pyobject)
703 return "__pyx_memoryview_fromslice(%s, %s, %s, %s, %d);" % tup
705 def dtype_object_conversion_funcs(self, env):
706 get_function = "__pyx_memview_get_%s" % self.dtype_name
707 set_function = "__pyx_memview_set_%s" % self.dtype_name
710 get_function = get_function,
711 set_function = set_function,
714 if self.dtype.is_pyobject:
715 utility_name = "MemviewObjectToObject"
717 to_py = self.dtype.create_to_py_utility_code(env)
718 from_py = self.dtype.create_from_py_utility_code(env)
719 if not (to_py or from_py):
720 return "NULL", "NULL"
722 if not self.dtype.to_py_function:
723 get_function = "NULL"
725 if not self.dtype.from_py_function:
726 set_function = "NULL"
728 utility_name = "MemviewDtypeToObject"
729 error_condition = (self.dtype.error_condition('value') or
732 to_py_function = self.dtype.to_py_function,
733 from_py_function = self.dtype.from_py_function,
734 dtype = self.dtype.declaration_code(""),
735 error_condition = error_condition,
738 utility = TempitaUtilityCode.load(
739 utility_name, "MemoryView_C.c", context=context)
740 env.use_utility_code(utility)
741 return get_function, set_function
743 def axes_to_code(self):
744 """Return a list of code constants for each axis"""
746 d = MemoryView._spec_to_const
747 return ["(%s | %s)" % (d[a], d[p]) for a, p in self.axes]
749 def axes_to_name(self):
750 """Return an abbreviated name for our axes"""
752 d = MemoryView._spec_to_abbrev
753 return "".join(["%s%s" % (d[a], d[p]) for a, p in self.axes])
755 def error_condition(self, result_code):
756 return "!%s.memview" % result_code
762 for idx, (access, packing) in enumerate(self.axes):
763 flag = MemoryView.get_memoryview_flag(access, packing)
764 if flag == "strided":
765 axes_code_list.append(":")
767 if flag == 'contiguous':
768 have_follow = [p for a, p in self.axes[idx - 1:idx + 2]
770 if have_follow or self.ndim == 1:
773 axes_code_list.append("::" + flag)
775 if self.dtype.is_pyobject:
776 dtype_name = self.dtype.name
778 dtype_name = self.dtype
780 return "%s[%s]" % (dtype_name, ", ".join(axes_code_list))
782 def specialize(self, values):
783 """This does not validate the base type!!"""
784 dtype = self.dtype.specialize(values)
785 if dtype is not self.dtype:
786 return MemoryViewSliceType(dtype, self.axes)
790 def cast_code(self, expr_code):
794 class BufferType(BaseType):
796 # Delegates most attribute lookups to the base type.
797 # (Anything not defined here or in the BaseType is delegated.)
802 # negative_indices bool
812 def __init__(self, base, dtype, ndim, mode, negative_indices, cast):
816 self.buffer_ptr_type = CPtrType(dtype)
818 self.negative_indices = negative_indices
821 def as_argument_type(self):
824 def specialize(self, values):
825 dtype = self.dtype.specialize(values)
826 if dtype is not self.dtype:
827 return BufferType(self.base, dtype, self.ndim, self.mode,
828 self.negative_indices, self.cast)
831 def __getattr__(self, name):
832 return getattr(self.base, name)
835 return "<BufferType %r>" % self.base
838 # avoid ', ', as fused functions split the signature string on ', '
841 cast_str = ',cast=True'
843 return "%s[%s,ndim=%d%s]" % (self.base, self.dtype, self.ndim,
846 def assignable_from(self, other_type):
847 if other_type.is_buffer:
848 return (self.same_as(other_type, compare_base=False) and
849 self.base.assignable_from(other_type.base))
851 return self.base.assignable_from(other_type)
853 def same_as(self, other_type, compare_base=True):
854 if not other_type.is_buffer:
855 return other_type.same_as(self.base)
857 return (self.dtype.same_as(other_type.dtype) and
858 self.ndim == other_type.ndim and
859 self.mode == other_type.mode and
860 self.cast == other_type.cast and
861 (not compare_base or self.base.same_as(other_type.base)))
864 class PyObjectType(PyrexType):
866 # Base class for all Python object types (reference-counted).
868 # buffer_defaults dict or None Default options for bu
873 buffer_defaults = None
875 is_subclassed = False
879 return "Python object"
882 return "<PyObjectType>"
884 def can_coerce_to_pyobject(self, env):
887 def default_coerced_ctype(self):
888 """The default C type that this Python type coerces to, or None."""
891 def assignable_from(self, src_type):
892 # except for pointers, conversion will be attempted
893 return not src_type.is_ptr or src_type.is_string or src_type.is_pyunicode_ptr
895 def declaration_code(self, entity_code,
896 for_display = 0, dll_linkage = None, pyrex = 0):
897 if pyrex or for_display:
900 base_code = public_decl("PyObject", dll_linkage)
901 entity_code = "*%s" % entity_code
902 return self.base_declaration_code(base_code, entity_code)
904 def as_pyobject(self, cname):
905 if (not self.is_complete()) or self.is_extension_type:
906 return "(PyObject *)" + cname
910 def py_type_name(self):
913 def __lt__(self, other):
915 Make sure we sort highest, as instance checking on py_type_name
916 ('object') is always true
920 def global_init_code(self, entry, code):
921 code.put_init_var_to_py_none(entry, nanny=False)
923 def check_for_null_code(self, cname):
927 builtin_types_that_cannot_create_refcycles = set([
928 'bool', 'int', 'long', 'float', 'complex',
929 'bytearray', 'bytes', 'unicode', 'str', 'basestring'
933 class BuiltinObjectType(PyObjectType):
934 # objstruct_cname string Name of PyObject struct
939 module_name = '__builtin__'
941 # fields that let it look like an extension type
942 vtabslot_cname = None
943 vtabstruct_cname = None
948 def __init__(self, name, cname, objstruct_cname=None):
951 self.typeptr_cname = "(&%s)" % cname
952 self.objstruct_cname = objstruct_cname
953 self.is_gc_simple = name in builtin_types_that_cannot_create_refcycles
955 def set_scope(self, scope):
958 scope.parent_type = self
961 return "%s object" % self.name
964 return "<%s>"% self.cname
966 def default_coerced_ctype(self):
967 if self.name in ('bytes', 'bytearray'):
968 return c_char_ptr_type
969 elif self.name == 'bool':
971 elif self.name == 'float':
975 def assignable_from(self, src_type):
976 if isinstance(src_type, BuiltinObjectType):
977 if self.name == 'basestring':
978 return src_type.name in ('str', 'unicode', 'basestring')
980 return src_type.name == self.name
981 elif src_type.is_extension_type:
982 # FIXME: This is an ugly special case that we currently
983 # keep supporting. It allows users to specify builtin
984 # types as external extension types, while keeping them
985 # compatible with the real builtin types. We already
986 # generate a warning for it. Big TODO: remove!
987 return (src_type.module_name == '__builtin__' and
988 src_type.name == self.name)
992 def typeobj_is_available(self):
995 def attributes_known(self):
998 def subtype_of(self, type):
999 return type.is_pyobject and type.assignable_from(self)
1001 def type_check_function(self, exact=True):
1002 type_name = self.name
1003 if type_name == 'str':
1004 type_check = 'PyString_Check'
1005 elif type_name == 'basestring':
1006 type_check = '__Pyx_PyBaseString_Check'
1007 elif type_name == 'bytearray':
1008 type_check = 'PyByteArray_Check'
1009 elif type_name == 'frozenset':
1010 type_check = 'PyFrozenSet_Check'
1012 type_check = 'Py%s_Check' % type_name.capitalize()
1013 if exact and type_name not in ('bool', 'slice'):
1014 type_check += 'Exact'
1017 def isinstance_code(self, arg):
1018 return '%s(%s)' % (self.type_check_function(exact=False), arg)
1020 def type_test_code(self, arg, notnone=False, exact=True):
1021 type_check = self.type_check_function(exact=exact)
1022 check = 'likely(%s(%s))' % (type_check, arg)
1024 check += '||((%s) == Py_None)' % arg
1025 if self.name == 'basestring':
1026 name = '(PY_MAJOR_VERSION < 3 ? "basestring" : "str")'
1029 name = '"%s"' % self.name
1030 # avoid wasting too much space but limit number of different format strings
1031 space_for_name = (len(self.name) // 16 + 1) * 16
1032 error = '(PyErr_Format(PyExc_TypeError, "Expected %%.%ds, got %%.200s", %s, Py_TYPE(%s)->tp_name), 0)' % (
1033 space_for_name, name, arg)
1034 return check + '||' + error
1036 def declaration_code(self, entity_code,
1037 for_display = 0, dll_linkage = None, pyrex = 0):
1038 if pyrex or for_display:
1039 base_code = self.name
1041 base_code = public_decl("PyObject", dll_linkage)
1042 entity_code = "*%s" % entity_code
1043 return self.base_declaration_code(base_code, entity_code)
1045 def cast_code(self, expr_code, to_object_struct = False):
1046 return "((%s*)%s)" % (
1047 to_object_struct and self.objstruct_cname or "PyObject", # self.objstruct_cname may be None
1050 def py_type_name(self):
1055 class PyExtensionType(PyObjectType):
1057 # A Python extension type.
1060 # scope CClassScope Attribute namespace
1062 # typedef_flag boolean
1063 # base_type PyExtensionType or None
1064 # module_name string or None Qualified name of defining module
1065 # objstruct_cname string Name of PyObject struct
1066 # objtypedef_cname string Name of PyObject struct typedef
1067 # typeobj_cname string or None C code fragment referring to type object
1068 # typeptr_cname string or None Name of pointer to external type object
1069 # vtabslot_cname string Name of C method table member
1070 # vtabstruct_cname string Name of C method table struct
1071 # vtabptr_cname string Name of pointer to C method table
1072 # vtable_cname string Name of C method table definition
1073 # defered_declarations [thunk] Used to declare class hierarchies in order
1075 is_extension_type = 1
1078 objtypedef_cname = None
1080 def __init__(self, name, typedef_flag, base_type, is_external=0):
1083 self.typedef_flag = typedef_flag
1084 if base_type is not None:
1085 base_type.is_subclassed = True
1086 self.base_type = base_type
1087 self.module_name = None
1088 self.objstruct_cname = None
1089 self.typeobj_cname = None
1090 self.typeptr_cname = None
1091 self.vtabslot_cname = None
1092 self.vtabstruct_cname = None
1093 self.vtabptr_cname = None
1094 self.vtable_cname = None
1095 self.is_external = is_external
1096 self.defered_declarations = []
1098 def set_scope(self, scope):
1101 scope.parent_type = self
1103 def needs_nonecheck(self):
1106 def subtype_of_resolved_type(self, other_type):
1107 if other_type.is_extension_type or other_type.is_builtin_type:
1108 return self is other_type or (
1109 self.base_type and self.base_type.subtype_of(other_type))
1111 return other_type is py_object_type
1113 def typeobj_is_available(self):
1114 # Do we have a pointer to the type object?
1115 return self.typeptr_cname
1117 def typeobj_is_imported(self):
1118 # If we don't know the C name of the type object but we do
1119 # know which module it's defined in, it will be imported.
1120 return self.typeobj_cname is None and self.module_name is not None
1122 def assignable_from(self, src_type):
1123 if self == src_type:
1125 if isinstance(src_type, PyExtensionType):
1126 if src_type.base_type is not None:
1127 return self.assignable_from(src_type.base_type)
1128 if isinstance(src_type, BuiltinObjectType):
1129 # FIXME: This is an ugly special case that we currently
1130 # keep supporting. It allows users to specify builtin
1131 # types as external extension types, while keeping them
1132 # compatible with the real builtin types. We already
1133 # generate a warning for it. Big TODO: remove!
1134 return (self.module_name == '__builtin__' and
1135 self.name == src_type.name)
1138 def declaration_code(self, entity_code,
1139 for_display = 0, dll_linkage = None, pyrex = 0, deref = 0):
1140 if pyrex or for_display:
1141 base_code = self.name
1143 if self.typedef_flag:
1144 objstruct = self.objstruct_cname
1146 objstruct = "struct %s" % self.objstruct_cname
1147 base_code = public_decl(objstruct, dll_linkage)
1149 assert not entity_code
1151 entity_code = "*%s" % entity_code
1152 return self.base_declaration_code(base_code, entity_code)
1154 def type_test_code(self, py_arg, notnone=False):
1156 none_check = "((%s) == Py_None)" % py_arg
1157 type_check = "likely(__Pyx_TypeTest(%s, %s))" % (
1158 py_arg, self.typeptr_cname)
1162 return "likely(%s || %s)" % (none_check, type_check)
1164 def attributes_known(self):
1165 return self.scope is not None
1171 return "<PyExtensionType %s%s>" % (self.scope.class_name,
1172 ("", " typedef")[self.typedef_flag])
1174 def py_type_name(self):
1175 if not self.module_name:
1178 return "__import__(%r, None, None, ['']).%s" % (self.module_name,
1181 class CType(PyrexType):
1183 # Base class for all C types (non-reference-counted).
1185 # to_py_function string C function for converting to Python object
1186 # from_py_function string C function for constructing from Python object
1189 to_py_function = None
1190 from_py_function = None
1191 exception_value = None
1194 def create_to_py_utility_code(self, env):
1195 return self.to_py_function is not None
1197 def create_from_py_utility_code(self, env):
1198 return self.from_py_function is not None
1200 def can_coerce_to_pyobject(self, env):
1201 return self.create_to_py_utility_code(env)
1203 def error_condition(self, result_code):
1205 if self.is_string or self.is_pyunicode_ptr:
1206 conds.append("(!%s)" % result_code)
1207 elif self.exception_value is not None:
1208 conds.append("(%s == (%s)%s)" % (result_code, self.sign_and_name(), self.exception_value))
1209 if self.exception_check:
1210 conds.append("PyErr_Occurred()")
1212 return " && ".join(conds)
1217 class CConstType(BaseType):
1221 def __init__(self, const_base_type):
1222 self.const_base_type = const_base_type
1223 if const_base_type.has_attributes and const_base_type.scope is not None:
1225 self.scope = Symtab.CConstScope(const_base_type.scope)
1228 return "<CConstType %s>" % repr(self.const_base_type)
1231 return self.declaration_code("", for_display=1)
1233 def declaration_code(self, entity_code,
1234 for_display = 0, dll_linkage = None, pyrex = 0):
1235 return self.const_base_type.declaration_code("const %s" % entity_code, for_display, dll_linkage, pyrex)
1237 def specialize(self, values):
1238 base_type = self.const_base_type.specialize(values)
1239 if base_type == self.const_base_type:
1242 return CConstType(base_type)
1244 def deduce_template_params(self, actual):
1245 return self.const_base_type.deduce_template_params(actual)
1247 def create_to_py_utility_code(self, env):
1248 if self.const_base_type.create_to_py_utility_code(env):
1249 self.to_py_function = self.const_base_type.to_py_function
1252 def __getattr__(self, name):
1253 return getattr(self.const_base_type, name)
1256 class FusedType(CType):
1258 Represents a Fused Type. All it needs to do is keep track of the types
1259 it aggregates, as it will be replaced with its specific version wherever
1262 See http://wiki.cython.org/enhancements/fusedtypes
1264 types [PyrexType] is the list of types to be fused
1265 name str the name of the ctypedef
1271 def __init__(self, types, name=None):
1275 def declaration_code(self, entity_code, for_display = 0,
1276 dll_linkage = None, pyrex = 0):
1277 if pyrex or for_display:
1280 raise Exception("This may never happen, please report a bug")
1283 return 'FusedType(name=%r)' % self.name
1285 def specialize(self, values):
1288 def get_fused_types(self, result=None, seen=None):
1292 if self not in seen:
1297 class CVoidType(CType):
1305 return "<CVoidType>"
1307 def declaration_code(self, entity_code,
1308 for_display = 0, dll_linkage = None, pyrex = 0):
1309 if pyrex or for_display:
1312 base_code = public_decl("void", dll_linkage)
1313 return self.base_declaration_code(base_code, entity_code)
1315 def is_complete(self):
1318 class InvisibleVoidType(CVoidType):
1320 # For use with C++ constructors and destructors return types.
1321 # Acts like void, but does not print out a declaration.
1323 def declaration_code(self, entity_code,
1324 for_display = 0, dll_linkage = None, pyrex = 0):
1325 if pyrex or for_display:
1326 base_code = "[void]"
1328 base_code = public_decl("", dll_linkage)
1329 return self.base_declaration_code(base_code, entity_code)
1332 class CNumericType(CType):
1334 # Base class for all C numeric types.
1336 # rank integer Relative size
1337 # signed integer 0 = unsigned, 1 = unspecified, 2 = explicitly signed
1342 has_attributes = True
1345 sign_words = ("unsigned ", "", "signed ")
1347 def __init__(self, rank, signed = 1):
1349 self.signed = signed
1351 def sign_and_name(self):
1352 s = self.sign_words[self.signed]
1353 n = rank_to_type_name[self.rank]
1357 return "<CNumericType %s>" % self.sign_and_name()
1359 def declaration_code(self, entity_code,
1360 for_display = 0, dll_linkage = None, pyrex = 0):
1361 type_name = self.sign_and_name()
1362 if pyrex or for_display:
1363 base_code = type_name.replace('PY_LONG_LONG', 'long long')
1365 base_code = public_decl(type_name, dll_linkage)
1366 return self.base_declaration_code(base_code, entity_code)
1368 def attributes_known(self):
1369 if self.scope is None:
1371 self.scope = scope = Symtab.CClassScope(
1374 visibility="extern")
1375 scope.parent_type = self
1376 scope.directives = {}
1377 scope.declare_cfunction(
1379 CFuncType(self, [CFuncTypeArg("self", self, None)], nogil=True),
1385 def __lt__(self, other):
1386 """Sort based on rank, preferring signed over unsigned"""
1387 if other.is_numeric:
1388 return self.rank > other.rank and self.signed >= other.signed
1390 # Prefer numeric types over others
1393 def py_type_name(self):
1395 return "(int, long)"
1399 class ForbidUseClass:
1401 raise RuntimeError()
1403 raise RuntimeError()
1404 ForbidUse = ForbidUseClass()
1407 class CIntType(CNumericType):
1411 to_py_function = None
1412 from_py_function = None
1413 exception_value = -1
1415 def create_to_py_utility_code(self, env):
1416 if type(self).to_py_function is None:
1417 self.to_py_function = "__Pyx_PyInt_From_" + self.specialization_name()
1418 env.use_utility_code(TempitaUtilityCode.load(
1419 "CIntToPy", "TypeConversion.c",
1420 context={"TYPE": self.declaration_code(''),
1421 "TO_PY_FUNCTION": self.to_py_function}))
1424 def create_from_py_utility_code(self, env):
1425 if type(self).from_py_function is None:
1426 self.from_py_function = "__Pyx_PyInt_As_" + self.specialization_name()
1427 env.use_utility_code(TempitaUtilityCode.load(
1428 "CIntFromPy", "TypeConversion.c",
1429 context={"TYPE": self.declaration_code(''),
1430 "FROM_PY_FUNCTION": self.from_py_function}))
1433 def get_to_py_type_conversion(self):
1434 if self.rank < list(rank_to_type_name).index('int'):
1435 # This assumes sizeof(short) < sizeof(int)
1436 return "PyInt_FromLong"
1438 # Py{Int|Long}_From[Unsigned]Long[Long]
1444 SignWord = "Unsigned"
1445 if self.rank >= list(rank_to_type_name).index('PY_LONG_LONG'):
1447 TypeName = "LongLong"
1448 return "Py%s_From%s%s" % (Prefix, SignWord, TypeName)
1450 def get_from_py_type_conversion(self):
1451 type_name = rank_to_type_name[self.rank]
1452 type_name = type_name.replace("PY_LONG_LONG", "long long")
1453 TypeName = type_name.title().replace(" ", "")
1454 SignWord = self.sign_words[self.signed].strip().title()
1455 if self.rank >= list(rank_to_type_name).index('long'):
1456 utility_code = c_long_from_py_function
1458 utility_code = c_int_from_py_function
1459 utility_code.specialize(self,
1462 func_name = "__Pyx_PyInt_As%s%s" % (SignWord, TypeName)
1465 def assignable_from_resolved_type(self, src_type):
1466 return src_type.is_int or src_type.is_enum or src_type is error_type
1468 def invalid_value(self):
1469 if rank_to_type_name[int(self.rank)] == 'char':
1472 # We do not really know the size of the type, so return
1473 # a 32-bit literal and rely on casting to final type. It will
1474 # be negative for signed ints, which is good.
1477 def overflow_check_binop(self, binop, env, const_rhs=False):
1478 env.use_utility_code(UtilityCode.load("Common", "Overflow.c"))
1479 type = self.declaration_code("")
1480 name = self.specialization_name()
1481 if binop == "lshift":
1482 env.use_utility_code(TempitaUtilityCode.load(
1483 "LeftShift", "Overflow.c",
1484 context={'TYPE': type, 'NAME': name, 'SIGNED': self.signed}))
1488 if type in ('int', 'long', 'long long'):
1489 env.use_utility_code(TempitaUtilityCode.load(
1490 "BaseCaseSigned", "Overflow.c",
1491 context={'INT': type, 'NAME': name}))
1492 elif type in ('unsigned int', 'unsigned long', 'unsigned long long'):
1493 env.use_utility_code(TempitaUtilityCode.load(
1494 "BaseCaseUnsigned", "Overflow.c",
1495 context={'UINT': type, 'NAME': name}))
1496 elif self.rank <= 1:
1497 # sizeof(short) < sizeof(int)
1498 return "__Pyx_%s_%s_no_overflow" % (binop, name)
1500 _load_overflow_base(env)
1501 env.use_utility_code(TempitaUtilityCode.load(
1502 "SizeCheck", "Overflow.c",
1503 context={'TYPE': type, 'NAME': name}))
1504 env.use_utility_code(TempitaUtilityCode.load(
1505 "Binop", "Overflow.c",
1506 context={'TYPE': type, 'NAME': name, 'BINOP': binop}))
1507 return "__Pyx_%s_%s_checking_overflow" % (binop, name)
1509 def _load_overflow_base(env):
1510 env.use_utility_code(UtilityCode.load("Common", "Overflow.c"))
1511 for type in ('int', 'long', 'long long'):
1512 env.use_utility_code(TempitaUtilityCode.load(
1513 "BaseCaseSigned", "Overflow.c",
1514 context={'INT': type, 'NAME': type.replace(' ', '_')}))
1515 for type in ('unsigned int', 'unsigned long', 'unsigned long long'):
1516 env.use_utility_code(TempitaUtilityCode.load(
1517 "BaseCaseUnsigned", "Overflow.c",
1518 context={'UINT': type, 'NAME': type.replace(' ', '_')}))
1521 class CAnonEnumType(CIntType):
1525 def sign_and_name(self):
1529 class CReturnCodeType(CIntType):
1531 to_py_function = "__Pyx_Owned_Py_None"
1533 is_returncode = True
1534 exception_check = False
1537 class CBIntType(CIntType):
1539 to_py_function = "__Pyx_PyBool_FromLong"
1540 from_py_function = "__Pyx_PyObject_IsTrue"
1541 exception_check = 1 # for C++ bool
1543 def declaration_code(self, entity_code,
1544 for_display = 0, dll_linkage = None, pyrex = 0):
1545 if pyrex or for_display:
1548 base_code = public_decl('int', dll_linkage)
1549 return self.base_declaration_code(base_code, entity_code)
1552 return "<CNumericType bint>"
1557 def py_type_name(self):
1561 class CPyUCS4IntType(CIntType):
1564 is_unicode_char = True
1566 # Py_UCS4 coerces from and to single character unicode strings (or
1567 # at most two characters on 16bit Unicode builds), but we also
1568 # allow Python integers as input. The value range for Py_UCS4
1569 # is 0..1114111, which is checked when converting from an integer
1572 to_py_function = "PyUnicode_FromOrdinal"
1573 from_py_function = "__Pyx_PyObject_AsPy_UCS4"
1575 def create_from_py_utility_code(self, env):
1576 env.use_utility_code(UtilityCode.load_cached("ObjectAsUCS4", "TypeConversion.c"))
1579 def sign_and_name(self):
1583 class CPyUnicodeIntType(CIntType):
1586 is_unicode_char = True
1588 # Py_UNICODE coerces from and to single character unicode strings,
1589 # but we also allow Python integers as input. The value range for
1590 # Py_UNICODE is 0..1114111, which is checked when converting from
1593 to_py_function = "PyUnicode_FromOrdinal"
1594 from_py_function = "__Pyx_PyObject_AsPy_UNICODE"
1596 def create_from_py_utility_code(self, env):
1597 env.use_utility_code(UtilityCode.load_cached("ObjectAsPyUnicode", "TypeConversion.c"))
1600 def sign_and_name(self):
1604 class CPyHashTType(CIntType):
1606 to_py_function = "__Pyx_PyInt_FromHash_t"
1607 from_py_function = "__Pyx_PyInt_AsHash_t"
1609 def sign_and_name(self):
1612 class CPySSizeTType(CIntType):
1614 to_py_function = "PyInt_FromSsize_t"
1615 from_py_function = "__Pyx_PyIndex_AsSsize_t"
1617 def sign_and_name(self):
1620 class CSSizeTType(CIntType):
1622 to_py_function = "PyInt_FromSsize_t"
1623 from_py_function = "PyInt_AsSsize_t"
1625 def sign_and_name(self):
1628 class CSizeTType(CIntType):
1630 to_py_function = "__Pyx_PyInt_FromSize_t"
1632 def sign_and_name(self):
1635 class CPtrdiffTType(CIntType):
1637 def sign_and_name(self):
1641 class CFloatType(CNumericType):
1644 to_py_function = "PyFloat_FromDouble"
1645 from_py_function = "__pyx_PyFloat_AsDouble"
1647 exception_value = -1
1649 def __init__(self, rank, math_h_modifier = ''):
1650 CNumericType.__init__(self, rank, 1)
1651 self.math_h_modifier = math_h_modifier
1652 if rank == RANK_FLOAT:
1653 self.from_py_function = "__pyx_PyFloat_AsFloat"
1655 def assignable_from_resolved_type(self, src_type):
1656 return (src_type.is_numeric and not src_type.is_complex) or src_type is error_type
1658 def invalid_value(self):
1659 return Naming.PYX_NAN
1661 class CComplexType(CNumericType):
1664 to_py_function = "__pyx_PyComplex_FromComplex"
1668 def __init__(self, real_type):
1669 while real_type.is_typedef and not real_type.typedef_is_external:
1670 real_type = real_type.typedef_base_type
1671 if real_type.is_typedef and real_type.typedef_is_external:
1672 # The below is not actually used: Coercions are currently disabled
1673 # so that complex types of external types can not be created
1674 self.funcsuffix = "_%s" % real_type.specialization_name()
1675 elif hasattr(real_type, 'math_h_modifier'):
1676 self.funcsuffix = real_type.math_h_modifier
1678 self.funcsuffix = "_%s" % real_type.specialization_name()
1680 self.real_type = real_type
1681 CNumericType.__init__(self, real_type.rank + 0.5, real_type.signed)
1683 self.from_parts = "%s_from_parts" % self.specialization_name()
1684 self.default_value = "%s(0, 0)" % self.from_parts
1686 def __eq__(self, other):
1687 if isinstance(self, CComplexType) and isinstance(other, CComplexType):
1688 return self.real_type == other.real_type
1692 def __ne__(self, other):
1693 if isinstance(self, CComplexType) and isinstance(other, CComplexType):
1694 return self.real_type != other.real_type
1698 def __lt__(self, other):
1699 if isinstance(self, CComplexType) and isinstance(other, CComplexType):
1700 return self.real_type < other.real_type
1702 # this is arbitrary, but it makes sure we always have
1703 # *some* kind of order
1707 return ~hash(self.real_type)
1709 def declaration_code(self, entity_code,
1710 for_display = 0, dll_linkage = None, pyrex = 0):
1711 if pyrex or for_display:
1712 real_code = self.real_type.declaration_code("", for_display, dll_linkage, pyrex)
1713 base_code = "%s complex" % real_code
1715 base_code = public_decl(self.sign_and_name(), dll_linkage)
1716 return self.base_declaration_code(base_code, entity_code)
1718 def sign_and_name(self):
1719 real_type_name = self.real_type.specialization_name()
1720 real_type_name = real_type_name.replace('long__double','long_double')
1721 real_type_name = real_type_name.replace('PY_LONG_LONG','long_long')
1722 return Naming.type_prefix + real_type_name + "_complex"
1724 def assignable_from(self, src_type):
1725 # Temporary hack/feature disabling, see #441
1726 if (not src_type.is_complex and src_type.is_numeric and src_type.is_typedef
1727 and src_type.typedef_is_external):
1730 return super(CComplexType, self).assignable_from(src_type)
1732 def assignable_from_resolved_type(self, src_type):
1733 return (src_type.is_complex and self.real_type.assignable_from_resolved_type(src_type.real_type)
1734 or src_type.is_numeric and self.real_type.assignable_from_resolved_type(src_type)
1735 or src_type is error_type)
1737 def attributes_known(self):
1738 if self.scope is None:
1740 self.scope = scope = Symtab.CClassScope(
1743 visibility="extern")
1744 scope.parent_type = self
1745 scope.directives = {}
1746 scope.declare_var("real", self.real_type, None, cname="real", is_cdef=True)
1747 scope.declare_var("imag", self.real_type, None, cname="imag", is_cdef=True)
1748 scope.declare_cfunction(
1750 CFuncType(self, [CFuncTypeArg("self", self, None)], nogil=True),
1753 cname="__Pyx_c_conj%s" % self.funcsuffix)
1757 def create_declaration_utility_code(self, env):
1758 # This must always be run, because a single CComplexType instance can be shared
1759 # across multiple compilations (the one created in the module scope)
1760 env.use_utility_code(complex_header_utility_code)
1761 env.use_utility_code(complex_real_imag_utility_code)
1762 for utility_code in (complex_type_utility_code,
1763 complex_from_parts_utility_code,
1764 complex_arithmetic_utility_code):
1765 env.use_utility_code(
1766 utility_code.specialize(
1768 real_type = self.real_type.declaration_code(''),
1769 m = self.funcsuffix,
1770 is_float = self.real_type.is_float))
1773 def create_to_py_utility_code(self, env):
1774 env.use_utility_code(complex_real_imag_utility_code)
1775 env.use_utility_code(complex_to_py_utility_code)
1778 def create_from_py_utility_code(self, env):
1779 self.real_type.create_from_py_utility_code(env)
1781 for utility_code in (complex_from_parts_utility_code,
1782 complex_from_py_utility_code):
1783 env.use_utility_code(
1784 utility_code.specialize(
1786 real_type = self.real_type.declaration_code(''),
1787 m = self.funcsuffix,
1788 is_float = self.real_type.is_float))
1789 self.from_py_function = "__Pyx_PyComplex_As_" + self.specialization_name()
1792 def lookup_op(self, nargs, op):
1794 return self.binops[nargs, op]
1798 op_name = complex_ops[nargs, op]
1799 self.binops[nargs, op] = func_name = "__Pyx_c_%s%s" % (op_name, self.funcsuffix)
1804 def unary_op(self, op):
1805 return self.lookup_op(1, op)
1807 def binary_op(self, op):
1808 return self.lookup_op(2, op)
1810 def py_type_name(self):
1813 def cast_code(self, expr_code):
1818 (1, 'zero'): 'is_zero',
1826 complex_header_utility_code = UtilityCode(
1827 proto_block='h_code',
1829 #if !defined(CYTHON_CCOMPLEX)
1830 #if defined(__cplusplus)
1831 #define CYTHON_CCOMPLEX 1
1832 #elif defined(_Complex_I)
1833 #define CYTHON_CCOMPLEX 1
1835 #define CYTHON_CCOMPLEX 0
1843 #include <complex.h>
1847 #if CYTHON_CCOMPLEX && !defined(__cplusplus) && defined(__sun__) && defined(__GNUC__)
1849 #define _Complex_I 1.0fj
1853 complex_real_imag_utility_code = UtilityCode(
1857 #define __Pyx_CREAL(z) ((z).real())
1858 #define __Pyx_CIMAG(z) ((z).imag())
1860 #define __Pyx_CREAL(z) (__real__(z))
1861 #define __Pyx_CIMAG(z) (__imag__(z))
1864 #define __Pyx_CREAL(z) ((z).real)
1865 #define __Pyx_CIMAG(z) ((z).imag)
1868 #if (defined(_WIN32) || defined(__clang__)) && defined(__cplusplus) && CYTHON_CCOMPLEX
1869 #define __Pyx_SET_CREAL(z,x) ((z).real(x))
1870 #define __Pyx_SET_CIMAG(z,y) ((z).imag(y))
1872 #define __Pyx_SET_CREAL(z,x) __Pyx_CREAL(z) = (x)
1873 #define __Pyx_SET_CIMAG(z,y) __Pyx_CIMAG(z) = (y)
1877 complex_type_utility_code = UtilityCode(
1878 proto_block='complex_type_declarations',
1882 typedef ::std::complex< %(real_type)s > %(type_name)s;
1884 typedef %(real_type)s _Complex %(type_name)s;
1887 typedef struct { %(real_type)s real, imag; } %(type_name)s;
1891 complex_from_parts_utility_code = UtilityCode(
1892 proto_block='utility_code_proto',
1894 static CYTHON_INLINE %(type)s %(type_name)s_from_parts(%(real_type)s, %(real_type)s);
1899 static CYTHON_INLINE %(type)s %(type_name)s_from_parts(%(real_type)s x, %(real_type)s y) {
1900 return ::std::complex< %(real_type)s >(x, y);
1903 static CYTHON_INLINE %(type)s %(type_name)s_from_parts(%(real_type)s x, %(real_type)s y) {
1904 return x + y*(%(type)s)_Complex_I;
1908 static CYTHON_INLINE %(type)s %(type_name)s_from_parts(%(real_type)s x, %(real_type)s y) {
1917 complex_to_py_utility_code = UtilityCode(
1919 #define __pyx_PyComplex_FromComplex(z) \\
1920 PyComplex_FromDoubles((double)__Pyx_CREAL(z), \\
1921 (double)__Pyx_CIMAG(z))
1924 complex_from_py_utility_code = UtilityCode(
1926 static %(type)s __Pyx_PyComplex_As_%(type_name)s(PyObject*);
1929 static %(type)s __Pyx_PyComplex_As_%(type_name)s(PyObject* o) {
1931 #if CYTHON_COMPILING_IN_CPYTHON
1932 if (PyComplex_CheckExact(o))
1933 cval = ((PyComplexObject *)o)->cval;
1936 cval = PyComplex_AsCComplex(o);
1937 return %(type_name)s_from_parts(
1938 (%(real_type)s)cval.real,
1939 (%(real_type)s)cval.imag);
1943 complex_arithmetic_utility_code = UtilityCode(
1946 #define __Pyx_c_eq%(m)s(a, b) ((a)==(b))
1947 #define __Pyx_c_sum%(m)s(a, b) ((a)+(b))
1948 #define __Pyx_c_diff%(m)s(a, b) ((a)-(b))
1949 #define __Pyx_c_prod%(m)s(a, b) ((a)*(b))
1950 #define __Pyx_c_quot%(m)s(a, b) ((a)/(b))
1951 #define __Pyx_c_neg%(m)s(a) (-(a))
1953 #define __Pyx_c_is_zero%(m)s(z) ((z)==(%(real_type)s)0)
1954 #define __Pyx_c_conj%(m)s(z) (::std::conj(z))
1956 #define __Pyx_c_abs%(m)s(z) (::std::abs(z))
1957 #define __Pyx_c_pow%(m)s(a, b) (::std::pow(a, b))
1960 #define __Pyx_c_is_zero%(m)s(z) ((z)==0)
1961 #define __Pyx_c_conj%(m)s(z) (conj%(m)s(z))
1963 #define __Pyx_c_abs%(m)s(z) (cabs%(m)s(z))
1964 #define __Pyx_c_pow%(m)s(a, b) (cpow%(m)s(a, b))
1968 static CYTHON_INLINE int __Pyx_c_eq%(m)s(%(type)s, %(type)s);
1969 static CYTHON_INLINE %(type)s __Pyx_c_sum%(m)s(%(type)s, %(type)s);
1970 static CYTHON_INLINE %(type)s __Pyx_c_diff%(m)s(%(type)s, %(type)s);
1971 static CYTHON_INLINE %(type)s __Pyx_c_prod%(m)s(%(type)s, %(type)s);
1972 static CYTHON_INLINE %(type)s __Pyx_c_quot%(m)s(%(type)s, %(type)s);
1973 static CYTHON_INLINE %(type)s __Pyx_c_neg%(m)s(%(type)s);
1974 static CYTHON_INLINE int __Pyx_c_is_zero%(m)s(%(type)s);
1975 static CYTHON_INLINE %(type)s __Pyx_c_conj%(m)s(%(type)s);
1977 static CYTHON_INLINE %(real_type)s __Pyx_c_abs%(m)s(%(type)s);
1978 static CYTHON_INLINE %(type)s __Pyx_c_pow%(m)s(%(type)s, %(type)s);
1985 static CYTHON_INLINE int __Pyx_c_eq%(m)s(%(type)s a, %(type)s b) {
1986 return (a.real == b.real) && (a.imag == b.imag);
1988 static CYTHON_INLINE %(type)s __Pyx_c_sum%(m)s(%(type)s a, %(type)s b) {
1990 z.real = a.real + b.real;
1991 z.imag = a.imag + b.imag;
1994 static CYTHON_INLINE %(type)s __Pyx_c_diff%(m)s(%(type)s a, %(type)s b) {
1996 z.real = a.real - b.real;
1997 z.imag = a.imag - b.imag;
2000 static CYTHON_INLINE %(type)s __Pyx_c_prod%(m)s(%(type)s a, %(type)s b) {
2002 z.real = a.real * b.real - a.imag * b.imag;
2003 z.imag = a.real * b.imag + a.imag * b.real;
2006 static CYTHON_INLINE %(type)s __Pyx_c_quot%(m)s(%(type)s a, %(type)s b) {
2008 %(real_type)s denom = b.real * b.real + b.imag * b.imag;
2009 z.real = (a.real * b.real + a.imag * b.imag) / denom;
2010 z.imag = (a.imag * b.real - a.real * b.imag) / denom;
2013 static CYTHON_INLINE %(type)s __Pyx_c_neg%(m)s(%(type)s a) {
2019 static CYTHON_INLINE int __Pyx_c_is_zero%(m)s(%(type)s a) {
2020 return (a.real == 0) && (a.imag == 0);
2022 static CYTHON_INLINE %(type)s __Pyx_c_conj%(m)s(%(type)s a) {
2029 static CYTHON_INLINE %(real_type)s __Pyx_c_abs%(m)s(%(type)s z) {
2030 #if !defined(HAVE_HYPOT) || defined(_MSC_VER)
2031 return sqrt%(m)s(z.real*z.real + z.imag*z.imag);
2033 return hypot%(m)s(z.real, z.imag);
2036 static CYTHON_INLINE %(type)s __Pyx_c_pow%(m)s(%(type)s a, %(type)s b) {
2038 %(real_type)s r, lnr, theta, z_r, z_theta;
2039 if (b.imag == 0 && b.real == (int)b.real) {
2041 %(real_type)s denom = a.real * a.real + a.imag * a.imag;
2042 a.real = a.real / denom;
2043 a.imag = -a.imag / denom;
2046 switch ((int)b.real) {
2054 z = __Pyx_c_prod%(m)s(a, a);
2055 return __Pyx_c_prod%(m)s(a, a);
2057 z = __Pyx_c_prod%(m)s(a, a);
2058 return __Pyx_c_prod%(m)s(z, a);
2060 z = __Pyx_c_prod%(m)s(a, a);
2061 return __Pyx_c_prod%(m)s(z, z);
2071 r = __Pyx_c_abs%(m)s(a);
2072 theta = atan2%(m)s(a.imag, a.real);
2075 z_r = exp%(m)s(lnr * b.real - theta * b.imag);
2076 z_theta = theta * b.real + lnr * b.imag;
2077 z.real = z_r * cos%(m)s(z_theta);
2078 z.imag = z_r * sin%(m)s(z_theta);
2085 class CPointerBaseType(CType):
2086 # common base type for pointer/array types
2088 # base_type CType Reference type
2090 subtypes = ['base_type']
2092 def __init__(self, base_type):
2093 self.base_type = base_type
2094 for char_type in (c_char_type, c_uchar_type, c_schar_type):
2095 if base_type.same_as(char_type):
2099 if base_type.same_as(c_py_unicode_type):
2100 self.is_pyunicode_ptr = 1
2102 if self.is_string and not base_type.is_error:
2103 if base_type.signed:
2104 self.to_py_function = "__Pyx_PyObject_FromString"
2106 if base_type.signed == 2:
2107 self.from_py_function = "__Pyx_PyObject_AsSString"
2109 self.from_py_function = "__Pyx_PyObject_AsString"
2111 self.to_py_function = "__Pyx_PyObject_FromUString"
2113 self.from_py_function = "__Pyx_PyObject_AsUString"
2114 self.exception_value = "NULL"
2115 elif self.is_pyunicode_ptr and not base_type.is_error:
2116 self.to_py_function = "__Pyx_PyUnicode_FromUnicode"
2118 self.from_py_function = "__Pyx_PyUnicode_AsUnicode"
2119 self.exception_value = "NULL"
2121 def py_type_name(self):
2124 elif self.is_pyunicode_ptr:
2127 return super(CPointerBaseType, self).py_type_name()
2129 def literal_code(self, value):
2131 assert isinstance(value, str)
2132 return '"%s"' % StringEncoding.escape_byte_string(value)
2135 class CArrayType(CPointerBaseType):
2136 # base_type CType Element type
2137 # size integer or None Number of elements
2141 def __init__(self, base_type, size):
2142 super(CArrayType, self).__init__(base_type)
2145 def __eq__(self, other):
2146 if isinstance(other, CType) and other.is_array and self.size == other.size:
2147 return self.base_type.same_as(other.base_type)
2151 return hash(self.base_type) + 28 # arbitrarily chosen offset
2154 return "<CArrayType %s %s>" % (self.size, repr(self.base_type))
2156 def same_as_resolved_type(self, other_type):
2157 return ((other_type.is_array and
2158 self.base_type.same_as(other_type.base_type))
2159 or other_type is error_type)
2161 def assignable_from_resolved_type(self, src_type):
2162 # Can't assign to a variable of an array type
2165 def element_ptr_type(self):
2166 return c_ptr_type(self.base_type)
2168 def declaration_code(self, entity_code,
2169 for_display = 0, dll_linkage = None, pyrex = 0):
2170 if self.size is not None:
2171 dimension_code = self.size
2174 if entity_code.startswith("*"):
2175 entity_code = "(%s)" % entity_code
2176 return self.base_type.declaration_code(
2177 "%s[%s]" % (entity_code, dimension_code),
2178 for_display, dll_linkage, pyrex)
2180 def as_argument_type(self):
2181 return c_ptr_type(self.base_type)
2183 def is_complete(self):
2184 return self.size is not None
2186 def specialize(self, values):
2187 base_type = self.base_type.specialize(values)
2188 if base_type == self.base_type:
2191 return CArrayType(base_type)
2193 def deduce_template_params(self, actual):
2194 if isinstance(actual, CArrayType):
2195 return self.base_type.deduce_template_params(actual.base_type)
2200 class CPtrType(CPointerBaseType):
2201 # base_type CType Reference type
2207 return hash(self.base_type) + 27 # arbitrarily chosen offset
2209 def __eq__(self, other):
2210 if isinstance(other, CType) and other.is_ptr:
2211 return self.base_type.same_as(other.base_type)
2214 def __ne__(self, other):
2215 return not (self == other)
2218 return "<CPtrType %s>" % repr(self.base_type)
2220 def same_as_resolved_type(self, other_type):
2221 return ((other_type.is_ptr and
2222 self.base_type.same_as(other_type.base_type))
2223 or other_type is error_type)
2225 def declaration_code(self, entity_code,
2226 for_display = 0, dll_linkage = None, pyrex = 0):
2227 #print "CPtrType.declaration_code: pointer to", self.base_type ###
2228 return self.base_type.declaration_code(
2229 "*%s" % entity_code,
2230 for_display, dll_linkage, pyrex)
2232 def assignable_from_resolved_type(self, other_type):
2233 if other_type is error_type:
2235 if other_type.is_null_ptr:
2237 if self.base_type.is_const:
2238 self = CPtrType(self.base_type.const_base_type)
2239 if self.base_type.is_cfunction:
2240 if other_type.is_ptr:
2241 other_type = other_type.base_type.resolve()
2242 if other_type.is_cfunction:
2243 return self.base_type.pointer_assignable_from_resolved_type(other_type)
2246 if (self.base_type.is_cpp_class and other_type.is_ptr
2247 and other_type.base_type.is_cpp_class and other_type.base_type.is_subclass(self.base_type)):
2249 if other_type.is_array or other_type.is_ptr:
2250 return self.base_type.is_void or self.base_type.same_as(other_type.base_type)
2253 def specialize(self, values):
2254 base_type = self.base_type.specialize(values)
2255 if base_type == self.base_type:
2258 return CPtrType(base_type)
2260 def deduce_template_params(self, actual):
2261 if isinstance(actual, CPtrType):
2262 return self.base_type.deduce_template_params(actual.base_type)
2266 def invalid_value(self):
2269 def find_cpp_operation_type(self, operator, operand_type=None):
2270 if self.base_type.is_cpp_class:
2271 return self.base_type.find_cpp_operation_type(operator, operand_type)
2274 class CNullPtrType(CPtrType):
2279 class CReferenceType(BaseType):
2283 def __init__(self, base_type):
2284 self.ref_base_type = base_type
2287 return "<CReferenceType %s>" % repr(self.ref_base_type)
2290 return "%s &" % self.ref_base_type
2292 def declaration_code(self, entity_code,
2293 for_display = 0, dll_linkage = None, pyrex = 0):
2294 #print "CReferenceType.declaration_code: pointer to", self.base_type ###
2295 return self.ref_base_type.declaration_code(
2296 "&%s" % entity_code,
2297 for_display, dll_linkage, pyrex)
2299 def specialize(self, values):
2300 base_type = self.ref_base_type.specialize(values)
2301 if base_type == self.ref_base_type:
2304 return CReferenceType(base_type)
2306 def deduce_template_params(self, actual):
2307 return self.ref_base_type.deduce_template_params(actual)
2309 def __getattr__(self, name):
2310 return getattr(self.ref_base_type, name)
2313 class CFuncType(CType):
2315 # args [CFuncTypeArg]
2316 # has_varargs boolean
2317 # exception_value string
2318 # exception_check boolean True if PyErr_Occurred check needed
2319 # calling_convention string Function calling convention
2320 # nogil boolean Can be called without gil
2321 # with_gil boolean Acquire gil around function body
2322 # templates [string] or None
2323 # cached_specialized_types [CFuncType] cached specialized versions of the CFuncType if defined in a pxd
2324 # from_fused boolean Indicates whether this is a specialized
2326 # is_strict_signature boolean function refuses to accept coerced arguments
2327 # (used for optimisation overrides)
2328 # is_const_method boolean
2332 cached_specialized_types = None
2334 is_const_method = False
2336 subtypes = ['return_type', 'args']
2338 def __init__(self, return_type, args, has_varargs = 0,
2339 exception_value = None, exception_check = 0, calling_convention = "",
2340 nogil = 0, with_gil = 0, is_overridable = 0, optional_arg_count = 0,
2341 is_const_method = False, templates = None, is_strict_signature = False):
2342 self.return_type = return_type
2344 self.has_varargs = has_varargs
2345 self.optional_arg_count = optional_arg_count
2346 self.exception_value = exception_value
2347 self.exception_check = exception_check
2348 self.calling_convention = calling_convention
2350 self.with_gil = with_gil
2351 self.is_overridable = is_overridable
2352 self.is_const_method = is_const_method
2353 self.templates = templates
2354 self.is_strict_signature = is_strict_signature
2357 arg_reprs = map(repr, self.args)
2358 if self.has_varargs:
2359 arg_reprs.append("...")
2360 if self.exception_value:
2361 except_clause = " %r" % self.exception_value
2364 if self.exception_check:
2365 except_clause += "?"
2366 return "<CFuncType %s %s[%s]%s>" % (
2367 repr(self.return_type),
2368 self.calling_convention_prefix(),
2369 ",".join(arg_reprs),
2372 def calling_convention_prefix(self):
2373 cc = self.calling_convention
2379 def as_argument_type(self):
2380 return c_ptr_type(self)
2382 def same_c_signature_as(self, other_type, as_cmethod = 0):
2383 return self.same_c_signature_as_resolved_type(
2384 other_type.resolve(), as_cmethod)
2386 def same_c_signature_as_resolved_type(self, other_type, as_cmethod = 0):
2387 #print "CFuncType.same_c_signature_as_resolved_type:", \
2388 # self, other_type, "as_cmethod =", as_cmethod ###
2389 if other_type is error_type:
2391 if not other_type.is_cfunction:
2393 if self.is_overridable != other_type.is_overridable:
2395 nargs = len(self.args)
2396 if nargs != len(other_type.args):
2398 # When comparing C method signatures, the first argument
2399 # is exempt from compatibility checking (the proper check
2400 # is performed elsewhere).
2401 for i in range(as_cmethod, nargs):
2402 if not self.args[i].type.same_as(
2403 other_type.args[i].type):
2405 if self.has_varargs != other_type.has_varargs:
2407 if self.optional_arg_count != other_type.optional_arg_count:
2409 if not self.return_type.same_as(other_type.return_type):
2411 if not self.same_calling_convention_as(other_type):
2415 def compatible_signature_with(self, other_type, as_cmethod = 0):
2416 return self.compatible_signature_with_resolved_type(other_type.resolve(), as_cmethod)
2418 def compatible_signature_with_resolved_type(self, other_type, as_cmethod):
2419 #print "CFuncType.same_c_signature_as_resolved_type:", \
2420 # self, other_type, "as_cmethod =", as_cmethod ###
2421 if other_type is error_type:
2423 if not other_type.is_cfunction:
2425 if not self.is_overridable and other_type.is_overridable:
2427 nargs = len(self.args)
2428 if nargs - self.optional_arg_count != len(other_type.args) - other_type.optional_arg_count:
2430 if self.optional_arg_count < other_type.optional_arg_count:
2432 # When comparing C method signatures, the first argument
2433 # is exempt from compatibility checking (the proper check
2434 # is performed elsewhere).
2435 for i in range(as_cmethod, len(other_type.args)):
2436 if not self.args[i].type.same_as(
2437 other_type.args[i].type):
2439 if self.has_varargs != other_type.has_varargs:
2441 if not self.return_type.subtype_of_resolved_type(other_type.return_type):
2443 if not self.same_calling_convention_as(other_type):
2445 if self.nogil != other_type.nogil:
2447 self.original_sig = other_type.original_sig or other_type
2451 def narrower_c_signature_than(self, other_type, as_cmethod = 0):
2452 return self.narrower_c_signature_than_resolved_type(other_type.resolve(), as_cmethod)
2454 def narrower_c_signature_than_resolved_type(self, other_type, as_cmethod):
2455 if other_type is error_type:
2457 if not other_type.is_cfunction:
2459 nargs = len(self.args)
2460 if nargs != len(other_type.args):
2462 for i in range(as_cmethod, nargs):
2463 if not self.args[i].type.subtype_of_resolved_type(other_type.args[i].type):
2466 self.args[i].needs_type_test = other_type.args[i].needs_type_test \
2467 or not self.args[i].type.same_as(other_type.args[i].type)
2468 if self.has_varargs != other_type.has_varargs:
2470 if self.optional_arg_count != other_type.optional_arg_count:
2472 if not self.return_type.subtype_of_resolved_type(other_type.return_type):
2476 def same_calling_convention_as(self, other):
2477 ## XXX Under discussion ...
2478 ## callspec_words = ("__stdcall", "__cdecl", "__fastcall")
2479 ## cs1 = self.calling_convention
2480 ## cs2 = other.calling_convention
2481 ## if (cs1 in callspec_words or
2482 ## cs2 in callspec_words):
2483 ## return cs1 == cs2
2486 sc1 = self.calling_convention == '__stdcall'
2487 sc2 = other.calling_convention == '__stdcall'
2490 def same_exception_signature_as(self, other_type):
2491 return self.same_exception_signature_as_resolved_type(
2492 other_type.resolve())
2494 def same_exception_signature_as_resolved_type(self, other_type):
2495 return self.exception_value == other_type.exception_value \
2496 and self.exception_check == other_type.exception_check
2498 def same_as_resolved_type(self, other_type, as_cmethod = 0):
2499 return self.same_c_signature_as_resolved_type(other_type, as_cmethod) \
2500 and self.same_exception_signature_as_resolved_type(other_type) \
2501 and self.nogil == other_type.nogil
2503 def pointer_assignable_from_resolved_type(self, other_type):
2504 return self.same_c_signature_as_resolved_type(other_type) \
2505 and self.same_exception_signature_as_resolved_type(other_type) \
2506 and not (self.nogil and not other_type.nogil)
2508 def declaration_code(self, entity_code,
2509 for_display = 0, dll_linkage = None, pyrex = 0,
2510 with_calling_convention = 1):
2512 for arg in self.args[:len(self.args)-self.optional_arg_count]:
2513 arg_decl_list.append(
2514 arg.type.declaration_code("", for_display, pyrex = pyrex))
2515 if self.is_overridable:
2516 arg_decl_list.append("int %s" % Naming.skip_dispatch_cname)
2517 if self.optional_arg_count:
2518 arg_decl_list.append(self.op_arg_struct.declaration_code(Naming.optional_args_cname))
2519 if self.has_varargs:
2520 arg_decl_list.append("...")
2521 arg_decl_code = ", ".join(arg_decl_list)
2522 if not arg_decl_code and not pyrex:
2523 arg_decl_code = "void"
2525 if (pyrex or for_display) and not self.return_type.is_pyobject:
2526 if self.exception_value and self.exception_check:
2527 trailer = " except? %s" % self.exception_value
2528 elif self.exception_value:
2529 trailer = " except %s" % self.exception_value
2530 elif self.exception_check == '+':
2531 trailer = " except +"
2533 " except *" # ignored
2536 if not with_calling_convention:
2539 cc = self.calling_convention_prefix()
2540 if (not entity_code and cc) or entity_code.startswith("*"):
2541 entity_code = "(%s%s)" % (cc, entity_code)
2543 if self.is_const_method:
2545 return self.return_type.declaration_code(
2546 "%s%s(%s)%s" % (cc, entity_code, arg_decl_code, trailer),
2547 for_display, dll_linkage, pyrex)
2549 def function_header_code(self, func_name, arg_code):
2550 if self.is_const_method:
2554 return "%s%s(%s)%s" % (self.calling_convention_prefix(),
2555 func_name, arg_code, trailer)
2557 def signature_string(self):
2558 s = self.declaration_code("")
2561 def signature_cast_string(self):
2562 s = self.declaration_code("(*)", with_calling_convention=False)
2565 def specialize(self, values):
2566 result = CFuncType(self.return_type.specialize(values),
2567 [arg.specialize(values) for arg in self.args],
2568 has_varargs = self.has_varargs,
2569 exception_value = self.exception_value,
2570 exception_check = self.exception_check,
2571 calling_convention = self.calling_convention,
2573 with_gil = self.with_gil,
2574 is_overridable = self.is_overridable,
2575 optional_arg_count = self.optional_arg_count,
2576 is_const_method = self.is_const_method,
2577 templates = self.templates)
2579 result.from_fused = self.is_fused
2582 def opt_arg_cname(self, arg_name):
2583 return self.op_arg_struct.base_type.scope.lookup(arg_name).cname
2585 # Methods that deal with Fused Types
2586 # All but map_with_specific_entries should be called only on functions
2587 # with fused types (and not on their corresponding specific versions).
2589 def get_all_specialized_permutations(self, fused_types=None):
2591 Permute all the types. For every specific instance of a fused type, we
2592 want all other specific instances of all other fused types.
2594 It returns an iterable of two-tuples of the cname that should prefix
2595 the cname of the function, and a dict mapping any fused types to their
2596 respective specific types.
2598 assert self.is_fused
2600 if fused_types is None:
2601 fused_types = self.get_fused_types()
2603 return get_all_specialized_permutations(fused_types)
2605 def get_all_specialized_function_types(self):
2607 Get all the specific function types of this one.
2609 assert self.is_fused
2611 if self.entry.fused_cfunction:
2612 return [n.type for n in self.entry.fused_cfunction.nodes]
2613 elif self.cached_specialized_types is not None:
2614 return self.cached_specialized_types
2616 cfunc_entries = self.entry.scope.cfunc_entries
2617 cfunc_entries.remove(self.entry)
2620 permutations = self.get_all_specialized_permutations()
2622 for cname, fused_to_specific in permutations:
2623 new_func_type = self.entry.type.specialize(fused_to_specific)
2625 if self.optional_arg_count:
2626 # Remember, this method is set by CFuncDeclaratorNode
2627 self.declare_opt_arg_struct(new_func_type, cname)
2629 new_entry = copy.deepcopy(self.entry)
2630 new_func_type.specialize_entry(new_entry, cname)
2632 new_entry.type = new_func_type
2633 new_func_type.entry = new_entry
2634 result.append(new_func_type)
2636 cfunc_entries.append(new_entry)
2638 self.cached_specialized_types = result
2642 def get_fused_types(self, result=None, seen=None, subtypes=None):
2643 """Return fused types in the order they appear as parameter types"""
2644 return super(CFuncType, self).get_fused_types(result, seen,
2647 def specialize_entry(self, entry, cname):
2648 assert not self.is_fused
2649 specialize_entry(entry, cname)
2652 def specialize_entry(entry, cname):
2654 Specialize an entry of a copied fused function or method
2656 entry.is_fused_specialized = True
2657 entry.name = get_fused_cname(cname, entry.name)
2659 if entry.is_cmethod:
2660 entry.cname = entry.name
2661 if entry.is_inherited:
2662 entry.cname = StringEncoding.EncodedString(
2663 "%s.%s" % (Naming.obj_base_cname, entry.cname))
2665 entry.cname = get_fused_cname(cname, entry.cname)
2667 if entry.func_cname:
2668 entry.func_cname = get_fused_cname(cname, entry.func_cname)
2670 def get_fused_cname(fused_cname, orig_cname):
2672 Given the fused cname id and an original cname, return a specialized cname
2674 assert fused_cname and orig_cname
2675 return StringEncoding.EncodedString('%s%s%s' % (Naming.fused_func_prefix,
2676 fused_cname, orig_cname))
2678 def unique(somelist):
2681 for obj in somelist:
2688 def get_all_specialized_permutations(fused_types):
2689 return _get_all_specialized_permutations(unique(fused_types))
2691 def _get_all_specialized_permutations(fused_types, id="", f2s=()):
2692 fused_type, = fused_types[0].get_fused_types()
2695 for newid, specific_type in enumerate(fused_type.types):
2696 # f2s = dict(f2s, **{ fused_type: specific_type })
2698 f2s.update({ fused_type: specific_type })
2701 cname = '%s_%s' % (id, newid)
2705 if len(fused_types) > 1:
2706 result.extend(_get_all_specialized_permutations(
2707 fused_types[1:], cname, f2s))
2709 result.append((cname, f2s))
2713 def specialization_signature_string(fused_compound_type, fused_to_specific):
2715 Return the signature for a specialization of a fused type. e.g.
2725 'float[:]' or 'double[:]'
2727 integral func(floating) ->
2728 'int (*func)(float)' or ...
2730 fused_types = fused_compound_type.get_fused_types()
2731 if len(fused_types) == 1:
2732 fused_type = fused_types[0]
2734 fused_type = fused_compound_type
2736 return fused_type.specialize(fused_to_specific).typeof_name()
2738 def get_specialized_types(type):
2740 Return a list of specialized types sorted in reverse order in accordance
2741 with their preference in runtime fused-type dispatch
2743 assert type.is_fused
2745 if isinstance(type, FusedType):
2747 for specialized_type in result:
2748 specialized_type.specialization_string = specialized_type.typeof_name()
2751 for cname, f2s in get_all_specialized_permutations(type.get_fused_types()):
2752 specialized_type = type.specialize(f2s)
2753 specialized_type.specialization_string = (
2754 specialization_signature_string(type, f2s))
2755 result.append(specialized_type)
2757 return sorted(result)
2760 class CFuncTypeArg(BaseType):
2764 # pos source file position
2766 # FIXME: is this the right setup? should None be allowed here?
2770 accept_builtin_subtypes = False
2774 def __init__(self, name, type, pos, cname=None):
2776 if cname is not None:
2779 self.cname = Naming.var_prefix + name
2782 self.needs_type_test = False # TODO: should these defaults be set in analyse_types()?
2785 return "%s:%s" % (self.name, repr(self.type))
2787 def declaration_code(self, for_display = 0):
2788 return self.type.declaration_code(self.cname, for_display)
2790 def specialize(self, values):
2791 return CFuncTypeArg(self.name, self.type.specialize(values), self.pos, self.cname)
2793 class ToPyStructUtilityCode(object):
2797 def __init__(self, type, forward_decl):
2799 self.header = "static PyObject* %s(%s)" % (type.to_py_function,
2800 type.declaration_code('s'))
2801 self.forward_decl = forward_decl
2803 def __eq__(self, other):
2804 return isinstance(other, ToPyStructUtilityCode) and self.header == other.header
2807 return hash(self.header)
2812 def put_code(self, output):
2813 code = output['utility_code_def']
2814 proto = output['utility_code_proto']
2816 code.putln("%s {" % self.header)
2817 code.putln("PyObject* res;")
2818 code.putln("PyObject* member;")
2819 code.putln("res = PyDict_New(); if (res == NULL) return NULL;")
2820 for member in self.type.scope.var_entries:
2821 nameconst_cname = code.get_py_string_const(member.name, identifier=True)
2822 code.putln("member = %s(s.%s); if (member == NULL) goto bad;" % (
2823 member.type.to_py_function, member.cname))
2824 code.putln("if (PyDict_SetItem(res, %s, member) < 0) goto bad;" % nameconst_cname)
2825 code.putln("Py_DECREF(member);")
2826 code.putln("return res;")
2828 code.putln("Py_XDECREF(member);")
2829 code.putln("Py_DECREF(res);")
2830 code.putln("return NULL;")
2833 # This is a bit of a hack, we need a forward declaration
2834 # due to the way things are ordered in the module...
2835 if self.forward_decl:
2836 proto.putln(self.type.declaration_code('') + ';')
2837 proto.putln(self.header + ";")
2839 def inject_tree_and_scope_into(self, module_node):
2843 class CStructOrUnionType(CType):
2846 # kind string "struct" or "union"
2847 # scope StructOrUnionScope, or None if incomplete
2848 # typedef_flag boolean
2853 is_struct_or_union = 1
2855 exception_check = True
2857 def __init__(self, name, kind, scope, typedef_flag, cname, packed=False):
2862 self.typedef_flag = typedef_flag
2863 self.is_struct = kind == 'struct'
2865 self.to_py_function = "%s_to_py_%s" % (Naming.convert_func_prefix, self.cname)
2866 self.from_py_function = "%s_from_py_%s" % (Naming.convert_func_prefix, self.cname)
2867 self.exception_check = True
2868 self._convert_to_py_code = None
2869 self._convert_from_py_code = None
2870 self.packed = packed
2872 def create_to_py_utility_code(self, env):
2873 if env.outer_scope is None:
2876 if self._convert_to_py_code is False:
2877 return None # tri-state-ish
2879 if self._convert_to_py_code is None:
2880 for member in self.scope.var_entries:
2881 if not member.type.create_to_py_utility_code(env):
2882 self.to_py_function = None
2883 self._convert_to_py_code = False
2885 forward_decl = (self.entry.visibility != 'extern')
2886 self._convert_to_py_code = ToPyStructUtilityCode(self, forward_decl)
2888 env.use_utility_code(self._convert_to_py_code)
2891 def create_from_py_utility_code(self, env):
2892 if env.outer_scope is None:
2895 if self._convert_from_py_code is False:
2896 return None # tri-state-ish
2898 if self._convert_from_py_code is None:
2899 for member in self.scope.var_entries:
2900 if not member.type.create_from_py_utility_code(env):
2901 self.from_py_function = None
2902 self._convert_from_py_code = False
2906 struct_type_decl=self.declaration_code(""),
2907 var_entries=self.scope.var_entries,
2908 funcname=self.from_py_function,
2910 self._convert_from_py_code = TempitaUtilityCode.load(
2911 "FromPyStructUtility", "TypeConversion.c", context=context)
2913 env.use_utility_code(self._convert_from_py_code)
2917 return "<CStructOrUnionType %s %s%s>" % (
2918 self.name, self.cname,
2919 ("", " typedef")[self.typedef_flag])
2921 def declaration_code(self, entity_code,
2922 for_display=0, dll_linkage=None, pyrex=0):
2923 if pyrex or for_display:
2924 base_code = self.name
2926 if self.typedef_flag:
2927 base_code = self.cname
2929 base_code = "%s %s" % (self.kind, self.cname)
2930 base_code = public_decl(base_code, dll_linkage)
2931 return self.base_declaration_code(base_code, entity_code)
2933 def __eq__(self, other):
2935 return (isinstance(other, CStructOrUnionType) and
2936 self.name == other.name)
2937 except AttributeError:
2940 def __lt__(self, other):
2942 return self.name < other.name
2943 except AttributeError:
2944 # this is arbitrary, but it makes sure we always have
2945 # *some* kind of order
2949 return hash(self.cname) ^ hash(self.kind)
2951 def is_complete(self):
2952 return self.scope is not None
2954 def attributes_known(self):
2955 return self.is_complete()
2957 def can_be_complex(self):
2958 # Does the struct consist of exactly two identical floats?
2959 fields = self.scope.var_entries
2960 if len(fields) != 2: return False
2962 return (a.type.is_float and b.type.is_float and
2963 a.type.declaration_code("") ==
2964 b.type.declaration_code(""))
2966 def struct_nesting_depth(self):
2967 child_depths = [x.type.struct_nesting_depth()
2968 for x in self.scope.var_entries]
2969 return max(child_depths) + 1
2971 def cast_code(self, expr_code):
2974 return super(CStructOrUnionType, self).cast_code(expr_code)
2977 builtin_cpp_conversions = ("std::string",
2979 "std::vector", "std::list",
2980 "std::set", "std::unordered_set",
2981 "std::map", "std::unordered_map")
2983 class CppClassType(CType):
2986 # scope CppClassScope
2987 # templates [string] or None
2991 exception_check = True
2994 # For struct-like declaration.
2997 typedef_flag = False
2999 subtypes = ['templates']
3001 def __init__(self, name, scope, cname, base_classes, templates = None, template_type = None):
3005 self.base_classes = base_classes
3007 self.templates = templates
3008 self.template_type = template_type
3009 self.specializations = {}
3010 self.is_cpp_string = cname == 'std::string'
3012 def use_conversion_utility(self, from_or_to):
3015 def maybe_unordered(self):
3016 if 'unordered' in self.cname:
3021 def create_from_py_utility_code(self, env):
3022 if self.from_py_function is not None:
3024 if self.cname in builtin_cpp_conversions:
3027 declarations = ["cdef extern from *:"]
3028 for ix, T in enumerate(self.templates or []):
3029 if T.is_pyobject or not T.create_from_py_utility_code(env):
3031 tags.append(T.specialization_name())
3032 if T.exception_value is not None:
3033 except_clause = T.exception_value
3034 if T.exception_check:
3035 except_clause = "? %s" % except_clause
3036 declarations.append(
3037 " ctypedef %s %s '%s'" % (
3038 T.declaration_code("", for_display=True), X[ix], T.declaration_code("")))
3041 declarations.append(
3042 " ctypedef struct %s '%s':\n pass" % (
3043 X[ix], T.declaration_code("")))
3044 declarations.append(
3045 " cdef %s %s_from_py '%s' (object) except %s" % (
3046 X[ix], X[ix], T.from_py_function, except_clause))
3047 cls = self.cname[5:]
3048 cname = '__pyx_convert_%s_from_py_%s' % (cls, '____'.join(tags))
3050 'template_type_declarations': '\n'.join(declarations),
3052 'maybe_unordered': self.maybe_unordered(),
3054 from UtilityCode import CythonUtilityCode
3055 env.use_utility_code(CythonUtilityCode.load(cls.replace('unordered_', '') + ".from_py", "CppConvert.pyx", context=context))
3056 self.from_py_function = cname
3059 def create_to_py_utility_code(self, env):
3060 if self.to_py_function is not None:
3062 if self.cname in builtin_cpp_conversions:
3065 declarations = ["cdef extern from *:"]
3066 for ix, T in enumerate(self.templates or []):
3067 if not T.create_to_py_utility_code(env):
3069 tags.append(T.specialization_name())
3070 declarations.append(
3071 " ctypedef struct %s '%s':\n pass" % (
3072 X[ix], T.declaration_code("")))
3073 declarations.append(
3074 " cdef object %s_to_py '%s' (%s)" % (
3075 X[ix], T.to_py_function, X[ix]))
3076 cls = self.cname[5:]
3077 cname = "__pyx_convert_%s_to_py_%s" % (cls, "____".join(tags))
3079 'template_type_declarations': '\n'.join(declarations),
3081 'maybe_unordered': self.maybe_unordered(),
3083 from UtilityCode import CythonUtilityCode
3084 env.use_utility_code(CythonUtilityCode.load(cls.replace('unordered_', '') + ".to_py", "CppConvert.pyx", context=context))
3085 self.to_py_function = cname
3088 def specialize_here(self, pos, template_values = None):
3089 if self.templates is None:
3090 error(pos, "'%s' type is not a template" % self)
3092 if len(self.templates) != len(template_values):
3093 error(pos, "%s templated type receives %d arguments, got %d" %
3094 (self.name, len(self.templates), len(template_values)))
3096 has_object_template_param = False
3097 for value in template_values:
3098 if value.is_pyobject:
3099 has_object_template_param = True
3101 "Python object type '%s' cannot be used as a template argument" % value)
3102 if has_object_template_param:
3104 return self.specialize(dict(zip(self.templates, template_values)))
3106 def specialize(self, values):
3107 if not self.templates and not self.namespace:
3109 if self.templates is None:
3111 key = tuple(values.items())
3112 if key in self.specializations:
3113 return self.specializations[key]
3114 template_values = [t.specialize(values) for t in self.templates]
3115 specialized = self.specializations[key] = \
3116 CppClassType(self.name, None, self.cname, [], template_values, template_type=self)
3117 # Need to do these *after* self.specializations[key] is set
3118 # to avoid infinite recursion on circular references.
3119 specialized.base_classes = [b.specialize(values) for b in self.base_classes]
3120 specialized.scope = self.scope.specialize(values)
3121 if self.namespace is not None:
3122 specialized.namespace = self.namespace.specialize(values)
3125 def deduce_template_params(self, actual):
3128 # TODO(robertwb): Actual type equality.
3129 elif self.declaration_code("") == actual.template_type.declaration_code(""):
3131 merge_template_deductions,
3132 [formal_param.deduce_template_params(actual_param) for (formal_param, actual_param) in zip(self.templates, actual.templates)],
3137 def declaration_code(self, entity_code,
3138 for_display = 0, dll_linkage = None, pyrex = 0):
3140 template_strings = [param.declaration_code('', for_display, None, pyrex)
3141 for param in self.templates]
3146 templates = brackets % ",".join(template_strings)
3147 if templates[-2:] == ">>":
3148 templates = templates[:-2] + "> >"
3151 if pyrex or for_display:
3152 base_code = "%s%s" % (self.name, templates)
3154 base_code = "%s%s" % (self.cname, templates)
3155 if self.namespace is not None:
3156 base_code = "%s::%s" % (self.namespace.declaration_code(''), base_code)
3157 base_code = public_decl(base_code, dll_linkage)
3158 return self.base_declaration_code(base_code, entity_code)
3160 def is_subclass(self, other_type):
3161 if self.same_as_resolved_type(other_type):
3163 for base_class in self.base_classes:
3164 if base_class.is_subclass(other_type):
3168 def same_as_resolved_type(self, other_type):
3169 if other_type.is_cpp_class:
3170 if self == other_type:
3172 elif (self.cname == other_type.cname and
3173 self.template_type and other_type.template_type):
3174 if self.templates == other_type.templates:
3176 for t1, t2 in zip(self.templates, other_type.templates):
3177 if not t1.same_as_resolved_type(t2):
3182 def assignable_from_resolved_type(self, other_type):
3183 # TODO: handle operator=(...) here?
3184 if other_type is error_type:
3186 return other_type.is_cpp_class and other_type.is_subclass(self)
3188 def attributes_known(self):
3189 return self.scope is not None
3191 def find_cpp_operation_type(self, operator, operand_type=None):
3193 if operand_type is not None:
3194 operands.append(operand_type)
3195 # pos == None => no errors
3196 operator_entry = self.scope.lookup_operator_for_types(None, operator, operands)
3197 if not operator_entry:
3199 func_type = operator_entry.type
3200 if func_type.is_ptr:
3201 func_type = func_type.base_type
3202 return func_type.return_type
3204 def check_nullary_constructor(self, pos, msg="stack allocated"):
3205 constructor = self.scope.lookup(u'<init>')
3206 if constructor is not None and best_match([], constructor.all_alternatives()) is None:
3207 error(pos, "C++ class must have a nullary constructor to be %s" % msg)
3210 class TemplatePlaceholderType(CType):
3212 def __init__(self, name):
3215 def declaration_code(self, entity_code,
3216 for_display = 0, dll_linkage = None, pyrex = 0):
3218 return self.name + " " + entity_code
3222 def specialize(self, values):
3228 def deduce_template_params(self, actual):
3229 return {self: actual}
3231 def same_as_resolved_type(self, other_type):
3232 if isinstance(other_type, TemplatePlaceholderType):
3233 return self.name == other_type.name
3238 return hash(self.name)
3240 def __cmp__(self, other):
3241 if isinstance(other, TemplatePlaceholderType):
3242 return cmp(self.name, other.name)
3244 return cmp(type(self), type(other))
3246 def __eq__(self, other):
3247 if isinstance(other, TemplatePlaceholderType):
3248 return self.name == other.name
3252 class CEnumType(CType):
3254 # cname string or None
3255 # typedef_flag boolean
3259 rank = -1 # Ranks below any integer type
3260 to_py_function = "PyInt_FromLong"
3261 from_py_function = "PyInt_AsLong"
3263 def __init__(self, name, cname, typedef_flag):
3267 self.typedef_flag = typedef_flag
3273 return "<CEnumType %s %s%s>" % (self.name, self.cname,
3274 ("", " typedef")[self.typedef_flag])
3276 def declaration_code(self, entity_code,
3277 for_display = 0, dll_linkage = None, pyrex = 0):
3278 if pyrex or for_display:
3279 base_code = self.name
3281 if self.typedef_flag:
3282 base_code = self.cname
3284 base_code = "enum %s" % self.cname
3285 base_code = public_decl(base_code, dll_linkage)
3286 return self.base_declaration_code(base_code, entity_code)
3288 class UnspecifiedType(PyrexType):
3289 # Used as a placeholder until the type can be determined.
3293 def declaration_code(self, entity_code,
3294 for_display = 0, dll_linkage = None, pyrex = 0):
3295 return "<unspecified>"
3297 def same_as_resolved_type(self, other_type):
3301 class ErrorType(PyrexType):
3302 # Used to prevent propagation of error messages.
3305 exception_value = "0"
3307 to_py_function = "dummy"
3308 from_py_function = "dummy"
3310 def create_to_py_utility_code(self, env):
3313 def create_from_py_utility_code(self, env):
3316 def declaration_code(self, entity_code,
3317 for_display = 0, dll_linkage = None, pyrex = 0):
3320 def same_as_resolved_type(self, other_type):
3323 def error_condition(self, result_code):
3327 rank_to_type_name = (
3338 _rank_to_type_name = list(rank_to_type_name)
3339 RANK_INT = _rank_to_type_name.index('int')
3340 RANK_LONG = _rank_to_type_name.index('long')
3341 RANK_FLOAT = _rank_to_type_name.index('float')
3345 error_type = ErrorType()
3346 unspecified_type = UnspecifiedType()
3348 py_object_type = PyObjectType()
3350 c_void_type = CVoidType()
3352 c_uchar_type = CIntType(0, UNSIGNED)
3353 c_ushort_type = CIntType(1, UNSIGNED)
3354 c_uint_type = CIntType(2, UNSIGNED)
3355 c_ulong_type = CIntType(3, UNSIGNED)
3356 c_ulonglong_type = CIntType(4, UNSIGNED)
3358 c_char_type = CIntType(0)
3359 c_short_type = CIntType(1)
3360 c_int_type = CIntType(2)
3361 c_long_type = CIntType(3)
3362 c_longlong_type = CIntType(4)
3364 c_schar_type = CIntType(0, SIGNED)
3365 c_sshort_type = CIntType(1, SIGNED)
3366 c_sint_type = CIntType(2, SIGNED)
3367 c_slong_type = CIntType(3, SIGNED)
3368 c_slonglong_type = CIntType(4, SIGNED)
3370 c_float_type = CFloatType(5, math_h_modifier='f')
3371 c_double_type = CFloatType(6)
3372 c_longdouble_type = CFloatType(7, math_h_modifier='l')
3374 c_float_complex_type = CComplexType(c_float_type)
3375 c_double_complex_type = CComplexType(c_double_type)
3376 c_longdouble_complex_type = CComplexType(c_longdouble_type)
3378 c_anon_enum_type = CAnonEnumType(-1)
3379 c_returncode_type = CReturnCodeType(RANK_INT)
3380 c_bint_type = CBIntType(RANK_INT)
3381 c_py_unicode_type = CPyUnicodeIntType(RANK_INT-0.5, UNSIGNED)
3382 c_py_ucs4_type = CPyUCS4IntType(RANK_LONG-0.5, UNSIGNED)
3383 c_py_hash_t_type = CPyHashTType(RANK_LONG+0.5, SIGNED)
3384 c_py_ssize_t_type = CPySSizeTType(RANK_LONG+0.5, SIGNED)
3385 c_ssize_t_type = CSSizeTType(RANK_LONG+0.5, SIGNED)
3386 c_size_t_type = CSizeTType(RANK_LONG+0.5, UNSIGNED)
3387 c_ptrdiff_t_type = CPtrdiffTType(RANK_LONG+0.75, SIGNED)
3389 c_null_ptr_type = CNullPtrType(c_void_type)
3390 c_void_ptr_type = CPtrType(c_void_type)
3391 c_void_ptr_ptr_type = CPtrType(c_void_ptr_type)
3392 c_char_ptr_type = CPtrType(c_char_type)
3393 c_uchar_ptr_type = CPtrType(c_uchar_type)
3394 c_char_ptr_ptr_type = CPtrType(c_char_ptr_type)
3395 c_int_ptr_type = CPtrType(c_int_type)
3396 c_py_unicode_ptr_type = CPtrType(c_py_unicode_type)
3397 c_py_ssize_t_ptr_type = CPtrType(c_py_ssize_t_type)
3398 c_ssize_t_ptr_type = CPtrType(c_ssize_t_type)
3399 c_size_t_ptr_type = CPtrType(c_size_t_type)
3402 c_gilstate_type = CEnumType("PyGILState_STATE", "PyGILState_STATE", True)
3403 c_threadstate_type = CStructOrUnionType("PyThreadState", "struct", None, 1, "PyThreadState")
3404 c_threadstate_ptr_type = CPtrType(c_threadstate_type)
3406 # the Py_buffer type is defined in Builtin.py
3407 c_py_buffer_type = CStructOrUnionType("Py_buffer", "struct", None, 1, "Py_buffer")
3408 c_py_buffer_ptr_type = CPtrType(c_py_buffer_type)
3410 # Not sure whether the unsigned versions and 'long long' should be in there
3411 # long long requires C99 and might be slow, and would always get preferred
3412 # when specialization happens through calling and not indexing
3413 cy_integral_type = FusedType([c_short_type, c_int_type, c_long_type],
3415 # Omitting long double as it might be slow
3416 cy_floating_type = FusedType([c_float_type, c_double_type], name="floating")
3417 cy_numeric_type = FusedType([c_short_type,
3422 c_float_complex_type,
3423 c_double_complex_type], name="numeric")
3425 # buffer-related structs
3426 c_buf_diminfo_type = CStructOrUnionType("__Pyx_Buf_DimInfo", "struct",
3427 None, 1, "__Pyx_Buf_DimInfo")
3428 c_pyx_buffer_type = CStructOrUnionType("__Pyx_Buffer", "struct", None, 1, "__Pyx_Buffer")
3429 c_pyx_buffer_ptr_type = CPtrType(c_pyx_buffer_type)
3430 c_pyx_buffer_nd_type = CStructOrUnionType("__Pyx_LocalBuf_ND", "struct",
3431 None, 1, "__Pyx_LocalBuf_ND")
3433 cython_memoryview_type = CStructOrUnionType("__pyx_memoryview_obj", "struct",
3434 None, 0, "__pyx_memoryview_obj")
3436 memoryviewslice_type = CStructOrUnionType("memoryviewslice", "struct",
3437 None, 1, "__Pyx_memviewslice")
3439 modifiers_and_name_to_type = {
3440 #(signed, longness, name) : type
3441 (0, 0, "char"): c_uchar_type,
3442 (1, 0, "char"): c_char_type,
3443 (2, 0, "char"): c_schar_type,
3445 (0, -1, "int"): c_ushort_type,
3446 (0, 0, "int"): c_uint_type,
3447 (0, 1, "int"): c_ulong_type,
3448 (0, 2, "int"): c_ulonglong_type,
3450 (1, -1, "int"): c_short_type,
3451 (1, 0, "int"): c_int_type,
3452 (1, 1, "int"): c_long_type,
3453 (1, 2, "int"): c_longlong_type,
3455 (2, -1, "int"): c_sshort_type,
3456 (2, 0, "int"): c_sint_type,
3457 (2, 1, "int"): c_slong_type,
3458 (2, 2, "int"): c_slonglong_type,
3460 (1, 0, "float"): c_float_type,
3461 (1, 0, "double"): c_double_type,
3462 (1, 1, "double"): c_longdouble_type,
3464 (1, 0, "complex"): c_double_complex_type, # C: float, Python: double => Python wins
3465 (1, 0, "floatcomplex"): c_float_complex_type,
3466 (1, 0, "doublecomplex"): c_double_complex_type,
3467 (1, 1, "doublecomplex"): c_longdouble_complex_type,
3470 (1, 0, "void"): c_void_type,
3472 (1, 0, "bint"): c_bint_type,
3473 (0, 0, "Py_UNICODE"): c_py_unicode_type,
3474 (0, 0, "Py_UCS4"): c_py_ucs4_type,
3475 (2, 0, "Py_hash_t"): c_py_hash_t_type,
3476 (2, 0, "Py_ssize_t"): c_py_ssize_t_type,
3477 (2, 0, "ssize_t") : c_ssize_t_type,
3478 (0, 0, "size_t") : c_size_t_type,
3479 (2, 0, "ptrdiff_t") : c_ptrdiff_t_type,
3481 (1, 0, "object"): py_object_type,
3484 def is_promotion(src_type, dst_type):
3485 # It's hard to find a hard definition of promotion, but empirical
3486 # evidence suggests that the below is all that's allowed.
3487 if src_type.is_numeric:
3488 if dst_type.same_as(c_int_type):
3489 unsigned = (not src_type.signed)
3490 return (src_type.is_enum or
3491 (src_type.is_int and
3492 unsigned + src_type.rank < dst_type.rank))
3493 elif dst_type.same_as(c_double_type):
3494 return src_type.is_float and src_type.rank <= dst_type.rank
3497 def best_match(args, functions, pos=None, env=None):
3499 Given a list args of arguments and a list of functions, choose one
3500 to call which seems to be the "best" fit for this list of arguments.
3501 This function is used, e.g., when deciding which overloaded method
3502 to dispatch for C++ classes.
3504 We first eliminate functions based on arity, and if only one
3505 function has the correct arity, we return it. Otherwise, we weight
3506 functions based on how much work must be done to convert the
3507 arguments, with the following priorities:
3508 * identical types or pointers to identical types
3511 That is, we prefer functions where no arguments need converted,
3512 and failing that, functions where only promotions are required, and
3515 If no function is deemed a good fit, or if two or more functions have
3516 the same weight, we return None (as there is no best match). If pos
3517 is not None, we also generate an error.
3519 # TODO: args should be a list of types, not a list of Nodes.
3520 actual_nargs = len(args)
3524 for func in functions:
3526 func_type = func.type
3527 if func_type.is_ptr:
3528 func_type = func_type.base_type
3529 # Check function type
3530 if not func_type.is_cfunction:
3531 if not func_type.is_error and pos is not None:
3532 error_mesg = "Calling non-function type '%s'" % func_type
3533 errors.append((func, error_mesg))
3536 max_nargs = len(func_type.args)
3537 min_nargs = max_nargs - func_type.optional_arg_count
3538 if actual_nargs < min_nargs or \
3539 (not func_type.has_varargs and actual_nargs > max_nargs):
3540 if max_nargs == min_nargs and not func_type.has_varargs:
3541 expectation = max_nargs
3542 elif actual_nargs < min_nargs:
3543 expectation = "at least %s" % min_nargs
3545 expectation = "at most %s" % max_nargs
3546 error_mesg = "Call with wrong number of arguments (expected %s, got %s)" \
3547 % (expectation, actual_nargs)
3548 errors.append((func, error_mesg))
3550 if func_type.templates:
3551 arg_types = [arg.type for arg in args]
3552 deductions = reduce(
3553 merge_template_deductions,
3554 [pattern.type.deduce_template_params(actual) for (pattern, actual) in zip(func_type.args, arg_types)],
3556 if deductions is None:
3557 errors.append((func, "Unable to deduce type parameters"))
3558 elif len(deductions) < len(func_type.templates):
3559 errors.append((func, "Unable to deduce type parameter %s" % (
3560 ", ".join([param.name for param in set(func_type.templates) - set(deductions.keys())]))))
3562 type_list = [deductions[param] for param in func_type.templates]
3563 from Symtab import Entry
3564 specialization = Entry(
3565 name = func.name + "[%s]" % ",".join([str(t) for t in type_list]),
3566 cname = func.cname + "<%s>" % ",".join([t.declaration_code("") for t in type_list]),
3567 type = func_type.specialize(deductions),
3569 candidates.append((specialization, specialization.type))
3571 candidates.append((func, func_type))
3573 # Optimize the most common case of no overloading...
3574 if len(candidates) == 1:
3575 return candidates[0][0]
3576 elif len(candidates) == 0:
3578 func, errmsg = errors[0]
3579 if len(errors) == 1 or [1 for func, e in errors if e == errmsg]:
3582 error(pos, "no suitable method found")
3587 needed_coercions = {}
3589 for index, (func, func_type) in enumerate(candidates):
3591 for i in range(min(len(args), len(func_type.args))):
3592 src_type = args[i].type
3593 dst_type = func_type.args[i].type
3595 assignable = dst_type.assignable_from(src_type)
3597 # Now take care of normal string literals. So when you call a cdef
3598 # function that takes a char *, the coercion will mean that the
3599 # type will simply become bytes. We need to do this coercion
3600 # manually for overloaded and fused functions
3601 if not assignable and src_type.is_pyobject:
3602 if (src_type.is_builtin_type and src_type.name == 'str' and
3603 dst_type.resolve() is c_char_ptr_type):
3604 c_src_type = c_char_ptr_type
3606 c_src_type = src_type.default_coerced_ctype()
3609 assignable = dst_type.assignable_from(c_src_type)
3611 src_type = c_src_type
3612 needed_coercions[func] = i, dst_type
3615 if src_type == dst_type or dst_type.same_as(src_type):
3617 elif func_type.is_strict_signature:
3618 break # exact match requested but not found
3619 elif is_promotion(src_type, dst_type):
3621 elif ((src_type.is_int and dst_type.is_int) or
3622 (src_type.is_float and dst_type.is_float)):
3623 score[2] += abs(dst_type.rank + (not dst_type.signed) -
3624 (src_type.rank + (not src_type.signed))) + 1
3625 elif not src_type.is_pyobject:
3630 error_mesg = "Invalid conversion from '%s' to '%s'"%(src_type,
3632 bad_types.append((func, error_mesg))
3635 possibilities.append((score, index, func)) # so we can sort it
3638 possibilities.sort()
3639 if len(possibilities) > 1:
3640 score1 = possibilities[0][0]
3641 score2 = possibilities[1][0]
3642 if score1 == score2:
3644 error(pos, "ambiguous overloaded method")
3647 function = possibilities[0][-1]
3649 if function in needed_coercions and env:
3650 arg_i, coerce_to_type = needed_coercions[function]
3651 args[arg_i] = args[arg_i].coerce_to(coerce_to_type, env)
3656 if len(bad_types) == 1:
3657 error(pos, bad_types[0][1])
3659 error(pos, "no suitable method found")
3663 def merge_template_deductions(a, b):
3664 if a is None or b is None:
3667 for param, value in b.iteritems():
3669 if a[param] != b[param]:
3675 def widest_numeric_type(type1, type2):
3676 # Given two numeric types, return the narrowest type
3677 # encompassing both of them.
3680 elif type1.is_complex or type2.is_complex:
3681 def real_type(ntype):
3682 if ntype.is_complex:
3683 return ntype.real_type
3685 widest_type = CComplexType(
3686 widest_numeric_type(
3689 elif type1.is_enum and type2.is_enum:
3690 widest_type = c_int_type
3691 elif type1.rank < type2.rank:
3693 elif type1.rank > type2.rank:
3695 elif type1.signed < type2.signed:
3701 def independent_spanning_type(type1, type2):
3702 # Return a type assignable independently from both type1 and
3703 # type2, but do not require any interoperability between the two.
3704 # For example, in "True * 2", it is safe to assume an integer
3705 # result type (so spanning_type() will do the right thing),
3706 # whereas "x = True or 2" must evaluate to a type that can hold
3707 # both a boolean value and an integer, so this function works
3711 elif (type1 is c_bint_type or type2 is c_bint_type) and (type1.is_numeric and type2.is_numeric):
3712 # special case: if one of the results is a bint and the other
3713 # is another C integer, we must prevent returning a numeric
3714 # type so that we do not lose the ability to coerce to a
3715 # Python bool if we have to.
3716 return py_object_type
3717 span_type = _spanning_type(type1, type2)
3718 if span_type is None:
3722 def spanning_type(type1, type2):
3723 # Return a type assignable from both type1 and type2, or
3724 # py_object_type if no better type is found. Assumes that the
3725 # code that calls this will try a coercion afterwards, which will
3726 # fail if the types cannot actually coerce to a py_object_type.
3729 elif type1 is py_object_type or type2 is py_object_type:
3730 return py_object_type
3731 elif type1 is c_py_unicode_type or type2 is c_py_unicode_type:
3732 # Py_UNICODE behaves more like a string than an int
3733 return py_object_type
3734 span_type = _spanning_type(type1, type2)
3735 if span_type is None:
3736 return py_object_type
3739 def _spanning_type(type1, type2):
3740 if type1.is_numeric and type2.is_numeric:
3741 return widest_numeric_type(type1, type2)
3742 elif type1.is_builtin_type and type1.name == 'float' and type2.is_numeric:
3743 return widest_numeric_type(c_double_type, type2)
3744 elif type2.is_builtin_type and type2.name == 'float' and type1.is_numeric:
3745 return widest_numeric_type(type1, c_double_type)
3746 elif type1.is_extension_type and type2.is_extension_type:
3747 return widest_extension_type(type1, type2)
3748 elif type1.is_pyobject or type2.is_pyobject:
3749 return py_object_type
3750 elif type1.assignable_from(type2):
3751 if type1.is_extension_type and type1.typeobj_is_imported():
3752 # external types are unsafe, so we use PyObject instead
3753 return py_object_type
3755 elif type2.assignable_from(type1):
3756 if type2.is_extension_type and type2.typeobj_is_imported():
3757 # external types are unsafe, so we use PyObject instead
3758 return py_object_type
3763 def widest_extension_type(type1, type2):
3764 if type1.typeobj_is_imported() or type2.typeobj_is_imported():
3765 return py_object_type
3767 if type1.subtype_of(type2):
3769 elif type2.subtype_of(type1):
3771 type1, type2 = type1.base_type, type2.base_type
3772 if type1 is None or type2 is None:
3773 return py_object_type
3775 def simple_c_type(signed, longness, name):
3776 # Find type descriptor for simple type given name and modifiers.
3777 # Returns None if arguments don't make sense.
3778 return modifiers_and_name_to_type.get((signed, longness, name))
3780 def parse_basic_type(name):
3782 if name.startswith('p_'):
3783 base = parse_basic_type(name[2:])
3784 elif name.startswith('p'):
3785 base = parse_basic_type(name[1:])
3786 elif name.endswith('*'):
3787 base = parse_basic_type(name[:-1])
3789 return CPtrType(base)
3791 basic_type = simple_c_type(1, 0, name)
3797 if name == 'Py_UNICODE':
3799 elif name == 'Py_UCS4':
3801 elif name == 'Py_hash_t':
3803 elif name == 'Py_ssize_t':
3805 elif name == 'ssize_t':
3807 elif name == 'size_t':
3810 if name.startswith('u'):
3813 elif (name.startswith('s') and
3814 not name.startswith('short')):
3818 while name.startswith('short'):
3819 name = name.replace('short', '', 1).strip()
3821 while name.startswith('long'):
3822 name = name.replace('long', '', 1).strip()
3824 if longness != 0 and not name:
3826 return simple_c_type(signed, longness, name)
3828 def c_array_type(base_type, size):
3829 # Construct a C array type.
3830 if base_type is error_type:
3833 return CArrayType(base_type, size)
3835 def c_ptr_type(base_type):
3836 # Construct a C pointer type.
3837 if base_type is error_type:
3840 return CPtrType(base_type)
3842 def c_ref_type(base_type):
3843 # Construct a C reference type
3844 if base_type is error_type:
3847 return CReferenceType(base_type)
3849 def c_const_type(base_type):
3850 # Construct a C const type.
3851 if base_type is error_type:
3854 return CConstType(base_type)
3856 def same_type(type1, type2):
3857 return type1.same_as(type2)
3859 def assignable_from(type1, type2):
3860 return type1.assignable_from(type2)
3862 def typecast(to_type, from_type, expr_code):
3863 # Return expr_code cast to a C type which can be
3864 # assigned to to_type, assuming its existing C type
3866 if (to_type is from_type or
3867 (not to_type.is_pyobject and assignable_from(to_type, from_type))):
3869 elif (to_type is py_object_type and from_type and
3870 from_type.is_builtin_type and from_type.name != 'type'):
3871 # no cast needed, builtins are PyObject* already
3874 #print "typecast: to", to_type, "from", from_type ###
3875 return to_type.cast_code(expr_code)