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

5
from Code 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
9
from Errors import error
William Stein's avatar
William Stein committed
10

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

15 16 17
    def can_coerce_to_pyobject(self, env):
        return False

18 19 20
    def cast_code(self, expr_code):
        return "((%s)%s)" % (self.declaration_code(""), expr_code)
    
Craig Citro's avatar
Craig Citro committed
21
    def specialization_name(self):
22 23
        return self.declaration_code("").replace(" ", "__")
    
24 25 26 27 28 29 30
    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
31 32 33 34 35 36 37 38
    #
    #  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
39
    #  is_complex            boolean     Is a C complex type
William Stein's avatar
William Stein committed
40 41 42 43
    #  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
Danilo Freitas's avatar
Danilo Freitas committed
44
    #  is_reference          boolean     Is a C reference type
William Stein's avatar
William Stein committed
45 46
    #  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
47
    #  is_struct             boolean     Is a C struct type
William Stein's avatar
William Stein committed
48
    #  is_enum               boolean     Is a C enum type
49
    #  is_typedef            boolean     Is a typedef type
William Stein's avatar
William Stein committed
50
    #  is_string             boolean     Is a C char * type
51
    #  is_unicode            boolean     Is a UTF-8 encoded C char * type
Stefan Behnel's avatar
Stefan Behnel committed
52
    #  is_unicode_char       boolean     Is either Py_UCS4 or Py_UNICODE
William Stein's avatar
William Stein committed
53 54
    #  is_returncode         boolean     Is used only to signal exceptions
    #  is_error              boolean     Is the dummy error type
55
    #  is_buffer             boolean     Is buffer access type
William Stein's avatar
William Stein committed
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 81 82 83 84
    #  has_attributes        boolean     Has C dot-selectable attributes
    #  default_value         string      Initial value
    #
    #  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
Robert Bradshaw's avatar
Robert Bradshaw committed
85
    is_unspecified = 0
William Stein's avatar
William Stein committed
86
    is_extension_type = 0
Robert Bradshaw's avatar
Robert Bradshaw committed
87
    is_builtin_type = 0
William Stein's avatar
William Stein committed
88 89 90
    is_numeric = 0
    is_int = 0
    is_float = 0
91
    is_complex = 0
William Stein's avatar
William Stein committed
92 93 94 95
    is_void = 0
    is_array = 0
    is_ptr = 0
    is_null_ptr = 0
96
    is_reference = 0
William Stein's avatar
William Stein committed
97 98
    is_cfunction = 0
    is_struct_or_union = 0
99
    is_cpp_class = 0
Robert Bradshaw's avatar
Robert Bradshaw committed
100
    is_struct = 0
William Stein's avatar
William Stein committed
101
    is_enum = 0
102
    is_typedef = 0
William Stein's avatar
William Stein committed
103
    is_string = 0
104
    is_unicode = 0
Stefan Behnel's avatar
Stefan Behnel committed
105
    is_unicode_char = 0
William Stein's avatar
William Stein committed
106 107
    is_returncode = 0
    is_error = 0
108
    is_buffer = 0
William Stein's avatar
William Stein committed
109 110 111 112 113 114 115
    has_attributes = 0
    default_value = ""
    
    def resolve(self):
        # If a typedef, returns the base type.
        return self
    
116
    def specialize(self, values):
Robert Bradshaw's avatar
Robert Bradshaw committed
117
        # TODO(danilo): Override wherever it makes sense.
118 119
        return self
    
William Stein's avatar
William Stein committed
120 121 122 123 124 125
    def literal_code(self, value):
        # Returns a C code fragment representing a literal
        # value of this type.
        return str(value)
    
    def __str__(self):
126
        return self.declaration_code("", for_display = 1).strip()
William Stein's avatar
William Stein committed
127 128 129 130 131
    
    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):
132
        return self == other_type or other_type is error_type
William Stein's avatar
William Stein committed
133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153
    
    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

154
    def is_simple_buffer_dtype(self):
155
        return (self.is_int or self.is_float or self.is_complex or self.is_pyobject or
156 157
                self.is_extension_type or self.is_ptr)

158 159 160 161 162 163
    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

164

165 166 167 168 169 170
def public_decl(base_code, dll_linkage):
    if dll_linkage:
        return "%s(%s)" % (dll_linkage, base_code)
    else:
        return base_code
    
171
def create_typedef_type(name, base_type, cname, is_external=0):
172 173 174 175 176
    if base_type.is_complex:
        if is_external:
            raise ValueError("Complex external typedefs not supported")
        return base_type
    else:
177
        return CTypedefType(name, base_type, cname, is_external)
178

179

180
class CTypedefType(BaseType):
William Stein's avatar
William Stein committed
181
    #
182
    #  Pseudo-type defined with a ctypedef statement in a
William Stein's avatar
William Stein committed
183
    #  'cdef extern from' block. Delegates most attribute
184 185
    #  lookups to the base type. ANYTHING NOT DEFINED
    #  HERE IS DELEGATED!
William Stein's avatar
William Stein committed
186
    #
187
    #  qualified_name      string
188
    #  typedef_name        string
189 190
    #  typedef_cname       string
    #  typedef_base_type   PyrexType
191
    #  typedef_is_external bool
192 193
    
    is_typedef = 1
194
    typedef_is_external = 0
195 196 197 198

    to_py_utility_code = None
    from_py_utility_code = None
    
William Stein's avatar
William Stein committed
199
    
200
    def __init__(self, name, base_type, cname, is_external=0):
201
        assert not base_type.is_complex
202
        self.typedef_name = name
William Stein's avatar
William Stein committed
203 204
        self.typedef_cname = cname
        self.typedef_base_type = base_type
205
        self.typedef_is_external = is_external
William Stein's avatar
William Stein committed
206 207 208 209 210 211
    
    def resolve(self):
        return self.typedef_base_type.resolve()
    
    def declaration_code(self, entity_code, 
            for_display = 0, dll_linkage = None, pyrex = 0):
212
        if pyrex or for_display:
213
            base_code = self.typedef_name
214
        else:
215
            base_code = public_decl(self.typedef_cname, dll_linkage)
216
        return self.base_declaration_code(base_code, entity_code)
217 218 219 220
    
    def as_argument_type(self):
        return self

221 222 223
    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. 
224 225 226
        if self.typedef_base_type.is_array:
            base_type = self.typedef_base_type.base_type
            return CPtrType(base_type).cast_code(expr_code)
227 228
        else:
            return BaseType.cast_code(self, expr_code)
229

230 231
    def __repr__(self):
        return "<CTypedefType %s>" % self.typedef_cname
William Stein's avatar
William Stein committed
232 233
    
    def __str__(self):
234
        return self.typedef_name
235 236 237

    def _create_utility_code(self, template_utility_code,
                             template_function_name):
238
        type_name = self.typedef_cname.replace(" ","_").replace("::","__")
239 240 241 242 243 244 245 246 247 248
        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
Robert Bradshaw's avatar
Robert Bradshaw committed
249 250 251
                if type(base_type) is CIntType:
                    # Various subclasses have special methods
                    # that should be inherited.
252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269
                    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
Robert Bradshaw's avatar
Robert Bradshaw committed
270 271 272
                if type(base_type) is CIntType:
                    # Various subclasses have special methods
                    # that should be inherited.
273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296
                    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
297 298 299
    def __getattr__(self, name):
        return getattr(self.typedef_base_type, name)

300

301 302 303 304 305 306
class BufferType(BaseType):
    #
    #  Delegates most attribute
    #  lookups to the base type. ANYTHING NOT DEFINED
    #  HERE IS DELEGATED!
    
307 308 309 310 311 312 313
    # dtype            PyrexType
    # ndim             int
    # mode             str
    # negative_indices bool
    # cast             bool
    # is_buffer        bool
    # writable         bool
314 315

    is_buffer = 1
316
    writable = True
317
    def __init__(self, base, dtype, ndim, mode, negative_indices, cast):
318 319 320
        self.base = base
        self.dtype = dtype
        self.ndim = ndim
321
        self.buffer_ptr_type = CPtrType(dtype)
322
        self.mode = mode
323
        self.negative_indices = negative_indices
324
        self.cast = cast
325
    
326 327 328
    def as_argument_type(self):
        return self

329 330 331
    def __getattr__(self, name):
        return getattr(self.base, name)

332 333 334
    def __repr__(self):
        return "<BufferType %r>" % self.base

335

William Stein's avatar
William Stein committed
336 337 338 339
class PyObjectType(PyrexType):
    #
    #  Base class for all Python object types (reference-counted).
    #
340
    #  buffer_defaults  dict or None     Default options for bu
341 342

    name = "object"
William Stein's avatar
William Stein committed
343 344
    is_pyobject = 1
    default_value = "0"
345
    buffer_defaults = None
346 347
    is_extern = False
    is_subclassed = False
William Stein's avatar
William Stein committed
348 349 350 351 352
    
    def __str__(self):
        return "Python object"
    
    def __repr__(self):
353
        return "<PyObjectType>"
354 355 356 357

    def can_coerce_to_pyobject(self, env):
        return True

358 359 360 361
    def default_coerced_ctype(self):
        "The default C type that this Python type coerces to, or None."
        return None

William Stein's avatar
William Stein committed
362
    def assignable_from(self, src_type):
363 364
        # except for pointers, conversion will be attempted
        return not src_type.is_ptr or src_type.is_string
William Stein's avatar
William Stein committed
365 366 367
        
    def declaration_code(self, entity_code, 
            for_display = 0, dll_linkage = None, pyrex = 0):
368
        if pyrex or for_display:
369
            base_code = "object"
William Stein's avatar
William Stein committed
370
        else:
371 372 373
            base_code = public_decl("PyObject", dll_linkage)
            entity_code = "*%s" % entity_code
        return self.base_declaration_code(base_code, entity_code)
William Stein's avatar
William Stein committed
374

375 376 377 378 379
    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
380

Robert Bradshaw's avatar
Robert Bradshaw committed
381
class BuiltinObjectType(PyObjectType):
382
    #  objstruct_cname  string           Name of PyObject struct
Robert Bradshaw's avatar
Robert Bradshaw committed
383 384 385 386 387 388

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

389 390 391 392 393 394 395
    # fields that let it look like an extension type
    vtabslot_cname = None
    vtabstruct_cname = None
    vtabptr_cname = None
    typedef_flag = True
    is_external = True

396
    def __init__(self, name, cname, objstruct_cname=None):
Robert Bradshaw's avatar
Robert Bradshaw committed
397 398
        self.name = name
        self.cname = cname
399
        self.typeptr_cname = "(&%s)" % cname
400
        self.objstruct_cname = objstruct_cname
Robert Bradshaw's avatar
Robert Bradshaw committed
401 402 403 404 405 406 407 408 409 410 411
                                 
    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
412 413 414 415 416 417 418 419 420 421

    def default_coerced_ctype(self):
        if self.name == 'bytes':
            return c_char_ptr_type
        elif self.name == 'bool':
            return c_bint_type
        elif self.name == 'float':
            return c_double_type
        return None

Robert Bradshaw's avatar
Robert Bradshaw committed
422 423
    def assignable_from(self, src_type):
        if isinstance(src_type, BuiltinObjectType):
424
            return src_type.name == self.name
425 426 427
        elif src_type.is_extension_type:
            return (src_type.module_name == '__builtin__' and
                    src_type.name == self.name)
Robert Bradshaw's avatar
Robert Bradshaw committed
428
        else:
429
            return True
Robert Bradshaw's avatar
Robert Bradshaw committed
430 431 432 433 434 435 436 437 438
            
    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)
439 440

    def type_check_function(self, exact=True):
441 442
        type_name = self.name
        if type_name == 'str':
443
            type_check = 'PyString_Check'
444
        elif type_name == 'frozenset':
445
            type_check = 'PyFrozenSet_Check'
446
        else:
447
            type_check = 'Py%s_Check' % type_name.capitalize()
Stefan Behnel's avatar
Stefan Behnel committed
448
        if exact and type_name not in ('bool', 'slice'):
449 450 451 452 453
            type_check += 'Exact'
        return type_check

    def isinstance_code(self, arg):
        return '%s(%s)' % (self.type_check_function(exact=False), arg)
454

455 456
    def type_test_code(self, arg, notnone=False):
        type_check = self.type_check_function(exact=True)
457 458 459 460 461
        check = 'likely(%s(%s))' % (type_check, arg)
        if not notnone:
            check = check + ('||((%s) == Py_None)' % arg)
        error = '(PyErr_Format(PyExc_TypeError, "Expected %s, got %%.200s", Py_TYPE(%s)->tp_name), 0)' % (self.name, arg)
        return check + '||' + error
Robert Bradshaw's avatar
Robert Bradshaw committed
462

463 464 465
    def declaration_code(self, entity_code, 
            for_display = 0, dll_linkage = None, pyrex = 0):
        if pyrex or for_display:
466
            base_code = self.name
467
        else:
468 469 470
            base_code = public_decl("PyObject", dll_linkage)
            entity_code = "*%s" % entity_code
        return self.base_declaration_code(base_code, entity_code)
471

472 473 474 475 476
    def cast_code(self, expr_code, to_object_struct = False):
        return "((%s*)%s)" % (
            to_object_struct and self.objstruct_cname or "PyObject", # self.objstruct_cname may be None
            expr_code)

Robert Bradshaw's avatar
Robert Bradshaw committed
477

William Stein's avatar
William Stein committed
478 479 480 481 482 483 484 485 486 487 488
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
489
    #  objtypedef_cname string           Name of PyObject struct typedef
William Stein's avatar
William Stein committed
490 491 492 493 494 495 496 497 498 499
    #  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
    
500 501
    objtypedef_cname = None
    
502
    def __init__(self, name, typedef_flag, base_type, is_external=0):
William Stein's avatar
William Stein committed
503 504 505
        self.name = name
        self.scope = None
        self.typedef_flag = typedef_flag
506 507
        if base_type is not None:
            base_type.is_subclassed = True
William Stein's avatar
William Stein committed
508 509 510 511 512 513 514 515 516
        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
517
        self.is_external = is_external
William Stein's avatar
William Stein committed
518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539
    
    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
    
540 541 542 543 544 545 546 547
    def assignable_from(self, src_type):
        if self == src_type:
            return True
        if isinstance(src_type, PyExtensionType):
            if src_type.base_type is not None:
                return self.assignable_from(src_type.base_type)
        return False

William Stein's avatar
William Stein committed
548
    def declaration_code(self, entity_code, 
549
            for_display = 0, dll_linkage = None, pyrex = 0, deref = 0):
550
        if pyrex or for_display:
551
            base_code = self.name
William Stein's avatar
William Stein committed
552 553
        else:
            if self.typedef_flag:
554
                objstruct = self.objstruct_cname
William Stein's avatar
William Stein committed
555
            else:
556
                objstruct = "struct %s" % self.objstruct_cname
557
            base_code = public_decl(objstruct, dll_linkage)
558
            if deref:
559
                assert not entity_code
560
            else:
561 562
                entity_code = "*%s" % entity_code
        return self.base_declaration_code(base_code, entity_code)
William Stein's avatar
William Stein committed
563

564 565 566 567 568 569 570 571 572 573
    def type_test_code(self, py_arg, notnone=False):

        none_check = "((%s) == Py_None)" % py_arg
        type_check = "likely(__Pyx_TypeTest(%s, %s))" % (
            py_arg, self.typeptr_cname)
        if notnone:
            return type_check
        else:
            return "likely(%s || %s)" % (none_check, type_check)

William Stein's avatar
William Stein committed
574 575 576 577 578 579 580
    def attributes_known(self):
        return self.scope is not None
    
    def __str__(self):
        return self.name
    
    def __repr__(self):
581 582
        return "<PyExtensionType %s%s>" % (self.scope.class_name,
            ("", " typedef")[self.typedef_flag])
William Stein's avatar
William Stein committed
583 584 585 586 587 588 589 590 591 592 593 594
    

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
595 596
    exception_value = None
    exception_check = 1
Robert Bradshaw's avatar
Robert Bradshaw committed
597

598
    def create_to_py_utility_code(self, env):
599
        return self.to_py_function is not None
600 601
        
    def create_from_py_utility_code(self, env):
602
        return self.from_py_function is not None
603 604 605 606

    def can_coerce_to_pyobject(self, env):
        return self.create_to_py_utility_code(env)

607 608 609 610 611 612 613 614 615 616 617 618
    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
619 620


621
class CVoidType(CType):
622 623 624 625
    #
    #   C "void" type
    #

William Stein's avatar
William Stein committed
626 627 628 629 630 631 632
    is_void = 1
    
    def __repr__(self):
        return "<CVoidType>"
    
    def declaration_code(self, entity_code, 
            for_display = 0, dll_linkage = None, pyrex = 0):
633 634 635 636 637
        if pyrex or for_display:
            base_code = "void"
        else:
            base_code = public_decl("void", dll_linkage)
        return self.base_declaration_code(base_code, entity_code)
William Stein's avatar
William Stein committed
638 639 640 641 642 643 644 645 646 647
    
    def is_complete(self):
        return 0


class CNumericType(CType):
    #
    #   Base class for all C numeric types.
    #
    #   rank      integer     Relative size
648
    #   signed    integer     0 = unsigned, 1 = unspecified, 2 = explicitly signed
William Stein's avatar
William Stein committed
649 650 651 652
    #
    
    is_numeric = 1
    default_value = "0"
653 654
    has_attributes = True
    scope = None
William Stein's avatar
William Stein committed
655
    
656 657
    sign_words = ("unsigned ", "", "signed ")
    
658
    def __init__(self, rank, signed = 1):
William Stein's avatar
William Stein committed
659 660 661
        self.rank = rank
        self.signed = signed
    
662 663 664 665 666
    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
667
    def __repr__(self):
668
        return "<CNumericType %s>" % self.sign_and_name()
William Stein's avatar
William Stein committed
669 670 671
    
    def declaration_code(self, entity_code, 
            for_display = 0, dll_linkage = None, pyrex = 0):
672 673 674 675 676 677
        type_name = self.sign_and_name()
        if pyrex or for_display:
            base_code = type_name.replace('PY_LONG_LONG', 'long long')
        else:
            base_code = public_decl(type_name, dll_linkage)
        return self.base_declaration_code(base_code, entity_code)
678 679 680 681 682 683 684 685 686 687 688 689
                    
    def attributes_known(self):
        if self.scope is None:
            import Symtab
            self.scope = scope = Symtab.CClassScope(
                    '',
                    None,
                    visibility="extern")
            scope.parent_type = self
            scope.directives = {}
            entry = scope.declare_cfunction(
                    "conjugate",
690
                    CFuncType(self, [CFuncTypeArg("self", self, None)], nogil=True),
691 692 693 694
                    pos=None,
                    defining=1,
                    cname=" ")
        return True
695 696 697


type_conversion_predeclarations = ""
698 699 700 701
type_conversion_functions = ""

c_int_from_py_function = UtilityCode(
proto="""
702
static CYTHON_INLINE %(type)s __Pyx_PyInt_As%(SignWord)s%(TypeName)s(PyObject *);
703 704
""",
impl="""
705
static CYTHON_INLINE %(type)s __Pyx_PyInt_As%(SignWord)s%(TypeName)s(PyObject* x) {
Robert Bradshaw's avatar
Robert Bradshaw committed
706 707
    const %(type)s neg_one = (%(type)s)-1, const_zero = 0;
    const int is_unsigned = neg_one > const_zero;
708 709 710
    if (sizeof(%(type)s) < sizeof(long)) {
        long val = __Pyx_PyInt_AsLong(x);
        if (unlikely(val != (long)(%(type)s)val)) {
711
            if (!unlikely(val == -1 && PyErr_Occurred())) {
712
                PyErr_SetString(PyExc_OverflowError,
713
                    (is_unsigned && unlikely(val < 0)) ?
714 715
                    "can't convert negative value to %(type)s" :
                    "value too large to convert to %(type)s");
716
            }
717 718 719 720 721 722
            return (%(type)s)-1;
        }
        return (%(type)s)val;
    }
    return (%(type)s)__Pyx_PyInt_As%(SignWord)sLong(x);
}
Dag Sverre Seljebotn's avatar
Dag Sverre Seljebotn committed
723
""") #fool emacs: '
724 725 726

c_long_from_py_function = UtilityCode(
proto="""
727
static CYTHON_INLINE %(type)s __Pyx_PyInt_As%(SignWord)s%(TypeName)s(PyObject *);
728 729
""",
impl="""
730
static CYTHON_INLINE %(type)s __Pyx_PyInt_As%(SignWord)s%(TypeName)s(PyObject* x) {
Robert Bradshaw's avatar
Robert Bradshaw committed
731 732
    const %(type)s neg_one = (%(type)s)-1, const_zero = 0;
    const int is_unsigned = neg_one > const_zero;
733
#if PY_VERSION_HEX < 0x03000000
734 735
    if (likely(PyInt_Check(x))) {
        long val = PyInt_AS_LONG(x);
736
        if (is_unsigned && unlikely(val < 0)) {
737 738 739 740
            PyErr_SetString(PyExc_OverflowError,
                            "can't convert negative value to %(type)s");
            return (%(type)s)-1;
        }
741 742 743
        return (%(type)s)val;
    } else
#endif
744
    if (likely(PyLong_Check(x))) {
745 746 747 748 749 750 751 752 753
        if (is_unsigned) {
            if (unlikely(Py_SIZE(x) < 0)) {
                PyErr_SetString(PyExc_OverflowError,
                                "can't convert negative value to %(type)s");
                return (%(type)s)-1;
            }
            return PyLong_AsUnsigned%(TypeName)s(x);
        } else {
            return PyLong_As%(TypeName)s(x);
754
        }
755 756 757 758 759 760 761 762 763 764 765
    } 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;
    }
}
""")

766 767
c_typedef_int_from_py_function = UtilityCode(
proto="""
768
static CYTHON_INLINE %(type)s __Pyx_PyInt_from_py_%(TypeName)s(PyObject *);
769 770
""",
impl="""
771
static CYTHON_INLINE %(type)s __Pyx_PyInt_from_py_%(TypeName)s(PyObject* x) {
772 773
    const %(type)s neg_one = (%(type)s)-1, const_zero = (%(type)s)0;
    const int is_unsigned = const_zero < neg_one;
774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798
    if (sizeof(%(type)s) == sizeof(char)) {
        if (is_unsigned)
            return (%(type)s)__Pyx_PyInt_AsUnsignedChar(x);
        else
            return (%(type)s)__Pyx_PyInt_AsSignedChar(x);
    } else if (sizeof(%(type)s) == sizeof(short)) {
        if (is_unsigned)
            return (%(type)s)__Pyx_PyInt_AsUnsignedShort(x);
        else
            return (%(type)s)__Pyx_PyInt_AsSignedShort(x);
    } else if (sizeof(%(type)s) == sizeof(int)) {
        if (is_unsigned)
            return (%(type)s)__Pyx_PyInt_AsUnsignedInt(x);
        else
            return (%(type)s)__Pyx_PyInt_AsSignedInt(x);
    } else if (sizeof(%(type)s) == sizeof(long)) {
        if (is_unsigned)
            return (%(type)s)__Pyx_PyInt_AsUnsignedLong(x);
        else
            return (%(type)s)__Pyx_PyInt_AsSignedLong(x);
    } else if (sizeof(%(type)s) == sizeof(PY_LONG_LONG)) {
        if (is_unsigned)
            return (%(type)s)__Pyx_PyInt_AsUnsignedLongLong(x);
        else
            return (%(type)s)__Pyx_PyInt_AsSignedLongLong(x);
799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819
    }  else {
        %(type)s val;
        PyObject *v = __Pyx_PyNumber_Int(x);
        #if PY_VERSION_HEX < 0x03000000
        if (likely(v) && !PyLong_Check(v)) {
            PyObject *tmp = v;
            v = PyNumber_Long(tmp);
            Py_DECREF(tmp);
        }
        #endif
        if (likely(v)) {
            int one = 1; int is_little = (int)*(unsigned char *)&one;
            unsigned char *bytes = (unsigned char *)&val;
            int ret = _PyLong_AsByteArray((PyLongObject *)v,
                                          bytes, sizeof(val),
                                          is_little, !is_unsigned);
            Py_DECREF(v);
            if (likely(!ret))
                return val;
        }
        return (%(type)s)-1;
820
    }
821 822
}
""")
823

824 825
c_typedef_int_to_py_function = UtilityCode(
proto="""
826
static CYTHON_INLINE PyObject *__Pyx_PyInt_to_py_%(TypeName)s(%(type)s);
827 828
""",
impl="""
829
static CYTHON_INLINE PyObject *__Pyx_PyInt_to_py_%(TypeName)s(%(type)s val) {
830 831 832 833
    const %(type)s neg_one = (%(type)s)-1, const_zero = (%(type)s)0;
    const int is_unsigned = const_zero < neg_one;
    if ((sizeof(%(type)s) == sizeof(char))  ||
        (sizeof(%(type)s) == sizeof(short))) {
834
        return PyInt_FromLong((long)val);
835 836
    } else if ((sizeof(%(type)s) == sizeof(int)) ||
               (sizeof(%(type)s) == sizeof(long))) {
837 838 839 840
        if (is_unsigned)
            return PyLong_FromUnsignedLong((unsigned long)val);
        else
            return PyInt_FromLong((long)val);
841
    } else if (sizeof(%(type)s) == sizeof(PY_LONG_LONG)) {
842 843 844 845
        if (is_unsigned)
            return PyLong_FromUnsignedLongLong((unsigned PY_LONG_LONG)val);
        else
            return PyLong_FromLongLong((PY_LONG_LONG)val);
846 847 848 849 850
    } else {
        int one = 1; int little = (int)*(unsigned char *)&one;
        unsigned char *bytes = (unsigned char *)&val;
        return _PyLong_FromByteArray(bytes, sizeof(%(type)s), 
                                     little, !is_unsigned);
851
    }
852 853
}
""")
William Stein's avatar
William Stein committed
854 855

class CIntType(CNumericType):
856

William Stein's avatar
William Stein committed
857 858
    is_int = 1
    typedef_flag = 0
859 860
    to_py_function = None
    from_py_function = None
861
    exception_value = -1
William Stein's avatar
William Stein committed
862

863
    def __init__(self, rank, signed = 1):
864
        CNumericType.__init__(self, rank, signed)
865 866 867 868 869 870
        if self.to_py_function is None:
            self.to_py_function = self.get_to_py_type_conversion()
        if self.from_py_function is None:
            self.from_py_function = self.get_from_py_type_conversion()

    def get_to_py_type_conversion(self):
871
        if self.rank < list(rank_to_type_name).index('int'):
872 873 874 875 876 877 878 879 880 881
            # This assumes sizeof(short) < sizeof(int)
            return "PyInt_FromLong"
        else:
            # Py{Int|Long}_From[Unsigned]Long[Long]
            Prefix = "Int"
            SignWord = ""
            TypeName = "Long"
            if not self.signed:
                Prefix = "Long"
                SignWord = "Unsigned"
882
            if self.rank >= list(rank_to_type_name).index('PY_LONG_LONG'):
883 884 885 886 887
                Prefix = "Long"
                TypeName = "LongLong"
            return "Py%s_From%s%s" % (Prefix, SignWord, TypeName)

    def get_from_py_type_conversion(self):
888 889 890 891
        type_name = rank_to_type_name[self.rank]
        type_name = type_name.replace("PY_LONG_LONG", "long long")
        TypeName = type_name.title().replace(" ", "")
        SignWord = self.sign_words[self.signed].strip().title()
892
        if self.rank >= list(rank_to_type_name).index('long'):
893 894 895 896 897
            utility_code = c_long_from_py_function
        else:
            utility_code = c_int_from_py_function
        utility_code.specialize(self,
                                SignWord=SignWord,
898
                                TypeName=TypeName)
899
        func_name = "__Pyx_PyInt_As%s%s" % (SignWord, TypeName)
900
        return func_name
901

902 903
    def assignable_from_resolved_type(self, src_type):
        return src_type.is_int or src_type.is_enum or src_type is error_type
904

William Stein's avatar
William Stein committed
905

906 907
class CAnonEnumType(CIntType):

908 909 910 911
    is_enum = 1

    def sign_and_name(self):
        return 'int'
912

913

914 915 916 917
class CReturnCodeType(CIntType):

    is_returncode = 1

918

919 920 921 922
class CBIntType(CIntType):

    to_py_function = "__Pyx_PyBool_FromLong"
    from_py_function = "__Pyx_PyObject_IsTrue"
Robert Bradshaw's avatar
Robert Bradshaw committed
923
    exception_check = 1 # for C++ bool
924 925 926 927 928

    def __repr__(self):
        return "<CNumericType bint>"


Stefan Behnel's avatar
Stefan Behnel committed
929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960
class CPyUCS4IntType(CIntType):
    # Py_UCS4

    is_unicode_char = True

    # Py_UCS4 coerces from and to single character unicode strings (or
    # at most two characters on 16bit Unicode builds), but we also
    # allow Python integers as input.  The value range for Py_UCS4
    # is 0..1114111, which is checked when converting from an integer
    # value.

    to_py_function = "PyUnicode_FromOrdinal"
    from_py_function = "__Pyx_PyObject_AsPy_UCS4"

    def create_from_py_utility_code(self, env):
        env.use_utility_code(pyobject_as_py_ucs4_utility_code)
        return True

    def sign_and_name(self):
        return "Py_UCS4"


pyobject_as_py_ucs4_utility_code = UtilityCode(
proto='''
static CYTHON_INLINE Py_UCS4 __Pyx_PyObject_AsPy_UCS4(PyObject*);
''',
impl='''
static CYTHON_INLINE Py_UCS4 __Pyx_PyObject_AsPy_UCS4(PyObject* x) {
   long ival;
   if (PyUnicode_Check(x)) {
       if (likely(PyUnicode_GET_SIZE(x) == 1)) {
           return PyUnicode_AS_UNICODE(x)[0];
961 962 963
       }
       #if Py_UNICODE_SIZE == 2
       else if (PyUnicode_GET_SIZE(x) == 2) {
Stefan Behnel's avatar
Stefan Behnel committed
964 965 966 967
           Py_UCS4 high_val = PyUnicode_AS_UNICODE(x)[0];
           if (high_val >= 0xD800 && high_val <= 0xDBFF) {
               Py_UCS4 low_val = PyUnicode_AS_UNICODE(x)[1];
               if (low_val >= 0xDC00 && low_val <= 0xDFFF) {
968
                   return 0x10000 + (((high_val & ((1<<10)-1)) << 10) | (low_val & ((1<<10)-1)));
Stefan Behnel's avatar
Stefan Behnel committed
969 970 971
               }
           }
       }
972
       #endif
Stefan Behnel's avatar
Stefan Behnel committed
973
       PyErr_Format(PyExc_ValueError,
974
           "only single character unicode strings can be converted to Py_UCS4, got length "
Stefan Behnel's avatar
Stefan Behnel committed
975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998
           #if PY_VERSION_HEX < 0x02050000
           "%d",
           #else
           "%zd",
           #endif
           PyUnicode_GET_SIZE(x));
       return (Py_UCS4)-1;
   }
   ival = __Pyx_PyInt_AsLong(x);
   if (unlikely(ival < 0)) {
       if (!PyErr_Occurred())
           PyErr_SetString(PyExc_OverflowError,
                           "cannot convert negative value to Py_UCS4");
       return (Py_UCS4)-1;
   } else if (unlikely(ival > 1114111)) {
       PyErr_SetString(PyExc_OverflowError,
                       "value too large to convert to Py_UCS4");
       return (Py_UCS4)-1;
   }
   return (Py_UCS4)ival;
}
''')


999 1000 1001
class CPyUnicodeIntType(CIntType):
    # Py_UNICODE

Stefan Behnel's avatar
Stefan Behnel committed
1002 1003
    is_unicode_char = True

1004 1005 1006 1007
    # Py_UNICODE coerces from and to single character unicode strings,
    # but we also allow Python integers as input.  The value range for
    # Py_UNICODE is 0..1114111, which is checked when converting from
    # an integer value.
1008

1009 1010 1011 1012 1013 1014
    to_py_function = "PyUnicode_FromOrdinal"
    from_py_function = "__Pyx_PyObject_AsPy_UNICODE"

    def create_from_py_utility_code(self, env):
        env.use_utility_code(pyobject_as_py_unicode_utility_code)
        return True
1015 1016 1017 1018

    def sign_and_name(self):
        return "Py_UNICODE"

1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057
pyobject_as_py_unicode_utility_code = UtilityCode(
proto='''
static CYTHON_INLINE Py_UNICODE __Pyx_PyObject_AsPy_UNICODE(PyObject*);
''',
impl='''
static CYTHON_INLINE Py_UNICODE __Pyx_PyObject_AsPy_UNICODE(PyObject* x) {
   static long maxval = 0;
   long ival;
   if (PyUnicode_Check(x)) {
       if (unlikely(PyUnicode_GET_SIZE(x) != 1)) {
           PyErr_Format(PyExc_ValueError,
               "only single character unicode strings can be converted to Py_UNICODE, got length "
               #if PY_VERSION_HEX < 0x02050000
               "%d",
               #else
               "%zd",
               #endif
               PyUnicode_GET_SIZE(x));
           return (Py_UNICODE)-1;
       }
       return PyUnicode_AS_UNICODE(x)[0];
   }
   if (unlikely(!maxval))
       maxval = (long)PyUnicode_GetMax();
   ival = __Pyx_PyInt_AsLong(x);
   if (unlikely(ival < 0)) {
       if (!PyErr_Occurred())
           PyErr_SetString(PyExc_OverflowError,
                           "cannot convert negative value to Py_UNICODE");
       return (Py_UNICODE)-1;
   } else if (unlikely(ival > maxval)) {
       PyErr_SetString(PyExc_OverflowError,
                       "value too large to convert to Py_UNICODE");
       return (Py_UNICODE)-1;
   }
   return (Py_UNICODE)ival;
}
''')

1058

1059 1060 1061 1062 1063 1064 1065 1066
class CPyHashTType(CIntType):

    to_py_function = "__Pyx_PyInt_FromHash_t"
    from_py_function = "__Pyx_PyInt_AsHash_t"

    def sign_and_name(self):
        return "Py_hash_t"

1067 1068 1069
class CPySSizeTType(CIntType):

    to_py_function = "PyInt_FromSsize_t"
1070
    from_py_function = "__Pyx_PyIndex_AsSsize_t"
1071

1072
    def sign_and_name(self):
1073
        return "Py_ssize_t"
1074

1075 1076 1077 1078 1079 1080
class CSSizeTType(CIntType):

    to_py_function = "PyInt_FromSsize_t"
    from_py_function = "PyInt_AsSsize_t"

    def sign_and_name(self):
1081
        return "Py_ssize_t"
1082

1083
class CSizeTType(CIntType):
1084

1085 1086
    to_py_function = "__Pyx_PyInt_FromSize_t"
    from_py_function = "__Pyx_PyInt_AsSize_t"
1087

1088
    def sign_and_name(self):
1089
        return "size_t"
1090

1091

William Stein's avatar
William Stein committed
1092 1093 1094 1095
class CFloatType(CNumericType):

    is_float = 1
    to_py_function = "PyFloat_FromDouble"
1096
    from_py_function = "__pyx_PyFloat_AsDouble"
1097 1098

    exception_value = -1
William Stein's avatar
William Stein committed
1099
    
1100 1101
    def __init__(self, rank, math_h_modifier = ''):
        CNumericType.__init__(self, rank, 1)
1102
        self.math_h_modifier = math_h_modifier
William Stein's avatar
William Stein committed
1103
    
1104
    def assignable_from_resolved_type(self, src_type):
1105 1106
        return (src_type.is_numeric and not src_type.is_complex) or src_type is error_type

1107

1108
class CComplexType(CNumericType):
1109 1110
    
    is_complex = 1
1111
    to_py_function = "__pyx_PyComplex_FromComplex"
1112 1113
    has_attributes = 1
    scope = None
1114 1115
    
    def __init__(self, real_type):
Dag Sverre Seljebotn's avatar
Dag Sverre Seljebotn committed
1116 1117 1118 1119 1120
        while real_type.is_typedef and not real_type.typedef_is_external:
            real_type = real_type.typedef_base_type
        if real_type.is_typedef and real_type.typedef_is_external:
            # The below is not actually used: Coercions are currently disabled
            # so that complex types of external types can not be created
Craig Citro's avatar
Craig Citro committed
1121
            self.funcsuffix = "_%s" % real_type.specialization_name()
1122
        elif hasattr(real_type, 'math_h_modifier'):
Dag Sverre Seljebotn's avatar
Dag Sverre Seljebotn committed
1123
            self.funcsuffix = real_type.math_h_modifier
1124
        else:
Craig Citro's avatar
Craig Citro committed
1125
            self.funcsuffix = "_%s" % real_type.specialization_name()
Dag Sverre Seljebotn's avatar
Dag Sverre Seljebotn committed
1126
    
1127 1128
        self.real_type = real_type
        CNumericType.__init__(self, real_type.rank + 0.5, real_type.signed)
1129
        self.binops = {}
Craig Citro's avatar
Craig Citro committed
1130
        self.from_parts = "%s_from_parts" % self.specialization_name()
1131
        self.default_value = "%s(0, 0)" % self.from_parts
Dag Sverre Seljebotn's avatar
Dag Sverre Seljebotn committed
1132

1133
    def __eq__(self, other):
1134
        if isinstance(self, CComplexType) and isinstance(other, CComplexType):
1135
            return self.real_type == other.real_type
1136
        else:
1137
            return False
1138 1139 1140 1141 1142 1143
    
    def __ne__(self, other):
        if isinstance(self, CComplexType) and isinstance(other, CComplexType):
            return self.real_type != other.real_type
        else:
            return True
1144 1145 1146 1147 1148 1149 1150 1151 1152

    def __lt__(self, other):
        if isinstance(self, CComplexType) and isinstance(other, CComplexType):
            return self.real_type < other.real_type
        else:
            # this is arbitrary, but it makes sure we always have
            # *some* kind of order
            return False

1153 1154
    def __hash__(self):
        return ~hash(self.real_type)
Dag Sverre Seljebotn's avatar
Dag Sverre Seljebotn committed
1155

1156 1157
    def declaration_code(self, entity_code, 
            for_display = 0, dll_linkage = None, pyrex = 0):
1158 1159 1160
        if pyrex or for_display:
            real_code = self.real_type.declaration_code("", for_display, dll_linkage, pyrex)
            base_code = "%s complex" % real_code
1161
        else:
1162 1163
            base_code = public_decl(self.sign_and_name(), dll_linkage)
        return self.base_declaration_code(base_code, entity_code)
1164

1165
    def sign_and_name(self):
Craig Citro's avatar
Craig Citro committed
1166
        real_type_name = self.real_type.specialization_name()
1167
        real_type_name = real_type_name.replace('long__double','long_double')
1168
        real_type_name = real_type_name.replace('PY_LONG_LONG','long_long')
1169
        return Naming.type_prefix + real_type_name + "_complex"
1170
    
1171 1172
    def assignable_from(self, src_type):
        # Temporary hack/feature disabling, see #441
Dag Sverre Seljebotn's avatar
Dag Sverre Seljebotn committed
1173 1174 1175
        if (not src_type.is_complex and src_type.is_numeric and src_type.is_typedef
            and src_type.typedef_is_external):
             return False
1176 1177 1178
        else:
            return super(CComplexType, self).assignable_from(src_type)
        
1179 1180 1181 1182
    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)
1183 1184 1185 1186
                    
    def attributes_known(self):
        if self.scope is None:
            import Symtab
1187 1188 1189 1190 1191
            self.scope = scope = Symtab.CClassScope(
                    '',
                    None,
                    visibility="extern")
            scope.parent_type = self
1192
            scope.directives = {}
1193 1194
            scope.declare_var("real", self.real_type, None, cname="real", is_cdef=True)
            scope.declare_var("imag", self.real_type, None, cname="imag", is_cdef=True)
1195 1196
            entry = scope.declare_cfunction(
                    "conjugate",
1197
                    CFuncType(self, [CFuncTypeArg("self", self, None)], nogil=True),
1198 1199
                    pos=None,
                    defining=1,
Dag Sverre Seljebotn's avatar
Dag Sverre Seljebotn committed
1200
                    cname="__Pyx_c_conj%s" % self.funcsuffix)
1201

1202
        return True
1203

1204
    def create_declaration_utility_code(self, env):
1205 1206
        # This must always be run, because a single CComplexType instance can be shared
        # across multiple compilations (the one created in the module scope)
1207 1208 1209 1210
        env.use_utility_code(complex_header_utility_code)
        env.use_utility_code(complex_real_imag_utility_code)
        for utility_code in (complex_type_utility_code,
                             complex_from_parts_utility_code,
Craig Citro's avatar
Craig Citro committed
1211
                             complex_arithmetic_utility_code):
1212 1213 1214 1215
            env.use_utility_code(
                utility_code.specialize(
                    self, 
                    real_type = self.real_type.declaration_code(''),
Robert Bradshaw's avatar
Robert Bradshaw committed
1216 1217
                    m = self.funcsuffix,
                    is_float = self.real_type.is_float))
1218 1219 1220 1221 1222
        return True

    def create_to_py_utility_code(self, env):
        env.use_utility_code(complex_real_imag_utility_code)
        env.use_utility_code(complex_to_py_utility_code)
1223 1224 1225 1226
        return True

    def create_from_py_utility_code(self, env):
        self.real_type.create_from_py_utility_code(env)
1227 1228 1229 1230 1231 1232 1233

        for utility_code in (complex_from_parts_utility_code,
                             complex_from_py_utility_code):
            env.use_utility_code(
                utility_code.specialize(
                    self, 
                    real_type = self.real_type.declaration_code(''),
Robert Bradshaw's avatar
Robert Bradshaw committed
1234 1235
                    m = self.funcsuffix,
                    is_float = self.real_type.is_float))
Craig Citro's avatar
Craig Citro committed
1236
        self.from_py_function = "__Pyx_PyComplex_As_" + self.specialization_name()
1237
        return True
1238
    
1239
    def lookup_op(self, nargs, op):
1240
        try:
1241
            return self.binops[nargs, op]
1242
        except KeyError:
1243 1244 1245
            pass
        try:
            op_name = complex_ops[nargs, op]
Dag Sverre Seljebotn's avatar
Dag Sverre Seljebotn committed
1246
            self.binops[nargs, op] = func_name = "__Pyx_c_%s%s" % (op_name, self.funcsuffix)
1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259
            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',
1260 1261 1262 1263
    (2, '+'): 'sum',
    (2, '-'): 'diff',
    (2, '*'): 'prod',
    (2, '/'): 'quot',
1264 1265
    (2, '=='): 'eq',
}
1266

1267
complex_header_utility_code = UtilityCode(
1268
proto_block='h_code',
1269
proto="""
1270 1271 1272 1273 1274 1275 1276 1277
#if !defined(CYTHON_CCOMPLEX)
  #if defined(__cplusplus)
    #define CYTHON_CCOMPLEX 1
  #elif defined(_Complex_I)
    #define CYTHON_CCOMPLEX 1
  #else
    #define CYTHON_CCOMPLEX 0
  #endif
1278 1279
#endif

1280 1281 1282 1283 1284 1285 1286
#if CYTHON_CCOMPLEX
  #ifdef __cplusplus
    #include <complex>
  #else
    #include <complex.h>
  #endif
#endif
Robert Bradshaw's avatar
Robert Bradshaw committed
1287 1288 1289 1290 1291

#if CYTHON_CCOMPLEX && !defined(__cplusplus) && defined(__sun__) && defined(__GNUC__)
  #undef _Complex_I
  #define _Complex_I 1.0fj
#endif
1292 1293
""")

1294
complex_real_imag_utility_code = UtilityCode(
1295
proto="""
1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307
#if CYTHON_CCOMPLEX
  #ifdef __cplusplus
    #define __Pyx_CREAL(z) ((z).real())
    #define __Pyx_CIMAG(z) ((z).imag())
  #else
    #define __Pyx_CREAL(z) (__real__(z))
    #define __Pyx_CIMAG(z) (__imag__(z))
  #endif
#else
    #define __Pyx_CREAL(z) ((z).real)
    #define __Pyx_CIMAG(z) ((z).imag)
#endif
1308 1309 1310 1311 1312 1313 1314 1315

#if defined(_WIN32) && defined(__cplusplus) && CYTHON_CCOMPLEX
    #define __Pyx_SET_CREAL(z,x) ((z).real(x))
    #define __Pyx_SET_CIMAG(z,y) ((z).imag(y))
#else
    #define __Pyx_SET_CREAL(z,x) __Pyx_CREAL(z) = (x)
    #define __Pyx_SET_CIMAG(z,y) __Pyx_CIMAG(z) = (y)
#endif
1316 1317
""")

1318
complex_type_utility_code = UtilityCode(
Dag Sverre Seljebotn's avatar
Dag Sverre Seljebotn committed
1319
proto_block='complex_type_declarations',
1320
proto="""
1321 1322 1323 1324
#if CYTHON_CCOMPLEX
  #ifdef __cplusplus
    typedef ::std::complex< %(real_type)s > %(type_name)s;
  #else
1325
    typedef %(real_type)s _Complex %(type_name)s;
1326 1327 1328 1329 1330 1331 1332
  #endif
#else
    typedef struct { %(real_type)s real, imag; } %(type_name)s;
#endif
""")

complex_from_parts_utility_code = UtilityCode(
1333
proto_block='utility_code_proto',
1334
proto="""
1335
static CYTHON_INLINE %(type)s %(type_name)s_from_parts(%(real_type)s, %(real_type)s);
1336 1337 1338 1339
""",
impl="""
#if CYTHON_CCOMPLEX
  #ifdef __cplusplus
1340
    static CYTHON_INLINE %(type)s %(type_name)s_from_parts(%(real_type)s x, %(real_type)s y) {
1341 1342 1343
      return ::std::complex< %(real_type)s >(x, y);
    }
  #else
1344
    static CYTHON_INLINE %(type)s %(type_name)s_from_parts(%(real_type)s x, %(real_type)s y) {
1345 1346
      return x + y*(%(type)s)_Complex_I;
    }
1347
  #endif
1348
#else
1349
    static CYTHON_INLINE %(type)s %(type_name)s_from_parts(%(real_type)s x, %(real_type)s y) {
1350
      %(type)s z;
Robert Bradshaw's avatar
Robert Bradshaw committed
1351 1352 1353
      z.real = x;
      z.imag = y;
      return z;
1354
    }
1355 1356
#endif
""")
1357

1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380
complex_to_py_utility_code = UtilityCode(
proto="""
#define __pyx_PyComplex_FromComplex(z) \\
        PyComplex_FromDoubles((double)__Pyx_CREAL(z), \\
                              (double)__Pyx_CIMAG(z))
""")

complex_from_py_utility_code = UtilityCode(
proto="""
static %(type)s __Pyx_PyComplex_As_%(type_name)s(PyObject*);
""",
impl="""
static %(type)s __Pyx_PyComplex_As_%(type_name)s(PyObject* o) {
    Py_complex cval;
    if (PyComplex_CheckExact(o))
        cval = ((PyComplexObject *)o)->cval;
    else
        cval = PyComplex_AsCComplex(o);
    return %(type_name)s_from_parts(
               (%(real_type)s)cval.real,
               (%(real_type)s)cval.imag);
}
""")
1381

Craig Citro's avatar
Craig Citro committed
1382
complex_arithmetic_utility_code = UtilityCode(
1383 1384 1385 1386 1387 1388 1389 1390 1391
proto="""
#if CYTHON_CCOMPLEX
    #define __Pyx_c_eq%(m)s(a, b)   ((a)==(b))
    #define __Pyx_c_sum%(m)s(a, b)  ((a)+(b))
    #define __Pyx_c_diff%(m)s(a, b) ((a)-(b))
    #define __Pyx_c_prod%(m)s(a, b) ((a)*(b))
    #define __Pyx_c_quot%(m)s(a, b) ((a)/(b))
    #define __Pyx_c_neg%(m)s(a)     (-(a))
  #ifdef __cplusplus
1392
    #define __Pyx_c_is_zero%(m)s(z) ((z)==(%(real_type)s)0)
1393
    #define __Pyx_c_conj%(m)s(z)    (::std::conj(z))
Robert Bradshaw's avatar
Robert Bradshaw committed
1394 1395 1396 1397
    #if %(is_float)s
        #define __Pyx_c_abs%(m)s(z)     (::std::abs(z))
        #define __Pyx_c_pow%(m)s(a, b)  (::std::pow(a, b))
    #endif
1398 1399 1400
  #else
    #define __Pyx_c_is_zero%(m)s(z) ((z)==0)
    #define __Pyx_c_conj%(m)s(z)    (conj%(m)s(z))
Robert Bradshaw's avatar
Robert Bradshaw committed
1401 1402 1403 1404
    #if %(is_float)s
        #define __Pyx_c_abs%(m)s(z)     (cabs%(m)s(z))
        #define __Pyx_c_pow%(m)s(a, b)  (cpow%(m)s(a, b))
    #endif
1405 1406
 #endif
#else
1407 1408 1409 1410 1411 1412 1413 1414
    static CYTHON_INLINE int __Pyx_c_eq%(m)s(%(type)s, %(type)s);
    static CYTHON_INLINE %(type)s __Pyx_c_sum%(m)s(%(type)s, %(type)s);
    static CYTHON_INLINE %(type)s __Pyx_c_diff%(m)s(%(type)s, %(type)s);
    static CYTHON_INLINE %(type)s __Pyx_c_prod%(m)s(%(type)s, %(type)s);
    static CYTHON_INLINE %(type)s __Pyx_c_quot%(m)s(%(type)s, %(type)s);
    static CYTHON_INLINE %(type)s __Pyx_c_neg%(m)s(%(type)s);
    static CYTHON_INLINE int __Pyx_c_is_zero%(m)s(%(type)s);
    static CYTHON_INLINE %(type)s __Pyx_c_conj%(m)s(%(type)s);
Robert Bradshaw's avatar
Robert Bradshaw committed
1415 1416 1417 1418
    #if %(is_float)s
        static CYTHON_INLINE %(real_type)s __Pyx_c_abs%(m)s(%(type)s);
        static CYTHON_INLINE %(type)s __Pyx_c_pow%(m)s(%(type)s, %(type)s);
    #endif
1419 1420 1421 1422 1423
#endif
""",
impl="""
#if CYTHON_CCOMPLEX
#else
1424
    static CYTHON_INLINE int __Pyx_c_eq%(m)s(%(type)s a, %(type)s b) {
1425 1426
       return (a.real == b.real) && (a.imag == b.imag);
    }
1427
    static CYTHON_INLINE %(type)s __Pyx_c_sum%(m)s(%(type)s a, %(type)s b) {
1428 1429 1430 1431 1432
        %(type)s z;
        z.real = a.real + b.real;
        z.imag = a.imag + b.imag;
        return z;
    }
1433
    static CYTHON_INLINE %(type)s __Pyx_c_diff%(m)s(%(type)s a, %(type)s b) {
1434 1435 1436 1437 1438
        %(type)s z;
        z.real = a.real - b.real;
        z.imag = a.imag - b.imag;
        return z;
    }
1439
    static CYTHON_INLINE %(type)s __Pyx_c_prod%(m)s(%(type)s a, %(type)s b) {
1440 1441 1442 1443 1444
        %(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;
    }
1445
    static CYTHON_INLINE %(type)s __Pyx_c_quot%(m)s(%(type)s a, %(type)s b) {
1446
        %(type)s z;
1447
        %(real_type)s denom = b.real * b.real + b.imag * b.imag;
1448 1449 1450 1451
        z.real = (a.real * b.real + a.imag * b.imag) / denom;
        z.imag = (a.imag * b.real - a.real * b.imag) / denom;
        return z;
    }
1452
    static CYTHON_INLINE %(type)s __Pyx_c_neg%(m)s(%(type)s a) {
1453 1454 1455 1456 1457
        %(type)s z;
        z.real = -a.real;
        z.imag = -a.imag;
        return z;
    }
1458
    static CYTHON_INLINE int __Pyx_c_is_zero%(m)s(%(type)s a) {
1459 1460
       return (a.real == 0) && (a.imag == 0);
    }
1461
    static CYTHON_INLINE %(type)s __Pyx_c_conj%(m)s(%(type)s a) {
1462 1463 1464 1465 1466
        %(type)s z;
        z.real =  a.real;
        z.imag = -a.imag;
        return z;
    }
Robert Bradshaw's avatar
Robert Bradshaw committed
1467 1468
    #if %(is_float)s
        static CYTHON_INLINE %(real_type)s __Pyx_c_abs%(m)s(%(type)s z) {
1469
          #if !defined(HAVE_HYPOT) || defined(_MSC_VER)
Robert Bradshaw's avatar
Robert Bradshaw committed
1470
            return sqrt%(m)s(z.real*z.real + z.imag*z.imag);
1471 1472
          #else
            return hypot%(m)s(z.real, z.imag);
Robert Bradshaw's avatar
Robert Bradshaw committed
1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520
          #endif
        }
        static CYTHON_INLINE %(type)s __Pyx_c_pow%(m)s(%(type)s a, %(type)s b) {
            %(type)s z;
            %(real_type)s r, lnr, theta, z_r, z_theta;
            if (b.imag == 0 && b.real == (int)b.real) {
                if (b.real < 0) {
                    %(real_type)s denom = a.real * a.real + a.imag * a.imag;
                    a.real = a.real / denom;
                    a.imag = -a.imag / denom;
                    b.real = -b.real;
                }
                switch ((int)b.real) {
                    case 0:
                        z.real = 1;
                        z.imag = 0;
                        return z;
                    case 1:
                        return a;
                    case 2:
                        z = __Pyx_c_prod%(m)s(a, a);
                        return __Pyx_c_prod%(m)s(a, a);
                    case 3:
                        z = __Pyx_c_prod%(m)s(a, a);
                        return __Pyx_c_prod%(m)s(z, a);
                    case 4:
                        z = __Pyx_c_prod%(m)s(a, a);
                        return __Pyx_c_prod%(m)s(z, z);
                }
            }
            if (a.imag == 0) {
                if (a.real == 0) {
                    return a;
                }
                r = a.real;
                theta = 0;
            } else {
                r = __Pyx_c_abs%(m)s(a);
                theta = atan2%(m)s(a.imag, a.real);
            }
            lnr = log%(m)s(r);
            z_r = exp%(m)s(lnr * b.real - theta * b.imag);
            z_theta = theta * b.real + lnr * b.imag;
            z.real = z_r * cos%(m)s(z_theta);
            z.imag = z_r * sin%(m)s(z_theta);
            return z;
        }
    #endif
1521
#endif
1522
""")
1523

William Stein's avatar
William Stein committed
1524 1525 1526 1527 1528 1529 1530 1531 1532
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
1533
        if base_type in (c_char_type, c_uchar_type, c_schar_type):
William Stein's avatar
William Stein committed
1534 1535 1536
            self.is_string = 1
    
    def __repr__(self):
1537
        return "<CArrayType %s %s>" % (self.size, repr(self.base_type))
William Stein's avatar
William Stein committed
1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556
    
    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 = ""
1557 1558
        if entity_code.startswith("*"):
            entity_code = "(%s)" % entity_code
William Stein's avatar
William Stein committed
1559
        return self.base_type.declaration_code(
1560
            "%s[%s]" % (entity_code, dimension_code),
William Stein's avatar
William Stein committed
1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573
            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
1574
    default_value = "0"
William Stein's avatar
William Stein committed
1575 1576 1577 1578 1579
    
    def __init__(self, base_type):
        self.base_type = base_type
    
    def __repr__(self):
1580
        return "<CPtrType %s>" % repr(self.base_type)
William Stein's avatar
William Stein committed
1581 1582 1583 1584 1585 1586 1587 1588 1589 1590
    
    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(
1591
            "*%s" % entity_code,
William Stein's avatar
William Stein committed
1592 1593 1594 1595 1596
            for_display, dll_linkage, pyrex)
    
    def assignable_from_resolved_type(self, other_type):
        if other_type is error_type:
            return 1
1597
        if other_type.is_null_ptr:
William Stein's avatar
William Stein committed
1598
            return 1
1599 1600 1601 1602 1603 1604 1605
        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
1606 1607 1608
        if (self.base_type.is_cpp_class and other_type.is_ptr 
                and other_type.base_type.is_cpp_class and other_type.base_type.is_subclass(self.base_type)):
            return 1
1609
        if other_type.is_array or other_type.is_ptr:
1610
            return self.base_type.is_void or self.base_type.same_as(other_type.base_type)
1611
        return 0
1612 1613 1614 1615 1616 1617 1618
    
    def specialize(self, values):
        base_type = self.base_type.specialize(values)
        if base_type == self.base_type:
            return self
        else:
            return CPtrType(base_type)
William Stein's avatar
William Stein committed
1619 1620 1621 1622 1623 1624 1625


class CNullPtrType(CPtrType):

    is_null_ptr = 1
    

Robert Bradshaw's avatar
Robert Bradshaw committed
1626
class CReferenceType(BaseType):
Danilo Freitas's avatar
Danilo Freitas committed
1627 1628 1629 1630

    is_reference = 1

    def __init__(self, base_type):
Robert Bradshaw's avatar
Robert Bradshaw committed
1631
        self.ref_base_type = base_type
Danilo Freitas's avatar
Danilo Freitas committed
1632 1633

    def __repr__(self):
Robert Bradshaw's avatar
Robert Bradshaw committed
1634
        return "<CReferenceType %s>" % repr(self.ref_base_type)
Robert Bradshaw's avatar
Robert Bradshaw committed
1635 1636 1637
    
    def __str__(self):
        return "%s &" % self.ref_base_type
Robert Bradshaw's avatar
Robert Bradshaw committed
1638 1639 1640

    def as_argument_type(self):
        return self
Danilo Freitas's avatar
Danilo Freitas committed
1641 1642 1643

    def declaration_code(self, entity_code, 
            for_display = 0, dll_linkage = None, pyrex = 0):
1644
        #print "CReferenceType.declaration_code: pointer to", self.base_type ###
Robert Bradshaw's avatar
Robert Bradshaw committed
1645
        return self.ref_base_type.declaration_code(
Danilo Freitas's avatar
Danilo Freitas committed
1646 1647 1648 1649
            "&%s" % entity_code,
            for_display, dll_linkage, pyrex)
    
    def specialize(self, values):
Robert Bradshaw's avatar
Robert Bradshaw committed
1650 1651
        base_type = self.ref_base_type.specialize(values)
        if base_type == self.ref_base_type:
Danilo Freitas's avatar
Danilo Freitas committed
1652 1653 1654 1655
            return self
        else:
            return CReferenceType(base_type)

Robert Bradshaw's avatar
Robert Bradshaw committed
1656 1657 1658 1659
    def __getattr__(self, name):
        return getattr(self.ref_base_type, name)


William Stein's avatar
William Stein committed
1660 1661 1662 1663 1664
class CFuncType(CType):
    #  return_type      CType
    #  args             [CFuncTypeArg]
    #  has_varargs      boolean
    #  exception_value  string
1665 1666 1667 1668
    #  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
Danilo Freitas's avatar
Danilo Freitas committed
1669
    #  templates        [string] or None
William Stein's avatar
William Stein committed
1670 1671
    
    is_cfunction = 1
1672
    original_sig = None
William Stein's avatar
William Stein committed
1673
    
1674 1675
    def __init__(self, return_type, args, has_varargs = 0,
            exception_value = None, exception_check = 0, calling_convention = "",
Danilo Freitas's avatar
Danilo Freitas committed
1676 1677
            nogil = 0, with_gil = 0, is_overridable = 0, optional_arg_count = 0,
            templates = None):
William Stein's avatar
William Stein committed
1678 1679 1680
        self.return_type = return_type
        self.args = args
        self.has_varargs = has_varargs
1681
        self.optional_arg_count = optional_arg_count
William Stein's avatar
William Stein committed
1682 1683
        self.exception_value = exception_value
        self.exception_check = exception_check
1684 1685
        self.calling_convention = calling_convention
        self.nogil = nogil
1686
        self.with_gil = with_gil
1687
        self.is_overridable = is_overridable
Danilo Freitas's avatar
Danilo Freitas committed
1688
        self.templates = templates
William Stein's avatar
William Stein committed
1689 1690 1691 1692 1693
    
    def __repr__(self):
        arg_reprs = map(repr, self.args)
        if self.has_varargs:
            arg_reprs.append("...")
1694 1695 1696 1697 1698 1699 1700
        if self.exception_value:
            except_clause = " %r" % self.exception_value
        else:
            except_clause = ""
        if self.exception_check:
            except_clause += "?"
        return "<CFuncType %s %s[%s]%s>" % (
William Stein's avatar
William Stein committed
1701
            repr(self.return_type),
1702
            self.calling_convention_prefix(),
1703 1704
            ",".join(arg_reprs),
            except_clause)
William Stein's avatar
William Stein committed
1705
    
1706 1707 1708 1709 1710 1711 1712
    def calling_convention_prefix(self):
        cc = self.calling_convention
        if cc:
            return cc + " "
        else:
            return ""
    
William Stein's avatar
William Stein committed
1713 1714 1715 1716
    def same_c_signature_as(self, other_type, as_cmethod = 0):
        return self.same_c_signature_as_resolved_type(
            other_type.resolve(), as_cmethod)

1717
    def same_c_signature_as_resolved_type(self, other_type, as_cmethod = 0):
1718
        #print "CFuncType.same_c_signature_as_resolved_type:", \
Robert Bradshaw's avatar
Robert Bradshaw committed
1719
        #    self, other_type, "as_cmethod =", as_cmethod ###
William Stein's avatar
William Stein committed
1720 1721 1722 1723
        if other_type is error_type:
            return 1
        if not other_type.is_cfunction:
            return 0
1724
        if self.is_overridable != other_type.is_overridable:
1725
            return 0
William Stein's avatar
William Stein committed
1726
        nargs = len(self.args)
Stefan Behnel's avatar
Stefan Behnel committed
1727
        if nargs != len(other_type.args):
William Stein's avatar
William Stein committed
1728 1729 1730 1731 1732 1733 1734 1735
            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
1736
        if self.has_varargs != other_type.has_varargs:
William Stein's avatar
William Stein committed
1737
            return 0
Stefan Behnel's avatar
Stefan Behnel committed
1738
        if self.optional_arg_count != other_type.optional_arg_count:
1739
            return 0
William Stein's avatar
William Stein committed
1740 1741
        if not self.return_type.same_as(other_type.return_type):
            return 0
1742 1743
        if not self.same_calling_convention_as(other_type):
            return 0
William Stein's avatar
William Stein committed
1744
        return 1
1745

1746 1747 1748 1749 1750
    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
1751
        #    self, other_type, "as_cmethod =", as_cmethod ###
1752 1753 1754 1755
        if other_type is error_type:
            return 1
        if not other_type.is_cfunction:
            return 0
1756
        if not self.is_overridable and other_type.is_overridable:
1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771
            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
1772
        if not self.return_type.subtype_of_resolved_type(other_type.return_type):
1773 1774 1775
            return 0
        if not self.same_calling_convention_as(other_type):
            return 0
Robert Bradshaw's avatar
Robert Bradshaw committed
1776 1777
        if self.nogil != other_type.nogil:
            return 0
1778
        self.original_sig = other_type.original_sig or other_type
1779 1780 1781 1782 1783
        if as_cmethod:
            self.args[0] = other_type.args[0]
        return 1
        
        
1784 1785 1786 1787 1788 1789 1790 1791 1792
    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
1793
        if nargs != len(other_type.args):
1794 1795 1796 1797 1798 1799 1800
            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
1801
        if self.has_varargs != other_type.has_varargs:
1802
            return 0
Stefan Behnel's avatar
Stefan Behnel committed
1803
        if self.optional_arg_count != other_type.optional_arg_count:
1804
            return 0
1805 1806 1807 1808
        if not self.return_type.subtype_of_resolved_type(other_type.return_type):
            return 0
        return 1

1809
    def same_calling_convention_as(self, other):
1810 1811 1812 1813 1814 1815 1816 1817 1818
        ## 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
1819 1820 1821
        sc1 = self.calling_convention == '__stdcall'
        sc2 = other.calling_convention == '__stdcall'
        return sc1 == sc2
William Stein's avatar
William Stein committed
1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832
    
    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) \
1833 1834 1835 1836 1837 1838 1839
            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
1840 1841
    
    def declaration_code(self, entity_code, 
1842 1843
                         for_display = 0, dll_linkage = None, pyrex = 0,
                         with_calling_convention = 1):
William Stein's avatar
William Stein committed
1844
        arg_decl_list = []
1845
        for arg in self.args[:len(self.args)-self.optional_arg_count]:
William Stein's avatar
William Stein committed
1846 1847
            arg_decl_list.append(
                arg.type.declaration_code("", for_display, pyrex = pyrex))
1848 1849
        if self.is_overridable:
            arg_decl_list.append("int %s" % Naming.skip_dispatch_cname)
1850
        if self.optional_arg_count:
1851
            arg_decl_list.append(self.op_arg_struct.declaration_code(Naming.optional_args_cname))
William Stein's avatar
William Stein committed
1852 1853
        if self.has_varargs:
            arg_decl_list.append("...")
1854
        arg_decl_code = ", ".join(arg_decl_list)
William Stein's avatar
William Stein committed
1855 1856
        if not arg_decl_code and not pyrex:
            arg_decl_code = "void"
1857
        trailer = ""
1858
        if (pyrex or for_display) and not self.return_type.is_pyobject:
William Stein's avatar
William Stein committed
1859
            if self.exception_value and self.exception_check:
1860
                trailer = " except? %s" % self.exception_value
William Stein's avatar
William Stein committed
1861
            elif self.exception_value:
1862
                trailer = " except %s" % self.exception_value
Felix Wu's avatar
Felix Wu committed
1863
            elif self.exception_check == '+':
1864
                trailer = " except +"
Felix Wu's avatar
Felix Wu committed
1865
            else:
1866 1867 1868
                " except *" # ignored
            if self.nogil:
                trailer += " nogil"
1869 1870 1871 1872 1873 1874 1875
        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
1876
        return self.return_type.declaration_code(
1877
            "%s%s(%s)%s" % (cc, entity_code, arg_decl_code, trailer),
William Stein's avatar
William Stein committed
1878
            for_display, dll_linkage, pyrex)
Robert Bradshaw's avatar
Robert Bradshaw committed
1879
    
1880 1881 1882
    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
1883

1884 1885 1886 1887
    def signature_string(self):
        s = self.declaration_code("")
        return s

1888 1889 1890
    def signature_cast_string(self):
        s = self.declaration_code("(*)", with_calling_convention=False)
        return '(%s)' % s
1891
    
Robert Bradshaw's avatar
Robert Bradshaw committed
1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907
    def specialize(self, values):
        if self.templates is None:
            new_templates = None
        else:
            new_templates = [v.specialize(values) for v in self.templates]
        return CFuncType(self.return_type.specialize(values),
                             [arg.specialize(values) for arg in self.args],
                             has_varargs = 0,
                             exception_value = self.exception_value,
                             exception_check = self.exception_check,
                             calling_convention = self.calling_convention,
                             nogil = self.nogil,
                             with_gil = self.with_gil,
                             is_overridable = self.is_overridable,
                             optional_arg_count = self.optional_arg_count,
                             templates = new_templates)
Robert Bradshaw's avatar
Robert Bradshaw committed
1908
    
1909 1910
    def opt_arg_cname(self, arg_name):
        return self.op_arg_struct.base_type.scope.lookup(arg_name).cname
1911

William Stein's avatar
William Stein committed
1912

1913
class CFuncTypeArg(object):
William Stein's avatar
William Stein committed
1914 1915 1916 1917
    #  name       string
    #  cname      string
    #  type       PyrexType
    #  pos        source file position
1918 1919 1920 1921 1922 1923

    # FIXME: is this the right setup? should None be allowed here?
    not_none = False
    or_none = False
    accept_none = True

1924
    def __init__(self, name, type, pos, cname=None):
William Stein's avatar
William Stein committed
1925
        self.name = name
1926 1927 1928 1929
        if cname is not None:
            self.cname = cname
        else:
            self.cname = Naming.var_prefix + name
William Stein's avatar
William Stein committed
1930 1931
        self.type = type
        self.pos = pos
1932
        self.needs_type_test = False # TODO: should these defaults be set in analyse_types()?
William Stein's avatar
William Stein committed
1933 1934 1935 1936 1937 1938
    
    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)
Robert Bradshaw's avatar
Robert Bradshaw committed
1939 1940 1941
    
    def specialize(self, values):
        return CFuncTypeArg(self.name, self.type.specialize(values), self.pos, self.cname)
William Stein's avatar
William Stein committed
1942

Dag Sverre Seljebotn's avatar
Dag Sverre Seljebotn committed
1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980
class StructUtilityCode(object):
    def __init__(self, type, forward_decl):
        self.type = type
        self.header = "static PyObject* %s(%s)" % (type.to_py_function, type.declaration_code('s'))
        self.forward_decl = forward_decl

    def __eq__(self, other):
        return isinstance(other, StructUtilityCode) and self.header == other.header
    def __hash__(self):
        return hash(self.header)
    
    def put_code(self, output):
        code = output['utility_code_def']
        proto = output['utility_code_proto']
        
        code.putln("%s {" % self.header)
        code.putln("PyObject* res;")
        code.putln("PyObject* member;")
        code.putln("res = PyDict_New(); if (res == NULL) return NULL;")
        for member in self.type.scope.var_entries:
            nameconst_cname = code.get_py_string_const(member.name, identifier=True)
            code.putln("member = %s(s.%s); if (member == NULL) goto bad;" % (
                member.type.to_py_function, member.cname))
            code.putln("if (PyDict_SetItem(res, %s, member) < 0) goto bad;" % nameconst_cname)
            code.putln("Py_DECREF(member);")
        code.putln("return res;")
        code.putln("bad:")
        code.putln("Py_XDECREF(member);")
        code.putln("Py_DECREF(res);")
        code.putln("return NULL;")
        code.putln("}")

        # This is a bit of a hack, we need a forward declaration
        # due to the way things are ordered in the module...
        if self.forward_decl:
            proto.putln(self.type.declaration_code('') + ';')
        proto.putln(self.header + ";")
        
William Stein's avatar
William Stein committed
1981 1982 1983 1984 1985 1986 1987

class CStructOrUnionType(CType):
    #  name          string
    #  cname         string
    #  kind          string              "struct" or "union"
    #  scope         StructOrUnionScope, or None if incomplete
    #  typedef_flag  boolean
1988
    #  packed        boolean
William Stein's avatar
William Stein committed
1989
    
1990 1991
    # entry          Entry
    
William Stein's avatar
William Stein committed
1992 1993 1994
    is_struct_or_union = 1
    has_attributes = 1
    
1995
    def __init__(self, name, kind, scope, typedef_flag, cname, packed=False):
William Stein's avatar
William Stein committed
1996 1997 1998 1999 2000
        self.name = name
        self.cname = cname
        self.kind = kind
        self.scope = scope
        self.typedef_flag = typedef_flag
Robert Bradshaw's avatar
Robert Bradshaw committed
2001
        self.is_struct = kind == 'struct'
Robert Bradshaw's avatar
Robert Bradshaw committed
2002 2003 2004 2005
        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
2006
        self.packed = packed
Robert Bradshaw's avatar
Robert Bradshaw committed
2007
        
2008
    def create_to_py_utility_code(self, env):
Robert Bradshaw's avatar
Robert Bradshaw committed
2009 2010
        if env.outer_scope is None:
            return False
Dag Sverre Seljebotn's avatar
Dag Sverre Seljebotn committed
2011 2012 2013

        if self._convert_code is False: return # tri-state-ish

Robert Bradshaw's avatar
Robert Bradshaw committed
2014 2015
        if self._convert_code is None:
            for member in self.scope.var_entries:
Dag Sverre Seljebotn's avatar
Dag Sverre Seljebotn committed
2016
                if not member.type.to_py_function or not member.type.create_to_py_utility_code(env):
Robert Bradshaw's avatar
Robert Bradshaw committed
2017
                    self.to_py_function = None
Dag Sverre Seljebotn's avatar
Dag Sverre Seljebotn committed
2018
                    self._convert_code = False
Robert Bradshaw's avatar
Robert Bradshaw committed
2019
                    return False
2020
            forward_decl = (self.entry.visibility != 'extern')
Dag Sverre Seljebotn's avatar
Dag Sverre Seljebotn committed
2021
            self._convert_code = StructUtilityCode(self, forward_decl)
Robert Bradshaw's avatar
Robert Bradshaw committed
2022 2023 2024
        
        env.use_utility_code(self._convert_code)
        return True
William Stein's avatar
William Stein committed
2025 2026
        
    def __repr__(self):
2027 2028
        return "<CStructOrUnionType %s %s%s>" % (self.name, self.cname,
            ("", " typedef")[self.typedef_flag])
William Stein's avatar
William Stein committed
2029 2030 2031

    def declaration_code(self, entity_code, 
            for_display = 0, dll_linkage = None, pyrex = 0):
2032 2033
        if pyrex or for_display:
            base_code = self.name
William Stein's avatar
William Stein committed
2034
        else:
2035 2036
            if self.typedef_flag:
                base_code = self.cname
William Stein's avatar
William Stein committed
2037
            else:
2038 2039 2040
                base_code = "%s %s" % (self.kind, self.cname)
            base_code = public_decl(base_code, dll_linkage)
        return self.base_declaration_code(base_code, entity_code)
William Stein's avatar
William Stein committed
2041

2042
    def __eq__(self, other):
2043
        try:
Stefan Behnel's avatar
Stefan Behnel committed
2044 2045
            return (isinstance(other, CStructOrUnionType) and
                    self.name == other.name)
2046
        except AttributeError:
2047 2048 2049 2050 2051 2052 2053 2054 2055
            return False

    def __lt__(self, other):
        try:
            return self.name < other.name
        except AttributeError:
            # this is arbitrary, but it makes sure we always have
            # *some* kind of order
            return False
2056

Stefan Behnel's avatar
Stefan Behnel committed
2057
    def __hash__(self):
2058
        return hash(self.cname) ^ hash(self.kind)
Stefan Behnel's avatar
Stefan Behnel committed
2059

William Stein's avatar
William Stein committed
2060 2061 2062 2063 2064 2065
    def is_complete(self):
        return self.scope is not None
    
    def attributes_known(self):
        return self.is_complete()

2066
    def can_be_complex(self):
2067
        # Does the struct consist of exactly two identical floats?
2068
        fields = self.scope.var_entries
2069 2070 2071 2072 2073
        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(""))
2074

2075 2076 2077 2078
    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
2079

2080 2081 2082 2083
class CppClassType(CType):
    #  name          string
    #  cname         string
    #  scope         CppClassScope
Danilo Freitas's avatar
Danilo Freitas committed
2084
    #  templates     [string] or None
2085 2086 2087
    
    is_cpp_class = 1
    has_attributes = 1
2088
    exception_check = True
Robert Bradshaw's avatar
Robert Bradshaw committed
2089
    namespace = None
2090
    
2091
    def __init__(self, name, scope, cname, base_classes, templates = None, template_type = None):
2092 2093 2094
        self.name = name
        self.cname = cname
        self.scope = scope
DaniloFreitas's avatar
DaniloFreitas committed
2095
        self.base_classes = base_classes
DaniloFreitas's avatar
DaniloFreitas committed
2096
        self.operators = []
Danilo Freitas's avatar
Danilo Freitas committed
2097
        self.templates = templates
2098
        self.template_type = template_type
Robert Bradshaw's avatar
Robert Bradshaw committed
2099
        self.specializations = {}
2100

2101
    def specialize_here(self, pos, template_values = None):
2102 2103 2104 2105 2106
        if self.templates is None:
            error(pos, "'%s' type is not a template" % self);
            return PyrexTypes.error_type
        if len(self.templates) != len(template_values):
            error(pos, "%s templated type receives %d arguments, got %d" % 
2107 2108
                  (self.name, len(self.templates), len(template_values)))
            return error_type
2109 2110 2111
        return self.specialize(dict(zip(self.templates, template_values)))
    
    def specialize(self, values):
Robert Bradshaw's avatar
Robert Bradshaw committed
2112
        if not self.templates and not self.namespace:
2113
            return self
Robert Bradshaw's avatar
Robert Bradshaw committed
2114 2115
        if self.templates is None:
            self.templates = []
Robert Bradshaw's avatar
Robert Bradshaw committed
2116 2117 2118
        key = tuple(values.items())
        if key in self.specializations:
            return self.specializations[key]
2119
        template_values = [t.specialize(values) for t in self.templates]
Robert Bradshaw's avatar
Robert Bradshaw committed
2120
        specialized = self.specializations[key] = \
2121
            CppClassType(self.name, None, self.cname, [], template_values, template_type=self)
Robert Bradshaw's avatar
Robert Bradshaw committed
2122 2123
        # Need to do these *after* self.specializations[key] is set
        # to avoid infinite recursion on circular references.
2124
        specialized.base_classes = [b.specialize(values) for b in self.base_classes]
Robert Bradshaw's avatar
Robert Bradshaw committed
2125
        specialized.scope = self.scope.specialize(values)
Robert Bradshaw's avatar
Robert Bradshaw committed
2126 2127
        if self.namespace is not None:
            specialized.namespace = self.namespace.specialize(values)
Robert Bradshaw's avatar
Robert Bradshaw committed
2128
        return specialized
2129

2130 2131
    def declaration_code(self, entity_code,
            for_display = 0, dll_linkage = None, pyrex = 0):
Danilo Freitas's avatar
Danilo Freitas committed
2132
        if self.templates:
2133 2134
            template_strings = [param.declaration_code('', for_display, None, pyrex)
                                for param in self.templates]
Stefan Behnel's avatar
Stefan Behnel committed
2135
            templates = "<%s>" % ",".join(template_strings)
2136 2137
            if templates[-2:] == ">>":
                templates = templates[:-2] + "> >"
2138 2139
        else:
            templates = ""
2140 2141
        if pyrex or for_display:
            base_code = "%s%s" % (self.name, templates)
Robert Bradshaw's avatar
Robert Bradshaw committed
2142
        else:
2143
            base_code = "%s%s" % (self.cname, templates)
Robert Bradshaw's avatar
Robert Bradshaw committed
2144
            if self.namespace is not None:
2145 2146 2147
                base_code = "%s::%s" % (self.namespace.declaration_code(''), base_code)
            base_code = public_decl(base_code, dll_linkage)
        return self.base_declaration_code(base_code, entity_code)
2148 2149

    def is_subclass(self, other_type):
Robert Bradshaw's avatar
Robert Bradshaw committed
2150
        # TODO(danilo): Handle templates.
2151 2152
        if self.same_as_resolved_type(other_type):
            return 1
2153 2154 2155
        for base_class in self.base_classes:
            if base_class.is_subclass(other_type):
                return 1
2156
        return 0
2157 2158 2159 2160 2161
    
    def same_as_resolved_type(self, other_type):
        if other_type.is_cpp_class:
            if self == other_type:
                return 1
2162
            elif self.template_type and self.template_type == other_type.template_type:
2163 2164
                if self.templates == other_type.templates:
                    return 1
2165
                for t1, t2 in zip(self.templates, other_type.templates):
2166 2167 2168 2169
                    if not t1.same_as_resolved_type(t2):
                        return 0
                return 1
        return 0
2170

2171 2172
    def assignable_from_resolved_type(self, other_type):
        # TODO: handle operator=(...) here?
2173 2174
        if other_type is error_type:
            return True
2175 2176
        return other_type.is_cpp_class and other_type.is_subclass(self)
    
Robert Bradshaw's avatar
Robert Bradshaw committed
2177 2178 2179
    def attributes_known(self):
        return self.scope is not None

2180

2181
class TemplatePlaceholderType(CType):
Danilo Freitas's avatar
Danilo Freitas committed
2182 2183 2184 2185
    
    def __init__(self, name):
        self.name = name
    
2186 2187
    def declaration_code(self, entity_code, 
            for_display = 0, dll_linkage = None, pyrex = 0):
2188 2189 2190 2191
        if entity_code:
            return self.name + " " + entity_code
        else:
            return self.name
2192 2193 2194 2195 2196 2197 2198 2199 2200
    
    def specialize(self, values):
        if self in values:
            return values[self]
        else:
            return self

    def same_as_resolved_type(self, other_type):
        if isinstance(other_type, TemplatePlaceholderType):
2201
            return self.name == other_type.name
2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212
        else:
            return 0
        
    def __hash__(self):
        return hash(self.name)
    
    def __cmp__(self, other):
        if isinstance(other, TemplatePlaceholderType):
            return cmp(self.name, other.name)
        else:
            return cmp(type(self), type(other))
Danilo Freitas's avatar
Danilo Freitas committed
2213

2214
class CEnumType(CType):
William Stein's avatar
William Stein committed
2215 2216 2217
    #  name           string
    #  cname          string or None
    #  typedef_flag   boolean
2218

William Stein's avatar
William Stein committed
2219
    is_enum = 1
2220 2221
    signed = 1
    rank = -1 # Ranks below any integer type
2222 2223
    to_py_function = "PyInt_FromLong"
    from_py_function = "PyInt_AsLong"
William Stein's avatar
William Stein committed
2224 2225 2226 2227 2228 2229 2230

    def __init__(self, name, cname, typedef_flag):
        self.name = name
        self.cname = cname
        self.values = []
        self.typedef_flag = typedef_flag
    
2231 2232 2233
    def __str__(self):
        return self.name
    
William Stein's avatar
William Stein committed
2234
    def __repr__(self):
2235 2236
        return "<CEnumType %s %s%s>" % (self.name, self.cname,
            ("", " typedef")[self.typedef_flag])
William Stein's avatar
William Stein committed
2237 2238 2239
    
    def declaration_code(self, entity_code, 
            for_display = 0, dll_linkage = None, pyrex = 0):
2240 2241
        if pyrex or for_display:
            base_code = self.name
William Stein's avatar
William Stein committed
2242 2243
        else:
            if self.typedef_flag:
2244
                base_code = self.cname
William Stein's avatar
William Stein committed
2245
            else:
2246 2247 2248
                base_code = "enum %s" % self.cname
            base_code = public_decl(base_code, dll_linkage)
        return self.base_declaration_code(base_code, entity_code)
William Stein's avatar
William Stein committed
2249 2250


2251
class CStringType(object):
William Stein's avatar
William Stein committed
2252 2253 2254
    #  Mixin class for C string types.

    is_string = 1
2255
    is_unicode = 0
William Stein's avatar
William Stein committed
2256
    
2257 2258
    to_py_function = "PyBytes_FromString"
    from_py_function = "PyBytes_AsString"
2259
    exception_value = "NULL"
William Stein's avatar
William Stein committed
2260 2261

    def literal_code(self, value):
2262
        assert isinstance(value, str)
2263
        return '"%s"' % StringEncoding.escape_byte_string(value)
2264 2265


2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276
class CUTF8CharArrayType(CStringType, CArrayType):
    #  C 'char []' type.
    
    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
2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290
class CCharArrayType(CStringType, CArrayType):
    #  C 'char []' type.
    
    def __init__(self, size):
        CArrayType.__init__(self, c_char_type, size)
    

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


2291 2292 2293 2294 2295 2296 2297 2298 2299 2300
class CUCharPtrType(CStringType, CPtrType):
    # C 'unsigned char *' type.
    
    to_py_function = "__Pyx_PyBytes_FromUString"
    from_py_function = "__Pyx_PyBytes_AsUString"

    def __init__(self):
        CPtrType.__init__(self, c_uchar_type)


Robert Bradshaw's avatar
Robert Bradshaw committed
2301 2302
class UnspecifiedType(PyrexType):
    # Used as a placeholder until the type can be determined.
Robert Bradshaw's avatar
Robert Bradshaw committed
2303 2304
    
    is_unspecified = 1
Robert Bradshaw's avatar
Robert Bradshaw committed
2305 2306 2307 2308 2309 2310 2311 2312 2313
        
    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
2314 2315 2316 2317 2318
class ErrorType(PyrexType):
    # Used to prevent propagation of error messages.
    
    is_error = 1
    exception_value = "0"
Robert Bradshaw's avatar
Robert Bradshaw committed
2319
    exception_check    = 0
William Stein's avatar
William Stein committed
2320 2321 2322
    to_py_function = "dummy"
    from_py_function = "dummy"
    
2323 2324 2325 2326
    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
2327 2328
        return True
    
William Stein's avatar
William Stein committed
2329 2330 2331 2332 2333 2334
    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
2335 2336 2337
        
    def error_condition(self, result_code):
        return "dummy"
William Stein's avatar
William Stein committed
2338 2339


2340 2341 2342
rank_to_type_name = (
    "char",         # 0
    "short",        # 1
2343 2344 2345 2346 2347 2348
    "int",          # 2
    "long",         # 3
    "PY_LONG_LONG", # 4
    "float",        # 5
    "double",       # 6
    "long double",  # 7
2349 2350
)

2351 2352 2353 2354 2355 2356
RANK_INT  = list(rank_to_type_name).index('int')
RANK_LONG = list(rank_to_type_name).index('long')
UNSIGNED = 0
SIGNED = 2


William Stein's avatar
William Stein committed
2357 2358
py_object_type = PyObjectType()

2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371
c_void_type =        CVoidType()

c_uchar_type =       CIntType(0, UNSIGNED)
c_ushort_type =      CIntType(1, UNSIGNED)
c_uint_type =        CIntType(2, UNSIGNED)
c_ulong_type =       CIntType(3, UNSIGNED)
c_ulonglong_type =   CIntType(4, UNSIGNED)

c_char_type =        CIntType(0)
c_short_type =       CIntType(1)
c_int_type =         CIntType(2)
c_long_type =        CIntType(3)
c_longlong_type =    CIntType(4)
William Stein's avatar
William Stein committed
2372

2373 2374 2375 2376 2377 2378 2379 2380 2381
c_schar_type =       CIntType(0, SIGNED)
c_sshort_type =      CIntType(1, SIGNED)
c_sint_type =        CIntType(2, SIGNED)
c_slong_type =       CIntType(3, SIGNED)
c_slonglong_type =   CIntType(4, SIGNED)

c_float_type =       CFloatType(5, math_h_modifier='f')
c_double_type =      CFloatType(6)
c_longdouble_type =  CFloatType(7, math_h_modifier='l')
William Stein's avatar
William Stein committed
2382

2383 2384 2385
c_float_complex_type =      CComplexType(c_float_type)
c_double_complex_type =     CComplexType(c_double_type)
c_longdouble_complex_type = CComplexType(c_longdouble_type)
2386

2387 2388 2389 2390
c_anon_enum_type =   CAnonEnumType(-1)
c_returncode_type =  CReturnCodeType(RANK_INT)
c_bint_type =        CBIntType(RANK_INT)
c_py_unicode_type =  CPyUnicodeIntType(RANK_INT-0.5, UNSIGNED)
Stefan Behnel's avatar
Stefan Behnel committed
2391
c_py_ucs4_type =     CPyUCS4IntType(RANK_LONG-0.5, UNSIGNED)
2392
c_py_hash_t_type =   CPyHashTType(RANK_LONG+0.5, SIGNED)
2393 2394 2395 2396
c_py_ssize_t_type =  CPySSizeTType(RANK_LONG+0.5, SIGNED)
c_ssize_t_type =     CSSizeTType(RANK_LONG+0.5, SIGNED)
c_size_t_type =      CSizeTType(RANK_LONG+0.5, UNSIGNED)

William Stein's avatar
William Stein committed
2397
c_null_ptr_type =     CNullPtrType(c_void_type)
2398 2399
c_void_ptr_type =     CPtrType(c_void_type)
c_void_ptr_ptr_type = CPtrType(c_void_ptr_type)
William Stein's avatar
William Stein committed
2400 2401
c_char_array_type =   CCharArrayType(None)
c_char_ptr_type =     CCharPtrType()
2402
c_uchar_ptr_type =    CUCharPtrType()
2403
c_utf8_char_array_type = CUTF8CharArrayType(None)
William Stein's avatar
William Stein committed
2404 2405
c_char_ptr_ptr_type = CPtrType(c_char_ptr_type)
c_int_ptr_type =      CPtrType(c_int_type)
Stefan Behnel's avatar
Stefan Behnel committed
2406
c_py_unicode_ptr_type = CPtrType(c_py_unicode_type)
2407
c_py_ssize_t_ptr_type =  CPtrType(c_py_ssize_t_type)
2408
c_ssize_t_ptr_type =  CPtrType(c_ssize_t_type)
2409
c_size_t_ptr_type =  CPtrType(c_size_t_type)
William Stein's avatar
William Stein committed
2410

2411

2412
# the Py_buffer type is defined in Builtin.py
2413 2414
c_py_buffer_type = CStructOrUnionType("Py_buffer", "struct", None, 1, "Py_buffer")
c_py_buffer_ptr_type = CPtrType(c_py_buffer_type)
2415

William Stein's avatar
William Stein committed
2416
error_type =    ErrorType()
Robert Bradshaw's avatar
Robert Bradshaw committed
2417
unspecified_type = UnspecifiedType()
William Stein's avatar
William Stein committed
2418 2419

modifiers_and_name_to_type = {
2420 2421 2422 2423 2424
    #(signed, longness, name) : type
    (0,  0, "char"): c_uchar_type,
    (1,  0, "char"): c_char_type,
    (2,  0, "char"): c_schar_type,

2425
    (0, -1, "int"): c_ushort_type,
2426 2427 2428 2429
    (0,  0, "int"): c_uint_type,
    (0,  1, "int"): c_ulong_type,
    (0,  2, "int"): c_ulonglong_type,

2430
    (1, -1, "int"): c_short_type,
2431 2432 2433 2434
    (1,  0, "int"): c_int_type,
    (1,  1, "int"): c_long_type,
    (1,  2, "int"): c_longlong_type,

2435
    (2, -1, "int"): c_sshort_type,
2436 2437 2438 2439 2440 2441 2442
    (2,  0, "int"): c_sint_type,
    (2,  1, "int"): c_slong_type,
    (2,  2, "int"): c_slonglong_type,

    (1,  0, "float"):  c_float_type,
    (1,  0, "double"): c_double_type,
    (1,  1, "double"): c_longdouble_type,
2443

2444
    (1,  0, "complex"):  c_double_complex_type,  # C: float, Python: double => Python wins
2445 2446 2447 2448 2449 2450
    (1,  0, "floatcomplex"):  c_float_complex_type,
    (1,  0, "doublecomplex"): c_double_complex_type,
    (1,  1, "doublecomplex"): c_longdouble_complex_type,

    #
    (1,  0, "void"): c_void_type,
2451 2452 2453

    (1,  0, "bint"):       c_bint_type,
    (0,  0, "Py_UNICODE"): c_py_unicode_type,
Stefan Behnel's avatar
Stefan Behnel committed
2454
    (0,  0, "Py_UCS4"):    c_py_ucs4_type,
2455
    (2,  0, "Py_hash_t"):  c_py_hash_t_type,
2456 2457 2458 2459
    (2,  0, "Py_ssize_t"): c_py_ssize_t_type,
    (2,  0, "ssize_t") :   c_ssize_t_type,
    (0,  0, "size_t") :    c_size_t_type,

2460
    (1,  0, "object"): py_object_type,
William Stein's avatar
William Stein committed
2461 2462
}

2463 2464 2465 2466 2467
def is_promotion(src_type, dst_type):
    # It's hard to find a hard definition of promotion, but empirical
    # evidence suggests that the below is all that's allowed. 
    if src_type.is_numeric:
        if dst_type.same_as(c_int_type):
2468 2469 2470 2471
            unsigned = (not src_type.signed)
            return (src_type.is_enum or
                    (src_type.is_int and
                     unsigned + src_type.rank < dst_type.rank))
2472 2473 2474 2475
        elif dst_type.same_as(c_double_type):
            return src_type.is_float and src_type.rank <= dst_type.rank
    return False

2476
def best_match(args, functions, pos=None):
Robert Bradshaw's avatar
merge  
Robert Bradshaw committed
2477
    """
2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496
    Given a list args of arguments and a list of functions, choose one
    to call which seems to be the "best" fit for this list of arguments.
    This function is used, e.g., when deciding which overloaded method
    to dispatch for C++ classes.

    We first eliminate functions based on arity, and if only one
    function has the correct arity, we return it. Otherwise, we weight
    functions based on how much work must be done to convert the
    arguments, with the following priorities:
      * identical types or pointers to identical types
      * promotions 
      * non-Python types
    That is, we prefer functions where no arguments need converted,
    and failing that, functions where only promotions are required, and
    so on.

    If no function is deemed a good fit, or if two or more functions have
    the same weight, we return None (as there is no best match). If pos
    is not None, we also generate an error.
Robert Bradshaw's avatar
merge  
Robert Bradshaw committed
2497
    """
2498
    # TODO: args should be a list of types, not a list of Nodes. 
2499
    actual_nargs = len(args)
2500 2501 2502

    candidates = []
    errors = []
2503
    for func in functions:
2504
        error_mesg = ""
2505 2506 2507
        func_type = func.type
        if func_type.is_ptr:
            func_type = func_type.base_type
2508 2509
        # Check function type
        if not func_type.is_cfunction:
2510
            if not func_type.is_error and pos is not None:
2511 2512 2513
                error_mesg = "Calling non-function type '%s'" % func_type
            errors.append((func, error_mesg))
            continue
2514 2515 2516
        # Check no. of args
        max_nargs = len(func_type.args)
        min_nargs = max_nargs - func_type.optional_arg_count
2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532
        if actual_nargs < min_nargs or \
            (not func_type.has_varargs and actual_nargs > max_nargs):
            if max_nargs == min_nargs and not func_type.has_varargs:
                expectation = max_nargs
            elif actual_nargs < min_nargs:
                expectation = "at least %s" % min_nargs
            else:
                expectation = "at most %s" % max_nargs
            error_mesg = "Call with wrong number of arguments (expected %s, got %s)" \
                         % (expectation, actual_nargs)
            errors.append((func, error_mesg))
            continue
        candidates.append((func, func_type))
        
    # Optimize the most common case of no overloading...
    if len(candidates) == 1:
2533
        return candidates[0][0]
2534
    elif len(candidates) == 0:
2535 2536 2537 2538 2539
        if pos is not None:
            if len(errors) == 1:
                error(pos, errors[0][1])
            else:
                error(pos, "no suitable method found")
2540 2541 2542 2543 2544
        return None
        
    possibilities = []
    bad_types = []
    for func, func_type in candidates:
2545
        score = [0,0,0]
2546
        for i in range(min(len(args), len(func_type.args))):
2547 2548 2549
            src_type = args[i].type
            dst_type = func_type.args[i].type
            if dst_type.assignable_from(src_type):
Robert Bradshaw's avatar
Robert Bradshaw committed
2550
                if src_type == dst_type or dst_type.same_as(src_type):
2551 2552 2553 2554 2555 2556 2557 2558
                    pass # score 0
                elif is_promotion(src_type, dst_type):
                    score[2] += 1
                elif not src_type.is_pyobject:
                    score[1] += 1
                else:
                    score[0] += 1
            else:
2559 2560 2561
                error_mesg = "Invalid conversion from '%s' to '%s'"%(src_type,
                                                                     dst_type)
                bad_types.append((func, error_mesg))
2562 2563 2564
                break
        else:
            possibilities.append((score, func)) # so we can sort it
2565
    if possibilities:
2566 2567
        possibilities.sort()
        if len(possibilities) > 1 and possibilities[0][0] == possibilities[1][0]:
2568 2569
            if pos is not None:
                error(pos, "ambiguous overloaded method")
2570 2571
            return None
        return possibilities[0][1]
2572
    if pos is not None:
2573 2574
        if len(bad_types) == 1:
            error(pos, bad_types[0][1])
2575
        else:
2576
            error(pos, "no suitable method found")
2577 2578
    return None

William Stein's avatar
William Stein committed
2579 2580 2581
def widest_numeric_type(type1, type2):
    # Given two numeric types, return the narrowest type
    # encompassing both of them.
2582
    if type1 == type2:
2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600
        widest_type = type1
    elif type1.is_complex or type2.is_complex:
        def real_type(ntype):
            if ntype.is_complex:
                return ntype.real_type
            return ntype
        widest_type = CComplexType(
            widest_numeric_type(
                real_type(type1), 
                real_type(type2)))
    elif type1.is_enum and type2.is_enum:
        widest_type = c_int_type
    elif type1.rank < type2.rank:
        widest_type = type2
    elif type1.rank > type2.rank:
        widest_type = type1
    elif type1.signed < type2.signed:
        widest_type = type1
2601
    else:
2602 2603
        widest_type = type2
    return widest_type
William Stein's avatar
William Stein committed
2604

2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617
def independent_spanning_type(type1, type2):
    # Return a type assignable independently from both type1 and
    # type2, but do not require any interoperability between the two.
    # For example, in "True * 2", it is safe to assume an integer
    # result type (so spanning_type() will do the right thing),
    # whereas "x = True or 2" must evaluate to a type that can hold
    # both a boolean value and an integer, so this function works
    # better.
    if type1 == type2:
        return type1
    elif (type1 is c_bint_type or type2 is c_bint_type) and (type1.is_numeric and type2.is_numeric):
        # special case: if one of the results is a bint and the other
        # is another C integer, we must prevent returning a numeric
Craig Citro's avatar
Craig Citro committed
2618
        # type so that we do not lose the ability to coerce to a
2619
        # Python bool if we have to.
Robert Bradshaw's avatar
Robert Bradshaw committed
2620
        return py_object_type
2621 2622
    span_type = _spanning_type(type1, type2)
    if span_type is None:
Stefan Behnel's avatar
Stefan Behnel committed
2623
        return error_type
2624 2625 2626 2627 2628 2629 2630 2631
    return span_type

def spanning_type(type1, type2):
    # Return a type assignable from both type1 and type2, or
    # py_object_type if no better type is found.  Assumes that the
    # code that calls this will try a coercion afterwards, which will
    # fail if the types cannot actually coerce to a py_object_type.
    if type1 == type2:
Robert Bradshaw's avatar
Robert Bradshaw committed
2632
        return type1
2633 2634
    elif type1 is py_object_type or type2 is py_object_type:
        return py_object_type
2635 2636 2637
    elif type1 is c_py_unicode_type or type2 is c_py_unicode_type:
        # Py_UNICODE behaves more like a string than an int
        return py_object_type
2638 2639 2640 2641 2642 2643 2644
    span_type = _spanning_type(type1, type2)
    if span_type is None:
        return py_object_type
    return span_type

def _spanning_type(type1, type2):
    if type1.is_numeric and type2.is_numeric:
Robert Bradshaw's avatar
Robert Bradshaw committed
2645
        return widest_numeric_type(type1, type2)
2646 2647 2648 2649
    elif type1.is_builtin_type and type1.name == 'float' and type2.is_numeric:
        return widest_numeric_type(c_double_type, type2)
    elif type2.is_builtin_type and type2.name == 'float' and type1.is_numeric:
        return widest_numeric_type(type1, c_double_type)
2650
    elif type1.is_extension_type and type2.is_extension_type:
2651 2652 2653
        return widest_extension_type(type1, type2)
    elif type1.is_pyobject or type2.is_pyobject:
        return py_object_type
Robert Bradshaw's avatar
Robert Bradshaw committed
2654
    elif type1.assignable_from(type2):
2655 2656 2657
        if type1.is_extension_type and type1.typeobj_is_imported():
            # external types are unsafe, so we use PyObject instead
            return py_object_type
Robert Bradshaw's avatar
Robert Bradshaw committed
2658
        return type1
2659
    elif type2.assignable_from(type1):
2660 2661 2662
        if type2.is_extension_type and type2.typeobj_is_imported():
            # external types are unsafe, so we use PyObject instead
            return py_object_type
Robert Bradshaw's avatar
Robert Bradshaw committed
2663 2664
        return type2
    else:
2665 2666 2667 2668
        return None

def widest_extension_type(type1, type2):
    if type1.typeobj_is_imported() or type2.typeobj_is_imported():
Robert Bradshaw's avatar
Robert Bradshaw committed
2669
        return py_object_type
2670 2671 2672 2673 2674 2675 2676 2677 2678
    while True:
        if type1.subtype_of(type2):
            return type2
        elif type2.subtype_of(type1):
            return type1
        type1, type2 = type1.base_type, type2.base_type
        if type1 is None or type2 is None:
            return py_object_type

William Stein's avatar
William Stein committed
2679 2680 2681 2682
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))
2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693
    
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)
2694 2695 2696 2697 2698 2699 2700
    #
    basic_type = simple_c_type(1, 0, name)
    if basic_type:
        return basic_type
    #
    signed = 1
    longness = 0
2701 2702
    if name == 'Py_UNICODE':
        signed = 0
Stefan Behnel's avatar
Stefan Behnel committed
2703 2704
    elif name == 'Py_UCS4':
        signed = 0
2705 2706
    elif name == 'Py_hash_t':
        signed = 2
2707 2708 2709
    elif name == 'Py_ssize_t':
        signed = 2
    elif name == 'ssize_t':
2710 2711 2712
        signed = 2
    elif name == 'size_t':
        signed = 0
2713
    else:
2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730
        if name.startswith('u'):
            name = name[1:]
            signed = 0
        elif (name.startswith('s') and 
              not name.startswith('short')):
            name = name[1:]
            signed = 2
        longness = 0
        while name.startswith('short'):
            name = name.replace('short', '', 1).strip()
            longness -= 1
        while name.startswith('long'):
            name = name.replace('long', '', 1).strip()
            longness += 1
        if longness != 0 and not name:
            name = 'int'
    return simple_c_type(signed, longness, name)
William Stein's avatar
William Stein committed
2731 2732 2733 2734 2735

def c_array_type(base_type, size):
    # Construct a C array type.
    if base_type is c_char_type:
        return CCharArrayType(size)
2736 2737
    elif base_type is error_type:
        return error_type
William Stein's avatar
William Stein committed
2738 2739 2740 2741 2742 2743 2744
    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
2745 2746
    elif base_type is c_uchar_type:
        return c_uchar_ptr_type
2747 2748
    elif base_type is error_type:
        return error_type
William Stein's avatar
William Stein committed
2749 2750 2751
    else:
        return CPtrType(base_type)

Danilo Freitas's avatar
Danilo Freitas committed
2752 2753
def c_ref_type(base_type):
    # Construct a C reference type
2754
    if base_type is error_type:
Danilo Freitas's avatar
Danilo Freitas committed
2755 2756 2757
        return error_type
    else:
        return CReferenceType(base_type)
William Stein's avatar
William Stein committed
2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774

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)
2775 2776 2777 2778 2779


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

2780 2781
#define __Pyx_PyBytes_FromUString(s) PyBytes_FromString((char*)s)
#define __Pyx_PyBytes_AsUString(s)   ((unsigned char*) PyBytes_AsString(s))
2782

2783
#define __Pyx_PyBool_FromLong(b) ((b) ? (Py_INCREF(Py_True), Py_True) : (Py_INCREF(Py_False), Py_False))
2784 2785
static CYTHON_INLINE int __Pyx_PyObject_IsTrue(PyObject*);
static CYTHON_INLINE PyObject* __Pyx_PyNumber_Int(PyObject* x);
2786

2787 2788 2789
static CYTHON_INLINE Py_ssize_t __Pyx_PyIndex_AsSsize_t(PyObject*);
static CYTHON_INLINE PyObject * __Pyx_PyInt_FromSize_t(size_t);
static CYTHON_INLINE size_t __Pyx_PyInt_AsSize_t(PyObject*);
2790

2791
#define __pyx_PyFloat_AsDouble(x) (PyFloat_CheckExact(x) ? PyFloat_AS_DOUBLE(x) : PyFloat_AsDouble(x))
2792

2793 2794
""" + type_conversion_predeclarations

2795
# Note: __Pyx_PyObject_IsTrue is written to minimize branching.
2796 2797 2798
type_conversion_functions = """
/* Type Conversion Functions */

2799
static CYTHON_INLINE int __Pyx_PyObject_IsTrue(PyObject* x) {
2800 2801
   int is_true = x == Py_True;
   if (is_true | (x == Py_False) | (x == Py_None)) return is_true;
2802 2803 2804
   else return PyObject_IsTrue(x);
}

2805
static CYTHON_INLINE PyObject* __Pyx_PyNumber_Int(PyObject* x) {
2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816
  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
2817
  if (m && m->nb_int) {
2818 2819 2820
    name = "int";
    res = PyNumber_Int(x);
  }
2821 2822 2823 2824
  else if (m && m->nb_long) {
    name = "long";
    res = PyNumber_Long(x);
  }
2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850
#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;
}

2851
static CYTHON_INLINE Py_ssize_t __Pyx_PyIndex_AsSsize_t(PyObject* b) {
2852 2853 2854 2855 2856 2857 2858 2859
  Py_ssize_t ival;
  PyObject* x = PyNumber_Index(b);
  if (!x) return -1;
  ival = PyInt_AsSsize_t(x);
  Py_DECREF(x);
  return ival;
}

2860
static CYTHON_INLINE PyObject * __Pyx_PyInt_FromSize_t(size_t ival) {
2861
#if PY_VERSION_HEX < 0x02050000
2862
   if (ival <= LONG_MAX)
2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873
       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
}

2874
static CYTHON_INLINE size_t __Pyx_PyInt_AsSize_t(PyObject* x) {
2875
   unsigned PY_LONG_LONG val = __Pyx_PyInt_AsUnsignedLongLong(x);
2876 2877 2878
   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)) {
2879 2880
       PyErr_SetString(PyExc_OverflowError,
                       "value too large to convert to size_t");
2881 2882
       return (size_t)-1;
   }
2883
   return (size_t)val;
2884 2885 2886
}

""" + type_conversion_functions
2887