ModuleNode.py 104 KB
Newer Older
1 2 3 4 5
#
#   Pyrex - Module parse tree node
#

import os, time
6
from PyrexTypes import CPtrType
Robert Bradshaw's avatar
Robert Bradshaw committed
7
import Future
8

9 10 11 12 13
try:
    set
except NameError: # Python 2.3
    from sets import Set as set

14
import Annotate
15 16 17 18 19 20 21
import Code
import Naming
import Nodes
import Options
import PyrexTypes
import TypeSlots
import Version
22
import DebugFlags
23

24
from Errors import error, warning
25
from PyrexTypes import py_object_type
26 27
from Cython.Utils import open_new_file, replace_suffix
from Code import UtilityCode
28
from StringEncoding import escape_byte_string, EncodedString
29

Gary Furnish's avatar
Gary Furnish committed
30

31 32 33 34
def check_c_declarations_pxd(module_node):
    module_node.scope.check_c_classes_pxd()
    return module_node

35
def check_c_declarations(module_node):
36
    module_node.scope.check_c_classes()
37
    module_node.scope.check_c_functions()
38 39
    return module_node

40 41 42
class ModuleNode(Nodes.Node, Nodes.BlockNode):
    #  doc       string or None
    #  body      StatListNode
43 44
    #
    #  referenced_modules   [ModuleScope]
45
    #  full_module_name     string
46 47 48
    #
    #  scope                The module scope.
    #  compilation_source   A CompilationSource (see Main)
49
    #  directives           Top-level compiler directives
50

51
    child_attrs = ["body"]
52
    directives = None
53 54
    
    def analyse_declarations(self, env):
55
        if Options.embed_pos_in_docstring:
Robert Bradshaw's avatar
Robert Bradshaw committed
56
            env.doc = EncodedString(u'File: %s (starting at line %s)' % Nodes.relative_position(self.pos))
57
            if not self.doc is None:
58
                env.doc = EncodedString(env.doc + u'\n' + self.doc)
Robert Bradshaw's avatar
Robert Bradshaw committed
59
                env.doc.encoding = self.doc.encoding
60 61
        else:
            env.doc = self.doc
62
        env.directives = self.directives
63 64
        self.body.analyse_declarations(env)
    
65 66
    def process_implementation(self, options, result):
        env = self.scope
67
        env.return_type = PyrexTypes.c_void_type
68 69
        self.referenced_modules = []
        self.find_referenced_modules(env, self.referenced_modules, {})
70 71
        if options.recursive:
            self.generate_dep_file(env, result)
72
        self.generate_c_code(env, options, result)
73 74
        self.generate_h_code(env, options, result)
        self.generate_api_code(env, result)
75
    
76 77 78 79 80 81 82
    def has_imported_c_functions(self):
        for module in self.referenced_modules:
            for entry in module.cfunc_entries:
                if entry.defined_in_pxd:
                    return 1
        return 0
    
83 84 85 86 87 88 89 90 91 92 93 94 95 96
    def generate_dep_file(self, env, result):
        modules = self.referenced_modules
        if len(modules) > 1 or env.included_files:
            dep_file = replace_suffix(result.c_file, ".dep")
            f = open(dep_file, "w")
            try:
                for module in modules:
                    if module is not env:
                        f.write("cimport %s\n" % module.qualified_name)
                    for path in module.included_files:
                        f.write("include %s\n" % path)
            finally:
                f.close()

97
    def generate_h_code(self, env, options, result):
Stefan Behnel's avatar
Stefan Behnel committed
98 99 100 101 102 103 104 105
        def h_entries(entries, pxd = 0):
            return [entry for entry in entries
                if entry.visibility == 'public' or pxd and entry.defined_in_pxd]
        h_types = h_entries(env.type_entries)
        h_vars = h_entries(env.var_entries)
        h_funcs = h_entries(env.cfunc_entries)
        h_extension_types = h_entries(env.c_class_entries)
        if h_types or h_vars or h_funcs or h_extension_types:
106
            result.h_file = replace_suffix(result.c_file, ".h")
107
            h_code = Code.CCodeWriter()
108
            Code.GlobalState(h_code)
109 110 111 112 113 114 115
            if options.generate_pxi:
                result.i_file = replace_suffix(result.c_file, ".pxi")
                i_code = Code.PyrexCodeWriter(result.i_file)
            else:
                i_code = None
            guard = Naming.h_guard_prefix + env.qualified_name.replace(".", "__")
            h_code.put_h_guard(guard)
116
            self.generate_extern_c_macro_definition(h_code)
Stefan Behnel's avatar
Stefan Behnel committed
117
            self.generate_type_header_code(h_types, h_code)
118 119
            h_code.putln("")
            h_code.putln("#ifndef %s" % Naming.api_guard_prefix + self.api_name(env))
Stefan Behnel's avatar
Stefan Behnel committed
120
            if h_vars:
121
                h_code.putln("")
Stefan Behnel's avatar
Stefan Behnel committed
122
                for entry in h_vars:
123
                    self.generate_public_declaration(entry, h_code, i_code)
Stefan Behnel's avatar
Stefan Behnel committed
124
            if h_funcs:
125
                h_code.putln("")
Stefan Behnel's avatar
Stefan Behnel committed
126
                for entry in h_funcs:
127
                    self.generate_public_declaration(entry, h_code, i_code)
Stefan Behnel's avatar
Stefan Behnel committed
128
            if h_extension_types:
129
                h_code.putln("")
Stefan Behnel's avatar
Stefan Behnel committed
130
                for entry in h_extension_types:
131 132 133 134 135 136
                    self.generate_cclass_header_code(entry.type, h_code)
                    if i_code:
                        self.generate_cclass_include_code(entry.type, i_code)
            h_code.putln("")
            h_code.putln("#endif")
            h_code.putln("")
137
            h_code.putln("PyMODINIT_FUNC init%s(void);" % env.module_name)
138 139
            h_code.putln("")
            h_code.putln("#endif")
140 141
            
            h_code.copyto(open_new_file(result.h_file))
142 143 144 145 146 147 148 149 150 151 152 153 154 155 156
    
    def generate_public_declaration(self, entry, h_code, i_code):
        h_code.putln("%s %s;" % (
            Naming.extern_c_macro,
            entry.type.declaration_code(
                entry.cname, dll_linkage = "DL_IMPORT")))
        if i_code:
            i_code.putln("cdef extern %s" % 
                entry.type.declaration_code(entry.cname, pyrex = 1))
    
    def api_name(self, env):
        return env.qualified_name.replace(".", "__")
    
    def generate_api_code(self, env, result):
        api_funcs = []
Stefan Behnel's avatar
Stefan Behnel committed
157 158
        public_extension_types = []
        has_api_extension_types = 0
159 160 161 162 163 164
        for entry in env.cfunc_entries:
            if entry.api:
                api_funcs.append(entry)
        for entry in env.c_class_entries:
            if entry.visibility == 'public':
                public_extension_types.append(entry)
Stefan Behnel's avatar
Stefan Behnel committed
165 166 167
            if entry.api:
                has_api_extension_types = 1
        if api_funcs or has_api_extension_types:
168
            result.api_file = replace_suffix(result.c_file, "_api.h")
169
            h_code = Code.CCodeWriter()
170
            Code.GlobalState(h_code)
171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189
            name = self.api_name(env)
            guard = Naming.api_guard_prefix + name
            h_code.put_h_guard(guard)
            h_code.putln('#include "Python.h"')
            if result.h_file:
                h_code.putln('#include "%s"' % os.path.basename(result.h_file))
            for entry in public_extension_types:
                type = entry.type
                h_code.putln("")
                h_code.putln("static PyTypeObject *%s;" % type.typeptr_cname)
                h_code.putln("#define %s (*%s)" % (
                    type.typeobj_cname, type.typeptr_cname))
            if api_funcs:
                h_code.putln("")
                for entry in api_funcs:
                    type = CPtrType(entry.type)
                    h_code.putln("static %s;" % type.declaration_code(entry.cname))
            h_code.putln("")
            h_code.put_h_guard(Naming.api_func_guard + "import_module")
190
            h_code.put(import_module_utility_code.impl)
191 192 193 194
            h_code.putln("")
            h_code.putln("#endif")
            if api_funcs:
                h_code.putln("")
195
                h_code.put(function_import_utility_code.impl)
196 197
            if public_extension_types:
                h_code.putln("")
198
                h_code.put(type_import_utility_code.impl)
199 200 201
            h_code.putln("")
            h_code.putln("static int import_%s(void) {" % name)
            h_code.putln("PyObject *module = 0;")
202
            h_code.putln('module = __Pyx_ImportModule("%s");' % env.qualified_name)
203 204 205 206
            h_code.putln("if (!module) goto bad;")
            for entry in api_funcs:
                sig = entry.type.signature_string()
                h_code.putln(
207
                    'if (__Pyx_ImportFunction(module, "%s", (void (**)(void))&%s, "%s") < 0) goto bad;' % (
208 209 210
                        entry.name,
                        entry.cname,
                        sig))
211
            h_code.putln("Py_DECREF(module); module = 0;")
212
            for entry in public_extension_types:
213 214 215
                self.generate_type_import_call(
                    entry.type, h_code,
                    "if (!%s) goto bad;" % entry.type.typeptr_cname)
216 217 218 219 220 221 222
            h_code.putln("return 0;")
            h_code.putln("bad:")
            h_code.putln("Py_XDECREF(module);")
            h_code.putln("return -1;")
            h_code.putln("}")
            h_code.putln("")
            h_code.putln("#endif")
223
            
224
            h_code.copyto(open_new_file(result.api_file))
225 226 227 228 229
    
    def generate_cclass_header_code(self, type, h_code):
        h_code.putln("%s DL_IMPORT(PyTypeObject) %s;" % (
            Naming.extern_c_macro,
            type.typeobj_cname))
230
        #self.generate_obj_struct_definition(type, h_code)
231 232 233 234 235 236 237 238 239 240 241 242 243
    
    def generate_cclass_include_code(self, type, i_code):
        i_code.putln("cdef extern class %s.%s:" % (
            type.module_name, type.name))
        i_code.indent()
        var_entries = type.scope.var_entries
        if var_entries:
            for entry in var_entries:
                i_code.putln("cdef %s" % 
                    entry.type.declaration_code(entry.cname, pyrex = 1))
        else:
            i_code.putln("pass")
        i_code.dedent()
Stefan Behnel's avatar
Stefan Behnel committed
244
    
245
    def generate_c_code(self, env, options, result):
246
        modules = self.referenced_modules
247

248
        if Options.annotate or options.annotate:
249 250
            emit_linenums = False
            rootwriter = Annotate.AnnotationCCodeWriter()
251
        else:
252 253 254
            emit_linenums = options.emit_linenums
            rootwriter = Code.CCodeWriter(emit_linenums=emit_linenums)
        globalstate = Code.GlobalState(rootwriter, emit_linenums)
255
        globalstate.initialize_main_c_code()
256 257
        h_code = globalstate['h_code']
        
258
        self.generate_module_preamble(env, modules, h_code)
259

260 261
        globalstate.module_pos = self.pos
        globalstate.directives = self.directives
262

263
        globalstate.use_utility_code(refnanny_utility_code)
264

265
        code = globalstate['before_global_var']
266
        code.putln('#define __Pyx_MODULE_NAME "%s"' % self.full_module_name)
267
        code.putln("int %s%s = 0;" % (Naming.module_is_main, self.full_module_name.replace('.', '__')))
268 269
        code.putln("")
        code.putln("/* Implementation of %s */" % env.qualified_name)
270

271
        code = globalstate['all_the_rest']
272

273
        self.generate_cached_builtins_decls(env, code)
274
        self.body.generate_function_definitions(env, code)
Robert Bradshaw's avatar
Robert Bradshaw committed
275
        code.mark_pos(None)
276 277 278
        self.generate_typeobj_definitions(env, code)
        self.generate_method_table(env, code)
        self.generate_filename_init_prototype(code)
Dag Sverre Seljebotn's avatar
Merge  
Dag Sverre Seljebotn committed
279 280
        if env.has_import_star:
            self.generate_import_star(env, code)
281
        self.generate_pymoduledef_struct(env, code)
282 283 284 285

        # init_globals is inserted before this
        self.generate_module_init_func(modules[:-1], env, globalstate['init_module'])
        self.generate_module_cleanup_func(env, globalstate['cleanup_module'])
286
        if Options.embed:
287 288
            self.generate_main_method(env, globalstate['main_method'])
        self.generate_filename_table(globalstate['filename_table'])
289
        
290
        self.generate_declarations_for_modules(env, modules, globalstate)
291
        h_code.write('\n')
Gary Furnish's avatar
Gary Furnish committed
292

293 294
        for utilcode in env.utility_code_list:
            globalstate.use_utility_code(utilcode)
295
        globalstate.finalize_main_c_code()
296
        
297
        f = open_new_file(result.c_file)
298
        rootwriter.copyto(f)
299 300
        f.close()
        result.c_file_generated = 1
301
        if Options.annotate or options.annotate:
302 303
            self.annotate(rootwriter)
            rootwriter.save_annotation(result.main_source_file, result.c_file)
304 305 306 307 308 309 310
    
    def find_referenced_modules(self, env, module_list, modules_seen):
        if env not in modules_seen:
            modules_seen[env] = 1
            for imported_module in env.cimported_modules:
                self.find_referenced_modules(imported_module, module_list, modules_seen)
            module_list.append(env)
Gary Furnish's avatar
Gary Furnish committed
311

312 313 314 315 316 317 318 319 320
    def sort_types_by_inheritance(self, type_dict, getkey):
        # copy the types into a list moving each parent type before
        # its first child
        type_items = type_dict.items()
        type_list = []
        for i, item in enumerate(type_items):
            key, new_entry = item

            # collect all base classes to check for children
321
            hierarchy = set()
322
            base = new_entry
323 324 325 326 327 328 329
            while base:
                base_type = base.type.base_type
                if not base_type:
                    break
                base_key = getkey(base_type)
                hierarchy.add(base_key)
                base = type_dict.get(base_key)
330
            new_entry.base_keys = hierarchy
331

332
            # find the first (sub-)subclass and insert before that
333 334
            for j in range(i):
                entry = type_list[j]
335
                if key in entry.base_keys:
336 337 338 339 340 341 342
                    type_list.insert(j, new_entry)
                    break
            else:
                type_list.append(new_entry)
        return type_list

    def sort_type_hierarchy(self, module_list, env):
Gary Furnish's avatar
Gary Furnish committed
343
        vtab_dict = {}
344
        vtabslot_dict = {}
Gary Furnish's avatar
Gary Furnish committed
345 346 347 348 349
        for module in module_list:
            for entry in module.c_class_entries:
                if not entry.in_cinclude:
                    type = entry.type
                    if type.vtabstruct_cname:
350 351 352 353
                        vtab_dict[type.vtabstruct_cname] = entry
            all_defined_here = module is env
            for entry in module.type_entries:
                if all_defined_here or entry.defined_in_pxd:
Gary Furnish's avatar
Gary Furnish committed
354
                    type = entry.type
355 356 357 358 359 360
                    if type.is_extension_type and not entry.in_cinclude:
                        type = entry.type
                        vtabslot_dict[type.objstruct_cname] = entry
                
        def vtabstruct_cname(entry_type):
            return entry_type.vtabstruct_cname
361 362
        vtab_list = self.sort_types_by_inheritance(
            vtab_dict, vtabstruct_cname)
363 364 365

        def objstruct_cname(entry_type):
            return entry_type.objstruct_cname
366 367
        vtabslot_list = self.sort_types_by_inheritance(
            vtabslot_dict, objstruct_cname)
368

369
        return (vtab_list, vtabslot_list)
370

Gary Furnish's avatar
Gary Furnish committed
371
    def generate_type_definitions(self, env, modules, vtab_list, vtabslot_list, code):
372
        vtabslot_entries = set(vtabslot_list)
Gary Furnish's avatar
Gary Furnish committed
373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391
        for module in modules:
            definition = module is env
            if definition:
                type_entries = module.type_entries
            else:
                type_entries = []
                for entry in module.type_entries:
                    if entry.defined_in_pxd:
                        type_entries.append(entry)
            for entry in type_entries:
                if not entry.in_cinclude:
                    #print "generate_type_header_code:", entry.name, repr(entry.type) ###
                    type = entry.type
                    if type.is_typedef: # Must test this first!
                        self.generate_typedef(entry, code)
                    elif type.is_struct_or_union:
                        self.generate_struct_union_definition(entry, code)
                    elif type.is_enum:
                        self.generate_enum_definition(entry, code)
392
                    elif type.is_extension_type and entry not in vtabslot_entries:
Gary Furnish's avatar
Gary Furnish committed
393 394 395 396 397 398 399
                        self.generate_obj_struct_definition(type, code)
        for entry in vtabslot_list:
            self.generate_obj_struct_definition(entry.type, code)
        for entry in vtab_list:
            self.generate_typeobject_predeclaration(entry, code)
            self.generate_exttype_vtable_struct(entry, code)
            self.generate_exttype_vtabptr_declaration(entry, code)
Gary Furnish's avatar
Gary Furnish committed
400

401 402 403 404
    def generate_declarations_for_modules(self, env, modules, globalstate):
        typecode = globalstate['type_declarations']
        typecode.putln("")
        typecode.putln("/* Type declarations */")
405 406
        vtab_list, vtabslot_list = self.sort_type_hierarchy(modules, env)
        self.generate_type_definitions(
407 408
            env, modules, vtab_list, vtabslot_list, typecode)
        modulecode = globalstate['module_declarations']
Gary Furnish's avatar
Gary Furnish committed
409
        for module in modules:
410
            defined_here = module is env
411
            modulecode.putln("/* Module declarations from %s */" %
Stefan Behnel's avatar
Stefan Behnel committed
412
                       module.qualified_name.encode("ASCII", "ignore"))
413 414
            self.generate_global_declarations(module, modulecode, defined_here)
            self.generate_cfunction_predeclarations(module, modulecode, defined_here)
Gary Furnish's avatar
Gary Furnish committed
415

416
    def generate_module_preamble(self, env, cimported_modules, code):
417
        code.putln('/* Generated by Cython %s on %s */' % (
418 419
            Version.version, time.asctime()))
        code.putln('')
420
        code.putln('#define PY_SSIZE_T_CLEAN')
421 422
        for filename in env.python_include_files:
            code.putln('#include "%s"' % filename)
423 424
        code.putln("#ifndef Py_PYTHON_H")
        code.putln("    #error Python headers needed to compile C extensions, please install development version of Python.")
425 426
        code.putln("#else")
        code.globalstate["end"].putln("#endif /* Py_PYTHON_H */")
427 428 429
        code.putln("#ifndef PY_LONG_LONG")
        code.putln("  #define PY_LONG_LONG LONG_LONG")
        code.putln("#endif")
430 431 432
        code.putln("#ifndef DL_EXPORT")
        code.putln("  #define DL_EXPORT(t) t")
        code.putln("#endif")
433 434
        code.putln("#if PY_VERSION_HEX < 0x02040000")
        code.putln("  #define METH_COEXIST 0")
Stefan Behnel's avatar
Stefan Behnel committed
435
        code.putln("  #define PyDict_CheckExact(op) (Py_TYPE(op) == &PyDict_Type)")
Stefan Behnel's avatar
Stefan Behnel committed
436
        code.putln("  #define PyDict_Contains(d,o)   PySequence_Contains(d,o)")
437 438
        code.putln("#endif")

439 440 441 442
        code.putln("#if PY_VERSION_HEX < 0x02050000")
        code.putln("  typedef int Py_ssize_t;")
        code.putln("  #define PY_SSIZE_T_MAX INT_MAX")
        code.putln("  #define PY_SSIZE_T_MIN INT_MIN")
443
        code.putln("  #define PY_FORMAT_SIZE_T \"\"")
444 445
        code.putln("  #define PyInt_FromSsize_t(z) PyInt_FromLong(z)")
        code.putln("  #define PyInt_AsSsize_t(o)   PyInt_AsLong(o)")
446 447
        code.putln("  #define PyNumber_Index(o)    PyNumber_Int(o)")
        code.putln("  #define PyIndex_Check(o)     PyNumber_Check(o)")
448
        code.putln("#endif")
449 450 451 452

        code.putln("#if PY_VERSION_HEX < 0x02060000")
        code.putln("  #define Py_REFCNT(ob) (((PyObject*)(ob))->ob_refcnt)")
        code.putln("  #define Py_TYPE(ob)   (((PyObject*)(ob))->ob_type)")
453
        code.putln("  #define Py_SIZE(ob)   (((PyVarObject*)(ob))->ob_size)")
454 455
        code.putln("  #define PyVarObject_HEAD_INIT(type, size) \\")
        code.putln("          PyObject_HEAD_INIT(type) size,")
456
        code.putln("  #define PyType_Modified(t)")
457
        code.putln("  #define PyBytes_CheckExact PyString_CheckExact")
458 459 460
        code.putln("")
        code.putln("  typedef struct {")
        code.putln("     void *buf;")
461
        code.putln("     PyObject *obj;")
462
        code.putln("     Py_ssize_t len;")
463
        code.putln("     Py_ssize_t itemsize;")
464 465
        code.putln("     int readonly;")
        code.putln("     int ndim;")
466
        code.putln("     char *format;")
467 468 469 470 471 472 473 474 475 476 477 478 479 480 481
        code.putln("     Py_ssize_t *shape;")
        code.putln("     Py_ssize_t *strides;")
        code.putln("     Py_ssize_t *suboffsets;")
        code.putln("     void *internal;")
        code.putln("  } Py_buffer;")
        code.putln("")
        code.putln("  #define PyBUF_SIMPLE 0")
        code.putln("  #define PyBUF_WRITABLE 0x0001")
        code.putln("  #define PyBUF_FORMAT 0x0004")
        code.putln("  #define PyBUF_ND 0x0008")
        code.putln("  #define PyBUF_STRIDES (0x0010 | PyBUF_ND)")
        code.putln("  #define PyBUF_C_CONTIGUOUS (0x0020 | PyBUF_STRIDES)")
        code.putln("  #define PyBUF_F_CONTIGUOUS (0x0040 | PyBUF_STRIDES)")
        code.putln("  #define PyBUF_ANY_CONTIGUOUS (0x0080 | PyBUF_STRIDES)")
        code.putln("  #define PyBUF_INDIRECT (0x0100 | PyBUF_STRIDES)")
482
        code.putln("")
483
        code.putln("#endif")
484

485
        code.put(builtin_module_name_utility_code.proto)
486 487 488 489 490 491

        code.putln("#if PY_MAJOR_VERSION >= 3")
        code.putln("  #define Py_TPFLAGS_CHECKTYPES 0")
        code.putln("  #define Py_TPFLAGS_HAVE_INDEX 0")
        code.putln("#endif")

492 493 494 495
        code.putln("#if (PY_VERSION_HEX < 0x02060000) || (PY_MAJOR_VERSION >= 3)")
        code.putln("  #define Py_TPFLAGS_HAVE_NEWBUFFER 0")
        code.putln("#endif")

496
        code.putln("#if PY_MAJOR_VERSION >= 3")
Stefan Behnel's avatar
Stefan Behnel committed
497
        code.putln("  #define PyBaseString_Type            PyUnicode_Type")
498
        code.putln("  #define PyString_Type                PyUnicode_Type")
499
        code.putln("  #define PyString_CheckExact          PyUnicode_CheckExact")
500
        code.putln("  #define PyInt_Type                   PyLong_Type")
501 502 503 504 505 506 507 508 509 510 511 512
        code.putln("  #define PyInt_Check(op)              PyLong_Check(op)")
        code.putln("  #define PyInt_CheckExact(op)         PyLong_CheckExact(op)")
        code.putln("  #define PyInt_FromString             PyLong_FromString")
        code.putln("  #define PyInt_FromUnicode            PyLong_FromUnicode")
        code.putln("  #define PyInt_FromLong               PyLong_FromLong")
        code.putln("  #define PyInt_FromSize_t             PyLong_FromSize_t")
        code.putln("  #define PyInt_FromSsize_t            PyLong_FromSsize_t")
        code.putln("  #define PyInt_AsLong                 PyLong_AsLong")
        code.putln("  #define PyInt_AS_LONG                PyLong_AS_LONG")
        code.putln("  #define PyInt_AsSsize_t              PyLong_AsSsize_t")
        code.putln("  #define PyInt_AsUnsignedLongMask     PyLong_AsUnsignedLongMask")
        code.putln("  #define PyInt_AsUnsignedLongLongMask PyLong_AsUnsignedLongLongMask")
Robert Bradshaw's avatar
Robert Bradshaw committed
513
        code.putln("  #define __Pyx_PyNumber_Divide(x,y)         PyNumber_TrueDivide(x,y)")
Stefan Behnel's avatar
Stefan Behnel committed
514
        code.putln("  #define __Pyx_PyNumber_InPlaceDivide(x,y)  PyNumber_InPlaceTrueDivide(x,y)")
515
        code.putln("#else")
Robert Bradshaw's avatar
Robert Bradshaw committed
516 517
        if Future.division in env.context.future_directives:
            code.putln("  #define __Pyx_PyNumber_Divide(x,y)         PyNumber_TrueDivide(x,y)")
Stefan Behnel's avatar
Stefan Behnel committed
518
            code.putln("  #define __Pyx_PyNumber_InPlaceDivide(x,y)  PyNumber_InPlaceTrueDivide(x,y)")
Robert Bradshaw's avatar
Robert Bradshaw committed
519 520
        else:
            code.putln("  #define __Pyx_PyNumber_Divide(x,y)         PyNumber_Divide(x,y)")
Stefan Behnel's avatar
Stefan Behnel committed
521
            code.putln("  #define __Pyx_PyNumber_InPlaceDivide(x,y)  PyNumber_InPlaceDivide(x,y)")
522
        code.putln("  #define PyBytes_Type                 PyString_Type")
523
        code.putln("#endif")
524 525

        code.putln("#if PY_MAJOR_VERSION >= 3")
526
        code.putln("  #define PyMethod_New(func, self, klass) PyInstanceMethod_New(func)")
527 528
        code.putln("#endif")

529 530 531 532 533 534 535
        code.putln("#if !defined(WIN32) && !defined(MS_WINDOWS)")
        code.putln("  #ifndef __stdcall")
        code.putln("    #define __stdcall")
        code.putln("  #endif")
        code.putln("  #ifndef __cdecl")
        code.putln("    #define __cdecl")
        code.putln("  #endif")
536 537 538
        code.putln("  #ifndef __fastcall")
        code.putln("    #define __fastcall")
        code.putln("  #endif")
539 540
        code.putln("#else")
        code.putln("  #define _USE_MATH_DEFINES")
541
        code.putln("#endif")
542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560

        code.putln("#if PY_VERSION_HEX < 0x02050000")
        code.putln("  #define __Pyx_GetAttrString(o,n)   PyObject_GetAttrString((o),((char *)(n)))")
        code.putln("  #define __Pyx_SetAttrString(o,n,a) PyObject_SetAttrString((o),((char *)(n)),(a))")
        code.putln("  #define __Pyx_DelAttrString(o,n)   PyObject_DelAttrString((o),((char *)(n)))")
        code.putln("#else")
        code.putln("  #define __Pyx_GetAttrString(o,n)   PyObject_GetAttrString((o),(n))")
        code.putln("  #define __Pyx_SetAttrString(o,n,a) PyObject_SetAttrString((o),(n),(a))")
        code.putln("  #define __Pyx_DelAttrString(o,n)   PyObject_DelAttrString((o),(n))")
        code.putln("#endif")

        code.putln("#if PY_VERSION_HEX < 0x02050000")
        code.putln("  #define __Pyx_NAMESTR(n) ((char *)(n))")
        code.putln("  #define __Pyx_DOCSTR(n)  ((char *)(n))")
        code.putln("#else")
        code.putln("  #define __Pyx_NAMESTR(n) (n)")
        code.putln("  #define __Pyx_DOCSTR(n)  (n)")
        code.putln("#endif")

561
        self.generate_extern_c_macro_definition(code)
562
        code.putln("#include <math.h>")
563
        code.putln("#define %s" % Naming.api_guard_prefix + self.api_name(env))
564
        self.generate_includes(env, cimported_modules, code)
565 566 567 568
        if env.directives['ccomplex']:
            code.putln("")
            code.putln("#if !defined(CYTHON_CCOMPLEX)")
            code.putln("#define CYTHON_CCOMPLEX 1")
569
            code.putln("#endif")
570
            code.putln("")
571
        code.put(Nodes.utility_function_predeclarations)
572
        code.put(PyrexTypes.type_conversion_predeclarations)
Robert Bradshaw's avatar
Robert Bradshaw committed
573
        code.put(Nodes.branch_prediction_macros)
574 575 576
        code.putln('')
        code.putln('static PyObject *%s;' % env.module_cname)
        code.putln('static PyObject *%s;' % Naming.builtins_cname)
Robert Bradshaw's avatar
Robert Bradshaw committed
577
        code.putln('static PyObject *%s;' % Naming.empty_tuple)
Robert Bradshaw's avatar
Robert Bradshaw committed
578
        code.putln('static PyObject *%s;' % Naming.empty_bytes)
579 580
        if Options.pre_import is not None:
            code.putln('static PyObject *%s;' % Naming.preimport_cname)
581
        code.putln('static int %s;' % Naming.lineno_cname)
582
        code.putln('static int %s = 0;' % Naming.clineno_cname)
583 584 585
        code.putln('static const char * %s= %s;' % (Naming.cfilenm_cname, Naming.file_c_macro))
        code.putln('static const char *%s;' % Naming.filename_cname)
        code.putln('static const char **%s;' % Naming.filetable_cname)
586

587 588 589 590 591 592
        # XXX this is a mess
        for utility_code in PyrexTypes.c_int_from_py_function.specialize_list:
            env.use_utility_code(utility_code)
        for utility_code in PyrexTypes.c_long_from_py_function.specialize_list:
            env.use_utility_code(utility_code)

593 594 595 596 597 598 599 600 601
    def generate_extern_c_macro_definition(self, code):
        name = Naming.extern_c_macro
        code.putln("#ifdef __cplusplus")
        code.putln('#define %s extern "C"' % name)
        code.putln("#else")
        code.putln("#define %s extern" % name)
        code.putln("#endif")

    def generate_includes(self, env, cimported_modules, code):
602
        includes = []
Robert Bradshaw's avatar
Robert Bradshaw committed
603
        for filename in env.include_files:
604
            # fake decoding of filenames to their original byte sequence
605
            code.putln('#include "%s"' % filename)
606 607 608
    
    def generate_filename_table(self, code):
        code.putln("")
609
        code.putln("static const char *%s[] = {" % Naming.filenames_cname)
610 611
        if code.globalstate.filename_list:
            for source_desc in code.globalstate.filename_list:
612
                filename = os.path.basename(source_desc.get_filenametable_entry())
613 614 615 616 617 618 619
                escaped_filename = filename.replace("\\", "\\\\").replace('"', r'\"')
                code.putln('"%s",' % 
                    escaped_filename)
        else:
            # Some C compilers don't like an empty array
            code.putln("0")
        code.putln("};")
620 621 622 623

    def generate_type_predeclarations(self, env, code):
        pass

624
    def generate_type_header_code(self, type_entries, code):
625 626
        # Generate definitions of structs/unions/enums/typedefs/objstructs.
        #self.generate_gcc33_hack(env, code) # Is this still needed?
627 628
        #for entry in env.type_entries:
        for entry in type_entries:
629
            if not entry.in_cinclude:
630
                #print "generate_type_header_code:", entry.name, repr(entry.type) ###
631
                type = entry.type
632 633 634
                if type.is_typedef: # Must test this first!
                    self.generate_typedef(entry, code)
                elif type.is_struct_or_union:
635
                    self.generate_struct_union_definition(entry, code)
636
                elif type.is_enum:
637
                    self.generate_enum_definition(entry, code)
638 639
                elif type.is_extension_type:
                    self.generate_obj_struct_definition(type, code)
Gary Furnish's avatar
Gary Furnish committed
640
        
641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659
    def generate_gcc33_hack(self, env, code):
        # Workaround for spurious warning generation in gcc 3.3
        code.putln("")
        for entry in env.c_class_entries:
            type = entry.type
            if not type.typedef_flag:
                name = type.objstruct_cname
                if name.startswith("__pyx_"):
                    tail = name[6:]
                else:
                    tail = name
                code.putln("typedef struct %s __pyx_gcc33_%s;" % (
                    name, tail))
    
    def generate_typedef(self, entry, code):
        base_type = entry.type.typedef_base_type
        code.putln("")
        code.putln("typedef %s;" % base_type.declaration_code(entry.cname))

660 661 662 663 664 665 666 667 668 669
    def sue_header_footer(self, type, kind, name):
        if type.typedef_flag:
            header = "typedef %s {" % kind
            footer = "} %s;" % name
        else:
            header = "%s %s {" % (kind, name)
            footer = "};"
        return header, footer
    
    def generate_struct_union_definition(self, entry, code):
670
        code.mark_pos(entry.pos)
671 672 673
        type = entry.type
        scope = type.scope
        if scope:
674 675 676 677 678
            kind = type.kind
            packed = type.is_struct and type.packed
            if packed:
                kind = "%s %s" % (type.kind, "__Pyx_PACKED")
                code.globalstate.use_utility_code(packed_struct_utility_code)
679
            header, footer = \
680
                self.sue_header_footer(type, kind, type.cname)
681
            code.putln("")
682 683 684 685
            if packed:
                code.putln("#if !defined(__GNUC__)")
                code.putln("#pragma pack(push, 1)")
                code.putln("#endif")
686 687 688 689 690 691 692 693 694 695 696
            code.putln(header)
            var_entries = scope.var_entries
            if not var_entries:
                error(entry.pos,
                    "Empty struct or union definition not allowed outside a"
                    " 'cdef extern from' block")
            for attr in var_entries:
                code.putln(
                    "%s;" %
                        attr.type.declaration_code(attr.cname))
            code.putln(footer)
697 698 699 700
            if packed:
                code.putln("#if !defined(__GNUC__)")
                code.putln("#pragma pack(pop)")
                code.putln("#endif")
701 702

    def generate_enum_definition(self, entry, code):
703
        code.mark_pos(entry.pos)
704 705 706 707 708 709 710 711 712 713 714 715 716
        type = entry.type
        name = entry.cname or entry.name or ""
        header, footer = \
            self.sue_header_footer(type, "enum", name)
        code.putln("")
        code.putln(header)
        enum_values = entry.enum_values
        if not enum_values:
            error(entry.pos,
                "Empty enum definition not allowed outside a"
                " 'cdef extern from' block")
        else:
            last_entry = enum_values[-1]
717
            # this does not really generate code, just builds the result value
718
            for value_entry in enum_values:
719 720 721 722 723
                if value_entry.value_node is not None:
                    value_entry.value_node.generate_evaluation_code(code)

            for value_entry in enum_values:
                if value_entry.value_node is None:
724 725 726 727
                    value_code = value_entry.cname
                else:
                    value_code = ("%s = %s" % (
                        value_entry.cname,
728
                        value_entry.value_node.result()))
729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748
                if value_entry is not last_entry:
                    value_code += ","
                code.putln(value_code)
        code.putln(footer)
    
    def generate_typeobject_predeclaration(self, entry, code):
        code.putln("")
        name = entry.type.typeobj_cname
        if name:
            if entry.visibility == 'extern' and not entry.in_cinclude:
                code.putln("%s DL_IMPORT(PyTypeObject) %s;" % (
                    Naming.extern_c_macro,
                    name))
            elif entry.visibility == 'public':
                #code.putln("DL_EXPORT(PyTypeObject) %s;" % name)
                code.putln("%s DL_EXPORT(PyTypeObject) %s;" % (
                    Naming.extern_c_macro,
                    name))
            # ??? Do we really need the rest of this? ???
            #else:
Robert Bradshaw's avatar
Robert Bradshaw committed
749
            #    code.putln("staticforward PyTypeObject %s;" % name)
750 751
    
    def generate_exttype_vtable_struct(self, entry, code):
752
        code.mark_pos(entry.pos)
753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772
        # Generate struct declaration for an extension type's vtable.
        type = entry.type
        scope = type.scope
        if type.vtabstruct_cname:
            code.putln("")
            code.putln(
                "struct %s {" %
                    type.vtabstruct_cname)
            if type.base_type and type.base_type.vtabstruct_cname:
                code.putln("struct %s %s;" % (
                    type.base_type.vtabstruct_cname,
                    Naming.obj_base_cname))
            for method_entry in scope.cfunc_entries:
                if not method_entry.is_inherited:
                    code.putln(
                        "%s;" % method_entry.type.declaration_code("(*%s)" % method_entry.name))
            code.putln(
                "};")
    
    def generate_exttype_vtabptr_declaration(self, entry, code):
773
        code.mark_pos(entry.pos)
774 775 776 777 778 779 780 781
        # Generate declaration of pointer to an extension type's vtable.
        type = entry.type
        if type.vtabptr_cname:
            code.putln("static struct %s *%s;" % (
                type.vtabstruct_cname,
                type.vtabptr_cname))
    
    def generate_obj_struct_definition(self, type, code):
782
        code.mark_pos(type.pos)
783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810
        # Generate object struct definition for an
        # extension type.
        if not type.scope:
            return # Forward declared but never defined
        header, footer = \
            self.sue_header_footer(type, "struct", type.objstruct_cname)
        code.putln("")
        code.putln(header)
        base_type = type.base_type
        if base_type:
            code.putln(
                "%s%s %s;" % (
                    ("struct ", "")[base_type.typedef_flag],
                    base_type.objstruct_cname,
                    Naming.obj_base_cname))
        else:
            code.putln(
                "PyObject_HEAD")
        if type.vtabslot_cname and not (type.base_type and type.base_type.vtabslot_cname):
            code.putln(
                "struct %s *%s;" % (
                    type.vtabstruct_cname,
                    type.vtabslot_cname))
        for attr in type.scope.var_entries:
            code.putln(
                "%s;" %
                    attr.type.declaration_code(attr.cname))
        code.putln(footer)
811 812 813
        if type.objtypedef_cname is not None:
            # Only for exposing public typedef name.
            code.putln("typedef struct %s %s;" % (type.objstruct_cname, type.objtypedef_cname))
814 815 816 817

    def generate_global_declarations(self, env, code, definition):
        code.putln("")
        for entry in env.c_class_entries:
818 819 820
            if definition or entry.defined_in_pxd:
                code.putln("static PyTypeObject *%s = 0;" % 
                    entry.type.typeptr_cname)
821 822 823
        code.put_var_declarations(env.var_entries, static = 1, 
            dll_linkage = "DL_EXPORT", definition = definition)
    
824
    def generate_cfunction_predeclarations(self, env, code, definition):
825
        for entry in env.cfunc_entries:
826 827
            if entry.inline_func_in_pxd or (not entry.in_cinclude and (definition
                    or entry.defined_in_pxd or entry.visibility == 'extern')):
828
                if entry.visibility in ('public', 'extern'):
829 830 831
                    dll_linkage = "DL_EXPORT"
                else:
                    dll_linkage = None
832 833 834 835
                type = entry.type
                if not definition and entry.defined_in_pxd:
                    type = CPtrType(type)
                header = type.declaration_code(entry.cname, 
836
                    dll_linkage = dll_linkage)
837 838
                if entry.visibility == 'private':
                    storage_class = "static "
839 840
                elif entry.visibility == 'public':
                    storage_class = ""
841
                else:
842
                    storage_class = "%s " % Naming.extern_c_macro
843 844 845 846 847 848
                if entry.func_modifiers:
                    modifiers = '%s ' % ' '.join([
                            modifier.upper() for modifier in entry.func_modifiers])
                else:
                    modifiers = ''
                code.putln("%s%s%s; /*proto*/" % (
849
                    storage_class,
850
                    modifiers,
851 852 853 854 855 856 857
                    header))
    
    def generate_typeobj_definitions(self, env, code):
        full_module_name = env.qualified_name
        for entry in env.c_class_entries:
            #print "generate_typeobj_definitions:", entry.name
            #print "...visibility =", entry.visibility
Stefan Behnel's avatar
Stefan Behnel committed
858
            if entry.visibility != 'extern':
859 860 861 862 863 864
                type = entry.type
                scope = type.scope
                if scope: # could be None if there was an error
                    self.generate_exttype_vtable(scope, code)
                    self.generate_new_function(scope, code)
                    self.generate_dealloc_function(scope, code)
865 866 867
                    if scope.needs_gc():
                        self.generate_traverse_function(scope, code)
                        self.generate_clear_function(scope, code)
868 869 870 871 872
                    if scope.defines_any(["__getitem__"]):
                        self.generate_getitem_int_function(scope, code)
                    if scope.defines_any(["__setitem__", "__delitem__"]):
                        self.generate_ass_subscript_function(scope, code)
                    if scope.defines_any(["__setslice__", "__delslice__"]):
873
                        warning(self.pos, "__setslice__ and __delslice__ are not supported by Python 3, use __setitem__ and __getitem__ instead", 1)
874
                        self.generate_ass_slice_function(scope, code)
875
                    if scope.defines_any(["__getattr__","__getattribute__"]):
876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904
                        self.generate_getattro_function(scope, code)
                    if scope.defines_any(["__setattr__", "__delattr__"]):
                        self.generate_setattro_function(scope, code)
                    if scope.defines_any(["__get__"]):
                        self.generate_descr_get_function(scope, code)
                    if scope.defines_any(["__set__", "__delete__"]):
                        self.generate_descr_set_function(scope, code)
                    self.generate_property_accessors(scope, code)
                    self.generate_method_table(scope, code)
                    self.generate_member_table(scope, code)
                    self.generate_getset_table(scope, code)
                    self.generate_typeobj_definition(full_module_name, entry, code)
    
    def generate_exttype_vtable(self, scope, code):
        # Generate the definition of an extension type's vtable.
        type = scope.parent_type
        if type.vtable_cname:
            code.putln("static struct %s %s;" % (
                type.vtabstruct_cname,
                type.vtable_cname))
        
    def generate_self_cast(self, scope, code):
        type = scope.parent_type
        code.putln(
            "%s = (%s)o;" % (
                type.declaration_code("p"),
                type.declaration_code("")))
    
    def generate_new_function(self, scope, code):
905 906
        tp_slot = TypeSlots.ConstructorSlot("tp_new", '__new__')
        slot_func = scope.mangle_internal("tp_new")
907 908 909 910 911 912 913
        type = scope.parent_type
        base_type = type.base_type
        py_attrs = []
        for entry in scope.var_entries:
            if entry.type.is_pyobject:
                py_attrs.append(entry)
        need_self_cast = type.vtabslot_cname or py_attrs
914 915 916 917
        code.putln("")
        code.putln(
            "static PyObject *%s(PyTypeObject *t, PyObject *a, PyObject *k) {"
                % scope.mangle_internal("tp_new"))
918 919 920 921
        if need_self_cast:
            code.putln(
                "%s;"
                    % scope.parent_type.declaration_code("p"))
922
        if base_type:
Robert Bradshaw's avatar
Robert Bradshaw committed
923 924
            tp_new = TypeSlots.get_base_slot_function(scope, tp_slot)
            if tp_new is None:
925
                tp_new = "%s->tp_new" % base_type.typeptr_cname
926
            code.putln(
927
                "PyObject *o = %s(t, a, k);" % tp_new)
928 929 930
        else:
            code.putln(
                "PyObject *o = (*t->tp_alloc)(t, 0);")
931 932 933 934 935 936 937
        code.putln(
                "if (!o) return 0;")
        if need_self_cast:
            code.putln(
                "p = %s;"
                    % type.cast_code("o"))
        #if need_self_cast:
Robert Bradshaw's avatar
Robert Bradshaw committed
938
        #    self.generate_self_cast(scope, code)
939
        if type.vtabslot_cname:
940 941 942 943 944
            vtab_base_type = type
            while vtab_base_type.base_type and vtab_base_type.base_type.vtabstruct_cname:
                vtab_base_type = vtab_base_type.base_type
            if vtab_base_type is not type:
                struct_type_cast = "(struct %s*)" % vtab_base_type.vtabstruct_cname
945 946 947
            else:
                struct_type_cast = ""
            code.putln("p->%s = %s%s;" % (
948
                type.vtabslot_cname,
949
                struct_type_cast, type.vtabptr_cname))
950 951
        for entry in py_attrs:
            if entry.name == "__weakref__":
952
                code.putln("p->%s = 0;" % entry.cname)
953
            else:
954
                code.put_init_var_to_py_none(entry, "p->%s", nanny=False)
955
        entry = scope.lookup_here("__new__")
956
        if entry and entry.is_special:
957 958 959 960
            if entry.trivial_signature:
                cinit_args = "o, %s, NULL" % Naming.empty_tuple
            else:
                cinit_args = "o, a, k"
961
            code.putln(
962 963
                "if (%s(%s) < 0) {" % 
                    (entry.func_cname, cinit_args))
964
            code.put_decref_clear("o", py_object_type, nanny=False);
965 966 967 968 969 970 971 972
            code.putln(
                "}")
        code.putln(
            "return o;")
        code.putln(
            "}")
    
    def generate_dealloc_function(self, scope, code):
973 974
        tp_slot = TypeSlots.ConstructorSlot("tp_dealloc", '__dealloc__')
        slot_func = scope.mangle_internal("tp_dealloc")
975
        base_type = scope.parent_type.base_type
976 977
        if tp_slot.slot_code(scope) != slot_func:
            return # never used
978 979 980 981 982
        code.putln("")
        code.putln(
            "static void %s(PyObject *o) {"
                % scope.mangle_internal("tp_dealloc"))
        py_attrs = []
983
        weakref_slot = scope.lookup_here("__weakref__")
984
        for entry in scope.var_entries:
985
            if entry.type.is_pyobject and entry is not weakref_slot:
986
                py_attrs.append(entry)
987
        if py_attrs or weakref_slot in scope.var_entries:
988 989
            self.generate_self_cast(scope, code)
        self.generate_usr_dealloc_call(scope, code)
990
        if weakref_slot in scope.var_entries:
991
            code.putln("if (p->__weakref__) PyObject_ClearWeakRefs(o);")
992
        for entry in py_attrs:
993
            code.put_xdecref("p->%s" % entry.cname, entry.type, nanny=False)
994
        if base_type:
Robert Bradshaw's avatar
Robert Bradshaw committed
995 996
            tp_dealloc = TypeSlots.get_base_slot_function(scope, tp_slot)
            if tp_dealloc is None:
997
                tp_dealloc = "%s->tp_dealloc" % base_type.typeptr_cname
998
            code.putln(
999
                    "%s(o);" % tp_dealloc)
1000 1001
        else:
            code.putln(
1002
                    "(*Py_TYPE(o)->tp_free)(o);")
1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015
        code.putln(
            "}")
    
    def generate_usr_dealloc_call(self, scope, code):
        entry = scope.lookup_here("__dealloc__")
        if entry:
            code.putln(
                "{")
            code.putln(
                    "PyObject *etype, *eval, *etb;")
            code.putln(
                    "PyErr_Fetch(&etype, &eval, &etb);")
            code.putln(
1016
                    "++Py_REFCNT(o);")
1017 1018 1019 1020 1021 1022
            code.putln(
                    "%s(o);" % 
                        entry.func_cname)
            code.putln(
                    "if (PyErr_Occurred()) PyErr_WriteUnraisable(o);")
            code.putln(
1023
                    "--Py_REFCNT(o);")
1024 1025 1026 1027 1028 1029
            code.putln(
                    "PyErr_Restore(etype, eval, etb);")
            code.putln(
                "}")
    
    def generate_traverse_function(self, scope, code):
1030 1031
        tp_slot = TypeSlots.GCDependentSlot("tp_traverse")
        slot_func = scope.mangle_internal("tp_traverse")
1032
        base_type = scope.parent_type.base_type
1033 1034
        if tp_slot.slot_code(scope) != slot_func:
            return # never used
1035 1036 1037
        code.putln("")
        code.putln(
            "static int %s(PyObject *o, visitproc v, void *a) {"
1038
                % slot_func)
1039 1040
        py_attrs = []
        for entry in scope.var_entries:
1041
            if entry.type.is_pyobject and entry.name != "__weakref__":
1042 1043
                py_attrs.append(entry)
        if base_type or py_attrs:
1044
            code.putln("int e;")
1045 1046 1047
        if py_attrs:
            self.generate_self_cast(scope, code)
        if base_type:
1048
            # want to call it explicitly if possible so inlining can be performed
Robert Bradshaw's avatar
Robert Bradshaw committed
1049 1050 1051
            static_call = TypeSlots.get_base_slot_function(scope, tp_slot)
            if static_call:
                code.putln("e = %s(o, v, a); if (e) return e;" % static_call)
1052 1053 1054 1055 1056 1057
            else:
                code.putln("if (%s->tp_traverse) {" % base_type.typeptr_cname)
                code.putln(
                        "e = %s->tp_traverse(o, v, a); if (e) return e;" %
                            base_type.typeptr_cname)
                code.putln("}")
1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075
        for entry in py_attrs:
            var_code = "p->%s" % entry.cname
            code.putln(
                    "if (%s) {"
                        % var_code)
            if entry.type.is_extension_type:
                var_code = "((PyObject*)%s)" % var_code
            code.putln(
                        "e = (*v)(%s, a); if (e) return e;" 
                            % var_code)
            code.putln(
                    "}")
        code.putln(
                "return 0;")
        code.putln(
            "}")
    
    def generate_clear_function(self, scope, code):
1076 1077
        tp_slot = TypeSlots.GCDependentSlot("tp_clear")
        slot_func = scope.mangle_internal("tp_clear")
1078
        base_type = scope.parent_type.base_type
1079 1080
        if tp_slot.slot_code(scope) != slot_func:
            return # never used
1081
        code.putln("")
1082
        code.putln("static int %s(PyObject *o) {" % slot_func)
1083 1084
        py_attrs = []
        for entry in scope.var_entries:
1085
            if entry.type.is_pyobject and entry.name != "__weakref__":
1086 1087 1088
                py_attrs.append(entry)
        if py_attrs:
            self.generate_self_cast(scope, code)
1089
            code.putln("PyObject* tmp;")
1090
        if base_type:
1091
            # want to call it explicitly if possible so inlining can be performed
Robert Bradshaw's avatar
Robert Bradshaw committed
1092 1093 1094
            static_call = TypeSlots.get_base_slot_function(scope, tp_slot)
            if static_call:
                code.putln("%s(o);" % static_call)
1095 1096 1097 1098
            else:
                code.putln("if (%s->tp_clear) {" % base_type.typeptr_cname)
                code.putln("%s->tp_clear(o);" % base_type.typeptr_cname)
                code.putln("}")
1099 1100
        for entry in py_attrs:
            name = "p->%s" % entry.cname
1101
            code.putln("tmp = ((PyObject*)%s);" % name)
1102
            code.put_init_to_py_none(name, entry.type, nanny=False)
1103
            code.putln("Py_XDECREF(tmp);")
1104 1105 1106 1107
        code.putln(
            "return 0;")
        code.putln(
            "}")
1108
            
1109 1110 1111 1112 1113
    def generate_getitem_int_function(self, scope, code):
        # This function is put into the sq_item slot when
        # a __getitem__ method is present. It converts its
        # argument to a Python integer and calls mp_subscript.
        code.putln(
1114
            "static PyObject *%s(PyObject *o, Py_ssize_t i) {" %
1115 1116 1117 1118
                scope.mangle_internal("sq_item"))
        code.putln(
                "PyObject *r;")
        code.putln(
1119
                "PyObject *x = PyInt_FromSsize_t(i); if(!x) return 0;")
1120
        code.putln(
1121
                "r = Py_TYPE(o)->tp_as_mapping->mp_subscript(o, x);")
1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151
        code.putln(
                "Py_DECREF(x);")
        code.putln(
                "return r;")
        code.putln(
            "}")

    def generate_ass_subscript_function(self, scope, code):
        # Setting and deleting an item are both done through
        # the ass_subscript method, so we dispatch to user's __setitem__
        # or __delitem__, or raise an exception.
        base_type = scope.parent_type.base_type
        set_entry = scope.lookup_here("__setitem__")
        del_entry = scope.lookup_here("__delitem__")
        code.putln("")
        code.putln(
            "static int %s(PyObject *o, PyObject *i, PyObject *v) {" %
                scope.mangle_internal("mp_ass_subscript"))
        code.putln(
                "if (v) {")
        if set_entry:
            code.putln(
                    "return %s(o, i, v);" %
                        set_entry.func_cname)
        else:
            self.generate_guarded_basetype_call(
                base_type, "tp_as_mapping", "mp_ass_subscript", "o, i, v", code)
            code.putln(
                    "PyErr_Format(PyExc_NotImplementedError,")
            code.putln(
1152
                    '  "Subscript assignment not supported by %s", Py_TYPE(o)->tp_name);')
1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168
            code.putln(
                    "return -1;")
        code.putln(
                "}")
        code.putln(
                "else {")
        if del_entry:
            code.putln(
                    "return %s(o, i);" %
                        del_entry.func_cname)
        else:
            self.generate_guarded_basetype_call(
                base_type, "tp_as_mapping", "mp_ass_subscript", "o, i, v", code)
            code.putln(
                    "PyErr_Format(PyExc_NotImplementedError,")
            code.putln(
1169
                    '  "Subscript deletion not supported by %s", Py_TYPE(o)->tp_name);')
1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199
            code.putln(
                    "return -1;")
        code.putln(
                "}")
        code.putln(
            "}")
    
    def generate_guarded_basetype_call(
            self, base_type, substructure, slot, args, code):
        if base_type:
            base_tpname = base_type.typeptr_cname
            if substructure:
                code.putln(
                    "if (%s->%s && %s->%s->%s)" % (
                        base_tpname, substructure, base_tpname, substructure, slot))
                code.putln(
                    "  return %s->%s->%s(%s);" % (
                        base_tpname, substructure, slot, args))
            else:
                code.putln(
                    "if (%s->%s)" % (
                        base_tpname, slot))
                code.putln(
                    "  return %s->%s(%s);" % (
                        base_tpname, slot, args))

    def generate_ass_slice_function(self, scope, code):
        # Setting and deleting a slice are both done through
        # the ass_slice method, so we dispatch to user's __setslice__
        # or __delslice__, or raise an exception.
1200 1201 1202
        code.putln("#if PY_MAJOR_VERSION >= 3")
        code.putln("#error __setslice__ and __delslice__ not supported in Python 3.")
        code.putln("#endif")
1203 1204 1205 1206 1207
        base_type = scope.parent_type.base_type
        set_entry = scope.lookup_here("__setslice__")
        del_entry = scope.lookup_here("__delslice__")
        code.putln("")
        code.putln(
1208
            "static int %s(PyObject *o, Py_ssize_t i, Py_ssize_t j, PyObject *v) {" %
1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221
                scope.mangle_internal("sq_ass_slice"))
        code.putln(
                "if (v) {")
        if set_entry:
            code.putln(
                    "return %s(o, i, j, v);" %
                        set_entry.func_cname)
        else:
            self.generate_guarded_basetype_call(
                base_type, "tp_as_sequence", "sq_ass_slice", "o, i, j, v", code)
            code.putln(
                    "PyErr_Format(PyExc_NotImplementedError,")
            code.putln(
1222
                    '  "2-element slice assignment not supported by %s", Py_TYPE(o)->tp_name);')
1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238
            code.putln(
                    "return -1;")
        code.putln(
                "}")
        code.putln(
                "else {")
        if del_entry:
            code.putln(
                    "return %s(o, i, j);" %
                        del_entry.func_cname)
        else:
            self.generate_guarded_basetype_call(
                base_type, "tp_as_sequence", "sq_ass_slice", "o, i, j, v", code)
            code.putln(
                    "PyErr_Format(PyExc_NotImplementedError,")
            code.putln(
1239
                    '  "2-element slice deletion not supported by %s", Py_TYPE(o)->tp_name);')
1240 1241 1242 1243 1244 1245 1246 1247
            code.putln(
                    "return -1;")
        code.putln(
                "}")
        code.putln(
            "}")

    def generate_getattro_function(self, scope, code):
1248 1249 1250
        # First try to get the attribute using __getattribute__, if defined, or
        # PyObject_GenericGetAttr.
        #
1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265
        # If that raises an AttributeError, call the __getattr__ if defined.
        #
        # In both cases, defined can be in this class, or any base class.
        def lookup_here_or_base(n,type=None):
            # Recursive lookup
            if type is None:
                type = scope.parent_type
            r = type.scope.lookup_here(n)
            if r is None and \
               type.base_type is not None:
                return lookup_here_or_base(n,type.base_type)
            else:
                return r
        getattr_entry = lookup_here_or_base("__getattr__")
        getattribute_entry = lookup_here_or_base("__getattribute__")
1266 1267 1268 1269
        code.putln("")
        code.putln(
            "static PyObject *%s(PyObject *o, PyObject *n) {"
                % scope.mangle_internal("tp_getattro"))
1270 1271 1272 1273 1274 1275
        if getattribute_entry is not None:
            code.putln(
                "PyObject *v = %s(o, n);" %
                    getattribute_entry.func_cname)
        else:
            code.putln(
1276
                "PyObject *v = PyObject_GenericGetAttr(o, n);")
1277 1278
        if getattr_entry is not None:
            code.putln(
1279
                "if (!v && PyErr_ExceptionMatches(PyExc_AttributeError)) {")
1280 1281 1282 1283 1284 1285
            code.putln(
                "PyErr_Clear();")
            code.putln(
                "v = %s(o, n);" %
                    getattr_entry.func_cname)
            code.putln(
1286 1287
                "}")
        code.putln(
1288
            "return v;")
1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399
        code.putln(
            "}")
    
    def generate_setattro_function(self, scope, code):
        # Setting and deleting an attribute are both done through
        # the setattro method, so we dispatch to user's __setattr__
        # or __delattr__ or fall back on PyObject_GenericSetAttr.
        base_type = scope.parent_type.base_type
        set_entry = scope.lookup_here("__setattr__")
        del_entry = scope.lookup_here("__delattr__")
        code.putln("")
        code.putln(
            "static int %s(PyObject *o, PyObject *n, PyObject *v) {" %
                scope.mangle_internal("tp_setattro"))
        code.putln(
                "if (v) {")
        if set_entry:
            code.putln(
                    "return %s(o, n, v);" %
                        set_entry.func_cname)
        else:
            self.generate_guarded_basetype_call(
                base_type, None, "tp_setattro", "o, n, v", code)
            code.putln(
                    "return PyObject_GenericSetAttr(o, n, v);")
        code.putln(
                "}")
        code.putln(
                "else {")
        if del_entry:
            code.putln(
                    "return %s(o, n);" %
                        del_entry.func_cname)
        else:
            self.generate_guarded_basetype_call(
                base_type, None, "tp_setattro", "o, n, v", code)
            code.putln(
                    "return PyObject_GenericSetAttr(o, n, 0);")
        code.putln(
                "}")
        code.putln(
            "}")
    
    def generate_descr_get_function(self, scope, code):
        # The __get__ function of a descriptor object can be
        # called with NULL for the second or third arguments
        # under some circumstances, so we replace them with
        # None in that case.
        user_get_entry = scope.lookup_here("__get__")
        code.putln("")
        code.putln(
            "static PyObject *%s(PyObject *o, PyObject *i, PyObject *c) {" %
                scope.mangle_internal("tp_descr_get"))
        code.putln(
            "PyObject *r = 0;")
        code.putln(
            "if (!i) i = Py_None;")
        code.putln(
            "if (!c) c = Py_None;")
        #code.put_incref("i", py_object_type)
        #code.put_incref("c", py_object_type)
        code.putln(
            "r = %s(o, i, c);" %
                user_get_entry.func_cname)
        #code.put_decref("i", py_object_type)
        #code.put_decref("c", py_object_type)
        code.putln(
            "return r;")
        code.putln(
            "}")
    
    def generate_descr_set_function(self, scope, code):
        # Setting and deleting are both done through the __set__
        # method of a descriptor, so we dispatch to user's __set__
        # or __delete__ or raise an exception.
        base_type = scope.parent_type.base_type
        user_set_entry = scope.lookup_here("__set__")
        user_del_entry = scope.lookup_here("__delete__")
        code.putln("")
        code.putln(
            "static int %s(PyObject *o, PyObject *i, PyObject *v) {" %
                scope.mangle_internal("tp_descr_set"))
        code.putln(
                "if (v) {")
        if user_set_entry:
            code.putln(
                    "return %s(o, i, v);" %
                        user_set_entry.func_cname)
        else:
            self.generate_guarded_basetype_call(
                base_type, None, "tp_descr_set", "o, i, v", code)
            code.putln(
                    'PyErr_SetString(PyExc_NotImplementedError, "__set__");')
            code.putln(
                    "return -1;")
        code.putln(
                "}")
        code.putln(
                "else {")
        if user_del_entry:
            code.putln(
                    "return %s(o, i);" %
                        user_del_entry.func_cname)
        else:
            self.generate_guarded_basetype_call(
                base_type, None, "tp_descr_set", "o, i, v", code)
            code.putln(
                    'PyErr_SetString(PyExc_NotImplementedError, "__delete__");')
            code.putln(
                    "return -1;")
        code.putln(
Robert Bradshaw's avatar
Robert Bradshaw committed
1400
                "}")        
1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479
        code.putln(
            "}")
    
    def generate_property_accessors(self, cclass_scope, code):
        for entry in cclass_scope.property_entries:
            property_scope = entry.scope
            if property_scope.defines_any(["__get__"]):
                self.generate_property_get_function(entry, code)
            if property_scope.defines_any(["__set__", "__del__"]):
                self.generate_property_set_function(entry, code)
    
    def generate_property_get_function(self, property_entry, code):
        property_scope = property_entry.scope
        property_entry.getter_cname = property_scope.parent_scope.mangle(
            Naming.prop_get_prefix, property_entry.name)
        get_entry = property_scope.lookup_here("__get__")
        code.putln("")
        code.putln(
            "static PyObject *%s(PyObject *o, void *x) {" %
                property_entry.getter_cname)
        code.putln(
                "return %s(o);" %
                    get_entry.func_cname)
        code.putln(
            "}")
    
    def generate_property_set_function(self, property_entry, code):
        property_scope = property_entry.scope
        property_entry.setter_cname = property_scope.parent_scope.mangle(
            Naming.prop_set_prefix, property_entry.name)
        set_entry = property_scope.lookup_here("__set__")
        del_entry = property_scope.lookup_here("__del__")
        code.putln("")
        code.putln(
            "static int %s(PyObject *o, PyObject *v, void *x) {" %
                property_entry.setter_cname)
        code.putln(
                "if (v) {")
        if set_entry:
            code.putln(
                    "return %s(o, v);" %
                        set_entry.func_cname)
        else:
            code.putln(
                    'PyErr_SetString(PyExc_NotImplementedError, "__set__");')
            code.putln(
                    "return -1;")
        code.putln(
                "}")
        code.putln(
                "else {")
        if del_entry:
            code.putln(
                    "return %s(o);" %
                        del_entry.func_cname)
        else:
            code.putln(
                    'PyErr_SetString(PyExc_NotImplementedError, "__del__");')
            code.putln(
                    "return -1;")
        code.putln(
                "}")
        code.putln(
            "}")

    def generate_typeobj_definition(self, modname, entry, code):
        type = entry.type
        scope = type.scope
        for suite in TypeSlots.substructures:
            suite.generate_substructure(scope, code)
        code.putln("")
        if entry.visibility == 'public':
            header = "DL_EXPORT(PyTypeObject) %s = {"
        else:
            #header = "statichere PyTypeObject %s = {"
            header = "PyTypeObject %s = {"
        #code.putln(header % scope.parent_type.typeobj_cname)
        code.putln(header % type.typeobj_cname)
        code.putln(
1480
            "PyVarObject_HEAD_INIT(0, 0)")
1481
        code.putln(
1482
            '__Pyx_NAMESTR("%s.%s"), /*tp_name*/' % (
1483
                self.full_module_name, scope.class_name))
1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504
        if type.typedef_flag:
            objstruct = type.objstruct_cname
        else:
            #objstruct = "struct %s" % scope.parent_type.objstruct_cname
            objstruct = "struct %s" % type.objstruct_cname
        code.putln(
            "sizeof(%s), /*tp_basicsize*/" %
                objstruct)
        code.putln(
            "0, /*tp_itemsize*/")
        for slot in TypeSlots.slot_table:
            slot.generate(scope, code)
        code.putln(
            "};")
    
    def generate_method_table(self, env, code):
        code.putln("")
        code.putln(
            "static struct PyMethodDef %s[] = {" % 
                env.method_table_cname)
        for entry in env.pyfunc_entries:
1505
            code.put_pymethoddef(entry, ",")
1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528
        code.putln(
                "{0, 0, 0, 0}")
        code.putln(
            "};")
    
    def generate_member_table(self, env, code):
        #print "ModuleNode.generate_member_table: scope =", env ###
        if env.public_attr_entries:
            code.putln("")
            code.putln(
                "static struct PyMemberDef %s[] = {" %
                    env.member_table_cname)
            type = env.parent_type
            if type.typedef_flag:
                objstruct = type.objstruct_cname
            else:
                objstruct = "struct %s" % type.objstruct_cname
            for entry in env.public_attr_entries:
                type_code = entry.type.pymemberdef_typecode
                if entry.visibility == 'readonly':
                    flags = "READONLY"
                else:
                    flags = "0"
1529
                code.putln('{(char *)"%s", %s, %s, %s, 0},' % (
1530 1531
                    entry.name,
                    type_code,
1532
                    "offsetof(%s, %s)" % (objstruct, entry.cname),
1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545
                    flags))
            code.putln(
                    "{0, 0, 0, 0, 0}")
            code.putln(
                "};")
    
    def generate_getset_table(self, env, code):
        if env.property_entries:
            code.putln("")
            code.putln(
                "static struct PyGetSetDef %s[] = {" %
                    env.getset_table_cname)
            for entry in env.property_entries:
1546 1547 1548 1549
                if entry.doc:
                    doc_code = "__Pyx_DOCSTR(%s)" % code.get_string_const(entry.doc)
                else:
                    doc_code = "0"
1550
                code.putln(
1551
                    '{(char *)"%s", %s, %s, %s, 0},' % (
1552 1553 1554
                        entry.name,
                        entry.getter_cname or "0",
                        entry.setter_cname or "0",
1555
                        doc_code))
1556 1557 1558 1559
            code.putln(
                    "{0, 0, 0, 0, 0}")
            code.putln(
                "};")
1560

1561 1562 1563
    def generate_filename_init_prototype(self, code):
        code.putln("");
        code.putln("static void %s(void); /*proto*/" % Naming.fileinit_cname)
Dag Sverre Seljebotn's avatar
Merge  
Dag Sverre Seljebotn committed
1564 1565
        
    def generate_import_star(self, env, code):
1566
        env.use_utility_code(streq_utility_code)
Dag Sverre Seljebotn's avatar
Merge  
Dag Sverre Seljebotn committed
1567 1568 1569 1570 1571 1572 1573 1574
        code.putln()
        code.putln("char* %s_type_names[] = {" % Naming.import_star)
        for name, entry in env.entries.items():
            if entry.is_type:
                code.putln('"%s",' % name)
        code.putln("0")
        code.putln("};")
        code.putln()
1575
        code.enter_cfunc_scope() # as we need labels
Dag Sverre Seljebotn's avatar
Merge  
Dag Sverre Seljebotn committed
1576 1577 1578
        code.putln("static int %s(PyObject *o, PyObject* py_name, char *name) {" % Naming.import_star_set)
        code.putln("char** type_name = %s_type_names;" % Naming.import_star)
        code.putln("while (*type_name) {")
1579
        code.putln("if (__Pyx_StrEq(name, *type_name)) {")
Dag Sverre Seljebotn's avatar
Merge  
Dag Sverre Seljebotn committed
1580 1581 1582 1583 1584 1585 1586 1587 1588
        code.putln('PyErr_Format(PyExc_TypeError, "Cannot overwrite C type %s", name);')
        code.putln('goto bad;')
        code.putln("}")
        code.putln("type_name++;")
        code.putln("}")
        old_error_label = code.new_error_label()
        code.putln("if (0);") # so the first one can be "else if"
        for name, entry in env.entries.items():
            if entry.is_cglobal and entry.used:
1589
                code.putln('else if (__Pyx_StrEq(name, "%s")) {' % name)
Dag Sverre Seljebotn's avatar
Merge  
Dag Sverre Seljebotn committed
1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625
                if entry.type.is_pyobject:
                    if entry.type.is_extension_type or entry.type.is_builtin_type:
                        code.putln("if (!(%s)) %s;" % (
                            entry.type.type_test_code("o"),
                            code.error_goto(entry.pos)))
                    code.put_var_decref(entry)
                    code.putln("%s = %s;" % (
                        entry.cname, 
                        PyrexTypes.typecast(entry.type, py_object_type, "o")))
                elif entry.type.from_py_function:
                    rhs = "%s(o)" % entry.type.from_py_function
                    if entry.type.is_enum:
                        rhs = typecast(entry.type, c_long_type, rhs)
                    code.putln("%s = %s; if (%s) %s;" % (
                        entry.cname,
                        rhs,
                        entry.type.error_condition(entry.cname),
                        code.error_goto(entry.pos)))
                    code.putln("Py_DECREF(o);")
                else:
                    code.putln('PyErr_Format(PyExc_TypeError, "Cannot convert Python object %s to %s");' % (name, entry.type))
                    code.putln(code.error_goto(entry.pos))
                code.putln("}")
        code.putln("else {")
        code.putln("if (PyObject_SetAttr(%s, py_name, o) < 0) goto bad;" % Naming.module_cname)
        code.putln("}")
        code.putln("return 0;")
        code.put_label(code.error_label)
        # This helps locate the offending name.
        code.putln('__Pyx_AddTraceback("%s");' % self.full_module_name);
        code.error_label = old_error_label
        code.putln("bad:")
        code.putln("Py_DECREF(o);")
        code.putln("return -1;")
        code.putln("}")
        code.putln(import_star_utility_code)
1626
        code.exit_cfunc_scope() # done with labels
1627 1628

    def generate_module_init_func(self, imported_modules, env, code):
1629
        code.enter_cfunc_scope()
1630
        code.putln("")
1631 1632 1633 1634 1635 1636 1637 1638 1639 1640
        header2 = "PyMODINIT_FUNC init%s(void)" % env.module_name
        header3 = "PyMODINIT_FUNC PyInit_%s(void)" % env.module_name
        code.putln("#if PY_MAJOR_VERSION < 3")
        code.putln("%s; /*proto*/" % header2)
        code.putln(header2)
        code.putln("#else")
        code.putln("%s; /*proto*/" % header3)
        code.putln(header3)
        code.putln("#endif")
        code.putln("{")
1641
        tempdecl_code = code.insertion_point()
1642

1643 1644 1645 1646
        code.putln("#if CYTHON_REFNANNY")
        code.putln("void* __pyx_refnanny = NULL;")
        code.putln("__Pyx_RefNanny = __Pyx_RefNannyImportAPI(\"refnanny\");")
        code.putln("if (!__Pyx_RefNanny) {")
1647
        code.putln("  PyErr_Clear();")
1648 1649 1650
        code.putln("  __Pyx_RefNanny = __Pyx_RefNannyImportAPI(\"Cython.Runtime.refnanny\");")
        code.putln("  if (!__Pyx_RefNanny)")
        code.putln("      Py_FatalError(\"failed to import 'refnanny' module\");")
1651
        code.putln("}")
1652
        code.putln("__pyx_refnanny = __Pyx_RefNanny->SetupContext(\"%s\", __LINE__, __FILE__);"% header3)
1653
        code.putln("#endif")
1654

1655 1656
        self.generate_filename_init_call(code)

1657
        code.putln("%s = PyTuple_New(0); %s" % (Naming.empty_tuple, code.error_goto_if_null(Naming.empty_tuple, self.pos)));
Robert Bradshaw's avatar
Robert Bradshaw committed
1658 1659 1660 1661 1662
        code.putln("#if PY_MAJOR_VERSION < 3");
        code.putln("%s = PyString_FromStringAndSize(\"\", 0); %s" % (Naming.empty_bytes, code.error_goto_if_null(Naming.empty_bytes, self.pos)));
        code.putln("#else");
        code.putln("%s = PyBytes_FromStringAndSize(\"\", 0); %s" % (Naming.empty_bytes, code.error_goto_if_null(Naming.empty_bytes, self.pos)));
        code.putln("#endif");
1663

1664
        code.putln("/*--- Library function declarations ---*/")
1665
        env.generate_library_function_declarations(code)
1666

1667 1668
        code.putln("/*--- Threads initialization code ---*/")
        code.putln("#if defined(__PYX_FORCE_INIT_THREADS) && __PYX_FORCE_INIT_THREADS")
1669
        code.putln("#ifdef WITH_THREAD /* Python build with threading support? */")
1670 1671 1672 1673
        code.putln("PyEval_InitThreads();")
        code.putln("#endif")
        code.putln("#endif")

1674
        code.putln("/*--- Module creation code ---*/")
1675
        self.generate_module_creation_code(env, code)
1676

1677 1678 1679
        code.putln("/*--- Initialize various global constants etc. ---*/")
        code.putln(code.error_goto_if_neg("__Pyx_InitGlobals()", self.pos))

1680 1681
        __main__name = code.globalstate.get_py_string_const(
            EncodedString("__main__"), identifier=True)
1682 1683 1684 1685
        code.putln("if (%s%s) {" % (Naming.module_is_main, self.full_module_name.replace('.', '__')))
        code.putln(
            'if (__Pyx_SetAttrString(%s, "__name__", %s) < 0) %s;' % (
                env.module_cname,
1686
                __main__name.cname,
1687 1688 1689
                code.error_goto(self.pos)))
        code.putln("}")

Robert Bradshaw's avatar
Robert Bradshaw committed
1690 1691
        if Options.cache_builtins:
            code.putln("/*--- Builtin init code ---*/")
1692 1693
            code.putln(code.error_goto_if_neg("__Pyx_InitCachedBuiltins()",
                                              self.pos))
1694

1695
        code.putln("/*--- Global init code ---*/")
1696
        self.generate_global_init_code(env, code)
Gary Furnish's avatar
Gary Furnish committed
1697

1698
        code.putln("/*--- Function export code ---*/")
1699 1700
        self.generate_c_function_export_code(env, code)

1701
        code.putln("/*--- Type init code ---*/")
1702
        self.generate_type_init_code(env, code)
1703

1704
        code.putln("/*--- Type import code ---*/")
1705 1706 1707
        for module in imported_modules:
            self.generate_type_import_code_for_module(module, env, code)

Gary Furnish's avatar
Gary Furnish committed
1708 1709 1710 1711
        code.putln("/*--- Function import code ---*/")
        for module in imported_modules:
            self.generate_c_function_import_code_for_module(module, env, code)

1712
        code.putln("/*--- Execution code ---*/")
Robert Bradshaw's avatar
Robert Bradshaw committed
1713
        code.mark_pos(None)
1714
        
1715
        self.body.generate_execution_code(code)
1716

1717
        if Options.generate_cleanup_code:
1718
            # this should be replaced by the module's tp_clear in Py3
1719
            env.use_utility_code(import_module_utility_code)
1720
            code.putln("if (__Pyx_RegisterCleanup()) %s;" % code.error_goto(self.pos))
1721

1722
        code.put_goto(code.return_label)
1723
        code.put_label(code.error_label)
Dag Sverre Seljebotn's avatar
Dag Sverre Seljebotn committed
1724 1725
        for cname, type in code.funcstate.all_managed_temps():
            code.put_xdecref(cname, type)
1726 1727
        code.putln('if (%s) {' % env.module_cname)
        code.putln('__Pyx_AddTraceback("init %s");' % env.qualified_name)
1728
        env.use_utility_code(Nodes.traceback_utility_code)
1729
        code.put_decref_clear(env.module_cname, py_object_type, nanny=False)
1730 1731 1732
        code.putln('} else if (!PyErr_Occurred()) {')
        code.putln('PyErr_SetString(PyExc_ImportError, "init %s");' % env.qualified_name)
        code.putln('}')
1733
        code.put_label(code.return_label)
1734 1735 1736

        code.put_finish_refcount_context()

1737 1738 1739
        code.putln("#if PY_MAJOR_VERSION < 3")
        code.putln("return;")
        code.putln("#else")
1740
        code.putln("return %s;" % env.module_cname)
1741
        code.putln("#endif")
1742
        code.putln('}')
1743

1744
        tempdecl_code.put_temp_declarations(code.funcstate)
1745

1746
        code.exit_cfunc_scope()
1747

1748 1749 1750
    def generate_module_cleanup_func(self, env, code):
        if not Options.generate_cleanup_code:
            return
1751
        code.globalstate.use_utility_code(register_cleanup_utility_code)
1752
        code.putln('static PyObject* %s(PyObject *self, PyObject *unused) {' % Naming.cleanup_cname)
1753 1754
        if Options.generate_cleanup_code >= 2:
            code.putln("/*--- Global cleanup code ---*/")
1755 1756 1757
            rev_entries = list(env.var_entries)
            rev_entries.reverse()
            for entry in rev_entries:
1758
                if entry.visibility != 'extern':
1759
                    if entry.type.is_pyobject and entry.used:
1760 1761
                        code.putln("Py_DECREF(%s); %s = 0;" % (
                            code.entry_as_pyobject(entry), entry.cname))
1762
        code.putln("__Pyx_CleanupGlobals();")
1763 1764 1765
        if Options.generate_cleanup_code >= 3:
            code.putln("/*--- Type import cleanup code ---*/")
            for type, _ in env.types_imported.items():
1766
                code.putln("Py_DECREF((PyObject *)%s);" % type.typeptr_cname)
1767 1768
        if Options.cache_builtins:
            code.putln("/*--- Builtin cleanup code ---*/")
1769
            for entry in env.cached_builtins:
1770 1771 1772
                code.put_decref_clear(entry.cname,
                                      PyrexTypes.py_object_type,
                                      nanny=False)
1773
        code.putln("/*--- Intern cleanup code ---*/")
1774 1775 1776
        code.put_decref_clear(Naming.empty_tuple,
                              PyrexTypes.py_object_type,
                              nanny=False)
1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789
#        for entry in env.pynum_entries:
#            code.put_decref_clear(entry.cname,
#                                  PyrexTypes.py_object_type,
#                                  nanny=False)
#        for entry in env.all_pystring_entries:
#            if entry.is_interned:
#                code.put_decref_clear(entry.pystring_cname,
#                                      PyrexTypes.py_object_type,
#                                      nanny=False)
#        for entry in env.default_entries:
#            if entry.type.is_pyobject and entry.used:
#                code.putln("Py_DECREF(%s); %s = 0;" % (
#                    code.entry_as_pyobject(entry), entry.cname))
1790 1791
        code.putln("Py_INCREF(Py_None); return Py_None;")

1792
    def generate_main_method(self, env, code):
1793 1794
        module_is_main = "%s%s" % (Naming.module_is_main, self.full_module_name.replace('.', '__'))
        code.globalstate.use_utility_code(main_method.specialize(module_name=env.module_name, module_is_main=module_is_main))
1795

1796 1797
    def generate_filename_init_call(self, code):
        code.putln("%s();" % Naming.fileinit_cname)
1798 1799 1800

    def generate_pymoduledef_struct(self, env, code):
        if env.doc:
1801
            doc = "__Pyx_DOCSTR(%s)" % code.get_string_const(env.doc)
1802 1803 1804 1805 1806 1807
        else:
            doc = "0"
        code.putln("")
        code.putln("#if PY_MAJOR_VERSION >= 3")
        code.putln("static struct PyModuleDef %s = {" % Naming.pymoduledef_cname)
        code.putln("  PyModuleDef_HEAD_INIT,")
1808
        code.putln('  __Pyx_NAMESTR("%s"),' % env.module_name)
1809 1810 1811 1812 1813 1814 1815 1816 1817 1818
        code.putln("  %s, /* m_doc */" % doc)
        code.putln("  -1, /* m_size */")
        code.putln("  %s /* m_methods */," % env.method_table_cname)
        code.putln("  NULL, /* m_reload */")
        code.putln("  NULL, /* m_traverse */")
        code.putln("  NULL, /* m_clear */")
        code.putln("  NULL /* m_free */")
        code.putln("};")
        code.putln("#endif")

1819 1820 1821 1822
    def generate_module_creation_code(self, env, code):
        # Generate code to create the module object and
        # install the builtins.
        if env.doc:
1823
            doc = "__Pyx_DOCSTR(%s)" % code.get_string_const(env.doc)
1824 1825
        else:
            doc = "0"
1826
        code.putln("#if PY_MAJOR_VERSION < 3")
1827
        code.putln(
1828
            '%s = Py_InitModule4(__Pyx_NAMESTR("%s"), %s, %s, 0, PYTHON_API_VERSION);' % (
1829 1830 1831 1832
                env.module_cname, 
                env.module_name, 
                env.method_table_cname, 
                doc))
1833 1834 1835 1836 1837 1838
        code.putln("#else")
        code.putln(
            "%s = PyModule_Create(&%s);" % (
                env.module_cname,
                Naming.pymoduledef_cname))
        code.putln("#endif")
1839 1840 1841 1842
        code.putln(
            "if (!%s) %s;" % (
                env.module_cname,
                code.error_goto(self.pos)));
1843
        code.putln("#if PY_MAJOR_VERSION < 3")
Dag Sverre Seljebotn's avatar
Merge  
Dag Sverre Seljebotn committed
1844 1845 1846
        code.putln(
            "Py_INCREF(%s);" %
                env.module_cname)
1847
        code.putln("#endif")
1848
        code.putln(
1849
            '%s = PyImport_AddModule(__Pyx_NAMESTR(__Pyx_BUILTIN_MODULE_NAME));' %
1850 1851 1852 1853 1854 1855
                Naming.builtins_cname)
        code.putln(
            "if (!%s) %s;" % (
                Naming.builtins_cname,
                code.error_goto(self.pos)));
        code.putln(
1856
            'if (__Pyx_SetAttrString(%s, "__builtins__", %s) < 0) %s;' % (
1857 1858 1859
                env.module_cname,
                Naming.builtins_cname,
                code.error_goto(self.pos)))
1860 1861
        if Options.pre_import is not None:
            code.putln(
1862
                '%s = PyImport_AddModule(__Pyx_NAMESTR("%s"));' % (
1863 1864 1865 1866 1867 1868
                    Naming.preimport_cname, 
                    Options.pre_import))
            code.putln(
                "if (!%s) %s;" % (
                    Naming.preimport_cname,
                    code.error_goto(self.pos)));
1869

1870 1871 1872 1873
    def generate_global_init_code(self, env, code):
        # Generate code to initialise global PyObject *
        # variables to None.
        for entry in env.var_entries:
1874
            if entry.visibility != 'extern':
1875
                if entry.type.is_pyobject and entry.used:
1876
                    code.put_init_var_to_py_none(entry, nanny=False)
1877 1878 1879 1880 1881 1882 1883

    def generate_c_function_export_code(self, env, code):
        # Generate code to create PyCFunction wrappers for exported C functions.
        for entry in env.cfunc_entries:
            if entry.api or entry.defined_in_pxd:
                env.use_utility_code(function_export_utility_code)
                signature = entry.type.signature_string()
1884
                code.putln('if (__Pyx_ExportFunction("%s", (void (*)(void))%s, "%s") < 0) %s' % (
1885 1886 1887 1888
                    entry.name,
                    entry.cname,
                    signature, 
                    code.error_goto(self.pos)))
1889 1890
    
    def generate_type_import_code_for_module(self, module, env, code):
1891
        # Generate type import code for all exported extension types in
1892
        # an imported module.
1893 1894 1895
        #if module.c_class_entries:
        for entry in module.c_class_entries:
            if entry.defined_in_pxd:
1896 1897
                self.generate_type_import_code(env, entry.type, entry.pos, code)
    
1898 1899 1900 1901 1902 1903 1904 1905 1906
    def generate_c_function_import_code_for_module(self, module, env, code):
        # Generate import code for all exported C functions in a cimported module.
        entries = []
        for entry in module.cfunc_entries:
            if entry.defined_in_pxd:
                entries.append(entry)
        if entries:
            env.use_utility_code(import_module_utility_code)
            env.use_utility_code(function_import_utility_code)
1907
            temp = code.funcstate.allocate_temp(py_object_type, manage_ref=True)
1908 1909 1910 1911 1912 1913
            code.putln(
                '%s = __Pyx_ImportModule("%s"); if (!%s) %s' % (
                    temp,
                    module.qualified_name,
                    temp,
                    code.error_goto(self.pos)))
1914 1915
            for entry in entries:
                code.putln(
1916
                    'if (__Pyx_ImportFunction(%s, "%s", (void (**)(void))&%s, "%s") < 0) %s' % (
1917
                        temp,
1918 1919 1920 1921
                        entry.name,
                        entry.cname,
                        entry.type.signature_string(),
                        code.error_goto(self.pos)))
1922
            code.putln("Py_DECREF(%s); %s = 0;" % (temp, temp))
1923
    
1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934
    def generate_type_init_code(self, env, code):
        # Generate type import code for extern extension types
        # and type ready code for non-extern ones.
        for entry in env.c_class_entries:
            if entry.visibility == 'extern':
                self.generate_type_import_code(env, entry.type, entry.pos, code)
            else:
                self.generate_base_type_import_code(env, entry, code)
                self.generate_exttype_vtable_init_code(entry, code)
                self.generate_type_ready_code(env, entry, code)
                self.generate_typeptr_assignment_code(entry, code)
1935

1936 1937
    def generate_base_type_import_code(self, env, entry, code):
        base_type = entry.type.base_type
Stefan Behnel's avatar
Stefan Behnel committed
1938
        if base_type and base_type.module_name != env.qualified_name:
1939 1940 1941
            self.generate_type_import_code(env, base_type, self.pos, code)
    
    def use_type_import_utility_code(self, env):
1942 1943
        env.use_utility_code(type_import_utility_code)
        env.use_utility_code(import_module_utility_code)
1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954
    
    def generate_type_import_code(self, env, type, pos, code):
        # If not already done, generate code to import the typeobject of an
        # extension type defined in another module, and extract its C method
        # table pointer if any.
        if type in env.types_imported:
            return
        if type.typedef_flag:
            objstruct = type.objstruct_cname
        else:
            objstruct = "struct %s" % type.objstruct_cname
1955 1956
        self.generate_type_import_call(type, code,
                                       code.error_goto_if_null(type.typeptr_cname, pos))
1957 1958 1959 1960 1961 1962 1963 1964 1965
        self.use_type_import_utility_code(env)
        if type.vtabptr_cname:
            code.putln(
                "if (__Pyx_GetVtable(%s->tp_dict, &%s) < 0) %s" % (
                    type.typeptr_cname,
                    type.vtabptr_cname,
                    code.error_goto(pos)))
            env.use_utility_code(Nodes.get_vtable_utility_code)
        env.types_imported[type] = 1
1966

1967 1968
    py3_type_name_map = {'str' : 'bytes', 'unicode' : 'str'}

1969 1970 1971 1972 1973
    def generate_type_import_call(self, type, code, error_code):
        if type.typedef_flag:
            objstruct = type.objstruct_cname
        else:
            objstruct = "struct %s" % type.objstruct_cname
1974 1975 1976 1977 1978
        module_name = type.module_name
        if module_name not in ('__builtin__', 'builtins'):
            module_name = '"%s"' % module_name
        else:
            module_name = '__Pyx_BUILTIN_MODULE_NAME'
1979 1980 1981 1982 1983 1984 1985 1986 1987
        if type.name in self.py3_type_name_map:
            code.putln("#if PY_MAJOR_VERSION >= 3")
            code.putln('%s = __Pyx_ImportType(%s, "%s", sizeof(%s)); %s' % (
                    type.typeptr_cname,
                    module_name,
                    self.py3_type_name_map[type.name],
                    objstruct,
                    error_code))
            code.putln("#else")
1988
        code.putln('%s = __Pyx_ImportType(%s, "%s", sizeof(%s)); %s' % (
1989 1990 1991 1992 1993 1994 1995
                type.typeptr_cname,
                module_name,
                type.name,
                objstruct,
                error_code))
        if type.name in self.py3_type_name_map:
            code.putln("#endif")
1996

1997 1998 1999 2000 2001 2002 2003
    def generate_type_ready_code(self, env, entry, code):
        # Generate a call to PyType_Ready for an extension
        # type defined in this module.
        type = entry.type
        typeobj_cname = type.typeobj_cname
        scope = type.scope
        if scope: # could be None if there was an error
Stefan Behnel's avatar
Stefan Behnel committed
2004
            if entry.visibility != 'extern':
2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018
                for slot in TypeSlots.slot_table:
                    slot.generate_dynamic_init_code(scope, code)
                code.putln(
                    "if (PyType_Ready(&%s) < 0) %s" % (
                        typeobj_cname,
                        code.error_goto(entry.pos)))
                if type.vtable_cname:
                    code.putln(
                        "if (__Pyx_SetVtable(%s.tp_dict, %s) < 0) %s" % (
                            typeobj_cname,
                            type.vtabptr_cname,
                            code.error_goto(entry.pos)))
                    env.use_utility_code(Nodes.set_vtable_utility_code)
                code.putln(
2019
                    'if (__Pyx_SetAttrString(%s, "%s", (PyObject *)&%s) < 0) %s' % (
2020 2021 2022 2023 2024 2025 2026 2027
                        Naming.module_cname,
                        scope.class_name,
                        typeobj_cname,
                        code.error_goto(entry.pos)))
                weakref_entry = scope.lookup_here("__weakref__")
                if weakref_entry:
                    if weakref_entry.type is py_object_type:
                        tp_weaklistoffset = "%s.tp_weaklistoffset" % typeobj_cname
2028 2029 2030 2031 2032
                        if type.typedef_flag:
                            objstruct = type.objstruct_cname
                        else:
                            objstruct = "struct %s" % type.objstruct_cname
                        code.putln("if (%s == 0) %s = offsetof(%s, %s);" % (
2033 2034
                            tp_weaklistoffset,
                            tp_weaklistoffset,
2035
                            objstruct,
2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054
                            weakref_entry.cname))
                    else:
                        error(weakref_entry.pos, "__weakref__ slot must be of type 'object'")
    
    def generate_exttype_vtable_init_code(self, entry, code):
        # Generate code to initialise the C method table of an
        # extension type.
        type = entry.type
        if type.vtable_cname:
            code.putln(
                "%s = &%s;" % (
                    type.vtabptr_cname,
                    type.vtable_cname))
            if type.base_type and type.base_type.vtabptr_cname:
                code.putln(
                    "%s.%s = *%s;" % (
                        type.vtable_cname,
                        Naming.obj_base_cname,
                        type.base_type.vtabptr_cname))
2055 2056 2057 2058

            c_method_entries = [
                entry for entry in type.scope.cfunc_entries
                if entry.func_cname ]
2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076
            if c_method_entries:
                code.putln('#if PY_MAJOR_VERSION >= 3')
                for meth_entry in c_method_entries:
                    cast = meth_entry.type.signature_cast_string()
                    code.putln(
                        "%s.%s = %s%s;" % (
                            type.vtable_cname,
                            meth_entry.cname,
                            cast,
                            meth_entry.func_cname))
                code.putln('#else')
                for meth_entry in c_method_entries:
                    code.putln(
                        "*(void(**)(void))&%s.%s = (void(*)(void))%s;" % (
                            type.vtable_cname,
                            meth_entry.cname,
                            meth_entry.func_cname))
                code.putln('#endif')
2077 2078 2079 2080 2081 2082 2083 2084 2085 2086
    
    def generate_typeptr_assignment_code(self, entry, code):
        # Generate code to initialise the typeptr of an extension
        # type defined in this module to point to its type object.
        type = entry.type
        if type.typeobj_cname:
            code.putln(
                "%s = &%s;" % (
                    type.typeptr_cname, type.typeobj_cname))
    
2087
#------------------------------------------------------------------------------------
Stefan Behnel's avatar
Stefan Behnel committed
2088 2089 2090
#
#  Runtime support code
#
2091 2092
#------------------------------------------------------------------------------------

2093 2094
builtin_module_name_utility_code = UtilityCode(
proto = """\
2095 2096 2097 2098 2099
#if PY_MAJOR_VERSION < 3
  #define __Pyx_BUILTIN_MODULE_NAME "__builtin__"
#else
  #define __Pyx_BUILTIN_MODULE_NAME "builtins"
#endif
2100
""")
2101

2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116
#------------------------------------------------------------------------------------

streq_utility_code = UtilityCode(
proto = """
static INLINE int __Pyx_StrEq(const char *, const char *); /*proto*/
""",
impl = """
static INLINE int __Pyx_StrEq(const char *s1, const char *s2) {
     while (*s1 != '\\0' && *s1 == *s2) { s1++; s2++; }
     return *s1 == *s2;
}
""")

#------------------------------------------------------------------------------------

2117 2118
import_module_utility_code = UtilityCode(
proto = """
2119
static PyObject *__Pyx_ImportModule(const char *name); /*proto*/
2120 2121
""",
impl = """
2122 2123
#ifndef __PYX_HAVE_RT_ImportModule
#define __PYX_HAVE_RT_ImportModule
2124
static PyObject *__Pyx_ImportModule(const char *name) {
2125
    PyObject *py_name = 0;
2126
    PyObject *py_module = 0;
2127 2128

    #if PY_MAJOR_VERSION < 3
2129
    py_name = PyString_FromString(name);
2130 2131 2132
    #else
    py_name = PyUnicode_FromString(name);
    #endif
2133 2134
    if (!py_name)
        goto bad;
2135 2136 2137
    py_module = PyImport_Import(py_name);
    Py_DECREF(py_name);
    return py_module;
2138 2139 2140 2141
bad:
    Py_XDECREF(py_name);
    return 0;
}
2142
#endif
2143
""")
2144 2145 2146

#------------------------------------------------------------------------------------

2147 2148
type_import_utility_code = UtilityCode(
proto = """
2149
static PyTypeObject *__Pyx_ImportType(const char *module_name, const char *class_name, long size);  /*proto*/
2150 2151
""",
impl = """
Stefan Behnel's avatar
Stefan Behnel committed
2152 2153
#ifndef __PYX_HAVE_RT_ImportType
#define __PYX_HAVE_RT_ImportType
2154
static PyTypeObject *__Pyx_ImportType(const char *module_name, const char *class_name,
2155 2156 2157
    long size)
{
    PyObject *py_module = 0;
2158
    PyObject *result = 0;
Gary Furnish's avatar
Gary Furnish committed
2159
    PyObject *py_name = 0;
2160

2161 2162 2163
    py_module = __Pyx_ImportModule(module_name);
    if (!py_module)
        goto bad;
2164
    #if PY_MAJOR_VERSION < 3
2165
    py_name = PyString_FromString(class_name);
2166
    #else
2167
    py_name = PyUnicode_FromString(class_name);
2168
    #endif
Gary Furnish's avatar
Gary Furnish committed
2169 2170
    if (!py_name)
        goto bad;
2171 2172
    result = PyObject_GetAttr(py_module, py_name);
    Py_DECREF(py_name);
2173 2174 2175
    py_name = 0;
    Py_DECREF(py_module);
    py_module = 0;
2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191
    if (!result)
        goto bad;
    if (!PyType_Check(result)) {
        PyErr_Format(PyExc_TypeError, 
            "%s.%s is not a type object",
            module_name, class_name);
        goto bad;
    }
    if (((PyTypeObject *)result)->tp_basicsize != size) {
        PyErr_Format(PyExc_ValueError, 
            "%s.%s does not appear to be the correct type object",
            module_name, class_name);
        goto bad;
    }
    return (PyTypeObject *)result;
bad:
2192
    Py_XDECREF(py_module);
2193 2194 2195
    Py_XDECREF(result);
    return 0;
}
Stefan Behnel's avatar
Stefan Behnel committed
2196
#endif
2197
""")
2198 2199 2200

#------------------------------------------------------------------------------------

2201 2202
function_export_utility_code = UtilityCode(
proto = """
2203
static int __Pyx_ExportFunction(const char *name, void (*f)(void), const char *sig); /*proto*/
2204 2205
""",
impl = r"""
2206
static int __Pyx_ExportFunction(const char *name, void (*f)(void), const char *sig) {
2207
    PyObject *d = 0;
2208 2209 2210 2211 2212 2213
    PyObject *cobj = 0;
    union {
        void (*fp)(void);
        void *p;
    } tmp;

2214
    d = PyObject_GetAttrString(%(MODULE)s, (char *)"%(API)s");
2215 2216 2217 2218 2219 2220
    if (!d) {
        PyErr_Clear();
        d = PyDict_New();
        if (!d)
            goto bad;
        Py_INCREF(d);
2221
        if (PyModule_AddObject(%(MODULE)s, (char *)"%(API)s", d) < 0)
2222 2223
            goto bad;
    }
2224
    tmp.fp = f;
2225
#if PY_VERSION_HEX < 0x03010000
2226
    cobj = PyCObject_FromVoidPtrAndDesc(tmp.p, (void *)sig, 0);
2227 2228 2229
#else
    cobj = PyCapsule_New(tmp.p, sig, 0);
#endif
2230
    if (!cobj)
2231
        goto bad;
2232
    if (PyDict_SetItemString(d, name, cobj) < 0)
2233
        goto bad;
2234
    Py_DECREF(cobj);
2235
    Py_DECREF(d);
2236 2237
    return 0;
bad:
2238
    Py_XDECREF(cobj);
2239
    Py_XDECREF(d);
2240 2241
    return -1;
}
2242 2243
""" % {'MODULE': Naming.module_cname, 'API': Naming.api_name}
)
2244

2245 2246
function_import_utility_code = UtilityCode(
proto = """
2247
static int __Pyx_ImportFunction(PyObject *module, const char *funcname, void (**f)(void), const char *sig); /*proto*/
2248 2249
""",
impl = """
Stefan Behnel's avatar
Stefan Behnel committed
2250 2251
#ifndef __PYX_HAVE_RT_ImportFunction
#define __PYX_HAVE_RT_ImportFunction
2252
static int __Pyx_ImportFunction(PyObject *module, const char *funcname, void (**f)(void), const char *sig) {
2253
    PyObject *d = 0;
2254
    PyObject *cobj = 0;
2255 2256 2257 2258
    union {
        void (*fp)(void);
        void *p;
    } tmp;
2259 2260 2261
#if PY_VERSION_HEX < 0x03010000
    const char *desc, *s1, *s2;
#endif
2262

2263
    d = PyObject_GetAttrString(module, (char *)"%(API)s");
2264 2265 2266
    if (!d)
        goto bad;
    cobj = PyDict_GetItemString(d, funcname);
2267 2268
    if (!cobj) {
        PyErr_Format(PyExc_ImportError,
2269
            "%%s does not export expected C function %%s",
2270 2271 2272
                PyModule_GetName(module), funcname);
        goto bad;
    }
2273
#if PY_VERSION_HEX < 0x03010000
2274
    desc = (const char *)PyCObject_GetDesc(cobj);
2275 2276
    if (!desc)
        goto bad;
2277 2278 2279
    s1 = desc; s2 = sig;
    while (*s1 != '\\0' && *s1 == *s2) { s1++; s2++; }
    if (*s1 != *s2) {
2280
        PyErr_Format(PyExc_TypeError,
2281
            "C function %%s.%%s has wrong signature (expected %%s, got %%s)",
2282
             PyModule_GetName(module), funcname, sig, desc);
2283 2284
        goto bad;
    }
2285
    tmp.p = PyCObject_AsVoidPtr(cobj);
2286 2287 2288 2289 2290 2291 2292 2293 2294
#else
    if (!PyCapsule_IsValid(cobj, sig)) {
        PyErr_Format(PyExc_TypeError,
            "C function %%s.%%s has wrong signature (expected %%s, got %%s)",
             PyModule_GetName(module), funcname, sig, PyCapsule_GetName(cobj));
        goto bad;
    }
    tmp.p = PyCapsule_GetPointer(cobj, sig);
#endif
2295
    *f = tmp.fp;
2296 2297
    if (!(*f))
        goto bad;
2298
    Py_DECREF(d);
2299 2300
    return 0;
bad:
2301
    Py_XDECREF(d);
2302 2303
    return -1;
}
Stefan Behnel's avatar
Stefan Behnel committed
2304
#endif
2305 2306
""" % dict(API = Naming.api_name)
)
2307

2308 2309
#------------------------------------------------------------------------------------

2310 2311
register_cleanup_utility_code = UtilityCode(
proto = """
2312
static int __Pyx_RegisterCleanup(void); /*proto*/
2313
static PyObject* __pyx_module_cleanup(PyObject *self, PyObject *unused); /*proto*/
2314
static PyMethodDef cleanup_def = {__Pyx_NAMESTR("__cleanup"), (PyCFunction)&__pyx_module_cleanup, METH_NOARGS, 0};
2315 2316
""",
impl = """
2317
static int __Pyx_RegisterCleanup(void) {
2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338
    /* Don't use Py_AtExit because that has a 32-call limit 
     * and is called after python finalization. 
     */

    PyObject *cleanup_func = 0;
    PyObject *atexit = 0;
    PyObject *reg = 0;
    PyObject *args = 0;
    PyObject *res = 0;
    int ret = -1;
    
    cleanup_func = PyCFunction_New(&cleanup_def, 0);
    args = PyTuple_New(1);
    if (!cleanup_func || !args)
        goto bad;
    PyTuple_SET_ITEM(args, 0, cleanup_func);
    cleanup_func = 0;

    atexit = __Pyx_ImportModule("atexit");
    if (!atexit)
        goto bad;
2339
    reg = __Pyx_GetAttrString(atexit, "register");
2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353
    if (!reg)
        goto bad;
    res = PyObject_CallObject(reg, args);
    if (!res)
        goto bad;
    ret = 0;
bad:
    Py_XDECREF(cleanup_func);
    Py_XDECREF(atexit);
    Py_XDECREF(reg);
    Py_XDECREF(args);
    Py_XDECREF(res);
    return ret;
}
2354
""")
Dag Sverre Seljebotn's avatar
Merge  
Dag Sverre Seljebotn committed
2355 2356 2357 2358 2359 2360 2361 2362

import_star_utility_code = """

/* import_all_from is an unexposed function from ceval.c */

static int
__Pyx_import_all_from(PyObject *locals, PyObject *v)
{
Robert Bradshaw's avatar
Robert Bradshaw committed
2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396
    PyObject *all = __Pyx_GetAttrString(v, "__all__");
    PyObject *dict, *name, *value;
    int skip_leading_underscores = 0;
    int pos, err;

    if (all == NULL) {
        if (!PyErr_ExceptionMatches(PyExc_AttributeError))
            return -1; /* Unexpected error */
        PyErr_Clear();
        dict = __Pyx_GetAttrString(v, "__dict__");
        if (dict == NULL) {
            if (!PyErr_ExceptionMatches(PyExc_AttributeError))
                return -1;
            PyErr_SetString(PyExc_ImportError,
            "from-import-* object has no __dict__ and no __all__");
            return -1;
        }
        all = PyMapping_Keys(dict);
        Py_DECREF(dict);
        if (all == NULL)
            return -1;
        skip_leading_underscores = 1;
    }

    for (pos = 0, err = 0; ; pos++) {
        name = PySequence_GetItem(all, pos);
        if (name == NULL) {
            if (!PyErr_ExceptionMatches(PyExc_IndexError))
                err = -1;
            else
                PyErr_Clear();
            break;
        }
        if (skip_leading_underscores &&
2397
#if PY_MAJOR_VERSION < 3
Robert Bradshaw's avatar
Robert Bradshaw committed
2398 2399
            PyString_Check(name) &&
            PyString_AS_STRING(name)[0] == '_')
2400
#else
Robert Bradshaw's avatar
Robert Bradshaw committed
2401 2402
            PyUnicode_Check(name) &&
            PyUnicode_AS_UNICODE(name)[0] == '_')
2403
#endif
Robert Bradshaw's avatar
Robert Bradshaw committed
2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421
        {
            Py_DECREF(name);
            continue;
        }
        value = PyObject_GetAttr(v, name);
        if (value == NULL)
            err = -1;
        else if (PyDict_CheckExact(locals))
            err = PyDict_SetItem(locals, name, value);
        else
            err = PyObject_SetItem(locals, name, value);
        Py_DECREF(name);
        Py_XDECREF(value);
        if (err != 0)
            break;
    }
    Py_DECREF(all);
    return err;
Dag Sverre Seljebotn's avatar
Merge  
Dag Sverre Seljebotn committed
2422 2423 2424
}


2425
static int %(IMPORT_STAR)s(PyObject* m) {
Dag Sverre Seljebotn's avatar
Merge  
Dag Sverre Seljebotn committed
2426 2427 2428

    int i;
    int ret = -1;
2429
    char* s;
Dag Sverre Seljebotn's avatar
Merge  
Dag Sverre Seljebotn committed
2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441
    PyObject *locals = 0;
    PyObject *list = 0;
    PyObject *name;
    PyObject *item;
    
    locals = PyDict_New();              if (!locals) goto bad;
    if (__Pyx_import_all_from(locals, m) < 0) goto bad;
    list = PyDict_Items(locals);        if (!list) goto bad;
    
    for(i=0; i<PyList_GET_SIZE(list); i++) {
        name = PyTuple_GET_ITEM(PyList_GET_ITEM(list, i), 0);
        item = PyTuple_GET_ITEM(PyList_GET_ITEM(list, i), 1);
2442 2443 2444 2445 2446 2447 2448
#if PY_MAJOR_VERSION < 3
        s = PyString_AsString(name);
#else
        s = PyUnicode_AsString(name);
#endif
        if (!s) goto bad;
        if (%(IMPORT_STAR_SET)s(item, name, s) < 0) goto bad;
Dag Sverre Seljebotn's avatar
Merge  
Dag Sverre Seljebotn committed
2449 2450 2451 2452 2453 2454 2455 2456
    }
    ret = 0;
    
bad:
    Py_XDECREF(locals);
    Py_XDECREF(list);
    return ret;
}
2457 2458
""" % {'IMPORT_STAR'     : Naming.import_star,
       'IMPORT_STAR_SET' : Naming.import_star_set }
2459
        
2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496
refnanny_utility_code = UtilityCode(proto="""
#ifndef CYTHON_REFNANNY
  #define CYTHON_REFNANNY 0
#endif

#if CYTHON_REFNANNY
  typedef struct {
    void (*INCREF)(void*, PyObject*, int);
    void (*DECREF)(void*, PyObject*, int);
    void (*GOTREF)(void*, PyObject*, int);
    void (*GIVEREF)(void*, PyObject*, int);
    void* (*SetupContext)(const char*, int, const char*);
    void (*FinishContext)(void**);
  } __Pyx_RefNannyAPIStruct;
  static __Pyx_RefNannyAPIStruct *__Pyx_RefNanny = NULL;
  static __Pyx_RefNannyAPIStruct * __Pyx_RefNannyImportAPI(const char *modname) {
    PyObject *m = NULL, *p = NULL;
    void *r = NULL;
    m = PyImport_ImportModule((char *)modname);
    if (!m) goto end;
    p = PyObject_GetAttrString(m, (char *)\"RefNannyAPI\");
    if (!p) goto end;
    r = PyLong_AsVoidPtr(p);
  end:
    Py_XDECREF(p);
    Py_XDECREF(m);
    return (__Pyx_RefNannyAPIStruct *)r;
  }
  #define __Pyx_RefNannySetupContext(name) \
          void *__pyx_refnanny = __Pyx_RefNanny->SetupContext((name), __LINE__, __FILE__)
  #define __Pyx_RefNannyFinishContext() \
          __Pyx_RefNanny->FinishContext(&__pyx_refnanny)
  #define __Pyx_INCREF(r) __Pyx_RefNanny->INCREF(__pyx_refnanny, (PyObject *)(r), __LINE__)
  #define __Pyx_DECREF(r) __Pyx_RefNanny->DECREF(__pyx_refnanny, (PyObject *)(r), __LINE__)
  #define __Pyx_GOTREF(r) __Pyx_RefNanny->GOTREF(__pyx_refnanny, (PyObject *)(r), __LINE__)
  #define __Pyx_GIVEREF(r) __Pyx_RefNanny->GIVEREF(__pyx_refnanny, (PyObject *)(r), __LINE__)
  #define __Pyx_XDECREF(r) do { if((r) != NULL) {__Pyx_DECREF(r);} } while(0)
2497
#else
2498 2499 2500 2501 2502 2503 2504
  #define __Pyx_RefNannySetupContext(name)
  #define __Pyx_RefNannyFinishContext()
  #define __Pyx_INCREF(r) Py_INCREF(r)
  #define __Pyx_DECREF(r) Py_DECREF(r)
  #define __Pyx_GOTREF(r)
  #define __Pyx_GIVEREF(r)
  #define __Pyx_XDECREF(r) Py_XDECREF(r)
2505
#endif /* CYTHON_REFNANNY */
2506 2507
#define __Pyx_XGIVEREF(r) do { if((r) != NULL) {__Pyx_GIVEREF(r);} } while(0)
#define __Pyx_XGOTREF(r) do { if((r) != NULL) {__Pyx_GOTREF(r);} } while(0)
2508
""")
2509

Robert Bradshaw's avatar
Robert Bradshaw committed
2510

2511 2512
main_method = UtilityCode(
impl = """
2513 2514 2515 2516 2517
#ifdef __FreeBSD__
#include <floatingpoint.h>
#endif

#if PY_MAJOR_VERSION < 3
2518
int main(int argc, char** argv) {
2519
#elif defined(WIN32) || defined(MS_WINDOWS)
2520
int wmain(int argc, wchar_t **argv) {
2521 2522
#else
static int __Pyx_main(int argc, wchar_t **argv) {
2523
#endif
2524 2525
    int r = 0;
    PyObject* m = NULL;
2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536
    /* 754 requires that FP exceptions run in "no stop" mode by default,
     * and until C vendors implement C99's ways to control FP exceptions,
     * Python requires non-stop mode.  Alas, some platforms enable FP
     * exceptions by default.  Here we disable them.
     */
#ifdef __FreeBSD__
    fp_except_t m;

    m = fpgetmask();
    fpsetmask(m & ~FP_X_OFL);
#endif
2537
    Py_SetProgramName(argv[0]);
2538 2539
    Py_Initialize();
    PySys_SetArgv(argc, argv);
2540
    %(module_is_main)s = 1;
2541 2542 2543
#if PY_MAJOR_VERSION < 3
        init%(module_name)s();
#else
2544
        m = PyInit_%(module_name)s();
2545
#endif
2546 2547 2548
    if (PyErr_Occurred() != NULL) {
        r = 1;
        PyErr_Print(); /* This exits with the right code if SystemExit. */
2549
#if PY_MAJOR_VERSION < 3
2550
        if (Py_FlushLine()) PyErr_Clear();
2551
#endif
2552 2553
    }
    Py_XDECREF(m);
2554 2555 2556
    Py_Finalize();
    return r;
}
2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694


#if PY_MAJOR_VERSION >= 3 && !defined(WIN32) && !defined(MS_WINDOWS)
#include <locale.h>

static wchar_t*
__Pyx_char2wchar(char* arg)
{
	wchar_t *res;
#ifdef HAVE_BROKEN_MBSTOWCS
	/* Some platforms have a broken implementation of
	 * mbstowcs which does not count the characters that
	 * would result from conversion.  Use an upper bound.
	 */
	size_t argsize = strlen(arg);
#else
	size_t argsize = mbstowcs(NULL, arg, 0);
#endif
	size_t count;
	unsigned char *in;
	wchar_t *out;
#ifdef HAVE_MBRTOWC
	mbstate_t mbs;
#endif
	if (argsize != (size_t)-1) {
		res = (wchar_t *)PyMem_Malloc((argsize+1)*sizeof(wchar_t));
		if (!res)
			goto oom;
		count = mbstowcs(res, arg, argsize+1);
		if (count != (size_t)-1) {
			wchar_t *tmp;
			/* Only use the result if it contains no
			   surrogate characters. */
			for (tmp = res; *tmp != 0 &&
				     (*tmp < 0xd800 || *tmp > 0xdfff); tmp++)
				;
			if (*tmp == 0)
				return res;
		}
		PyMem_Free(res);
	}
	/* Conversion failed. Fall back to escaping with surrogateescape. */
#ifdef HAVE_MBRTOWC
	/* Try conversion with mbrtwoc (C99), and escape non-decodable bytes. */

	/* Overallocate; as multi-byte characters are in the argument, the
	   actual output could use less memory. */
	argsize = strlen(arg) + 1;
	res = PyMem_Malloc(argsize*sizeof(wchar_t));
	if (!res) goto oom;
	in = (unsigned char*)arg;
	out = res;
	memset(&mbs, 0, sizeof mbs);
	while (argsize) {
		size_t converted = mbrtowc(out, (char*)in, argsize, &mbs);
		if (converted == 0)
			/* Reached end of string; null char stored. */
			break;
		if (converted == (size_t)-2) {
			/* Incomplete character. This should never happen,
			   since we provide everything that we have -
			   unless there is a bug in the C library, or I
			   misunderstood how mbrtowc works. */
			fprintf(stderr, "unexpected mbrtowc result -2\\n");
			return NULL;
		}
		if (converted == (size_t)-1) {
			/* Conversion error. Escape as UTF-8b, and start over
			   in the initial shift state. */
			*out++ = 0xdc00 + *in++;
			argsize--;
			memset(&mbs, 0, sizeof mbs);
			continue;
		}
		if (*out >= 0xd800 && *out <= 0xdfff) {
			/* Surrogate character.  Escape the original
			   byte sequence with surrogateescape. */
			argsize -= converted;
			while (converted--)
				*out++ = 0xdc00 + *in++;
			continue;
		}
		/* successfully converted some bytes */
		in += converted;
		argsize -= converted;
		out++;
	}
#else
	/* Cannot use C locale for escaping; manually escape as if charset
	   is ASCII (i.e. escape all bytes > 128. This will still roundtrip
	   correctly in the locale's charset, which must be an ASCII superset. */
	res = PyMem_Malloc((strlen(arg)+1)*sizeof(wchar_t));
	if (!res) goto oom;
	in = (unsigned char*)arg;
	out = res;
	while(*in)
		if(*in < 128)
			*out++ = *in++;
		else
			*out++ = 0xdc00 + *in++;
	*out = 0;
#endif
	return res;
oom:
	fprintf(stderr, "out of memory\\n");
	return NULL;
}

int
main(int argc, char **argv)
{
	wchar_t **argv_copy = (wchar_t **)PyMem_Malloc(sizeof(wchar_t*)*argc);
	/* We need a second copies, as Python might modify the first one. */
	wchar_t **argv_copy2 = (wchar_t **)PyMem_Malloc(sizeof(wchar_t*)*argc);
	int i, res;
	char *oldloc;
	if (!argv_copy || !argv_copy2) {
		fprintf(stderr, "out of memory\\n");
		return 1;
	}
	oldloc = strdup(setlocale(LC_ALL, NULL));
	setlocale(LC_ALL, "");
	for (i = 0; i < argc; i++) {
		argv_copy2[i] = argv_copy[i] = __Pyx_char2wchar(argv[i]);
		if (!argv_copy[i])
			return 1;
	}
	setlocale(LC_ALL, oldloc);
	free(oldloc);
	res = __Pyx_main(argc, argv_copy);
	for (i = 0; i < argc; i++) {
		PyMem_Free(argv_copy2[i]);
	}
	PyMem_Free(argv_copy);
	PyMem_Free(argv_copy2);
	return res;
}
#endif
2695
""")
2696 2697 2698 2699 2700 2701 2702

packed_struct_utility_code = UtilityCode(proto="""
#if defined(__GNUC__)
#define __Pyx_PACKED __attribute__((__packed__))
#else
#define __Pyx_PACKED
#endif
Dag Sverre Seljebotn's avatar
Dag Sverre Seljebotn committed
2703
""", impl="", proto_block='utility_code_proto_before_types')