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

import os, time
from cStringIO import StringIO
7
from PyrexTypes import CPtrType
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 22
import Code
import Naming
import Nodes
import Options
import PyrexTypes
import TypeSlots
import Version

23
from Errors import error, warning
24
from PyrexTypes import py_object_type
William Stein's avatar
William Stein committed
25
from Cython.Utils import open_new_file, replace_suffix
26

Gary Furnish's avatar
Gary Furnish committed
27

28 29 30
class ModuleNode(Nodes.Node, Nodes.BlockNode):
    #  doc       string or None
    #  body      StatListNode
31 32 33
    #
    #  referenced_modules   [ModuleScope]
    #  module_temp_cname    string
34
    #  full_module_name     string
35 36

    children_attrs = ["body"]
37 38
    
    def analyse_declarations(self, env):
39
        if Options.embed_pos_in_docstring:
40
            env.doc = 'File: %s (starting at line %s)'%Nodes.relative_position(self.pos)
41 42 43 44
            if not self.doc is None:
                env.doc = env.doc + '\\n' + self.doc
        else:
            env.doc = self.doc
45 46
        self.body.analyse_declarations(env)
    
47
    def process_implementation(self, env, options, result):
48 49 50 51
        self.analyse_declarations(env)
        env.check_c_classes()
        self.body.analyse_expressions(env)
        env.return_type = PyrexTypes.c_void_type
52 53 54 55 56
        self.referenced_modules = []
        self.find_referenced_modules(env, self.referenced_modules, {})
        if self.has_imported_c_functions():
            self.module_temp_cname = env.allocate_temp_pyobject()
            env.release_temp(self.module_temp_cname)
57
        self.generate_c_code(env, options, result)
58 59
        self.generate_h_code(env, options, result)
        self.generate_api_code(env, result)
60
    
61 62 63 64 65 66 67 68
    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
    
    def generate_h_code(self, env, options, result):
Stefan Behnel's avatar
Stefan Behnel committed
69 70 71 72 73 74 75 76
        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:
77 78
            result.h_file = replace_suffix(result.c_file, ".h")
            h_code = Code.CCodeWriter(open_new_file(result.h_file))
79 80 81 82 83 84 85
            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)
86
            self.generate_extern_c_macro_definition(h_code)
Stefan Behnel's avatar
Stefan Behnel committed
87
            self.generate_type_header_code(h_types, h_code)
88 89
            h_code.putln("")
            h_code.putln("#ifndef %s" % Naming.api_guard_prefix + self.api_name(env))
Stefan Behnel's avatar
Stefan Behnel committed
90
            if h_vars:
91
                h_code.putln("")
Stefan Behnel's avatar
Stefan Behnel committed
92
                for entry in h_vars:
93
                    self.generate_public_declaration(entry, h_code, i_code)
Stefan Behnel's avatar
Stefan Behnel committed
94
            if h_funcs:
95
                h_code.putln("")
Stefan Behnel's avatar
Stefan Behnel committed
96
                for entry in h_funcs:
97
                    self.generate_public_declaration(entry, h_code, i_code)
Stefan Behnel's avatar
Stefan Behnel committed
98
            if h_extension_types:
99
                h_code.putln("")
Stefan Behnel's avatar
Stefan Behnel committed
100
                for entry in h_extension_types:
101 102 103 104 105 106
                    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("")
107
            h_code.putln("PyMODINIT_FUNC init%s(void);" % env.module_name)
108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124
            h_code.putln("")
            h_code.putln("#endif")
    
    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
125 126
        public_extension_types = []
        has_api_extension_types = 0
127 128 129 130 131 132
        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
133 134 135
            if entry.api:
                has_api_extension_types = 1
        if api_funcs or has_api_extension_types:
136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168
            result.api_file = replace_suffix(result.c_file, "_api.h")
            h_code = Code.CCodeWriter(open_new_file(result.api_file))
            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")
            h_code.put(import_module_utility_code[1])
            h_code.putln("")
            h_code.putln("#endif")
            if api_funcs:
                h_code.putln("")
                h_code.put(function_import_utility_code[1])
            if public_extension_types:
                h_code.putln("")
                h_code.put(type_import_utility_code[1])
            h_code.putln("")
            h_code.putln("static int import_%s(void) {" % name)
            h_code.putln("PyObject *module = 0;")
169
            h_code.putln('module = __Pyx_ImportModule("%s");' % env.qualified_name)
170 171 172 173 174 175 176 177
            h_code.putln("if (!module) goto bad;")
            for entry in api_funcs:
                sig = entry.type.signature_string()
                h_code.putln(
                    'if (__Pyx_ImportFunction(module, "%s", (void**)&%s, "%s") < 0) goto bad;' % (
                        entry.name,
                        entry.cname,
                        sig))
178
            h_code.putln("Py_DECREF(module); module = 0;")
179
            for entry in public_extension_types:
180 181 182
                self.generate_type_import_call(
                    entry.type, h_code,
                    "if (!%s) goto bad;" % entry.type.typeptr_cname)
183 184 185 186 187 188 189
            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")
190 191 192 193 194
    
    def generate_cclass_header_code(self, type, h_code):
        h_code.putln("%s DL_IMPORT(PyTypeObject) %s;" % (
            Naming.extern_c_macro,
            type.typeobj_cname))
195
        #self.generate_obj_struct_definition(type, h_code)
196 197 198 199 200 201 202 203 204 205 206 207 208
    
    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
209
    
210
    def generate_c_code(self, env, options, result):
211
        modules = self.referenced_modules
212
        if Options.annotate or options.annotate:
213 214 215
            code = Annotate.AnnotationCCodeWriter(StringIO())
        else:
            code = Code.CCodeWriter(StringIO())
216 217 218 219 220 221 222
        code.h = Code.CCodeWriter(StringIO())
        code.init_labels()
        self.generate_module_preamble(env, modules, code.h)

        code.putln("")
        code.putln("/* Implementation of %s */" % env.qualified_name)
        self.generate_const_definitions(env, code)
223
        self.generate_interned_num_decls(env, code)
224
        self.generate_interned_string_decls(env, code)
225
        self.generate_py_string_decls(env, code)
226
        self.generate_cached_builtins_decls(env, code)
227
        self.body.generate_function_definitions(env, code, options.transforms)
Robert Bradshaw's avatar
Robert Bradshaw committed
228
        code.mark_pos(None)
229 230 231 232 233
        self.generate_py_string_table(env, code)
        self.generate_typeobj_definitions(env, code)
        self.generate_method_table(env, code)
        self.generate_filename_init_prototype(code)
        self.generate_module_init_func(modules[:-1], env, code)
Robert Bradshaw's avatar
Robert Bradshaw committed
234
        code.mark_pos(None)
235
        self.generate_module_cleanup_func(env, code)
236 237 238
        self.generate_filename_table(code)
        self.generate_utility_functions(env, code)

Gary Furnish's avatar
Gary Furnish committed
239 240
        self.generate_declarations_for_modules(env, modules, code.h)

241 242 243 244 245 246
        f = open_new_file(result.c_file)
        f.write(code.h.f.getvalue())
        f.write("\n")
        f.write(code.f.getvalue())
        f.close()
        result.c_file_generated = 1
247
        if Options.annotate or options.annotate:
248
            self.annotate(code)
249
            code.save_annotation(result.main_source_file, result.c_file)
250 251 252 253 254 255 256
    
    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
257

258 259 260 261 262 263 264 265 266
    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
267
            hierarchy = set()
268
            base = new_entry
269 270 271 272 273 274 275
            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)
276
            new_entry.base_keys = hierarchy
277

278
            # find the first (sub-)subclass and insert before that
279 280
            for j in range(i):
                entry = type_list[j]
281
                if key in entry.base_keys:
282 283 284 285 286 287 288
                    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
289
        vtab_dict = {}
290
        vtabslot_dict = {}
Gary Furnish's avatar
Gary Furnish committed
291 292 293 294 295
        for module in module_list:
            for entry in module.c_class_entries:
                if not entry.in_cinclude:
                    type = entry.type
                    if type.vtabstruct_cname:
296 297 298 299
                        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
300
                    type = entry.type
301 302 303 304 305 306
                    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
307 308
        vtab_list = self.sort_types_by_inheritance(
            vtab_dict, vtabstruct_cname)
309 310 311

        def objstruct_cname(entry_type):
            return entry_type.objstruct_cname
312 313
        vtabslot_list = self.sort_types_by_inheritance(
            vtabslot_dict, objstruct_cname)
314

315
        return (vtab_list, vtabslot_list)
316

Gary Furnish's avatar
Gary Furnish committed
317
    def generate_type_definitions(self, env, modules, vtab_list, vtabslot_list, code):
318
        vtabslot_entries = set(vtabslot_list)
Gary Furnish's avatar
Gary Furnish committed
319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337
        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)
338
                    elif type.is_extension_type and entry not in vtabslot_entries:
Gary Furnish's avatar
Gary Furnish committed
339 340 341 342 343 344 345
                        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
346

Gary Furnish's avatar
Gary Furnish committed
347 348 349
    def generate_declarations_for_modules(self, env, modules, code):
        code.putln("")
        code.putln("/* Declarations */")
350 351 352
        vtab_list, vtabslot_list = self.sort_type_hierarchy(modules, env)
        self.generate_type_definitions(
            env, modules, vtab_list, vtabslot_list, code)
Gary Furnish's avatar
Gary Furnish committed
353
        for module in modules:
354 355 356
            defined_here = module is env
            self.generate_global_declarations(module, code, defined_here)
            self.generate_cfunction_predeclarations(module, code, defined_here)
Gary Furnish's avatar
Gary Furnish committed
357

358
    def generate_module_preamble(self, env, cimported_modules, code):
359
        code.putln('/* Generated by Cython %s on %s */' % (
360 361
            Version.version, time.asctime()))
        code.putln('')
362
        code.putln('#define PY_SSIZE_T_CLEAN')
363 364 365 366 367
        for filename in env.python_include_files:
            code.putln('#include "%s"' % filename)
        code.putln("#ifndef PY_LONG_LONG")
        code.putln("  #define PY_LONG_LONG LONG_LONG")
        code.putln("#endif")
368 369 370
        code.putln("#ifndef DL_EXPORT")
        code.putln("  #define DL_EXPORT(t) t")
        code.putln("#endif")
371 372 373 374
        code.putln("#if PY_VERSION_HEX < 0x02040000")
        code.putln("  #define METH_COEXIST 0")
        code.putln("#endif")

375 376 377 378 379 380
        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")
        code.putln("  #define PyInt_FromSsize_t(z) PyInt_FromLong(z)")
        code.putln("  #define PyInt_AsSsize_t(o)   PyInt_AsLong(o)")
381 382
        code.putln("  #define PyNumber_Index(o)    PyNumber_Int(o)")
        code.putln("  #define PyIndex_Check(o)     PyNumber_Check(o)")
383
        code.putln("#endif")
384 385 386 387 388 389 390

        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)")
        code.putln("  #define Py_SIZE(ob)   ((PyVarObject*)(ob))->ob_size)")
        code.putln("  #define PyVarObject_HEAD_INIT(type, size) \\")
        code.putln("          PyObject_HEAD_INIT(type) size,")
391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414
        code.putln("")
        code.putln("  typedef struct {")
        code.putln("     void *buf;")
        code.putln("     Py_ssize_t len;")
        code.putln("     int readonly;")
        code.putln("     const char *format;")
        code.putln("     int ndim;")
        code.putln("     Py_ssize_t *shape;")
        code.putln("     Py_ssize_t *strides;")
        code.putln("     Py_ssize_t *suboffsets;")
        code.putln("     Py_ssize_t itemsize;")
        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_LOCK 0x0002")
        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)")
415
        code.putln("#endif")
416 417 418 419 420 421 422 423 424

        code.put(builtin_module_name_utility_code[0])

        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")

        code.putln("#if PY_MAJOR_VERSION >= 3")
425
        code.putln("  #include \"stringobject.h\"") # Py3 compat header for PyString_*()
Stefan Behnel's avatar
Stefan Behnel committed
426
        code.putln("  #define PyBaseString_Type            PyUnicode_Type")
427
        code.putln("  #define PyInt_Type                   PyLong_Type")
428 429 430 431 432 433 434 435 436 437 438 439
        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")
Stefan Behnel's avatar
Stefan Behnel committed
440
        code.putln("  #define PyNumber_Divide(x,y)         PyNumber_TrueDivide(x,y)")
441 442 443
        code.putln("#endif")

        code.putln("#if PY_MAJOR_VERSION >= 3")
444
        code.putln("  #define PyMethod_New(func, self, klass) PyInstanceMethod_New(func)")
445 446
        code.putln("#endif")

447
        code.putln("#ifndef __stdcall")
448
        code.putln("  #define __stdcall")
449 450
        code.putln("#endif")
        code.putln("#ifndef __cdecl")
451 452
        code.putln("  #define __cdecl")
        code.putln("#endif")
453
        self.generate_extern_c_macro_definition(code)
454
        code.putln("#include <math.h>")
455 456 457
        self.generate_includes(env, cimported_modules, code)
        code.putln('')
        code.put(Nodes.utility_function_predeclarations)
458
        code.put(PyrexTypes.type_conversion_predeclarations)
Robert Bradshaw's avatar
Robert Bradshaw committed
459
        code.put(Nodes.branch_prediction_macros)
460 461 462
        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
463
        code.putln('static PyObject *%s;' % Naming.empty_tuple)
464 465
        if Options.pre_import is not None:
            code.putln('static PyObject *%s;' % Naming.preimport_cname)
466
        code.putln('static int %s;' % Naming.lineno_cname)
467
        code.putln('static int %s = 0;' % Naming.clineno_cname)
Gary Furnish's avatar
Gary Furnish committed
468
        code.putln('static char * %s= %s;' % (Naming.cfilenm_cname, Naming.file_c_macro))
469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504
        code.putln('static char *%s;' % Naming.filename_cname)
        code.putln('static char **%s;' % Naming.filetable_cname)
        if env.doc:
            code.putln('')
            code.putln('static char %s[] = "%s";' % (env.doc_cname, env.doc))
    
    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):
        includes = env.include_files[:]
        for module in cimported_modules:
            for filename in module.include_files:
                if filename not in includes:
                    includes.append(filename)
        for filename in includes:
            code.putln('#include "%s"' % filename)
    
    def generate_filename_table(self, code):
        code.putln("")
        code.putln("static char *%s[] = {" % Naming.filenames_cname)
        if code.filename_list:
            for filename in code.filename_list:
                filename = os.path.basename(filename)
                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("};")
505 506 507 508

    def generate_type_predeclarations(self, env, code):
        pass

509
    def generate_type_header_code(self, type_entries, code):
510 511
        # Generate definitions of structs/unions/enums/typedefs/objstructs.
        #self.generate_gcc33_hack(env, code) # Is this still needed?
512 513
        #for entry in env.type_entries:
        for entry in type_entries:
514
            if not entry.in_cinclude:
515
                #print "generate_type_header_code:", entry.name, repr(entry.type) ###
516
                type = entry.type
517 518 519
                if type.is_typedef: # Must test this first!
                    self.generate_typedef(entry, code)
                elif type.is_struct_or_union:
520
                    self.generate_struct_union_definition(entry, code)
521
                elif type.is_enum:
522
                    self.generate_enum_definition(entry, code)
523 524
                elif type.is_extension_type:
                    self.generate_obj_struct_definition(type, code)
Gary Furnish's avatar
Gary Furnish committed
525
        
526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544
    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))

545 546 547 548 549 550 551 552 553 554
    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):
555
        code.mark_pos(entry.pos)
556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574
        type = entry.type
        scope = type.scope
        if scope:
            header, footer = \
                self.sue_header_footer(type, type.kind, type.cname)
            code.putln("")
            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)

    def generate_enum_definition(self, entry, code):
575
        code.mark_pos(entry.pos)
576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618
        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]
            for value_entry in enum_values:
                if value_entry.value == value_entry.name:
                    value_code = value_entry.cname
                else:
                    value_code = ("%s = %s" % (
                        value_entry.cname,
                        value_entry.value))
                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:
            #	code.putln("staticforward PyTypeObject %s;" % name)
    
    def generate_exttype_vtable_struct(self, entry, code):
619
        code.mark_pos(entry.pos)
620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639
        # 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):
640
        code.mark_pos(entry.pos)
641 642 643 644 645 646 647 648
        # 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):
649
        code.mark_pos(type.pos)
650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681
        # 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)

    def generate_global_declarations(self, env, code, definition):
        code.putln("")
        for entry in env.c_class_entries:
682 683 684
            if definition or entry.defined_in_pxd:
                code.putln("static PyTypeObject *%s = 0;" % 
                    entry.type.typeptr_cname)
685 686
        code.put_var_declarations(env.var_entries, static = 1, 
            dll_linkage = "DL_EXPORT", definition = definition)
687 688
        code.put_var_declarations(env.default_entries, static = 1,
                                  definition = definition)
689
    
690
    def generate_cfunction_predeclarations(self, env, code, definition):
691
        for entry in env.cfunc_entries:
692 693 694
            if not entry.in_cinclude and (definition
                    or entry.defined_in_pxd or entry.visibility == 'extern'):
                if entry.visibility in ('public', 'extern'):
695 696 697
                    dll_linkage = "DL_EXPORT"
                else:
                    dll_linkage = None
698 699 700 701
                type = entry.type
                if not definition and entry.defined_in_pxd:
                    type = CPtrType(type)
                header = type.declaration_code(entry.cname, 
702
                    dll_linkage = dll_linkage)
703 704 705
                if entry.visibility == 'private':
                    storage_class = "static "
                elif entry.visibility == 'extern':
706 707
                    storage_class = "%s " % Naming.extern_c_macro
                else:
708
                    storage_class = ""
709 710 711 712 713 714 715 716 717
                code.putln("%s%s; /*proto*/" % (
                    storage_class,
                    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
718
            if entry.visibility != 'extern':
719 720 721 722 723 724
                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)
725 726 727
                    if scope.needs_gc():
                        self.generate_traverse_function(scope, code)
                        self.generate_clear_function(scope, code)
728 729 730 731 732
                    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__"]):
733
                        warning(self.pos, "__setslice__ and __delslice__ are not supported by Python 3")
734
                        self.generate_ass_slice_function(scope, code)
735
                    if scope.defines_any(["__getattr__","__getattribute__"]):
736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764
                        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):
765 766
        tp_slot = TypeSlots.ConstructorSlot("tp_new", '__new__')
        slot_func = scope.mangle_internal("tp_new")
767 768 769 770 771 772 773
        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
774 775 776 777
        code.putln("")
        code.putln(
            "static PyObject *%s(PyTypeObject *t, PyObject *a, PyObject *k) {"
                % scope.mangle_internal("tp_new"))
778 779 780 781
        if need_self_cast:
            code.putln(
                "%s;"
                    % scope.parent_type.declaration_code("p"))
782
        if base_type:
Robert Bradshaw's avatar
Robert Bradshaw committed
783 784
            tp_new = TypeSlots.get_base_slot_function(scope, tp_slot)
            if tp_new is None:
785
                tp_new = "%s->tp_new" % base_type.typeptr_cname
786
            code.putln(
787
                "PyObject *o = %s(t, a, k);" % tp_new)
788 789 790
        else:
            code.putln(
                "PyObject *o = (*t->tp_alloc)(t, 0);")
791 792 793 794 795 796 797 798
        code.putln(
                "if (!o) return 0;")
        if need_self_cast:
            code.putln(
                "p = %s;"
                    % type.cast_code("o"))
        #if need_self_cast:
        #	self.generate_self_cast(scope, code)
799 800 801 802 803 804 805
        if type.vtabslot_cname:
            code.putln("*(struct %s **)&p->%s = %s;" % (
                type.vtabstruct_cname,
                type.vtabslot_cname,
                type.vtabptr_cname))
        for entry in py_attrs:
            if entry.name == "__weakref__":
806
                code.putln("p->%s = 0;" % entry.cname)
807 808 809 810
            else:
                code.put_init_var_to_py_none(entry, "p->%s")
        entry = scope.lookup_here("__new__")
        if entry:
811 812 813 814
            if entry.trivial_signature:
                cinit_args = "o, %s, NULL" % Naming.empty_tuple
            else:
                cinit_args = "o, a, k"
815
            code.putln(
816 817
                "if (%s(%s) < 0) {" % 
                    (entry.func_cname, cinit_args))
818 819 820 821 822 823 824 825 826
            code.put_decref_clear("o", py_object_type);
            code.putln(
                "}")
        code.putln(
            "return o;")
        code.putln(
            "}")
    
    def generate_dealloc_function(self, scope, code):
827 828
        tp_slot = TypeSlots.ConstructorSlot("tp_dealloc", '__dealloc__')
        slot_func = scope.mangle_internal("tp_dealloc")
829
        base_type = scope.parent_type.base_type
830 831
        if tp_slot.slot_code(scope) != slot_func:
            return # never used
832 833 834 835 836
        code.putln("")
        code.putln(
            "static void %s(PyObject *o) {"
                % scope.mangle_internal("tp_dealloc"))
        py_attrs = []
837
        weakref_slot = scope.lookup_here("__weakref__")
838
        for entry in scope.var_entries:
839
            if entry.type.is_pyobject and entry is not weakref_slot:
840
                py_attrs.append(entry)
841
        if py_attrs or weakref_slot in scope.var_entries:
842 843
            self.generate_self_cast(scope, code)
        self.generate_usr_dealloc_call(scope, code)
844
        if weakref_slot in scope.var_entries:
845
            code.putln("if (p->__weakref__) PyObject_ClearWeakRefs(o);")
846 847 848
        for entry in py_attrs:
            code.put_xdecref("p->%s" % entry.cname, entry.type)
        if base_type:
Robert Bradshaw's avatar
Robert Bradshaw committed
849 850
            tp_dealloc = TypeSlots.get_base_slot_function(scope, tp_slot)
            if tp_dealloc is None:
851
                tp_dealloc = "%s->tp_dealloc" % base_type.typeptr_cname
852
            code.putln(
853
                    "%s(o);" % tp_dealloc)
854 855
        else:
            code.putln(
856
                    "(*Py_TYPE(o)->tp_free)(o);")
857 858 859 860 861 862 863 864 865 866 867 868 869
        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(
870
                    "++Py_REFCNT(o);")
871 872 873 874 875 876
            code.putln(
                    "%s(o);" % 
                        entry.func_cname)
            code.putln(
                    "if (PyErr_Occurred()) PyErr_WriteUnraisable(o);")
            code.putln(
877
                    "--Py_REFCNT(o);")
878 879 880 881 882 883
            code.putln(
                    "PyErr_Restore(etype, eval, etb);")
            code.putln(
                "}")
    
    def generate_traverse_function(self, scope, code):
884 885
        tp_slot = TypeSlots.GCDependentSlot("tp_traverse")
        slot_func = scope.mangle_internal("tp_traverse")
886
        base_type = scope.parent_type.base_type
887 888
        if tp_slot.slot_code(scope) != slot_func:
            return # never used
889 890 891
        code.putln("")
        code.putln(
            "static int %s(PyObject *o, visitproc v, void *a) {"
892
                % slot_func)
893 894
        py_attrs = []
        for entry in scope.var_entries:
895
            if entry.type.is_pyobject and entry.name != "__weakref__":
896 897
                py_attrs.append(entry)
        if base_type or py_attrs:
898
            code.putln("int e;")
899 900 901
        if py_attrs:
            self.generate_self_cast(scope, code)
        if base_type:
902
            # want to call it explicitly if possible so inlining can be performed
Robert Bradshaw's avatar
Robert Bradshaw committed
903 904 905
            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)
906 907 908 909 910 911
            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("}")
912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929
        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):
930 931
        tp_slot = TypeSlots.GCDependentSlot("tp_clear")
        slot_func = scope.mangle_internal("tp_clear")
932
        base_type = scope.parent_type.base_type
933 934
        if tp_slot.slot_code(scope) != slot_func:
            return # never used
935
        code.putln("")
936
        code.putln("static int %s(PyObject *o) {" % slot_func)
937 938
        py_attrs = []
        for entry in scope.var_entries:
939
            if entry.type.is_pyobject and entry.name != "__weakref__":
940 941 942
                py_attrs.append(entry)
        if py_attrs:
            self.generate_self_cast(scope, code)
943
            code.putln("PyObject* tmp;")
944
        if base_type:
945
            # want to call it explicitly if possible so inlining can be performed
Robert Bradshaw's avatar
Robert Bradshaw committed
946 947 948
            static_call = TypeSlots.get_base_slot_function(scope, tp_slot)
            if static_call:
                code.putln("%s(o);" % static_call)
949 950 951 952
            else:
                code.putln("if (%s->tp_clear) {" % base_type.typeptr_cname)
                code.putln("%s->tp_clear(o);" % base_type.typeptr_cname)
                code.putln("}")
953 954
        for entry in py_attrs:
            name = "p->%s" % entry.cname
955 956
            code.putln("tmp = ((PyObject*)%s);" % name)
            code.put_init_to_py_none(name, entry.type)
957
            code.putln("Py_XDECREF(tmp);")
958 959 960 961
        code.putln(
            "return 0;")
        code.putln(
            "}")
962
            
963 964 965 966 967
    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(
968
            "static PyObject *%s(PyObject *o, Py_ssize_t i) {" %
969 970 971 972
                scope.mangle_internal("sq_item"))
        code.putln(
                "PyObject *r;")
        code.putln(
973
                "PyObject *x = PyInt_FromSsize_t(i); if(!x) return 0;")
974
        code.putln(
975
                "r = Py_TYPE(o)->tp_as_mapping->mp_subscript(o, x);")
976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005
        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(
1006
                    '  "Subscript assignment not supported by %s", Py_TYPE(o)->tp_name);')
1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022
            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(
1023
                    '  "Subscript deletion not supported by %s", Py_TYPE(o)->tp_name);')
1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058
            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.
        base_type = scope.parent_type.base_type
        set_entry = scope.lookup_here("__setslice__")
        del_entry = scope.lookup_here("__delslice__")
        code.putln("")
        code.putln(
1059
            "static int %s(PyObject *o, Py_ssize_t i, Py_ssize_t j, PyObject *v) {" %
1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072
                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(
1073
                    '  "2-element slice assignment not supported by %s", Py_TYPE(o)->tp_name);')
1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089
            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(
1090
                    '  "2-element slice deletion not supported by %s", Py_TYPE(o)->tp_name);')
1091 1092 1093 1094 1095 1096 1097 1098
            code.putln(
                    "return -1;")
        code.putln(
                "}")
        code.putln(
            "}")

    def generate_getattro_function(self, scope, code):
1099 1100 1101
        # First try to get the attribute using __getattribute__, if defined, or
        # PyObject_GenericGetAttr.
        #
1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116
        # 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__")
1117 1118 1119 1120
        code.putln("")
        code.putln(
            "static PyObject *%s(PyObject *o, PyObject *n) {"
                % scope.mangle_internal("tp_getattro"))
1121 1122 1123 1124 1125 1126
        if getattribute_entry is not None:
            code.putln(
                "PyObject *v = %s(o, n);" %
                    getattribute_entry.func_cname)
        else:
            code.putln(
1127
                "PyObject *v = PyObject_GenericGetAttr(o, n);")
1128 1129
        if getattr_entry is not None:
            code.putln(
1130
                "if (!v && PyErr_ExceptionMatches(PyExc_AttributeError)) {")
1131 1132 1133 1134 1135 1136
            code.putln(
                "PyErr_Clear();")
            code.putln(
                "v = %s(o, n);" %
                    getattr_entry.func_cname)
            code.putln(
1137 1138
                "}")
        code.putln(
1139
            "return v;")
1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 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 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 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
        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(
                "}")		
        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(
1331
            "PyVarObject_HEAD_INIT(0, 0)")
1332 1333
        code.putln(
            '"%s.%s", /*tp_name*/' % (
1334
                self.full_module_name, scope.class_name))
1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355
        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:
1356
            code.put_pymethoddef(entry, ",")
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
        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"
                code.putln('{"%s", %s, %s, %s, 0},' % (
                    entry.name,
                    type_code,
1383
                    "offsetof(%s, %s)" % (objstruct, entry.cname),
1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406
                    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:
                code.putln(
                    '{"%s", %s, %s, %s, 0},' % (
                        entry.name,
                        entry.getter_cname or "0",
                        entry.setter_cname or "0",
                        entry.doc_cname or "0"))
            code.putln(
                    "{0, 0, 0, 0, 0}")
            code.putln(
                "};")
1407

1408 1409 1410 1411 1412 1413 1414 1415 1416
    def generate_py_string_table(self, env, code):
        entries = env.all_pystring_entries
        if entries:
            code.putln("")
            code.putln(
                "static __Pyx_StringTabEntry %s[] = {" %
                    Naming.stringtab_cname)
            for entry in entries:
                code.putln(
1417
                    "{&%s, %s, sizeof(%s), %d, %d, %d}," % (
1418 1419
                        entry.pystring_cname,
                        entry.cname,
1420
                        entry.cname,
1421
                        entry.type.is_unicode,
1422 1423
                        entry.is_interned,
                        entry.is_identifier
1424
                        ))
1425
            code.putln(
1426
                "{0, 0, 0, 0, 0}")
1427 1428
            code.putln(
                "};")
1429

1430 1431 1432 1433 1434 1435 1436 1437 1438 1439
    def generate_filename_init_prototype(self, code):
        code.putln("");
        code.putln("static void %s(void); /*proto*/" % Naming.fileinit_cname)

    def generate_module_init_func(self, imported_modules, env, code):
        code.putln("")
        header = "PyMODINIT_FUNC init%s(void)" % env.module_name
        code.putln("%s; /*proto*/" % header)
        code.putln("%s {" % header)
        code.put_var_declarations(env.temp_entries)
1440
        code.putln("%s = PyTuple_New(0); %s" % (Naming.empty_tuple, code.error_goto_if_null(Naming.empty_tuple, self.pos)));
1441

1442
        code.putln("/*--- Libary function declarations ---*/")
1443 1444
        env.generate_library_function_declarations(code)
        self.generate_filename_init_call(code)
1445

1446
        code.putln("/*--- Module creation code ---*/")
1447
        self.generate_module_creation_code(env, code)
1448

1449
        code.putln("/*--- Intern code ---*/")
1450
        self.generate_intern_code(env, code)
1451

1452
        code.putln("/*--- String init code ---*/")
1453
        self.generate_string_init_code(env, code)
1454

Robert Bradshaw's avatar
Robert Bradshaw committed
1455 1456 1457
        if Options.cache_builtins:
            code.putln("/*--- Builtin init code ---*/")
            self.generate_builtin_init_code(env, code)
Robert Bradshaw's avatar
Robert Bradshaw committed
1458
            
Robert Bradshaw's avatar
Robert Bradshaw committed
1459
        code.putln("%s = 0;" % Naming.skip_dispatch_cname);
1460

1461
        code.putln("/*--- Global init code ---*/")
1462
        self.generate_global_init_code(env, code)
Gary Furnish's avatar
Gary Furnish committed
1463

1464
        code.putln("/*--- Function export code ---*/")
1465 1466
        self.generate_c_function_export_code(env, code)

1467
        code.putln("/*--- Type init code ---*/")
1468
        self.generate_type_init_code(env, code)
1469

1470
        code.putln("/*--- Type import code ---*/")
1471 1472 1473
        for module in imported_modules:
            self.generate_type_import_code_for_module(module, env, code)

Gary Furnish's avatar
Gary Furnish committed
1474 1475 1476 1477
        code.putln("/*--- Function import code ---*/")
        for module in imported_modules:
            self.generate_c_function_import_code_for_module(module, env, code)

1478
        code.putln("/*--- Execution code ---*/")
Robert Bradshaw's avatar
Robert Bradshaw committed
1479
        code.mark_pos(None)
1480
        self.body.generate_execution_code(code)
1481

1482 1483
        if Options.generate_cleanup_code:
            code.putln("if (__Pyx_RegisterCleanup()) %s;" % code.error_goto(self.pos))
1484

1485 1486 1487
        code.putln("return;")
        code.put_label(code.error_label)
        code.put_var_xdecrefs(env.temp_entries)
Robert Bradshaw's avatar
Robert Bradshaw committed
1488
        code.putln('__Pyx_AddTraceback("%s");' % env.qualified_name)
1489
        env.use_utility_code(Nodes.traceback_utility_code)
1490 1491
        code.putln('}')

1492 1493 1494 1495 1496 1497
    def generate_module_cleanup_func(self, env, code):
        if not Options.generate_cleanup_code:
            return
        env.use_utility_code(import_module_utility_code)
        env.use_utility_code(register_cleanup_utility_code)
        code.putln()
1498
        code.putln('static PyObject* %s(PyObject *self, PyObject *unused) {' % Naming.cleanup_cname)
1499 1500
        if Options.generate_cleanup_code >= 2:
            code.putln("/*--- Global cleanup code ---*/")
1501 1502 1503
            rev_entries = list(env.var_entries)
            rev_entries.reverse()
            for entry in rev_entries:
1504 1505 1506 1507 1508 1509 1510 1511 1512
                if entry.visibility != 'extern':
                    if entry.type.is_pyobject:
                        code.put_var_decref_clear(entry)
        if Options.generate_cleanup_code >= 3:
            code.putln("/*--- Type import cleanup code ---*/")
            for type, _ in env.types_imported.items():
                code.put_decref("((PyObject*)%s)" % type.typeptr_cname, PyrexTypes.py_object_type)
        if Options.cache_builtins:
            code.putln("/*--- Builtin cleanup code ---*/")
1513
            for entry in env.cached_builtins:
1514
                code.put_var_decref_clear(entry)
Robert Bradshaw's avatar
Robert Bradshaw committed
1515
        code.putln("Py_DECREF(%s); %s = 0;" % (Naming.empty_tuple, Naming.empty_tuple));
1516 1517 1518
        code.putln("/*--- Intern cleanup code ---*/")
        for entry in env.pynum_entries:
            code.put_var_decref_clear(entry)
1519 1520 1521 1522 1523
        if env.all_pystring_entries:
            for entry in env.all_pystring_entries:
                if entry.is_interned:
                    code.put_decref_clear(
                        entry.pystring_cname, PyrexTypes.py_object_type)
1524 1525 1526
        code.putln("Py_INCREF(Py_None); return Py_None;")
        code.putln('}')

1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547
    def generate_filename_init_call(self, code):
        code.putln("%s();" % Naming.fileinit_cname)
    
    def generate_module_creation_code(self, env, code):
        # Generate code to create the module object and
        # install the builtins.
        if env.doc:
            doc = env.doc_cname
        else:
            doc = "0"
        code.putln(
            '%s = Py_InitModule4("%s", %s, %s, 0, PYTHON_API_VERSION);' % (
                env.module_cname, 
                env.module_name, 
                env.method_table_cname, 
                doc))
        code.putln(
            "if (!%s) %s;" % (
                env.module_cname,
                code.error_goto(self.pos)));
        code.putln(
1548
            '%s = PyImport_AddModule(__Pyx_BUILTIN_MODULE_NAME);' %
1549 1550 1551 1552 1553 1554 1555 1556 1557 1558
                Naming.builtins_cname)
        code.putln(
            "if (!%s) %s;" % (
                Naming.builtins_cname,
                code.error_goto(self.pos)));
        code.putln(
            'if (PyObject_SetAttrString(%s, "__builtins__", %s) < 0) %s;' % (
                env.module_cname,
                Naming.builtins_cname,
                code.error_goto(self.pos)))
1559 1560 1561 1562 1563 1564 1565 1566 1567
        if Options.pre_import is not None:
            code.putln(
                '%s = PyImport_AddModule("%s");' % (
                    Naming.preimport_cname, 
                    Options.pre_import))
            code.putln(
                "if (!%s) %s;" % (
                    Naming.preimport_cname,
                    code.error_goto(self.pos)));
1568 1569
    
    def generate_intern_code(self, env, code):
1570 1571 1572 1573 1574
        for entry in env.pynum_entries:
            code.putln("%s = PyInt_FromLong(%s); %s;" % (
                entry.cname,
                entry.init,
                code.error_goto_if_null(entry.cname, self.pos)))
1575 1576 1577 1578 1579 1580 1581 1582
    
    def generate_string_init_code(self, env, code):
        if env.all_pystring_entries:
            env.use_utility_code(Nodes.init_string_tab_utility_code)
            code.putln(
                "if (__Pyx_InitStrings(%s) < 0) %s;" % (
                    Naming.stringtab_cname,
                    code.error_goto(self.pos)))
1583 1584 1585 1586

    def generate_builtin_init_code(self, env, code):
        # Lookup and cache builtin objects.
        if Options.cache_builtins:
1587
            for entry in env.cached_builtins:
1588 1589 1590 1591 1592 1593 1594 1595
                #assert entry.interned_cname is not None
                code.putln(
                    '%s = __Pyx_GetName(%s, %s); if (!%s) %s' % (
                    entry.cname,
                    Naming.builtins_cname,
                    entry.interned_cname,
                    entry.cname,
                    code.error_goto(entry.pos)))
1596 1597 1598 1599 1600
    
    def generate_global_init_code(self, env, code):
        # Generate code to initialise global PyObject *
        # variables to None.
        for entry in env.var_entries:
1601
            if entry.visibility != 'extern':
1602 1603
                if entry.type.is_pyobject:
                    code.put_init_var_to_py_none(entry)
1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615

    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()
                code.putln('if (__Pyx_ExportFunction("%s", (void*)%s, "%s") < 0) %s' % (
                    entry.name,
                    entry.cname,
                    signature, 
                    code.error_goto(self.pos)))
1616 1617
    
    def generate_type_import_code_for_module(self, module, env, code):
1618
        # Generate type import code for all exported extension types in
1619
        # an imported module.
1620 1621 1622
        #if module.c_class_entries:
        for entry in module.c_class_entries:
            if entry.defined_in_pxd:
1623 1624
                self.generate_type_import_code(env, entry.type, entry.pos, code)
    
1625 1626 1627 1628 1629 1630 1631 1632 1633
    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)
1634 1635 1636 1637 1638 1639 1640
            temp = self.module_temp_cname
            code.putln(
                '%s = __Pyx_ImportModule("%s"); if (!%s) %s' % (
                    temp,
                    module.qualified_name,
                    temp,
                    code.error_goto(self.pos)))
1641 1642 1643
            for entry in entries:
                code.putln(
                    'if (__Pyx_ImportFunction(%s, "%s", (void**)&%s, "%s") < 0) %s' % (
1644
                        temp,
1645 1646 1647 1648
                        entry.name,
                        entry.cname,
                        entry.type.signature_string(),
                        code.error_goto(self.pos)))
1649
            code.putln("Py_DECREF(%s); %s = 0;" % (temp, temp))
1650
    
1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661
    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)
1662

1663 1664
    def generate_base_type_import_code(self, env, entry, code):
        base_type = entry.type.base_type
Stefan Behnel's avatar
Stefan Behnel committed
1665
        if base_type and base_type.module_name != env.qualified_name:
1666 1667 1668
            self.generate_type_import_code(env, base_type, self.pos, code)
    
    def use_type_import_utility_code(self, env):
1669 1670
        env.use_utility_code(type_import_utility_code)
        env.use_utility_code(import_module_utility_code)
1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681
    
    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
1682 1683
        self.generate_type_import_call(type, code,
                                       code.error_goto_if_null(type.typeptr_cname, pos))
1684 1685 1686 1687 1688 1689 1690 1691 1692
        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
1693

1694 1695
    py3_type_name_map = {'str' : 'bytes', 'unicode' : 'str'}

1696 1697 1698 1699 1700
    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
1701 1702 1703 1704 1705
        module_name = type.module_name
        if module_name not in ('__builtin__', 'builtins'):
            module_name = '"%s"' % module_name
        else:
            module_name = '__Pyx_BUILTIN_MODULE_NAME'
1706 1707 1708 1709 1710 1711 1712 1713 1714
        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")
1715
        code.putln('%s = __Pyx_ImportType(%s, "%s", sizeof(%s)); %s' % (
1716 1717 1718 1719 1720 1721 1722
                type.typeptr_cname,
                module_name,
                type.name,
                objstruct,
                error_code))
        if type.name in self.py3_type_name_map:
            code.putln("#endif")
1723

1724 1725 1726 1727 1728 1729 1730
    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
1731
            if entry.visibility != 'extern':
1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780
                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(
                    'if (PyObject_SetAttrString(%s, "%s", (PyObject *)&%s) < 0) %s' % (
                        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
                        code.putln("if (%s == 0) %s = offsetof(struct %s, %s);" % (
                            tp_weaklistoffset,
                            tp_weaklistoffset,
                            type.objstruct_cname,
                            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))
            for meth_entry in type.scope.cfunc_entries:
                if meth_entry.func_cname:
                    code.putln(
1781
                        "*(void(**)(void))&%s.%s = (void(*)(void))%s;" % (
1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805
                            type.vtable_cname,
                            meth_entry.cname,
                            meth_entry.func_cname))
    
    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))
    
    def generate_utility_functions(self, env, code):
        code.putln("")
        code.putln("/* Runtime support code */")
        code.putln("")
        code.putln("static void %s(void) {" % Naming.fileinit_cname)
        code.putln("%s = %s;" % 
            (Naming.filetable_cname, Naming.filenames_cname))
        code.putln("}")
        for utility_code in env.utility_code_used:
            code.h.put(utility_code[0])
            code.put(utility_code[1])
1806
        code.put(PyrexTypes.type_conversion_functions)
1807 1808

#------------------------------------------------------------------------------------
Stefan Behnel's avatar
Stefan Behnel committed
1809 1810 1811
#
#  Runtime support code
#
1812 1813
#------------------------------------------------------------------------------------

1814 1815 1816 1817 1818 1819 1820 1821 1822 1823
builtin_module_name_utility_code = [
"""\
#if PY_MAJOR_VERSION < 3
  #define __Pyx_BUILTIN_MODULE_NAME "__builtin__"
#else
  #define __Pyx_BUILTIN_MODULE_NAME "builtins"
#endif
"""]


1824 1825
import_module_utility_code = [
"""
1826
static PyObject *__Pyx_ImportModule(char *name); /*proto*/
1827
""","""
1828 1829 1830
#ifndef __PYX_HAVE_RT_ImportModule
#define __PYX_HAVE_RT_ImportModule
static PyObject *__Pyx_ImportModule(char *name) {
1831
    PyObject *py_name = 0;
1832
    PyObject *py_module = 0;
1833 1834

    #if PY_MAJOR_VERSION < 3
1835
    py_name = PyString_FromString(name);
1836 1837 1838
    #else
    py_name = PyUnicode_FromString(name);
    #endif
1839 1840
    if (!py_name)
        goto bad;
1841 1842 1843
    py_module = PyImport_Import(py_name);
    Py_DECREF(py_name);
    return py_module;
1844 1845 1846 1847
bad:
    Py_XDECREF(py_name);
    return 0;
}
1848
#endif
1849 1850 1851 1852 1853 1854
"""]

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

type_import_utility_code = [
"""
1855
static PyTypeObject *__Pyx_ImportType(char *module_name, char *class_name, long size);  /*proto*/
1856
""","""
Stefan Behnel's avatar
Stefan Behnel committed
1857 1858
#ifndef __PYX_HAVE_RT_ImportType
#define __PYX_HAVE_RT_ImportType
1859 1860 1861 1862
static PyTypeObject *__Pyx_ImportType(char *module_name, char *class_name,
    long size)
{
    PyObject *py_module = 0;
1863
    PyObject *result = 0;
Gary Furnish's avatar
Gary Furnish committed
1864
    PyObject *py_name = 0;
1865 1866

    #if PY_MAJOR_VERSION < 3
Gary Furnish's avatar
Gary Furnish committed
1867
    py_name = PyString_FromString(module_name);
1868 1869 1870
    #else
    py_name = PyUnicode_FromString(module_name);
    #endif
Gary Furnish's avatar
Gary Furnish committed
1871 1872
    if (!py_name)
        goto bad;
1873

1874 1875 1876
    py_module = __Pyx_ImportModule(module_name);
    if (!py_module)
        goto bad;
1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893
    result = PyObject_GetAttrString(py_module, class_name);
    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:
Gary Furnish's avatar
Gary Furnish committed
1894
    Py_XDECREF(py_name);
1895 1896 1897
    Py_XDECREF(result);
    return 0;
}
Stefan Behnel's avatar
Stefan Behnel committed
1898
#endif
1899 1900 1901 1902 1903 1904
"""]

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

function_export_utility_code = [
"""
1905
static int __Pyx_ExportFunction(char *name, void *f, char *sig); /*proto*/
1906
""",r"""
Gary Furnish's avatar
Gary Furnish committed
1907
static int __Pyx_ExportFunction(char *name, void *f, char *sig) {
1908
    PyObject *d = 0;
1909
    PyObject *p = 0;
1910 1911 1912 1913 1914 1915 1916 1917 1918 1919
    d = PyObject_GetAttrString(%(MODULE)s, "%(API)s");
    if (!d) {
        PyErr_Clear();
        d = PyDict_New();
        if (!d)
            goto bad;
        Py_INCREF(d);
        if (PyModule_AddObject(%(MODULE)s, "%(API)s", d) < 0)
            goto bad;
    }
Gary Furnish's avatar
Gary Furnish committed
1920
    p = PyCObject_FromVoidPtrAndDesc(f, sig, 0);
1921 1922
    if (!p)
        goto bad;
Gary Furnish's avatar
Gary Furnish committed
1923
    if (PyDict_SetItemString(d, name, p) < 0)
1924
        goto bad;
1925
    Py_DECREF(d);
1926 1927 1928
    return 0;
bad:
    Py_XDECREF(p);
1929
    Py_XDECREF(d);
1930 1931
    return -1;
}
1932
""" % {'MODULE': Naming.module_cname, 'API': Naming.api_name}]
1933 1934 1935 1936 1937 1938 1939

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

function_import_utility_code = [
"""
static int __Pyx_ImportFunction(PyObject *module, char *funcname, void **f, char *sig); /*proto*/
""","""
Stefan Behnel's avatar
Stefan Behnel committed
1940 1941
#ifndef __PYX_HAVE_RT_ImportFunction
#define __PYX_HAVE_RT_ImportFunction
1942
static int __Pyx_ImportFunction(PyObject *module, char *funcname, void **f, char *sig) {
1943
    PyObject *d = 0;
1944 1945 1946
    PyObject *cobj = 0;
    char *desc;
    
1947 1948 1949 1950
    d = PyObject_GetAttrString(module, "%(API)s");
    if (!d)
        goto bad;
    cobj = PyDict_GetItemString(d, funcname);
1951 1952
    if (!cobj) {
        PyErr_Format(PyExc_ImportError,
1953
            "%%s does not export expected C function %%s",
1954 1955 1956 1957 1958 1959 1960 1961
                PyModule_GetName(module), funcname);
        goto bad;
    }
    desc = (char *)PyCObject_GetDesc(cobj);
    if (!desc)
        goto bad;
    if (strcmp(desc, sig) != 0) {
        PyErr_Format(PyExc_TypeError,
1962
            "C function %%s.%%s has wrong signature (expected %%s, got %%s)",
1963 1964 1965 1966
                PyModule_GetName(module), funcname, sig, desc);
        goto bad;
    }
    *f = PyCObject_AsVoidPtr(cobj);
1967
    Py_DECREF(d);
1968 1969
    return 0;
bad:
1970
    Py_XDECREF(d);
1971 1972
    return -1;
}
Stefan Behnel's avatar
Stefan Behnel committed
1973
#endif
1974
""" % dict(API = Naming.api_name)]
1975 1976 1977

register_cleanup_utility_code = [
"""
1978
static int __Pyx_RegisterCleanup(void); /*proto*/
1979 1980
static PyObject* __pyx_module_cleanup(PyObject *self, PyObject *unused); /*proto*/
static PyMethodDef cleanup_def = {"__cleanup", (PyCFunction)&__pyx_module_cleanup, METH_NOARGS, 0};
1981
""","""
1982
static int __Pyx_RegisterCleanup(void) {
1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019
    /* 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;
    reg = PyObject_GetAttrString(atexit, "register");
    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;
}
"""]