PyrexTypes.py 65.9 KB
Newer Older
William Stein's avatar
William Stein committed
1 2 3 4
#
#   Pyrex - Types
#

Stefan Behnel's avatar
Stefan Behnel committed
5
from Cython.Utils import UtilityCode
6
import StringEncoding
William Stein's avatar
William Stein committed
7
import Naming
Dag Sverre Seljebotn's avatar
Dag Sverre Seljebotn committed
8
import copy
William Stein's avatar
William Stein committed
9

10
class BaseType(object):
11 12 13 14 15 16
    #
    #  Base class for all Pyrex types including pseudo-types.

    def cast_code(self, expr_code):
        return "((%s)%s)" % (self.declaration_code(""), expr_code)
    
17 18 19
    def specalization_name(self):
        return self.declaration_code("").replace(" ", "__")
    
20 21 22 23 24 25 26
    def base_declaration_code(self, base_code, entity_code):
        if entity_code:
            return "%s %s" % (base_code, entity_code)
        else:
            return base_code

class PyrexType(BaseType):
William Stein's avatar
William Stein committed
27 28 29 30 31 32 33 34
    #
    #  Base class for all Pyrex types.
    #
    #  is_pyobject           boolean     Is a Python object type
    #  is_extension_type     boolean     Is a Python extension type
    #  is_numeric            boolean     Is a C numeric type
    #  is_int                boolean     Is a C integer type
    #  is_float              boolean     Is a C floating point type
35
    #  is_complex            boolean     Is a C complex type
William Stein's avatar
William Stein committed
36 37 38 39 40 41
    #  is_void               boolean     Is the C void type
    #  is_array              boolean     Is a C array type
    #  is_ptr                boolean     Is a C pointer type
    #  is_null_ptr           boolean     Is the type of NULL
    #  is_cfunction          boolean     Is a C function type
    #  is_struct_or_union    boolean     Is a C struct or union type
Robert Bradshaw's avatar
Robert Bradshaw committed
42
    #  is_struct             boolean     Is a C struct type
William Stein's avatar
William Stein committed
43
    #  is_enum               boolean     Is a C enum type
44
    #  is_typedef            boolean     Is a typedef type
William Stein's avatar
William Stein committed
45
    #  is_string             boolean     Is a C char * type
46
    #  is_unicode            boolean     Is a UTF-8 encoded C char * type
William Stein's avatar
William Stein committed
47 48
    #  is_returncode         boolean     Is used only to signal exceptions
    #  is_error              boolean     Is the dummy error type
49
    #  is_buffer             boolean     Is buffer access type
William Stein's avatar
William Stein committed
50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80
    #  has_attributes        boolean     Has C dot-selectable attributes
    #  default_value         string      Initial value
    #  pymemberdef_typecode  string      Type code for PyMemberDef struct
    #
    #  declaration_code(entity_code, 
    #      for_display = 0, dll_linkage = None, pyrex = 0)
    #    Returns a code fragment for the declaration of an entity
    #    of this type, given a code fragment for the entity.
    #    * If for_display, this is for reading by a human in an error
    #      message; otherwise it must be valid C code.
    #    * If dll_linkage is not None, it must be 'DL_EXPORT' or
    #      'DL_IMPORT', and will be added to the base type part of
    #      the declaration.
    #    * If pyrex = 1, this is for use in a 'cdef extern'
    #      statement of a Pyrex include file.
    #
    #  assignable_from(src_type)
    #    Tests whether a variable of this type can be
    #    assigned a value of type src_type.
    #
    #  same_as(other_type)
    #    Tests whether this type represents the same type
    #    as other_type.
    #
    #  as_argument_type():
    #    Coerces array type into pointer type for use as
    #    a formal argument type.
    #
        
    is_pyobject = 0
    is_extension_type = 0
Robert Bradshaw's avatar
Robert Bradshaw committed
81
    is_builtin_type = 0
William Stein's avatar
William Stein committed
82 83 84
    is_numeric = 0
    is_int = 0
    is_float = 0
85
    is_complex = 0
William Stein's avatar
William Stein committed
86 87 88 89 90 91
    is_void = 0
    is_array = 0
    is_ptr = 0
    is_null_ptr = 0
    is_cfunction = 0
    is_struct_or_union = 0
Robert Bradshaw's avatar
Robert Bradshaw committed
92
    is_struct = 0
William Stein's avatar
William Stein committed
93
    is_enum = 0
94
    is_typedef = 0
William Stein's avatar
William Stein committed
95
    is_string = 0
96
    is_unicode = 0
William Stein's avatar
William Stein committed
97 98
    is_returncode = 0
    is_error = 0
99
    is_buffer = 0
William Stein's avatar
William Stein committed
100 101 102 103 104 105 106 107 108 109 110 111 112 113
    has_attributes = 0
    default_value = ""
    pymemberdef_typecode = None
    
    def resolve(self):
        # If a typedef, returns the base type.
        return self
    
    def literal_code(self, value):
        # Returns a C code fragment representing a literal
        # value of this type.
        return str(value)
    
    def __str__(self):
114
        return self.declaration_code("", for_display = 1).strip()
William Stein's avatar
William Stein committed
115 116 117 118 119
    
    def same_as(self, other_type, **kwds):
        return self.same_as_resolved_type(other_type.resolve(), **kwds)
    
    def same_as_resolved_type(self, other_type):
120
        return self == other_type or other_type is error_type
William Stein's avatar
William Stein committed
121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141
    
    def subtype_of(self, other_type):
        return self.subtype_of_resolved_type(other_type.resolve())
    
    def subtype_of_resolved_type(self, other_type):
        return self.same_as(other_type)
    
    def assignable_from(self, src_type):
        return self.assignable_from_resolved_type(src_type.resolve())
    
    def assignable_from_resolved_type(self, src_type):
        return self.same_as(src_type)
    
    def as_argument_type(self):
        return self
    
    def is_complete(self):
        # A type is incomplete if it is an unsized array,
        # a struct whose attributes are not defined, etc.
        return 1

142
    def is_simple_buffer_dtype(self):
143
        return (self.is_int or self.is_float or self.is_complex or self.is_pyobject or
144 145
                self.is_extension_type or self.is_ptr)

146 147 148 149 150 151
    def struct_nesting_depth(self):
        # Returns the number levels of nested structs. This is
        # used for constructing a stack for walking the run-time
        # type information of the struct.
        return 1

152
class CTypedefType(BaseType):
William Stein's avatar
William Stein committed
153
    #
154
    #  Pseudo-type defined with a ctypedef statement in a
William Stein's avatar
William Stein committed
155
    #  'cdef extern from' block. Delegates most attribute
156 157
    #  lookups to the base type. ANYTHING NOT DEFINED
    #  HERE IS DELEGATED!
William Stein's avatar
William Stein committed
158
    #
159 160 161
    #  qualified_name      string
    #  typedef_cname       string
    #  typedef_base_type   PyrexType
162
    #  typedef_is_external bool
163 164
    
    is_typedef = 1
165
    typedef_is_external = 0
166 167 168 169

    to_py_utility_code = None
    from_py_utility_code = None
    
William Stein's avatar
William Stein committed
170
    
171
    def __init__(self, cname, base_type, is_external=0):
William Stein's avatar
William Stein committed
172 173
        self.typedef_cname = cname
        self.typedef_base_type = base_type
174
        self.typedef_is_external = is_external
Dag Sverre Seljebotn's avatar
Dag Sverre Seljebotn committed
175 176 177 178 179 180 181 182 183 184 185 186
        # Make typecodes in external typedefs use typesize-neutral macros
        if is_external:
            typecode = None
            if base_type.is_int:
                if base_type.signed == 0:
                    typecode = "__Pyx_T_UNSIGNED_INT"
                else:
                    typecode = "__Pyx_T_SIGNED_INT"
            elif base_type.is_float and not rank_to_type_name[base_type.rank] == "long double":
                typecode = "__Pyx_T_FLOATING"
            if typecode:
                self.pymemberdef_typecode = "%s(%s)" % (typecode, cname)
William Stein's avatar
William Stein committed
187 188 189 190 191 192
    
    def resolve(self):
        return self.typedef_base_type.resolve()
    
    def declaration_code(self, entity_code, 
            for_display = 0, dll_linkage = None, pyrex = 0):
193 194 195 196 197 198 199 200 201 202 203 204
        name = self.declaration_name(for_display, pyrex)
        return self.base_declaration_code(name, entity_code)
    
    def declaration_name(self, for_display = 0, pyrex = 0):
        if pyrex or for_display:
            return self.qualified_name
        else:
            return self.typedef_cname
    
    def as_argument_type(self):
        return self

205 206 207 208 209 210 211
    def cast_code(self, expr_code):
        # If self is really an array (rather than pointer), we can't cast.
        # For example, the gmp mpz_t. 
        if self.typedef_base_type.is_ptr:
            return self.typedef_base_type.cast_code(expr_code)
        else:
            return BaseType.cast_code(self, expr_code)
212

213 214
    def __repr__(self):
        return "<CTypedefType %s>" % self.typedef_cname
William Stein's avatar
William Stein committed
215 216
    
    def __str__(self):
217
        return self.declaration_name(for_display = 1)
218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275

    def _create_utility_code(self, template_utility_code,
                             template_function_name):
        type_name = self.typedef_cname.replace(" ","_")
        utility_code = template_utility_code.specialize(
            type     = self.typedef_cname,
            TypeName = type_name)
        function_name = template_function_name % type_name
        return utility_code, function_name

    def create_to_py_utility_code(self, env):
        if self.typedef_is_external:
            if not self.to_py_utility_code:
                base_type = self.typedef_base_type
                if base_type.is_int:
                    self.to_py_utility_code, self.to_py_function = \
                        self._create_utility_code(c_typedef_int_to_py_function,
                                                  '__Pyx_PyInt_to_py_%s')
                elif base_type.is_float:
                    pass # XXX implement!
                elif base_type.is_complex:
                    pass # XXX implement!
                    pass
            if self.to_py_utility_code:
                env.use_utility_code(self.to_py_utility_code)
                return True
        # delegation
        return self.typedef_base_type.create_to_py_utility_code(env)

    def create_from_py_utility_code(self, env):
        if self.typedef_is_external:
            if not self.from_py_utility_code:
                base_type = self.typedef_base_type
                if base_type.is_int:
                    self.from_py_utility_code, self.from_py_function = \
                        self._create_utility_code(c_typedef_int_from_py_function,
                                                  '__Pyx_PyInt_from_py_%s')
                elif base_type.is_float:
                    pass # XXX implement!
                elif base_type.is_complex:
                    pass # XXX implement!
            if self.from_py_utility_code:
                env.use_utility_code(self.from_py_utility_code)
                return True
        # delegation
        return self.typedef_base_type.create_from_py_utility_code(env)

    def error_condition(self, result_code):
        if self.typedef_is_external:
            if self.exception_value:
                condition = "(%s == (%s)%s)" % (
                    result_code, self.typedef_cname, self.exception_value)
                if self.exception_check:
                    condition += " && PyErr_Occurred()"
                return condition
        # delegation
        return self.typedef_base_type.error_condition(result_code)

William Stein's avatar
William Stein committed
276 277 278
    def __getattr__(self, name):
        return getattr(self.typedef_base_type, name)

279 280 281 282 283 284
class BufferType(BaseType):
    #
    #  Delegates most attribute
    #  lookups to the base type. ANYTHING NOT DEFINED
    #  HERE IS DELEGATED!
    
285 286 287 288 289 290 291
    # dtype            PyrexType
    # ndim             int
    # mode             str
    # negative_indices bool
    # cast             bool
    # is_buffer        bool
    # writable         bool
292 293

    is_buffer = 1
294
    writable = True
295
    def __init__(self, base, dtype, ndim, mode, negative_indices, cast):
296 297 298
        self.base = base
        self.dtype = dtype
        self.ndim = ndim
299
        self.buffer_ptr_type = CPtrType(dtype)
300
        self.mode = mode
301
        self.negative_indices = negative_indices
302
        self.cast = cast
303
    
304 305 306
    def as_argument_type(self):
        return self

307 308 309
    def __getattr__(self, name):
        return getattr(self.base, name)

310 311 312
    def __repr__(self):
        return "<BufferType %r>" % self.base

313 314 315 316 317
def public_decl(base, dll_linkage):
    if dll_linkage:
        return "%s(%s)" % (dll_linkage, base)
    else:
        return base
318
    
William Stein's avatar
William Stein committed
319 320 321 322
class PyObjectType(PyrexType):
    #
    #  Base class for all Python object types (reference-counted).
    #
323
    #  buffer_defaults  dict or None     Default options for bu
William Stein's avatar
William Stein committed
324 325 326 327
    
    is_pyobject = 1
    default_value = "0"
    pymemberdef_typecode = "T_OBJECT"
328
    buffer_defaults = None
William Stein's avatar
William Stein committed
329 330 331 332 333
    
    def __str__(self):
        return "Python object"
    
    def __repr__(self):
334
        return "<PyObjectType>"
William Stein's avatar
William Stein committed
335 336 337 338 339 340
    
    def assignable_from(self, src_type):
        return 1 # Conversion will be attempted
        
    def declaration_code(self, entity_code, 
            for_display = 0, dll_linkage = None, pyrex = 0):
341 342
        if pyrex or for_display:
            return self.base_declaration_code("object", entity_code)
William Stein's avatar
William Stein committed
343 344 345
        else:
            return "%s *%s" % (public_decl("PyObject", dll_linkage), entity_code)

346 347 348 349 350
    def as_pyobject(self, cname):
        if (not self.is_complete()) or self.is_extension_type:
            return "(PyObject *)" + cname
        else:
            return cname
William Stein's avatar
William Stein committed
351

Robert Bradshaw's avatar
Robert Bradshaw committed
352 353 354 355 356 357 358
class BuiltinObjectType(PyObjectType):

    is_builtin_type = 1
    has_attributes = 1
    base_type = None
    module_name = '__builtin__'

359 360
    alternative_name = None # used for str/bytes duality

Robert Bradshaw's avatar
Robert Bradshaw committed
361 362
    def __init__(self, name, cname):
        self.name = name
363 364 365 366
        if name == 'str':
            self.alternative_name = 'bytes'
        elif name == 'bytes':
            self.alternative_name = 'str'
Robert Bradshaw's avatar
Robert Bradshaw committed
367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382
        self.cname = cname
        self.typeptr_cname = "&" + cname
                                 
    def set_scope(self, scope):
        self.scope = scope
        if scope:
            scope.parent_type = self
        
    def __str__(self):
        return "%s object" % self.name
    
    def __repr__(self):
        return "<%s>"% self.cname
        
    def assignable_from(self, src_type):
        if isinstance(src_type, BuiltinObjectType):
383 384 385
            return src_type.name == self.name or (
                src_type.name == self.alternative_name and
                src_type.name is not None)
Robert Bradshaw's avatar
Robert Bradshaw committed
386 387 388 389 390 391 392 393 394 395 396 397 398
        else:
            return not src_type.is_extension_type
            
    def typeobj_is_available(self):
        return True
        
    def attributes_known(self):
        return True
        
    def subtype_of(self, type):
        return type.is_pyobject and self.assignable_from(type)
        
    def type_test_code(self, arg):
399 400
        type_name = self.name
        if type_name == 'str':
401
            check = 'PyString_CheckExact'
402
        elif type_name == 'set':
403
            check = 'PyAnySet_CheckExact'
404
        elif type_name == 'frozenset':
405 406 407
            check = 'PyFrozenSet_CheckExact'
        elif type_name == 'bool':
            check = 'PyBool_Check'
408
        else:
409 410
            check = 'Py%s_CheckExact' % type_name.capitalize()
        return 'likely(%s(%s)) || (%s) == Py_None || (PyErr_Format(PyExc_TypeError, "Expected %s, got %%s", Py_TYPE(%s)->tp_name), 0)' % (check, arg, arg, self.name, arg)
Robert Bradshaw's avatar
Robert Bradshaw committed
411

412 413 414 415 416 417 418
    def declaration_code(self, entity_code, 
            for_display = 0, dll_linkage = None, pyrex = 0):
        if pyrex or for_display:
            return self.base_declaration_code(self.name, entity_code)
        else:
            return "%s *%s" % (public_decl("PyObject", dll_linkage), entity_code)

Robert Bradshaw's avatar
Robert Bradshaw committed
419

William Stein's avatar
William Stein committed
420 421 422 423 424 425 426 427 428 429 430
class PyExtensionType(PyObjectType):
    #
    #  A Python extension type.
    #
    #  name             string
    #  scope            CClassScope      Attribute namespace
    #  visibility       string
    #  typedef_flag     boolean
    #  base_type        PyExtensionType or None
    #  module_name      string or None   Qualified name of defining module
    #  objstruct_cname  string           Name of PyObject struct
431
    #  objtypedef_cname string           Name of PyObject struct typedef
William Stein's avatar
William Stein committed
432 433 434 435 436 437 438 439 440 441
    #  typeobj_cname    string or None   C code fragment referring to type object
    #  typeptr_cname    string or None   Name of pointer to external type object
    #  vtabslot_cname   string           Name of C method table member
    #  vtabstruct_cname string           Name of C method table struct
    #  vtabptr_cname    string           Name of pointer to C method table
    #  vtable_cname     string           Name of C method table definition
    
    is_extension_type = 1
    has_attributes = 1
    
442 443
    objtypedef_cname = None
    
William Stein's avatar
William Stein committed
444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479
    def __init__(self, name, typedef_flag, base_type):
        self.name = name
        self.scope = None
        self.typedef_flag = typedef_flag
        self.base_type = base_type
        self.module_name = None
        self.objstruct_cname = None
        self.typeobj_cname = None
        self.typeptr_cname = None
        self.vtabslot_cname = None
        self.vtabstruct_cname = None
        self.vtabptr_cname = None
        self.vtable_cname = None
    
    def set_scope(self, scope):
        self.scope = scope
        if scope:
            scope.parent_type = self
    
    def subtype_of_resolved_type(self, other_type):
        if other_type.is_extension_type:
            return self is other_type or (
                self.base_type and self.base_type.subtype_of(other_type))
        else:
            return other_type is py_object_type
    
    def typeobj_is_available(self):
        # Do we have a pointer to the type object?
        return self.typeptr_cname
    
    def typeobj_is_imported(self):
        # If we don't know the C name of the type object but we do
        # know which module it's defined in, it will be imported.
        return self.typeobj_cname is None and self.module_name is not None
    
    def declaration_code(self, entity_code, 
480
            for_display = 0, dll_linkage = None, pyrex = 0, deref = 0):
481 482
        if pyrex or for_display:
            return self.base_declaration_code(self.name, entity_code)
William Stein's avatar
William Stein committed
483 484 485 486 487 488
        else:
            if self.typedef_flag:
                base_format = "%s"
            else:
                base_format = "struct %s"
            base = public_decl(base_format % self.objstruct_cname, dll_linkage)
489 490 491 492
            if deref:
                return "%s %s" % (base,  entity_code)
            else:
                return "%s *%s" % (base,  entity_code)
William Stein's avatar
William Stein committed
493

Robert Bradshaw's avatar
Robert Bradshaw committed
494 495 496
    def type_test_code(self, py_arg):
        return "__Pyx_TypeTest(%s, %s)" % (py_arg, self.typeptr_cname)
    
William Stein's avatar
William Stein committed
497 498 499 500 501 502 503
    def attributes_known(self):
        return self.scope is not None
    
    def __str__(self):
        return self.name
    
    def __repr__(self):
504 505
        return "<PyExtensionType %s%s>" % (self.scope.class_name,
            ("", " typedef")[self.typedef_flag])
William Stein's avatar
William Stein committed
506 507 508 509 510 511 512 513 514 515 516 517
    

class CType(PyrexType):
    #
    #  Base class for all C types (non-reference-counted).
    #
    #  to_py_function     string     C function for converting to Python object
    #  from_py_function   string     C function for constructing from Python object
    #
    
    to_py_function = None
    from_py_function = None
518 519
    exception_value = None
    exception_check = 1
Robert Bradshaw's avatar
Robert Bradshaw committed
520

521
    def create_to_py_utility_code(self, env):
522
        return self.to_py_function is not None
523 524
        
    def create_from_py_utility_code(self, env):
525
        return self.from_py_function is not None
Robert Bradshaw's avatar
Robert Bradshaw committed
526
        
527 528 529 530 531 532 533 534 535 536 537 538
    def error_condition(self, result_code):
        conds = []
        if self.is_string:
            conds.append("(!%s)" % result_code)
        elif self.exception_value is not None:
            conds.append("(%s == (%s)%s)" % (result_code, self.sign_and_name(), self.exception_value))
        if self.exception_check:
            conds.append("PyErr_Occurred()")
        if len(conds) > 0:
            return " && ".join(conds)
        else:
            return 0
William Stein's avatar
William Stein committed
539 540


541
class CVoidType(CType):
William Stein's avatar
William Stein committed
542 543 544 545 546 547 548 549
    is_void = 1
    
    def __repr__(self):
        return "<CVoidType>"
    
    def declaration_code(self, entity_code, 
            for_display = 0, dll_linkage = None, pyrex = 0):
        base = public_decl("void", dll_linkage)
550
        return self.base_declaration_code(base, entity_code)
William Stein's avatar
William Stein committed
551 552 553 554 555 556 557 558 559 560
    
    def is_complete(self):
        return 0


class CNumericType(CType):
    #
    #   Base class for all C numeric types.
    #
    #   rank      integer     Relative size
561
    #   signed    integer     0 = unsigned, 1 = unspecified, 2 = explicitly signed
William Stein's avatar
William Stein committed
562 563 564 565 566
    #
    
    is_numeric = 1
    default_value = "0"
    
567 568
    sign_words = ("unsigned ", "", "signed ")
    
569
    def __init__(self, rank, signed = 1, pymemberdef_typecode = None):
William Stein's avatar
William Stein committed
570 571 572 573
        self.rank = rank
        self.signed = signed
        self.pymemberdef_typecode = pymemberdef_typecode
    
574 575 576 577 578
    def sign_and_name(self):
        s = self.sign_words[self.signed]
        n = rank_to_type_name[self.rank]
        return s + n
    
William Stein's avatar
William Stein committed
579
    def __repr__(self):
580
        return "<CNumericType %s>" % self.sign_and_name()
William Stein's avatar
William Stein committed
581 582 583
    
    def declaration_code(self, entity_code, 
            for_display = 0, dll_linkage = None, pyrex = 0):
584
        base = public_decl(self.sign_and_name(), dll_linkage)
585
        if for_display:
586
            base = base.replace('PY_LONG_LONG', 'long long')
587
        return self.base_declaration_code(base,  entity_code)
588 589 590


type_conversion_predeclarations = ""
591 592 593 594 595 596 597 598 599 600 601 602
type_conversion_functions = ""

c_int_from_py_function = UtilityCode(
proto="""
static INLINE %(type)s __Pyx_PyInt_As%(SignWord)s%(TypeName)s(PyObject *);
""",
impl="""
static INLINE %(type)s __Pyx_PyInt_As%(SignWord)s%(TypeName)s(PyObject* x) {
    if (sizeof(%(type)s) < sizeof(long)) {
        long val = __Pyx_PyInt_AsLong(x);
        if (unlikely(val != (long)(%(type)s)val)) {
            if (unlikely(val == -1 && PyErr_Occurred()))
603 604 605 606 607 608
                return (%(type)s)-1;
            if (((%(type)s)-1) > ((%(type)s)0) && unlikely(val < 0)) {
                PyErr_SetString(PyExc_OverflowError,
                                "can't convert negative value to %(type)s");
                return (%(type)s)-1;
            }
609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625
            PyErr_SetString(PyExc_OverflowError,
                           "value too large to convert to %(type)s");
            return (%(type)s)-1;
        }
        return (%(type)s)val;
    }
    return (%(type)s)__Pyx_PyInt_As%(SignWord)sLong(x);
}
""")

c_long_from_py_function = UtilityCode(
proto="""
static INLINE %(type)s __Pyx_PyInt_As%(SignWord)s%(TypeName)s(PyObject *);
""",
impl="""
static INLINE %(type)s __Pyx_PyInt_As%(SignWord)s%(TypeName)s(PyObject* x) {
#if PY_VERSION_HEX < 0x03000000
626 627 628 629 630 631 632
    if (likely(PyInt_Check(x))) {
        long val = PyInt_AS_LONG(x);
        if (((%(type)s)-1) > ((%(type)s)0) && unlikely(val < 0)) {
            PyErr_SetString(PyExc_OverflowError,
                            "can't convert negative value to %(type)s");
            return (%(type)s)-1;
        }
633 634 635
        return (%(type)s)val;
    } else
#endif
636 637 638 639 640 641 642 643 644
    if (likely(PyLong_Check(x))) {
        if (((%(type)s)-1) > ((%(type)s)0) && unlikely(Py_SIZE(x) < 0)) {
            PyErr_SetString(PyExc_OverflowError,
                            "can't convert negative value to %(type)s");
            return (%(type)s)-1;
        }
        return (((%(type)s)-1) < ((%(type)s)0)) ?
               PyLong_As%(TypeName)s(x) :
               PyLong_AsUnsigned%(TypeName)s(x);
645 646 647 648 649 650 651 652 653 654 655
    } else {
        %(type)s val;
        PyObject *tmp = __Pyx_PyNumber_Int(x);
        if (!tmp) return (%(type)s)-1;
        val = __Pyx_PyInt_As%(SignWord)s%(TypeName)s(tmp);
        Py_DECREF(tmp);
        return val;
    }
}
""")

656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692
c_typedef_int_from_py_function = UtilityCode(
proto="""
static INLINE %(type)s __Pyx_PyInt_from_py_%(TypeName)s(PyObject *);
""",
impl="""
static INLINE %(type)s __Pyx_PyInt_from_py_%(TypeName)s(PyObject* x) {
  /**/ if (sizeof(%(type)s) == sizeof(char))
     return (((%(type)s)-1) < ((%(type)s)0)) ?
            (%(type)s)__Pyx_PyInt_AsSignedChar(x) :
            (%(type)s)__Pyx_PyInt_AsUnsignedChar(x);
  else if (sizeof(%(type)s) == sizeof(short))
     return (((%(type)s)-1) < ((%(type)s)0)) ?
            (%(type)s)__Pyx_PyInt_AsSignedShort(x) :
            (%(type)s)__Pyx_PyInt_AsUnsignedShort(x);
  else if (sizeof(%(type)s) == sizeof(int))
     return (((%(type)s)-1) < ((%(type)s)0)) ?
            (%(type)s)__Pyx_PyInt_AsSignedInt(x) :
            (%(type)s)__Pyx_PyInt_AsUnsignedInt(x);
  else if (sizeof(%(type)s) == sizeof(long))
     return (((%(type)s)-1) < ((%(type)s)0)) ?
            (%(type)s)__Pyx_PyInt_AsSignedLong(x) :
            (%(type)s)__Pyx_PyInt_AsUnsignedLong(x);
  else if (sizeof(%(type)s) == sizeof(PY_LONG_LONG))
     return (((%(type)s)-1) < ((%(type)s)0)) ?
            (%(type)s)__Pyx_PyInt_AsSignedLongLong(x) :
            (%(type)s)__Pyx_PyInt_AsUnsignedLongLong(x);
#if 0
  else if (sizeof(%(type)s) > sizeof(short) &&
           sizeof(%(type)s) < sizeof(int)) /*  __int32 ILP64 ? */
     return (((%(type)s)-1) < ((%(type)s)0)) ?
            (%(type)s)__Pyx_PyInt_AsSignedInt(x) :
            (%(type)s)__Pyx_PyInt_AsUnsignedInt(x);
#endif
  PyErr_SetString(PyExc_TypeError, "%(TypeName)s");
  return (%(type)s)-1;
}
""")
693

694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711
c_typedef_int_to_py_function = UtilityCode(
proto="""
static INLINE PyObject *__Pyx_PyInt_to_py_%(TypeName)s(%(type)s);
""",
impl="""
static INLINE PyObject *__Pyx_PyInt_to_py_%(TypeName)s(%(type)s val) {
  /**/ if (sizeof(%(type)s) <  sizeof(long))
      return PyInt_FromLong((long)val);
  else if (sizeof(%(type)s) == sizeof(long))
     return (((%(type)s)-1) < ((%(type)s)0)) ? 
            PyInt_FromLong((long)val) :
            PyLong_FromUnsignedLong((unsigned long)val);
  else /* (sizeof(%(type)s) >  sizeof(long)) */
     return (((%(type)s)-1) < ((%(type)s)0)) ?
            PyLong_FromLongLong((PY_LONG_LONG)val) :
            PyLong_FromUnsignedLongLong((unsigned PY_LONG_LONG)val);
}
""")
William Stein's avatar
William Stein committed
712 713

class CIntType(CNumericType):
714

William Stein's avatar
William Stein committed
715 716 717
    is_int = 1
    typedef_flag = 0
    to_py_function = "PyInt_FromLong"
718
    from_py_function = "__Pyx_PyInt_AsInt"
719
    exception_value = -1
William Stein's avatar
William Stein committed
720

721 722
    def __init__(self, rank, signed, pymemberdef_typecode = None, is_returncode = 0):
        CNumericType.__init__(self, rank, signed, pymemberdef_typecode)
William Stein's avatar
William Stein committed
723
        self.is_returncode = is_returncode
724
        if self.from_py_function == "__Pyx_PyInt_AsInt":
725 726 727
            self.from_py_function = self.get_type_conversion()

    def get_type_conversion(self):
728 729 730 731 732 733 734 735 736 737 738 739 740 741 742
        ctype = self.declaration_code('')
        bits = ctype.split(" ", 1)
        if len(bits) == 1:
            sign_word, type_name = "", bits[0]
        else:
            sign_word, type_name = bits
        type_name = type_name.replace("PY_LONG_LONG","long long")
        SignWord  = sign_word.title()
        TypeName  = type_name.title().replace(" ", "")
        if "Long" in TypeName:
            utility_code = c_long_from_py_function
        else:
            utility_code = c_int_from_py_function
        utility_code.specialize(self,
                                SignWord=SignWord,
743
                                TypeName=TypeName)
744
        func_name = "__Pyx_PyInt_As%s%s" % (SignWord, TypeName)
745
        return func_name
746

747 748
    def assignable_from_resolved_type(self, src_type):
        return src_type.is_int or src_type.is_enum or src_type is error_type
749

William Stein's avatar
William Stein committed
750

751
class CBIntType(CIntType):
Robert Bradshaw's avatar
Robert Bradshaw committed
752

753 754
    to_py_function = "__Pyx_PyBool_FromLong"
    from_py_function = "__Pyx_PyObject_IsTrue"
755
    exception_check = 0
William Stein's avatar
William Stein committed
756

757

758 759
class CAnonEnumType(CIntType):

760 761 762 763
    is_enum = 1

    def sign_and_name(self):
        return 'int'
764

765

William Stein's avatar
William Stein committed
766 767 768
class CUIntType(CIntType):

    to_py_function = "PyLong_FromUnsignedLong"
769
    exception_value = -1
William Stein's avatar
William Stein committed
770 771


772 773 774 775 776
class CLongType(CIntType):

    to_py_function = "PyInt_FromLong"


777
class CULongType(CUIntType):
William Stein's avatar
William Stein committed
778 779 780 781

    to_py_function = "PyLong_FromUnsignedLong"


782
class CLongLongType(CIntType):
William Stein's avatar
William Stein committed
783 784 785 786

    to_py_function = "PyLong_FromLongLong"


787
class CULongLongType(CUIntType):
William Stein's avatar
William Stein committed
788 789 790 791

    to_py_function = "PyLong_FromUnsignedLongLong"


792 793 794
class CPySSizeTType(CIntType):

    to_py_function = "PyInt_FromSsize_t"
795
    from_py_function = "__Pyx_PyIndex_AsSsize_t"
796

797 798 799
    def sign_and_name(self):
        return rank_to_type_name[self.rank]

800

801 802
class CSizeTType(CUIntType):

803 804
    to_py_function = "__Pyx_PyInt_FromSize_t"
    from_py_function = "__Pyx_PyInt_AsSize_t"
805

806 807 808
    def sign_and_name(self):
        return rank_to_type_name[self.rank]

809

William Stein's avatar
William Stein committed
810 811 812 813
class CFloatType(CNumericType):

    is_float = 1
    to_py_function = "PyFloat_FromDouble"
814
    from_py_function = "__pyx_PyFloat_AsDouble"
William Stein's avatar
William Stein committed
815
    
816
    def __init__(self, rank, pymemberdef_typecode = None, math_h_modifier = ''):
817
        CNumericType.__init__(self, rank, 1, pymemberdef_typecode)
818
        self.math_h_modifier = math_h_modifier
William Stein's avatar
William Stein committed
819
    
820
    def assignable_from_resolved_type(self, src_type):
821 822
        return (src_type.is_numeric and not src_type.is_complex) or src_type is error_type

823

824
class CComplexType(CNumericType):
825 826
    
    is_complex = 1
827
    to_py_function = "__pyx_PyObject_from_complex"
828 829
    has_attributes = 1
    scope = None
830 831 832 833
    
    def __init__(self, real_type):
        self.real_type = real_type
        CNumericType.__init__(self, real_type.rank + 0.5, real_type.signed)
834
        self.binops = {}
835
        self.from_parts = "%s_from_parts" % self.specalization_name()
836 837 838 839 840 841
    
    def __cmp__(self, other):
        if isinstance(self, CComplexType) and isinstance(other, CComplexType):
            return cmp(self.real_type, other.real_type)
        else:
            return 1
842
    
843 844 845
    def __hash__(self):
        return ~hash(self.real_type)
    
846
    def sign_and_name(self):
847
        return Naming.type_prefix + self.real_type.specalization_name() + "_complex"
848 849 850 851 852

    def assignable_from_resolved_type(self, src_type):
        return (src_type.is_complex and self.real_type.assignable_from_resolved_type(src_type.real_type)
                    or src_type.is_numeric and self.real_type.assignable_from_resolved_type(src_type) 
                    or src_type is error_type)
853 854 855 856 857 858 859 860
                    
    def attributes_known(self):
        if self.scope is None:
            import Symtab
            self.scope = Symtab.StructOrUnionScope(self.specalization_name())
            self.scope.declare_var("real", self.real_type, None, "real")
            self.scope.declare_var("imag", self.real_type, None, "imag")
        return True
861

862
    def create_declaration_utility_code(self, env):
863 864 865 866 867 868 869
        # This must always be run, because a single CComplexType instance can be shared
        # across multiple compilations (the one created in the module scope)
        env.use_utility_code(complex_generic_utility_code)
        env.use_utility_code(
            complex_arithmatic_utility_code.specialize(self, 
                math_h_modifier = self.real_type.math_h_modifier,
                real_type = self.real_type.declaration_code('')))
870 871 872 873
        return True

    def create_from_py_utility_code(self, env):
        self.real_type.create_from_py_utility_code(env)
874
        env.use_utility_code(
875 876 877 878 879
            complex_conversion_utility_code.specialize(self, 
                        math_h_modifier = self.real_type.math_h_modifier,
                        real_type = self.real_type.declaration_code(''),
                        type_convert = self.real_type.from_py_function))
        self.from_py_function = "__pyx_PyObject_As_" + self.specalization_name()
880
        return True
881
    
882
    def lookup_op(self, nargs, op):
883
        try:
884
            return self.binops[nargs, op]
885
        except KeyError:
886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908
            pass
        try:
            op_name = complex_ops[nargs, op]
            self.binops[nargs, op] = func_name = "%s_%s" % (self.specalization_name(), op_name)
            return func_name
        except KeyError:
            return None

    def unary_op(self, op):
        return self.lookup_op(1, op)
        
    def binary_op(self, op):
        return self.lookup_op(2, op)
        
complex_ops = {
    (1, '-'): 'neg',
    (1, 'zero'): 'is_zero',
    (2, '+'): 'add',
    (2, '-') : 'sub',
    (2, '*'): 'mul',
    (2, '/'): 'div',
    (2, '=='): 'eq',
}
909

910 911 912 913 914 915 916 917 918 919 920 921 922 923
complex_generic_utility_code = UtilityCode(
proto="""
#if __PYX_USE_C99_COMPLEX
    #define __Pyx_REAL_PART(z) __real__(z)
    #define __Pyx_IMAG_PART(z) __imag__(z)
#else
    #define __Pyx_REAL_PART(z) ((z).real)
    #define __Pyx_IMAG_PART(z) ((z).imag)
#endif

#define __pyx_PyObject_from_complex(z) PyComplex_FromDoubles((double)__Pyx_REAL_PART(z), (double)__Pyx_IMAG_PART(z))
""")

complex_conversion_utility_code = UtilityCode(
924 925 926 927 928
proto="""
static %(type)s __pyx_PyObject_As_%(type_name)s(PyObject* o); /* proto */
""", 
impl="""
static %(type)s __pyx_PyObject_As_%(type_name)s(PyObject* o) {
Robert Bradshaw's avatar
Robert Bradshaw committed
929
    if (PyComplex_CheckExact(o)) {
930
        return %(type_name)s_from_parts(
931 932 933 934
            (%(real_type)s)((PyComplexObject *)o)->cval.real,
            (%(real_type)s)((PyComplexObject *)o)->cval.imag);
    }
    else {
Robert Bradshaw's avatar
Robert Bradshaw committed
935 936
        Py_complex cval = PyComplex_AsCComplex(o);
        return %(type_name)s_from_parts((%(real_type)s)cval.real, (%(real_type)s)cval.imag);
937 938 939 940
    }
}
""")

941
complex_arithmatic_utility_code = UtilityCode(
942
proto="""
943 944 945
#if __PYX_USE_C99_COMPLEX

    typedef %(real_type)s _Complex %(type_name)s;
946 947 948 949
    static INLINE %(type)s %(type_name)s_from_parts(%(real_type)s x, %(real_type)s y) {
      return x + y*(%(type)s)_Complex_I;
    }
    
950
    #define %(type_name)s_is_zero(a) ((a) == 0)
951
    #define %(type_name)s_eq(a, b) ((a) == (b))
952 953 954 955 956 957 958 959 960
    #define %(type_name)s_add(a, b) ((a)+(b))
    #define %(type_name)s_sub(a, b) ((a)-(b))
    #define %(type_name)s_mul(a, b) ((a)*(b))
    #define %(type_name)s_div(a, b) ((a)/(b))
    #define %(type_name)s_neg(a) (-(a))

#else

    typedef struct { %(real_type)s real, imag; } %(type_name)s;
961 962 963 964
    static INLINE %(type)s %(type_name)s_from_parts(%(real_type)s x, %(real_type)s y) {
      %(type)s c; c.real = x; c.imag = y; return c;
    }
    
965 966 967 968
    static INLINE int %(type_name)s_is_zero(%(type)s a) {
       return (a.real == 0) & (a.imag == 0);
    }

969 970 971 972
    static INLINE int %(type_name)s_eq(%(type)s a, %(type)s b) {
       return (a.real == b.real) & (a.imag == b.imag);
    }

973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009
    static INLINE %(type)s %(type_name)s_add(%(type)s a, %(type)s b) {
        %(type)s z;
        z.real = a.real + b.real;
        z.imag = a.imag + b.imag;
        return z;
    }

    static INLINE %(type)s %(type_name)s_sub(%(type)s a, %(type)s b) {
        %(type)s z;
        z.real = a.real - b.real;
        z.imag = a.imag - b.imag;
        return z;
    }

    static INLINE %(type)s %(type_name)s_mul(%(type)s a, %(type)s b) {
        %(type)s z;
        z.real = a.real * b.real - a.imag * b.imag;
        z.imag = a.real * b.imag + a.imag * b.real;
        return z;
    }

    static INLINE %(type)s %(type_name)s_div(%(type)s a, %(type)s b) {
        %(type)s z;
        %(real_type)s denom = b.real*b.real + b.imag*b.imag;
        z.real = (a.real * b.real + a.imag * b.imag) / denom;
        z.imag = (a.imag * b.real - a.real * b.imag) / denom;
        return z;
    }

    static INLINE %(type)s %(type_name)s_neg(%(type)s a) {
        %(type)s z;
        z.real = -a.real;
        z.imag = -a.imag;
        return z;
    }

#endif
1010
""")
1011

William Stein's avatar
William Stein committed
1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025

class CArrayType(CType):
    #  base_type     CType              Element type
    #  size          integer or None    Number of elements
    
    is_array = 1
    
    def __init__(self, base_type, size):
        self.base_type = base_type
        self.size = size
        if base_type is c_char_type:
            self.is_string = 1
    
    def __repr__(self):
1026
        return "<CArrayType %s %s>" % (self.size, repr(self.base_type))
William Stein's avatar
William Stein committed
1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045
    
    def same_as_resolved_type(self, other_type):
        return ((other_type.is_array and
            self.base_type.same_as(other_type.base_type))
                or other_type is error_type)
    
    def assignable_from_resolved_type(self, src_type):
        # Can't assign to a variable of an array type
        return 0
    
    def element_ptr_type(self):
        return c_ptr_type(self.base_type)

    def declaration_code(self, entity_code, 
            for_display = 0, dll_linkage = None, pyrex = 0):
        if self.size is not None:
            dimension_code = self.size
        else:
            dimension_code = ""
1046 1047
        if entity_code.startswith("*"):
            entity_code = "(%s)" % entity_code
William Stein's avatar
William Stein committed
1048
        return self.base_type.declaration_code(
1049
            "%s[%s]" % (entity_code, dimension_code),
William Stein's avatar
William Stein committed
1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062
            for_display, dll_linkage, pyrex)
    
    def as_argument_type(self):
        return c_ptr_type(self.base_type)
    
    def is_complete(self):
        return self.size is not None


class CPtrType(CType):
    #  base_type     CType    Referenced type
    
    is_ptr = 1
1063
    default_value = "0"
William Stein's avatar
William Stein committed
1064 1065 1066 1067 1068
    
    def __init__(self, base_type):
        self.base_type = base_type
    
    def __repr__(self):
1069
        return "<CPtrType %s>" % repr(self.base_type)
William Stein's avatar
William Stein committed
1070 1071 1072 1073 1074 1075 1076 1077 1078 1079
    
    def same_as_resolved_type(self, other_type):
        return ((other_type.is_ptr and
            self.base_type.same_as(other_type.base_type))
                or other_type is error_type)
    
    def declaration_code(self, entity_code, 
            for_display = 0, dll_linkage = None, pyrex = 0):
        #print "CPtrType.declaration_code: pointer to", self.base_type ###
        return self.base_type.declaration_code(
1080
            "*%s" % entity_code,
William Stein's avatar
William Stein committed
1081 1082 1083 1084 1085
            for_display, dll_linkage, pyrex)
    
    def assignable_from_resolved_type(self, other_type):
        if other_type is error_type:
            return 1
1086
        if other_type.is_null_ptr:
William Stein's avatar
William Stein committed
1087
            return 1
1088 1089 1090 1091 1092 1093 1094 1095
        if self.base_type.is_cfunction:
            if other_type.is_ptr:
                other_type = other_type.base_type.resolve()
            if other_type.is_cfunction:
                return self.base_type.pointer_assignable_from_resolved_type(other_type)
            else:
                return 0
        if other_type.is_array or other_type.is_ptr:
1096
            return self.base_type.is_void or self.base_type.same_as(other_type.base_type)
1097
        return 0
William Stein's avatar
William Stein committed
1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109


class CNullPtrType(CPtrType):

    is_null_ptr = 1
    

class CFuncType(CType):
    #  return_type      CType
    #  args             [CFuncTypeArg]
    #  has_varargs      boolean
    #  exception_value  string
1110 1111 1112 1113
    #  exception_check  boolean    True if PyErr_Occurred check needed
    #  calling_convention  string  Function calling convention
    #  nogil            boolean    Can be called without gil
    #  with_gil         boolean    Acquire gil around function body
William Stein's avatar
William Stein committed
1114 1115
    
    is_cfunction = 1
1116
    original_sig = None
William Stein's avatar
William Stein committed
1117
    
1118 1119
    def __init__(self, return_type, args, has_varargs = 0,
            exception_value = None, exception_check = 0, calling_convention = "",
1120
            nogil = 0, with_gil = 0, is_overridable = 0, optional_arg_count = 0):
William Stein's avatar
William Stein committed
1121 1122 1123
        self.return_type = return_type
        self.args = args
        self.has_varargs = has_varargs
1124
        self.optional_arg_count = optional_arg_count
William Stein's avatar
William Stein committed
1125 1126
        self.exception_value = exception_value
        self.exception_check = exception_check
1127 1128
        self.calling_convention = calling_convention
        self.nogil = nogil
1129
        self.with_gil = with_gil
1130
        self.is_overridable = is_overridable
William Stein's avatar
William Stein committed
1131 1132 1133 1134 1135
    
    def __repr__(self):
        arg_reprs = map(repr, self.args)
        if self.has_varargs:
            arg_reprs.append("...")
1136
        return "<CFuncType %s %s[%s]>" % (
William Stein's avatar
William Stein committed
1137
            repr(self.return_type),
1138
            self.calling_convention_prefix(),
1139
            ",".join(arg_reprs))
William Stein's avatar
William Stein committed
1140
    
1141 1142 1143 1144 1145 1146 1147
    def calling_convention_prefix(self):
        cc = self.calling_convention
        if cc:
            return cc + " "
        else:
            return ""
    
William Stein's avatar
William Stein committed
1148 1149 1150 1151
    def same_c_signature_as(self, other_type, as_cmethod = 0):
        return self.same_c_signature_as_resolved_type(
            other_type.resolve(), as_cmethod)

1152
    def same_c_signature_as_resolved_type(self, other_type, as_cmethod = 0):
1153
        #print "CFuncType.same_c_signature_as_resolved_type:", \
Robert Bradshaw's avatar
Robert Bradshaw committed
1154
        #    self, other_type, "as_cmethod =", as_cmethod ###
William Stein's avatar
William Stein committed
1155 1156 1157 1158
        if other_type is error_type:
            return 1
        if not other_type.is_cfunction:
            return 0
1159
        if self.is_overridable != other_type.is_overridable:
1160
            return 0
William Stein's avatar
William Stein committed
1161
        nargs = len(self.args)
Stefan Behnel's avatar
Stefan Behnel committed
1162
        if nargs != len(other_type.args):
William Stein's avatar
William Stein committed
1163 1164 1165 1166 1167 1168 1169 1170
            return 0
        # When comparing C method signatures, the first argument
        # is exempt from compatibility checking (the proper check
        # is performed elsewhere).
        for i in range(as_cmethod, nargs):
            if not self.args[i].type.same_as(
                other_type.args[i].type):
                    return 0
Stefan Behnel's avatar
Stefan Behnel committed
1171
        if self.has_varargs != other_type.has_varargs:
William Stein's avatar
William Stein committed
1172
            return 0
Stefan Behnel's avatar
Stefan Behnel committed
1173
        if self.optional_arg_count != other_type.optional_arg_count:
1174
            return 0
William Stein's avatar
William Stein committed
1175 1176
        if not self.return_type.same_as(other_type.return_type):
            return 0
1177 1178
        if not self.same_calling_convention_as(other_type):
            return 0
William Stein's avatar
William Stein committed
1179
        return 1
1180

1181 1182 1183 1184 1185
    def compatible_signature_with(self, other_type, as_cmethod = 0):
        return self.compatible_signature_with_resolved_type(other_type.resolve(), as_cmethod)
    
    def compatible_signature_with_resolved_type(self, other_type, as_cmethod):
        #print "CFuncType.same_c_signature_as_resolved_type:", \
Robert Bradshaw's avatar
Robert Bradshaw committed
1186
        #    self, other_type, "as_cmethod =", as_cmethod ###
1187 1188 1189 1190
        if other_type is error_type:
            return 1
        if not other_type.is_cfunction:
            return 0
1191
        if not self.is_overridable and other_type.is_overridable:
1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206
            return 0
        nargs = len(self.args)
        if nargs - self.optional_arg_count != len(other_type.args) - other_type.optional_arg_count:
            return 0
        if self.optional_arg_count < other_type.optional_arg_count:
            return 0
        # When comparing C method signatures, the first argument
        # is exempt from compatibility checking (the proper check
        # is performed elsewhere).
        for i in range(as_cmethod, len(other_type.args)):
            if not self.args[i].type.same_as(
                other_type.args[i].type):
                    return 0
        if self.has_varargs != other_type.has_varargs:
            return 0
1207
        if not self.return_type.subtype_of_resolved_type(other_type.return_type):
1208 1209 1210
            return 0
        if not self.same_calling_convention_as(other_type):
            return 0
Robert Bradshaw's avatar
Robert Bradshaw committed
1211 1212
        if self.nogil != other_type.nogil:
            return 0
1213
        self.original_sig = other_type.original_sig or other_type
1214 1215 1216 1217 1218
        if as_cmethod:
            self.args[0] = other_type.args[0]
        return 1
        
        
1219 1220 1221 1222 1223 1224 1225 1226 1227
    def narrower_c_signature_than(self, other_type, as_cmethod = 0):
        return self.narrower_c_signature_than_resolved_type(other_type.resolve(), as_cmethod)
        
    def narrower_c_signature_than_resolved_type(self, other_type, as_cmethod):
        if other_type is error_type:
            return 1
        if not other_type.is_cfunction:
            return 0
        nargs = len(self.args)
Stefan Behnel's avatar
Stefan Behnel committed
1228
        if nargs != len(other_type.args):
1229 1230 1231 1232 1233 1234 1235
            return 0
        for i in range(as_cmethod, nargs):
            if not self.args[i].type.subtype_of_resolved_type(other_type.args[i].type):
                return 0
            else:
                self.args[i].needs_type_test = other_type.args[i].needs_type_test \
                        or not self.args[i].type.same_as(other_type.args[i].type)
Stefan Behnel's avatar
Stefan Behnel committed
1236
        if self.has_varargs != other_type.has_varargs:
1237
            return 0
Stefan Behnel's avatar
Stefan Behnel committed
1238
        if self.optional_arg_count != other_type.optional_arg_count:
1239
            return 0
1240 1241 1242 1243
        if not self.return_type.subtype_of_resolved_type(other_type.return_type):
            return 0
        return 1

1244
    def same_calling_convention_as(self, other):
1245 1246 1247 1248 1249 1250 1251 1252 1253
        ## XXX Under discussion ...
        ## callspec_words = ("__stdcall", "__cdecl", "__fastcall")
        ## cs1 = self.calling_convention
        ## cs2 = other.calling_convention
        ## if (cs1 in callspec_words or
        ##     cs2 in callspec_words):
        ##     return cs1 == cs2
        ## else:
        ##     return True
1254 1255 1256
        sc1 = self.calling_convention == '__stdcall'
        sc2 = other.calling_convention == '__stdcall'
        return sc1 == sc2
William Stein's avatar
William Stein committed
1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267
    
    def same_exception_signature_as(self, other_type):
        return self.same_exception_signature_as_resolved_type(
            other_type.resolve())

    def same_exception_signature_as_resolved_type(self, other_type):
        return self.exception_value == other_type.exception_value \
            and self.exception_check == other_type.exception_check
    
    def same_as_resolved_type(self, other_type, as_cmethod = 0):
        return self.same_c_signature_as_resolved_type(other_type, as_cmethod) \
1268 1269 1270 1271 1272 1273 1274
            and self.same_exception_signature_as_resolved_type(other_type) \
            and self.nogil == other_type.nogil
    
    def pointer_assignable_from_resolved_type(self, other_type):
        return self.same_c_signature_as_resolved_type(other_type) \
            and self.same_exception_signature_as_resolved_type(other_type) \
            and not (self.nogil and not other_type.nogil)
William Stein's avatar
William Stein committed
1275 1276
    
    def declaration_code(self, entity_code, 
1277 1278
                         for_display = 0, dll_linkage = None, pyrex = 0,
                         with_calling_convention = 1):
William Stein's avatar
William Stein committed
1279
        arg_decl_list = []
1280
        for arg in self.args[:len(self.args)-self.optional_arg_count]:
William Stein's avatar
William Stein committed
1281 1282
            arg_decl_list.append(
                arg.type.declaration_code("", for_display, pyrex = pyrex))
1283 1284
        if self.is_overridable:
            arg_decl_list.append("int %s" % Naming.skip_dispatch_cname)
1285
        if self.optional_arg_count:
1286
            arg_decl_list.append(self.op_arg_struct.declaration_code(Naming.optional_args_cname))
William Stein's avatar
William Stein committed
1287 1288
        if self.has_varargs:
            arg_decl_list.append("...")
1289
        arg_decl_code = ", ".join(arg_decl_list)
William Stein's avatar
William Stein committed
1290 1291
        if not arg_decl_code and not pyrex:
            arg_decl_code = "void"
1292
        trailer = ""
1293
        if (pyrex or for_display) and not self.return_type.is_pyobject:
William Stein's avatar
William Stein committed
1294
            if self.exception_value and self.exception_check:
1295
                trailer = " except? %s" % self.exception_value
William Stein's avatar
William Stein committed
1296
            elif self.exception_value:
1297
                trailer = " except %s" % self.exception_value
Felix Wu's avatar
Felix Wu committed
1298
            elif self.exception_check == '+':
1299
                trailer = " except +"
Felix Wu's avatar
Felix Wu committed
1300
            else:
1301 1302 1303
                " except *" # ignored
            if self.nogil:
                trailer += " nogil"
1304 1305 1306 1307 1308 1309 1310
        if not with_calling_convention:
            cc = ''
        else:
            cc = self.calling_convention_prefix()
            if (not entity_code and cc) or entity_code.startswith("*"):
                entity_code = "(%s%s)" % (cc, entity_code)
                cc = ""
William Stein's avatar
William Stein committed
1311
        return self.return_type.declaration_code(
1312
            "%s%s(%s)%s" % (cc, entity_code, arg_decl_code, trailer),
William Stein's avatar
William Stein committed
1313
            for_display, dll_linkage, pyrex)
Robert Bradshaw's avatar
Robert Bradshaw committed
1314
    
1315 1316 1317
    def function_header_code(self, func_name, arg_code):
        return "%s%s(%s)" % (self.calling_convention_prefix(),
            func_name, arg_code)
William Stein's avatar
William Stein committed
1318

1319 1320 1321 1322
    def signature_string(self):
        s = self.declaration_code("")
        return s

1323 1324 1325 1326
    def signature_cast_string(self):
        s = self.declaration_code("(*)", with_calling_convention=False)
        return '(%s)' % s

William Stein's avatar
William Stein committed
1327

1328
class CFuncTypeArg(object):
William Stein's avatar
William Stein committed
1329 1330 1331 1332 1333
    #  name       string
    #  cname      string
    #  type       PyrexType
    #  pos        source file position
    
1334
    def __init__(self, name, type, pos, cname=None):
William Stein's avatar
William Stein committed
1335
        self.name = name
1336 1337 1338 1339
        if cname is not None:
            self.cname = cname
        else:
            self.cname = Naming.var_prefix + name
William Stein's avatar
William Stein committed
1340 1341
        self.type = type
        self.pos = pos
1342 1343
        self.not_none = False
        self.needs_type_test = False # TODO: should these defaults be set in analyse_types()?
William Stein's avatar
William Stein committed
1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357
    
    def __repr__(self):
        return "%s:%s" % (self.name, repr(self.type))
    
    def declaration_code(self, for_display = 0):
        return self.type.declaration_code(self.cname, for_display)


class CStructOrUnionType(CType):
    #  name          string
    #  cname         string
    #  kind          string              "struct" or "union"
    #  scope         StructOrUnionScope, or None if incomplete
    #  typedef_flag  boolean
1358
    #  packed        boolean
William Stein's avatar
William Stein committed
1359 1360 1361 1362
    
    is_struct_or_union = 1
    has_attributes = 1
    
1363
    def __init__(self, name, kind, scope, typedef_flag, cname, packed=False):
William Stein's avatar
William Stein committed
1364 1365 1366 1367 1368
        self.name = name
        self.cname = cname
        self.kind = kind
        self.scope = scope
        self.typedef_flag = typedef_flag
Robert Bradshaw's avatar
Robert Bradshaw committed
1369
        self.is_struct = kind == 'struct'
Robert Bradshaw's avatar
Robert Bradshaw committed
1370 1371 1372 1373
        if self.is_struct:
            self.to_py_function = "%s_to_py_%s" % (Naming.convert_func_prefix, self.cname)
        self.exception_check = True
        self._convert_code = None
1374
        self.packed = packed
Robert Bradshaw's avatar
Robert Bradshaw committed
1375
        
1376
    def create_to_py_utility_code(self, env):
Robert Bradshaw's avatar
Robert Bradshaw committed
1377 1378 1379 1380 1381
        if env.outer_scope is None:
            return False
        if self._convert_code is None:
            import Code
            code = Code.CCodeWriter()
1382
            Code.GlobalState(code)
Robert Bradshaw's avatar
Robert Bradshaw committed
1383 1384 1385 1386 1387 1388
            header = "static PyObject* %s(%s)" % (self.to_py_function, self.declaration_code('s'))
            code.putln("%s {" % header)
            code.putln("PyObject* res;")
            code.putln("PyObject* member;")
            code.putln("res = PyDict_New(); if (res == NULL) return NULL;")
            for member in self.scope.var_entries:
1389
                if member.type.to_py_function and member.type.create_to_py_utility_code(env):
Robert Bradshaw's avatar
Robert Bradshaw committed
1390 1391
                    interned_name = env.get_string_const(member.name, identifier=True)
                    env.add_py_string(interned_name)
Robert Bradshaw's avatar
Robert Bradshaw committed
1392 1393
                    code.putln("member = %s(s.%s); if (member == NULL) goto bad;" % (
                                                member.type.to_py_function, member.cname))
Robert Bradshaw's avatar
Robert Bradshaw committed
1394
                    code.putln("if (PyDict_SetItem(res, %s, member) < 0) goto bad;" % interned_name.pystring_cname)
Robert Bradshaw's avatar
Robert Bradshaw committed
1395 1396 1397 1398 1399 1400 1401 1402 1403 1404
                    code.putln("Py_DECREF(member);")
                else:
                    self.to_py_function = None
                    return False
            code.putln("return res;")
            code.putln("bad:")
            code.putln("Py_XDECREF(member);")
            code.putln("Py_DECREF(res);")
            code.putln("return NULL;")
            code.putln("}")
1405 1406 1407 1408 1409 1410
            proto = header + ";"
            # This is a bit of a hack, we need a forward declaration
            # due to the way things are ordered in the module...
            entry = env.lookup(self.name)
            if entry.visibility != 'extern':
                proto = self.declaration_code('') + ';\n' + proto
Stefan Behnel's avatar
Stefan Behnel committed
1411
            self._convert_code = UtilityCode(proto=proto, impl=code.buffer.getvalue())
Robert Bradshaw's avatar
Robert Bradshaw committed
1412 1413 1414
        
        env.use_utility_code(self._convert_code)
        return True
William Stein's avatar
William Stein committed
1415 1416
        
    def __repr__(self):
1417 1418
        return "<CStructOrUnionType %s %s%s>" % (self.name, self.cname,
            ("", " typedef")[self.typedef_flag])
William Stein's avatar
William Stein committed
1419 1420 1421 1422

    def declaration_code(self, entity_code, 
            for_display = 0, dll_linkage = None, pyrex = 0):
        if pyrex:
1423
            return self.base_declaration_code(self.name, entity_code)
William Stein's avatar
William Stein committed
1424 1425 1426 1427 1428 1429 1430
        else:
            if for_display:
                base = self.name
            elif self.typedef_flag:
                base = self.cname
            else:
                base = "%s %s" % (self.kind, self.cname)
1431
            return self.base_declaration_code(public_decl(base, dll_linkage), entity_code)
William Stein's avatar
William Stein committed
1432

1433 1434 1435 1436 1437 1438 1439 1440 1441
    def __cmp__(self, other):
        try:
            if self.name == other.name:
                return 0
            else:
                return 1
        except AttributeError:
            return 1

William Stein's avatar
William Stein committed
1442 1443 1444 1445 1446 1447
    def is_complete(self):
        return self.scope is not None
    
    def attributes_known(self):
        return self.is_complete()

1448
    def can_be_complex(self):
1449
        # Does the struct consist of exactly two identical floats?
1450
        fields = self.scope.var_entries
1451 1452 1453 1454 1455
        if len(fields) != 2: return False
        a, b = fields
        return (a.type.is_float and b.type.is_float and
                a.type.declaration_code("") ==
                b.type.declaration_code(""))
1456

1457 1458 1459 1460
    def struct_nesting_depth(self):
        child_depths = [x.type.struct_nesting_depth()
                        for x in self.scope.var_entries]
        return max(child_depths) + 1
William Stein's avatar
William Stein committed
1461

1462
class CEnumType(CType):
William Stein's avatar
William Stein committed
1463 1464 1465
    #  name           string
    #  cname          string or None
    #  typedef_flag   boolean
1466

William Stein's avatar
William Stein committed
1467
    is_enum = 1
1468 1469
    signed = 1
    rank = -1 # Ranks below any integer type
1470 1471
    to_py_function = "PyInt_FromLong"
    from_py_function = "PyInt_AsLong"
William Stein's avatar
William Stein committed
1472 1473 1474 1475 1476 1477 1478

    def __init__(self, name, cname, typedef_flag):
        self.name = name
        self.cname = cname
        self.values = []
        self.typedef_flag = typedef_flag
    
1479 1480 1481
    def __str__(self):
        return self.name
    
William Stein's avatar
William Stein committed
1482
    def __repr__(self):
1483 1484
        return "<CEnumType %s %s%s>" % (self.name, self.cname,
            ("", " typedef")[self.typedef_flag])
William Stein's avatar
William Stein committed
1485 1486 1487 1488
    
    def declaration_code(self, entity_code, 
            for_display = 0, dll_linkage = None, pyrex = 0):
        if pyrex:
1489
            return self.base_declaration_code(self.cname, entity_code)
William Stein's avatar
William Stein committed
1490 1491 1492 1493 1494
        else:
            if self.typedef_flag:
                base = self.cname
            else:
                base = "enum %s" % self.cname
1495
            return self.base_declaration_code(public_decl(base, dll_linkage), entity_code)
William Stein's avatar
William Stein committed
1496 1497


1498
class CStringType(object):
William Stein's avatar
William Stein committed
1499 1500 1501
    #  Mixin class for C string types.

    is_string = 1
1502
    is_unicode = 0
William Stein's avatar
William Stein committed
1503
    
1504 1505
    to_py_function = "__Pyx_PyBytes_FromString"
    from_py_function = "__Pyx_PyBytes_AsString"
1506
    exception_value = "NULL"
William Stein's avatar
William Stein committed
1507 1508

    def literal_code(self, value):
1509
        assert isinstance(value, str)
1510
        return '"%s"' % StringEncoding.escape_byte_string(value)
1511 1512


1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524
class CUTF8CharArrayType(CStringType, CArrayType):
    #  C 'char []' type.
    
    pymemberdef_typecode = "T_STRING_INPLACE"
    is_unicode = 1
    
    to_py_function = "PyUnicode_DecodeUTF8"
    exception_value = "NULL"
    
    def __init__(self, size):
        CArrayType.__init__(self, c_char_type, size)

William Stein's avatar
William Stein committed
1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542
class CCharArrayType(CStringType, CArrayType):
    #  C 'char []' type.
    
    pymemberdef_typecode = "T_STRING_INPLACE"
    
    def __init__(self, size):
        CArrayType.__init__(self, c_char_type, size)
    

class CCharPtrType(CStringType, CPtrType):
    # C 'char *' type.
    
    pymemberdef_typecode = "T_STRING"
    
    def __init__(self):
        CPtrType.__init__(self, c_char_type)


Robert Bradshaw's avatar
Robert Bradshaw committed
1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553
class UnspecifiedType(PyrexType):
    # Used as a placeholder until the type can be determined.
        
    def declaration_code(self, entity_code, 
            for_display = 0, dll_linkage = None, pyrex = 0):
        return "<unspecified>"
    
    def same_as_resolved_type(self, other_type):
        return False
        

William Stein's avatar
William Stein committed
1554 1555 1556 1557 1558
class ErrorType(PyrexType):
    # Used to prevent propagation of error messages.
    
    is_error = 1
    exception_value = "0"
Robert Bradshaw's avatar
Robert Bradshaw committed
1559
    exception_check    = 0
William Stein's avatar
William Stein committed
1560 1561 1562
    to_py_function = "dummy"
    from_py_function = "dummy"
    
1563 1564 1565 1566
    def create_to_py_utility_code(self, env):
        return True
    
    def create_from_py_utility_code(self, env):
Robert Bradshaw's avatar
Robert Bradshaw committed
1567 1568
        return True
    
William Stein's avatar
William Stein committed
1569 1570 1571 1572 1573 1574
    def declaration_code(self, entity_code, 
            for_display = 0, dll_linkage = None, pyrex = 0):
        return "<error>"
    
    def same_as_resolved_type(self, other_type):
        return 1
1575 1576 1577
        
    def error_condition(self, result_code):
        return "dummy"
William Stein's avatar
William Stein committed
1578 1579


1580 1581 1582 1583 1584
rank_to_type_name = (
    "char",         # 0
    "short",        # 1
    "int",          # 2
    "long",         # 3
1585 1586 1587
    "Py_ssize_t",   # 4
    "size_t",       # 5
    "PY_LONG_LONG", # 6
1588 1589 1590
    "float",        # 7
    "double",       # 8
    "long double",  # 9
1591 1592
)

William Stein's avatar
William Stein committed
1593 1594 1595 1596 1597 1598
py_object_type = PyObjectType()

c_void_type =         CVoidType()
c_void_ptr_type =     CPtrType(c_void_type)
c_void_ptr_ptr_type = CPtrType(c_void_ptr_type)

1599 1600 1601 1602
c_uchar_type =       CIntType(0, 0, "T_UBYTE")
c_ushort_type =      CIntType(1, 0, "T_USHORT")
c_uint_type =        CUIntType(2, 0, "T_UINT")
c_ulong_type =       CULongType(3, 0, "T_ULONG")
1603
c_ulonglong_type =   CULongLongType(6, 0, "T_ULONGLONG")
1604 1605 1606 1607

c_char_type =        CIntType(0, 1, "T_CHAR")
c_short_type =       CIntType(1, 1, "T_SHORT")
c_int_type =         CIntType(2, 1, "T_INT")
1608
c_long_type =        CLongType(3, 1, "T_LONG")
1609
c_longlong_type =    CLongLongType(6, 1, "T_LONGLONG")
1610
c_bint_type =        CBIntType(2, 1, "T_INT")
1611

1612 1613 1614
c_schar_type =       CIntType(0, 2, "T_CHAR")
c_sshort_type =      CIntType(1, 2, "T_SHORT")
c_sint_type =        CIntType(2, 2, "T_INT")
1615
c_slong_type =       CLongType(3, 2, "T_LONG")
1616
c_slonglong_type =   CLongLongType(6, 2, "T_LONGLONG")
1617

1618 1619
c_py_ssize_t_type =  CPySSizeTType(4, 2, "T_PYSSIZET")
c_size_t_type =      CSizeTType(5, 0, "T_SIZET")
1620

1621
c_float_type =       CFloatType(7, "T_FLOAT", math_h_modifier='f')
1622
c_double_type =      CFloatType(8, "T_DOUBLE")
1623
c_longdouble_type =  CFloatType(9, math_h_modifier='l')
William Stein's avatar
William Stein committed
1624

1625 1626
c_double_complex_type = CComplexType(c_double_type)

William Stein's avatar
William Stein committed
1627 1628 1629
c_null_ptr_type =     CNullPtrType(c_void_type)
c_char_array_type =   CCharArrayType(None)
c_char_ptr_type =     CCharPtrType()
1630
c_utf8_char_array_type = CUTF8CharArrayType(None)
William Stein's avatar
William Stein committed
1631 1632
c_char_ptr_ptr_type = CPtrType(c_char_ptr_type)
c_int_ptr_type =      CPtrType(c_int_type)
1633 1634
c_py_ssize_t_ptr_type =  CPtrType(c_py_ssize_t_type)
c_size_t_ptr_type =  CPtrType(c_size_t_type)
William Stein's avatar
William Stein committed
1635 1636 1637

c_returncode_type =   CIntType(2, 1, "T_INT", is_returncode = 1)

1638 1639
c_anon_enum_type =    CAnonEnumType(-1, 1)

1640
# the Py_buffer type is defined in Builtin.py
1641 1642
c_py_buffer_type = CStructOrUnionType("Py_buffer", "struct", None, 1, "Py_buffer")
c_py_buffer_ptr_type = CPtrType(c_py_buffer_type)
1643

William Stein's avatar
William Stein committed
1644
error_type =    ErrorType()
Robert Bradshaw's avatar
Robert Bradshaw committed
1645
unspecified_type = UnspecifiedType()
William Stein's avatar
William Stein committed
1646 1647 1648

sign_and_rank_to_type = {
    #(signed, rank)
1649 1650 1651
    (0, 0): c_uchar_type,
    (0, 1): c_ushort_type,
    (0, 2): c_uint_type,
1652
    (0, 3): c_ulong_type,
1653 1654
    (0, 6): c_ulonglong_type,

1655 1656 1657
    (1, 0): c_char_type,
    (1, 1): c_short_type,
    (1, 2): c_int_type,
William Stein's avatar
William Stein committed
1658
    (1, 3): c_long_type,
1659
    (1, 6): c_longlong_type,
1660

1661 1662 1663
    (2, 0): c_schar_type,
    (2, 1): c_sshort_type,
    (2, 2): c_sint_type,
1664
    (2, 3): c_slong_type,
1665
    (2, 6): c_slonglong_type,
1666

1667 1668 1669 1670 1671 1672
    (0, 4): c_py_ssize_t_type,
    (1, 4): c_py_ssize_t_type,
    (2, 4): c_py_ssize_t_type,
    (0, 5): c_size_t_type,
    (1, 5): c_size_t_type,
    (2, 5): c_size_t_type,
1673

1674
    (1, 7): c_float_type,
1675 1676
    (1, 8): c_double_type,
    (1, 9): c_longdouble_type,
1677
# In case we're mixing unsigned ints and floats...
1678
    (0, 7): c_float_type,
1679 1680
    (0, 8): c_double_type,
    (0, 9): c_longdouble_type,
William Stein's avatar
William Stein committed
1681 1682 1683 1684
}

modifiers_and_name_to_type = {
    #(signed, longness, name)
1685 1686 1687
    (0, 0, "char"): c_uchar_type,
    (0, -1, "int"): c_ushort_type,
    (0, 0, "int"): c_uint_type,
1688 1689
    (0, 1, "int"): c_ulong_type,
    (0, 2, "int"): c_ulonglong_type,
William Stein's avatar
William Stein committed
1690
    (1, 0, "void"): c_void_type,
1691 1692 1693
    (1, 0, "char"): c_char_type,
    (1, -1, "int"): c_short_type,
    (1, 0, "int"): c_int_type,
William Stein's avatar
William Stein committed
1694 1695
    (1, 1, "int"): c_long_type,
    (1, 2, "int"): c_longlong_type,
1696
    (1, 0, "float"): c_float_type,
William Stein's avatar
William Stein committed
1697 1698 1699
    (1, 0, "double"): c_double_type,
    (1, 1, "double"): c_longdouble_type,
    (1, 0, "object"): py_object_type,
1700 1701 1702 1703
    (1, 0, "bint"): c_bint_type,
    (2, 0, "char"): c_schar_type,
    (2, -1, "int"): c_sshort_type,
    (2, 0, "int"): c_sint_type,
1704 1705
    (2, 1, "int"): c_slong_type,
    (2, 2, "int"): c_slonglong_type,
1706

1707 1708
    (2, 0, "Py_ssize_t"): c_py_ssize_t_type,
    (0, 0, "size_t") : c_size_t_type,
1709

1710
    (1, 0, "long"): c_long_type,
1711
    (1, 0, "short"): c_short_type,
1712
    (1, 0, "longlong"): c_longlong_type,
1713
    (1, 0, "bint"): c_bint_type,
William Stein's avatar
William Stein committed
1714 1715 1716 1717 1718
}

def widest_numeric_type(type1, type2):
    # Given two numeric types, return the narrowest type
    # encompassing both of them.
1719 1720 1721
    if type1 == type2:
        return type1
    if type1.is_complex:
1722 1723 1724 1725
        if type2.is_complex:
            return CComplexType(widest_numeric_type(type1.real_type, type2.real_type))
        else:
            return CComplexType(widest_numeric_type(type1.real_type, type2))
1726 1727
    elif type2.is_complex:
        return CComplexType(widest_numeric_type(type1, type2.real_type))
1728
    if type1.is_enum and type2.is_enum:
1729 1730 1731 1732 1733 1734 1735 1736
        return c_int_type
    elif type1 is type2:
        return type1
    elif (type1.signed and type2.signed) or (not type1.signed and not type2.signed):
        if type2.rank > type1.rank:
            return type2
        else:
            return type1
1737
    else:
1738
        return sign_and_rank_to_type[min(type1.signed, type2.signed), max(type1.rank, type2.rank)]
1739
    return widest_type
William Stein's avatar
William Stein committed
1740 1741 1742 1743 1744

def simple_c_type(signed, longness, name):
    # Find type descriptor for simple type given name and modifiers.
    # Returns None if arguments don't make sense.
    return modifiers_and_name_to_type.get((signed, longness, name))
1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759
    
def parse_basic_type(name):
    base = None
    if name.startswith('p_'):
        base = parse_basic_type(name[2:])
    elif name.startswith('p'):
        base = parse_basic_type(name[1:])
    elif name.endswith('*'):
        base = parse_basic_type(name[:-1])
    if base:
        return CPtrType(base)
    elif name.startswith('u'):
        return simple_c_type(0, 0, name[1:])
    else:
        return simple_c_type(1, 0, name)
William Stein's avatar
William Stein committed
1760 1761 1762 1763 1764

def c_array_type(base_type, size):
    # Construct a C array type.
    if base_type is c_char_type:
        return CCharArrayType(size)
1765 1766
    elif base_type is error_type:
        return error_type
William Stein's avatar
William Stein committed
1767 1768 1769 1770 1771 1772 1773
    else:
        return CArrayType(base_type, size)

def c_ptr_type(base_type):
    # Construct a C pointer type.
    if base_type is c_char_type:
        return c_char_ptr_type
1774 1775
    elif base_type is error_type:
        return error_type
William Stein's avatar
William Stein committed
1776 1777
    else:
        return CPtrType(base_type)
1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790
        
def Node_to_type(node, env):
    from ExprNodes import NameNode, AttributeNode, StringNode, error
    if isinstance(node, StringNode):
        node = NameNode(node.pos, name=node.value)
    if isinstance(node, NameNode) and node.name in rank_to_type_name:
        return simple_c_type(1, 0, node.name)
    elif isinstance(node, (AttributeNode, NameNode)):
        node.analyze_types(env)
        if not node.entry.is_type:
            pass
    else:
        error(node.pos, "Bad type")
William Stein's avatar
William Stein committed
1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807

def same_type(type1, type2):
    return type1.same_as(type2)
    
def assignable_from(type1, type2):
    return type1.assignable_from(type2)

def typecast(to_type, from_type, expr_code):
    #  Return expr_code cast to a C type which can be
    #  assigned to to_type, assuming its existing C type
    #  is from_type.
    if to_type is from_type or \
        (not to_type.is_pyobject and assignable_from(to_type, from_type)):
            return expr_code
    else:
        #print "typecast: to", to_type, "from", from_type ###
        return to_type.cast_code(expr_code)
1808 1809 1810 1811 1812


type_conversion_predeclarations = """
/* Type Conversion Predeclarations */

Stefan Behnel's avatar
Stefan Behnel committed
1813
#if PY_MAJOR_VERSION < 3
Robert Bradshaw's avatar
Robert Bradshaw committed
1814 1815 1816
#define __Pyx_PyBytes_FromString          PyString_FromString
#define __Pyx_PyBytes_FromStringAndSize   PyString_FromStringAndSize
#define __Pyx_PyBytes_AsString            PyString_AsString
1817
#else
Robert Bradshaw's avatar
Robert Bradshaw committed
1818 1819 1820
#define __Pyx_PyBytes_FromString          PyBytes_FromString
#define __Pyx_PyBytes_FromStringAndSize   PyBytes_FromStringAndSize
#define __Pyx_PyBytes_AsString            PyBytes_AsString
1821 1822
#endif

1823
#define __Pyx_PyBool_FromLong(b) ((b) ? (Py_INCREF(Py_True), Py_True) : (Py_INCREF(Py_False), Py_False))
1824 1825
static INLINE int __Pyx_PyObject_IsTrue(PyObject*);
static INLINE PyObject* __Pyx_PyNumber_Int(PyObject* x);
1826

1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841
#if !defined(T_PYSSIZET)
#if PY_VERSION_HEX < 0x02050000
#define T_PYSSIZET T_INT
#elif !defined(T_LONGLONG)
#define T_PYSSIZET \\
        ((sizeof(Py_ssize_t) == sizeof(int))  ? T_INT  : \\
        ((sizeof(Py_ssize_t) == sizeof(long)) ? T_LONG : -1))
#else
#define T_PYSSIZET \\
        ((sizeof(Py_ssize_t) == sizeof(int))          ? T_INT      : \\
        ((sizeof(Py_ssize_t) == sizeof(long))         ? T_LONG     : \\
        ((sizeof(Py_ssize_t) == sizeof(PY_LONG_LONG)) ? T_LONGLONG : -1)))
#endif
#endif

Dag Sverre Seljebotn's avatar
Dag Sverre Seljebotn committed
1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875

#if !defined(T_ULONGLONG)
#define __Pyx_T_UNSIGNED_INT(x) \\
        ((sizeof(x) == sizeof(unsigned char))  ? T_UBYTE : \\
        ((sizeof(x) == sizeof(unsigned short)) ? T_USHORT : \\
        ((sizeof(x) == sizeof(unsigned int))   ? T_UINT : \\
        ((sizeof(x) == sizeof(unsigned long))  ? T_ULONG : -1))))
#else
#define __Pyx_T_UNSIGNED_INT(x) \\
        ((sizeof(x) == sizeof(unsigned char))  ? T_UBYTE : \\
        ((sizeof(x) == sizeof(unsigned short)) ? T_USHORT : \\
        ((sizeof(x) == sizeof(unsigned int))   ? T_UINT : \\
        ((sizeof(x) == sizeof(unsigned long))  ? T_ULONG : \\
        ((sizeof(x) == sizeof(unsigned PY_LONG_LONG)) ? T_ULONGLONG : -1)))))
#endif
#if !defined(T_LONGLONG)
#define __Pyx_T_SIGNED_INT(x) \\
        ((sizeof(x) == sizeof(char))  ? T_BYTE : \\
        ((sizeof(x) == sizeof(short)) ? T_SHORT : \\
        ((sizeof(x) == sizeof(int))   ? T_INT : \\
        ((sizeof(x) == sizeof(long))  ? T_LONG : -1))))
#else
#define __Pyx_T_SIGNED_INT(x) \\
        ((sizeof(x) == sizeof(char))  ? T_BYTE : \\
        ((sizeof(x) == sizeof(short)) ? T_SHORT : \\
        ((sizeof(x) == sizeof(int))   ? T_INT : \\
        ((sizeof(x) == sizeof(long))  ? T_LONG : \\
        ((sizeof(x) == sizeof(PY_LONG_LONG))   ? T_LONGLONG : -1)))))
#endif

#define __Pyx_T_FLOATING(x) \\
        ((sizeof(x) == sizeof(float)) ? T_FLOAT : \\
        ((sizeof(x) == sizeof(double)) ? T_DOUBLE : -1))

1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888
#if !defined(T_SIZET)
#if !defined(T_ULONGLONG)
#define T_SIZET \\
        ((sizeof(size_t) == sizeof(unsigned int))  ? T_UINT  : \\
        ((sizeof(size_t) == sizeof(unsigned long)) ? T_ULONG : -1))
#else
#define T_SIZET \\
        ((sizeof(size_t) == sizeof(unsigned int))          ? T_UINT      : \\
        ((sizeof(size_t) == sizeof(unsigned long))         ? T_ULONG     : \\
        ((sizeof(size_t) == sizeof(unsigned PY_LONG_LONG)) ? T_ULONGLONG : -1)))
#endif
#endif

1889 1890 1891
static INLINE Py_ssize_t __Pyx_PyIndex_AsSsize_t(PyObject*);
static INLINE PyObject * __Pyx_PyInt_FromSize_t(size_t);
static INLINE size_t __Pyx_PyInt_AsSize_t(PyObject*);
1892

1893
#define __pyx_PyFloat_AsDouble(x) (PyFloat_CheckExact(x) ? PyFloat_AS_DOUBLE(x) : PyFloat_AsDouble(x))
1894

1895 1896 1897 1898 1899
""" + type_conversion_predeclarations

type_conversion_functions = """
/* Type Conversion Functions */

1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917
static INLINE int __Pyx_PyObject_IsTrue(PyObject* x) {
   if (x == Py_True) return 1;
   else if ((x == Py_False) | (x == Py_None)) return 0;
   else return PyObject_IsTrue(x);
}

static INLINE PyObject* __Pyx_PyNumber_Int(PyObject* x) {
  PyNumberMethods *m;
  const char *name = NULL;
  PyObject *res = NULL;
#if PY_VERSION_HEX < 0x03000000
  if (PyInt_Check(x) || PyLong_Check(x))
#else
  if (PyLong_Check(x))
#endif
    return Py_INCREF(x), x;
  m = Py_TYPE(x)->tp_as_number;
#if PY_VERSION_HEX < 0x03000000
1918
  if (m && m->nb_int) {
1919 1920 1921
    name = "int";
    res = PyNumber_Int(x);
  }
1922 1923 1924 1925
  else if (m && m->nb_long) {
    name = "long";
    res = PyNumber_Long(x);
  }
1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952
#else
  if (m && m->nb_int) {
    name = "int";
    res = PyNumber_Long(x);
  }
#endif
  if (res) {
#if PY_VERSION_HEX < 0x03000000
    if (!PyInt_Check(res) && !PyLong_Check(res)) {
#else
    if (!PyLong_Check(res)) {
#endif
      PyErr_Format(PyExc_TypeError,
                   "__%s__ returned non-%s (type %.200s)",
                   name, name, Py_TYPE(res)->tp_name);
      Py_DECREF(res);
      return NULL;
    }
  }
  else if (!PyErr_Occurred()) {
    PyErr_SetString(PyExc_TypeError,
                    "an integer is required");
  }
  return res;
}

static INLINE Py_ssize_t __Pyx_PyIndex_AsSsize_t(PyObject* b) {
1953 1954 1955 1956 1957 1958 1959 1960
  Py_ssize_t ival;
  PyObject* x = PyNumber_Index(b);
  if (!x) return -1;
  ival = PyInt_AsSsize_t(x);
  Py_DECREF(x);
  return ival;
}

1961
static INLINE PyObject * __Pyx_PyInt_FromSize_t(size_t ival) {
1962
#if PY_VERSION_HEX < 0x02050000
1963
   if (ival <= LONG_MAX)
1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974
       return PyInt_FromLong((long)ival);
   else {
       unsigned char *bytes = (unsigned char *) &ival;
       int one = 1; int little = (int)*(unsigned char*)&one;
       return _PyLong_FromByteArray(bytes, sizeof(size_t), little, 0);
   }
#else
   return PyInt_FromSize_t(ival);
#endif
}

1975 1976
static INLINE size_t __Pyx_PyInt_AsSize_t(PyObject* x) {
   unsigned PY_LONG_LONG val = __Pyx_PyInt_AsUnsignedLongLong(x);
1977 1978 1979
   if (unlikely(val == (unsigned PY_LONG_LONG)-1 && PyErr_Occurred())) {
       return (size_t)-1;
   } else if (unlikely(val != (unsigned PY_LONG_LONG)(size_t)val)) {
1980 1981
       PyErr_SetString(PyExc_OverflowError,
                       "value too large to convert to size_t");
1982 1983
       return (size_t)-1;
   }
1984
   return (size_t)val;
1985 1986 1987
}

""" + type_conversion_functions
1988 1989