Cython has moved to github.
cython-devel
view Cython/Compiler/ModuleNode.py @ 2112:c951607190c2
Ticket #216, Exceptions in __Pyx_InitGlobals() lead to a crash
| author | Robert Bradshaw <robertwb@math.washington.edu> |
|---|---|
| date | Thu Sep 10 00:06:45 2009 -0700 (2 years ago) |
| parents | 181618626844 |
| children | 41c5c91cbc5b |
line source
1 #
2 # Pyrex - Module parse tree node
3 #
5 import os, time
6 from PyrexTypes import CPtrType
7 import Future
9 try:
10 set
11 except NameError: # Python 2.3
12 from sets import Set as set
14 import Annotate
15 import Code
16 import Naming
17 import Nodes
18 import Options
19 import PyrexTypes
20 import TypeSlots
21 import Version
22 import DebugFlags
24 from Errors import error, warning
25 from PyrexTypes import py_object_type
26 from Cython.Utils import open_new_file, replace_suffix, UtilityCode
27 from StringEncoding import escape_byte_string, EncodedString
30 def check_c_declarations(module_node):
31 module_node.scope.check_c_classes()
32 module_node.scope.check_c_functions()
33 return module_node
35 class ModuleNode(Nodes.Node, Nodes.BlockNode):
36 # doc string or None
37 # body StatListNode
38 #
39 # referenced_modules [ModuleScope]
40 # module_temp_cname string
41 # full_module_name string
42 #
43 # scope The module scope.
44 # compilation_source A CompilationSource (see Main)
45 # directives Top-level compiler directives
47 child_attrs = ["body"]
48 directives = None
50 def analyse_declarations(self, env):
51 if Options.embed_pos_in_docstring:
52 env.doc = EncodedString(u'File: %s (starting at line %s)' % Nodes.relative_position(self.pos))
53 if not self.doc is None:
54 env.doc = EncodedString(env.doc + u'\n' + self.doc)
55 env.doc.encoding = self.doc.encoding
56 else:
57 env.doc = self.doc
58 env.directives = self.directives
59 self.__main__cname = env.intern_identifier(EncodedString("__main__"))
60 self.body.analyse_declarations(env)
62 def process_implementation(self, options, result):
63 env = self.scope
64 env.return_type = PyrexTypes.c_void_type
65 self.referenced_modules = []
66 self.find_referenced_modules(env, self.referenced_modules, {})
67 if self.has_imported_c_functions():
68 self.module_temp_cname = env.allocate_temp_pyobject()
69 env.release_temp(self.module_temp_cname)
70 if options.recursive:
71 self.generate_dep_file(env, result)
72 self.generate_c_code(env, options, result)
73 self.generate_h_code(env, options, result)
74 self.generate_api_code(env, result)
76 def has_imported_c_functions(self):
77 for module in self.referenced_modules:
78 for entry in module.cfunc_entries:
79 if entry.defined_in_pxd:
80 return 1
81 return 0
83 def generate_dep_file(self, env, result):
84 modules = self.referenced_modules
85 if len(modules) > 1 or env.included_files:
86 dep_file = replace_suffix(result.c_file, ".dep")
87 f = open(dep_file, "w")
88 try:
89 for module in modules:
90 if module is not env:
91 f.write("cimport %s\n" % module.qualified_name)
92 for path in module.included_files:
93 f.write("include %s\n" % path)
94 finally:
95 f.close()
97 def generate_h_code(self, env, options, result):
98 def h_entries(entries, pxd = 0):
99 return [entry for entry in entries
100 if entry.visibility == 'public' or pxd and entry.defined_in_pxd]
101 h_types = h_entries(env.type_entries)
102 h_vars = h_entries(env.var_entries)
103 h_funcs = h_entries(env.cfunc_entries)
104 h_extension_types = h_entries(env.c_class_entries)
105 if h_types or h_vars or h_funcs or h_extension_types:
106 result.h_file = replace_suffix(result.c_file, ".h")
107 h_code = Code.CCodeWriter()
108 Code.GlobalState(h_code)
109 if options.generate_pxi:
110 result.i_file = replace_suffix(result.c_file, ".pxi")
111 i_code = Code.PyrexCodeWriter(result.i_file)
112 else:
113 i_code = None
114 guard = Naming.h_guard_prefix + env.qualified_name.replace(".", "__")
115 h_code.put_h_guard(guard)
116 self.generate_extern_c_macro_definition(h_code)
117 self.generate_type_header_code(h_types, h_code)
118 h_code.putln("")
119 h_code.putln("#ifndef %s" % Naming.api_guard_prefix + self.api_name(env))
120 if h_vars:
121 h_code.putln("")
122 for entry in h_vars:
123 self.generate_public_declaration(entry, h_code, i_code)
124 if h_funcs:
125 h_code.putln("")
126 for entry in h_funcs:
127 self.generate_public_declaration(entry, h_code, i_code)
128 if h_extension_types:
129 h_code.putln("")
130 for entry in h_extension_types:
131 self.generate_cclass_header_code(entry.type, h_code)
132 if i_code:
133 self.generate_cclass_include_code(entry.type, i_code)
134 h_code.putln("")
135 h_code.putln("#endif")
136 h_code.putln("")
137 h_code.putln("PyMODINIT_FUNC init%s(void);" % env.module_name)
138 h_code.putln("")
139 h_code.putln("#endif")
141 h_code.copyto(open_new_file(result.h_file))
143 def generate_public_declaration(self, entry, h_code, i_code):
144 h_code.putln("%s %s;" % (
145 Naming.extern_c_macro,
146 entry.type.declaration_code(
147 entry.cname, dll_linkage = "DL_IMPORT")))
148 if i_code:
149 i_code.putln("cdef extern %s" %
150 entry.type.declaration_code(entry.cname, pyrex = 1))
152 def api_name(self, env):
153 return env.qualified_name.replace(".", "__")
155 def generate_api_code(self, env, result):
156 api_funcs = []
157 public_extension_types = []
158 has_api_extension_types = 0
159 for entry in env.cfunc_entries:
160 if entry.api:
161 api_funcs.append(entry)
162 for entry in env.c_class_entries:
163 if entry.visibility == 'public':
164 public_extension_types.append(entry)
165 if entry.api:
166 has_api_extension_types = 1
167 if api_funcs or has_api_extension_types:
168 result.api_file = replace_suffix(result.c_file, "_api.h")
169 h_code = Code.CCodeWriter()
170 Code.GlobalState(h_code)
171 name = self.api_name(env)
172 guard = Naming.api_guard_prefix + name
173 h_code.put_h_guard(guard)
174 h_code.putln('#include "Python.h"')
175 if result.h_file:
176 h_code.putln('#include "%s"' % os.path.basename(result.h_file))
177 for entry in public_extension_types:
178 type = entry.type
179 h_code.putln("")
180 h_code.putln("static PyTypeObject *%s;" % type.typeptr_cname)
181 h_code.putln("#define %s (*%s)" % (
182 type.typeobj_cname, type.typeptr_cname))
183 if api_funcs:
184 h_code.putln("")
185 for entry in api_funcs:
186 type = CPtrType(entry.type)
187 h_code.putln("static %s;" % type.declaration_code(entry.cname))
188 h_code.putln("")
189 h_code.put_h_guard(Naming.api_func_guard + "import_module")
190 h_code.put(import_module_utility_code.impl)
191 h_code.putln("")
192 h_code.putln("#endif")
193 if api_funcs:
194 h_code.putln("")
195 h_code.put(function_import_utility_code.impl)
196 if public_extension_types:
197 h_code.putln("")
198 h_code.put(type_import_utility_code.impl)
199 h_code.putln("")
200 h_code.putln("static int import_%s(void) {" % name)
201 h_code.putln("PyObject *module = 0;")
202 h_code.putln('module = __Pyx_ImportModule("%s");' % env.qualified_name)
203 h_code.putln("if (!module) goto bad;")
204 for entry in api_funcs:
205 sig = entry.type.signature_string()
206 h_code.putln(
207 'if (__Pyx_ImportFunction(module, "%s", (void (**)(void))&%s, "%s") < 0) goto bad;' % (
208 entry.name,
209 entry.cname,
210 sig))
211 h_code.putln("Py_DECREF(module); module = 0;")
212 for entry in public_extension_types:
213 self.generate_type_import_call(
214 entry.type, h_code,
215 "if (!%s) goto bad;" % entry.type.typeptr_cname)
216 h_code.putln("return 0;")
217 h_code.putln("bad:")
218 h_code.putln("Py_XDECREF(module);")
219 h_code.putln("return -1;")
220 h_code.putln("}")
221 h_code.putln("")
222 h_code.putln("#endif")
224 h_code.copyto(open_new_file(result.api_file))
226 def generate_cclass_header_code(self, type, h_code):
227 h_code.putln("%s DL_IMPORT(PyTypeObject) %s;" % (
228 Naming.extern_c_macro,
229 type.typeobj_cname))
230 #self.generate_obj_struct_definition(type, h_code)
232 def generate_cclass_include_code(self, type, i_code):
233 i_code.putln("cdef extern class %s.%s:" % (
234 type.module_name, type.name))
235 i_code.indent()
236 var_entries = type.scope.var_entries
237 if var_entries:
238 for entry in var_entries:
239 i_code.putln("cdef %s" %
240 entry.type.declaration_code(entry.cname, pyrex = 1))
241 else:
242 i_code.putln("pass")
243 i_code.dedent()
245 def generate_c_code(self, env, options, result):
246 modules = self.referenced_modules
248 if Options.annotate or options.annotate:
249 emit_linenums = False
250 rootwriter = Annotate.AnnotationCCodeWriter()
251 else:
252 emit_linenums = options.emit_linenums
253 rootwriter = Code.CCodeWriter(emit_linenums=emit_linenums)
254 globalstate = Code.GlobalState(rootwriter, emit_linenums)
255 globalstate.initialize_main_c_code()
256 h_code = globalstate['h_code']
258 self.generate_module_preamble(env, modules, h_code)
260 globalstate.module_pos = self.pos
261 globalstate.directives = self.directives
263 globalstate.use_utility_code(refcount_utility_code)
265 code = globalstate['before_global_var']
266 code.putln('#define __Pyx_MODULE_NAME "%s"' % self.full_module_name)
267 code.putln("int %s%s = %s;" % (Naming.module_is_main, self.full_module_name.replace('.', '__'), int(Options.embed)))
268 code.putln("")
269 code.putln("/* Implementation of %s */" % env.qualified_name)
270 self.generate_const_definitions(env, code)
271 self.generate_interned_num_decls(env, code)
272 self.generate_interned_string_decls(env, code)
273 self.generate_py_string_decls(env, code)
275 code = globalstate['all_the_rest']
277 self.generate_cached_builtins_decls(env, code)
278 self.body.generate_function_definitions(env, code)
279 code.mark_pos(None)
280 self.generate_typeobj_definitions(env, code)
281 self.generate_method_table(env, code)
282 self.generate_filename_init_prototype(code)
283 if env.has_import_star:
284 self.generate_import_star(env, code)
285 self.generate_pymoduledef_struct(env, code)
286 self.generate_module_init_func(modules[:-1], env, code)
287 code.mark_pos(None)
288 self.generate_module_cleanup_func(env, code)
289 if Options.embed:
290 self.generate_main_method(env, code)
291 self.generate_filename_table(code)
293 self.generate_declarations_for_modules(env, modules, globalstate)
294 h_code.write('\n')
296 for codetup, name in env.utility_code_list:
297 globalstate.use_utility_code(codetup, name)
298 globalstate.finalize_main_c_code()
300 f = open_new_file(result.c_file)
301 rootwriter.copyto(f)
302 f.close()
303 result.c_file_generated = 1
304 if Options.annotate or options.annotate:
305 self.annotate(rootwriter)
306 rootwriter.save_annotation(result.main_source_file, result.c_file)
308 def find_referenced_modules(self, env, module_list, modules_seen):
309 if env not in modules_seen:
310 modules_seen[env] = 1
311 for imported_module in env.cimported_modules:
312 self.find_referenced_modules(imported_module, module_list, modules_seen)
313 module_list.append(env)
315 def sort_types_by_inheritance(self, type_dict, getkey):
316 # copy the types into a list moving each parent type before
317 # its first child
318 type_items = type_dict.items()
319 type_list = []
320 for i, item in enumerate(type_items):
321 key, new_entry = item
323 # collect all base classes to check for children
324 hierarchy = set()
325 base = new_entry
326 while base:
327 base_type = base.type.base_type
328 if not base_type:
329 break
330 base_key = getkey(base_type)
331 hierarchy.add(base_key)
332 base = type_dict.get(base_key)
333 new_entry.base_keys = hierarchy
335 # find the first (sub-)subclass and insert before that
336 for j in range(i):
337 entry = type_list[j]
338 if key in entry.base_keys:
339 type_list.insert(j, new_entry)
340 break
341 else:
342 type_list.append(new_entry)
343 return type_list
345 def sort_type_hierarchy(self, module_list, env):
346 vtab_dict = {}
347 vtabslot_dict = {}
348 for module in module_list:
349 for entry in module.c_class_entries:
350 if not entry.in_cinclude:
351 type = entry.type
352 if type.vtabstruct_cname:
353 vtab_dict[type.vtabstruct_cname] = entry
354 all_defined_here = module is env
355 for entry in module.type_entries:
356 if all_defined_here or entry.defined_in_pxd:
357 type = entry.type
358 if type.is_extension_type and not entry.in_cinclude:
359 type = entry.type
360 vtabslot_dict[type.objstruct_cname] = entry
362 def vtabstruct_cname(entry_type):
363 return entry_type.vtabstruct_cname
364 vtab_list = self.sort_types_by_inheritance(
365 vtab_dict, vtabstruct_cname)
367 def objstruct_cname(entry_type):
368 return entry_type.objstruct_cname
369 vtabslot_list = self.sort_types_by_inheritance(
370 vtabslot_dict, objstruct_cname)
372 return (vtab_list, vtabslot_list)
374 def generate_type_definitions(self, env, modules, vtab_list, vtabslot_list, code):
375 vtabslot_entries = set(vtabslot_list)
376 for module in modules:
377 definition = module is env
378 if definition:
379 type_entries = module.type_entries
380 else:
381 type_entries = []
382 for entry in module.type_entries:
383 if entry.defined_in_pxd:
384 type_entries.append(entry)
385 for entry in type_entries:
386 if not entry.in_cinclude:
387 #print "generate_type_header_code:", entry.name, repr(entry.type) ###
388 type = entry.type
389 if type.is_typedef: # Must test this first!
390 self.generate_typedef(entry, code)
391 elif type.is_struct_or_union:
392 self.generate_struct_union_definition(entry, code)
393 elif type.is_enum:
394 self.generate_enum_definition(entry, code)
395 elif type.is_extension_type and entry not in vtabslot_entries:
396 self.generate_obj_struct_definition(type, code)
397 for entry in vtabslot_list:
398 self.generate_obj_struct_definition(entry.type, code)
399 for entry in vtab_list:
400 self.generate_typeobject_predeclaration(entry, code)
401 self.generate_exttype_vtable_struct(entry, code)
402 self.generate_exttype_vtabptr_declaration(entry, code)
404 def generate_declarations_for_modules(self, env, modules, globalstate):
405 typecode = globalstate['type_declarations']
406 typecode.putln("")
407 typecode.putln("/* Type declarations */")
408 vtab_list, vtabslot_list = self.sort_type_hierarchy(modules, env)
409 self.generate_type_definitions(
410 env, modules, vtab_list, vtabslot_list, typecode)
411 modulecode = globalstate['module_declarations']
412 for module in modules:
413 defined_here = module is env
414 modulecode.putln("/* Module declarations from %s */" %
415 module.qualified_name.encode("ASCII", "ignore"))
416 self.generate_global_declarations(module, modulecode, defined_here)
417 self.generate_cfunction_predeclarations(module, modulecode, defined_here)
419 def generate_module_preamble(self, env, cimported_modules, code):
420 code.putln('/* Generated by Cython %s on %s */' % (
421 Version.version, time.asctime()))
422 code.putln('')
423 code.putln('#define PY_SSIZE_T_CLEAN')
424 for filename in env.python_include_files:
425 code.putln('#include "%s"' % filename)
426 code.putln("#ifndef Py_PYTHON_H")
427 code.putln(" #error Python headers needed to compile C extensions, please install development version of Python.")
428 code.putln("#else")
429 code.globalstate["end"].putln("#endif /* Py_PYTHON_H */")
430 code.putln("#ifndef PY_LONG_LONG")
431 code.putln(" #define PY_LONG_LONG LONG_LONG")
432 code.putln("#endif")
433 code.putln("#ifndef DL_EXPORT")
434 code.putln(" #define DL_EXPORT(t) t")
435 code.putln("#endif")
436 code.putln("#if PY_VERSION_HEX < 0x02040000")
437 code.putln(" #define METH_COEXIST 0")
438 code.putln(" #define PyDict_CheckExact(op) (Py_TYPE(op) == &PyDict_Type)")
439 code.putln("#endif")
441 code.putln("#if PY_VERSION_HEX < 0x02050000")
442 code.putln(" typedef int Py_ssize_t;")
443 code.putln(" #define PY_SSIZE_T_MAX INT_MAX")
444 code.putln(" #define PY_SSIZE_T_MIN INT_MIN")
445 code.putln(" #define PY_FORMAT_SIZE_T \"\"")
446 code.putln(" #define PyInt_FromSsize_t(z) PyInt_FromLong(z)")
447 code.putln(" #define PyInt_AsSsize_t(o) PyInt_AsLong(o)")
448 code.putln(" #define PyNumber_Index(o) PyNumber_Int(o)")
449 code.putln(" #define PyIndex_Check(o) PyNumber_Check(o)")
450 code.putln("#endif")
452 code.putln("#if PY_VERSION_HEX < 0x02060000")
453 code.putln(" #define Py_REFCNT(ob) (((PyObject*)(ob))->ob_refcnt)")
454 code.putln(" #define Py_TYPE(ob) (((PyObject*)(ob))->ob_type)")
455 code.putln(" #define Py_SIZE(ob) (((PyVarObject*)(ob))->ob_size)")
456 code.putln(" #define PyVarObject_HEAD_INIT(type, size) \\")
457 code.putln(" PyObject_HEAD_INIT(type) size,")
458 code.putln(" #define PyType_Modified(t)")
459 code.putln("")
460 code.putln(" typedef struct {")
461 code.putln(" void *buf;")
462 code.putln(" PyObject *obj;")
463 code.putln(" Py_ssize_t len;")
464 code.putln(" Py_ssize_t itemsize;")
465 code.putln(" int readonly;")
466 code.putln(" int ndim;")
467 code.putln(" char *format;")
468 code.putln(" Py_ssize_t *shape;")
469 code.putln(" Py_ssize_t *strides;")
470 code.putln(" Py_ssize_t *suboffsets;")
471 code.putln(" void *internal;")
472 code.putln(" } Py_buffer;")
473 code.putln("")
474 code.putln(" #define PyBUF_SIMPLE 0")
475 code.putln(" #define PyBUF_WRITABLE 0x0001")
476 code.putln(" #define PyBUF_FORMAT 0x0004")
477 code.putln(" #define PyBUF_ND 0x0008")
478 code.putln(" #define PyBUF_STRIDES (0x0010 | PyBUF_ND)")
479 code.putln(" #define PyBUF_C_CONTIGUOUS (0x0020 | PyBUF_STRIDES)")
480 code.putln(" #define PyBUF_F_CONTIGUOUS (0x0040 | PyBUF_STRIDES)")
481 code.putln(" #define PyBUF_ANY_CONTIGUOUS (0x0080 | PyBUF_STRIDES)")
482 code.putln(" #define PyBUF_INDIRECT (0x0100 | PyBUF_STRIDES)")
483 code.putln("")
484 code.putln("#endif")
486 code.put(builtin_module_name_utility_code.proto)
488 code.putln("#if PY_MAJOR_VERSION >= 3")
489 code.putln(" #define Py_TPFLAGS_CHECKTYPES 0")
490 code.putln(" #define Py_TPFLAGS_HAVE_INDEX 0")
491 code.putln("#endif")
493 code.putln("#if (PY_VERSION_HEX < 0x02060000) || (PY_MAJOR_VERSION >= 3)")
494 code.putln(" #define Py_TPFLAGS_HAVE_NEWBUFFER 0")
495 code.putln("#endif")
497 code.putln("#if PY_MAJOR_VERSION >= 3")
498 code.putln(" #define PyBaseString_Type PyUnicode_Type")
499 code.putln(" #define PyString_Type PyBytes_Type")
500 code.putln(" #define PyString_CheckExact PyBytes_CheckExact")
501 code.putln(" #define PyInt_Type PyLong_Type")
502 code.putln(" #define PyInt_Check(op) PyLong_Check(op)")
503 code.putln(" #define PyInt_CheckExact(op) PyLong_CheckExact(op)")
504 code.putln(" #define PyInt_FromString PyLong_FromString")
505 code.putln(" #define PyInt_FromUnicode PyLong_FromUnicode")
506 code.putln(" #define PyInt_FromLong PyLong_FromLong")
507 code.putln(" #define PyInt_FromSize_t PyLong_FromSize_t")
508 code.putln(" #define PyInt_FromSsize_t PyLong_FromSsize_t")
509 code.putln(" #define PyInt_AsLong PyLong_AsLong")
510 code.putln(" #define PyInt_AS_LONG PyLong_AS_LONG")
511 code.putln(" #define PyInt_AsSsize_t PyLong_AsSsize_t")
512 code.putln(" #define PyInt_AsUnsignedLongMask PyLong_AsUnsignedLongMask")
513 code.putln(" #define PyInt_AsUnsignedLongLongMask PyLong_AsUnsignedLongLongMask")
514 code.putln(" #define __Pyx_PyNumber_Divide(x,y) PyNumber_TrueDivide(x,y)")
515 code.putln("#else")
516 if Future.division in env.context.future_directives:
517 code.putln(" #define __Pyx_PyNumber_Divide(x,y) PyNumber_TrueDivide(x,y)")
518 else:
519 code.putln(" #define __Pyx_PyNumber_Divide(x,y) PyNumber_Divide(x,y)")
520 code.putln(" #define PyBytes_Type PyString_Type")
521 code.putln("#endif")
523 code.putln("#if PY_MAJOR_VERSION >= 3")
524 code.putln(" #define PyMethod_New(func, self, klass) PyInstanceMethod_New(func)")
525 code.putln("#endif")
527 code.putln("#if !defined(WIN32) && !defined(MS_WINDOWS)")
528 code.putln(" #ifndef __stdcall")
529 code.putln(" #define __stdcall")
530 code.putln(" #endif")
531 code.putln(" #ifndef __cdecl")
532 code.putln(" #define __cdecl")
533 code.putln(" #endif")
534 code.putln(" #ifndef __fastcall")
535 code.putln(" #define __fastcall")
536 code.putln(" #endif")
537 code.putln("#else")
538 code.putln(" #define _USE_MATH_DEFINES")
539 code.putln("#endif")
541 code.putln("#if PY_VERSION_HEX < 0x02050000")
542 code.putln(" #define __Pyx_GetAttrString(o,n) PyObject_GetAttrString((o),((char *)(n)))")
543 code.putln(" #define __Pyx_SetAttrString(o,n,a) PyObject_SetAttrString((o),((char *)(n)),(a))")
544 code.putln(" #define __Pyx_DelAttrString(o,n) PyObject_DelAttrString((o),((char *)(n)))")
545 code.putln("#else")
546 code.putln(" #define __Pyx_GetAttrString(o,n) PyObject_GetAttrString((o),(n))")
547 code.putln(" #define __Pyx_SetAttrString(o,n,a) PyObject_SetAttrString((o),(n),(a))")
548 code.putln(" #define __Pyx_DelAttrString(o,n) PyObject_DelAttrString((o),(n))")
549 code.putln("#endif")
551 code.putln("#if PY_VERSION_HEX < 0x02050000")
552 code.putln(" #define __Pyx_NAMESTR(n) ((char *)(n))")
553 code.putln(" #define __Pyx_DOCSTR(n) ((char *)(n))")
554 code.putln("#else")
555 code.putln(" #define __Pyx_NAMESTR(n) (n)")
556 code.putln(" #define __Pyx_DOCSTR(n) (n)")
557 code.putln("#endif")
559 self.generate_extern_c_macro_definition(code)
560 code.putln("#include <math.h>")
561 code.putln("#define %s" % Naming.api_guard_prefix + self.api_name(env))
562 self.generate_includes(env, cimported_modules, code)
563 if env.directives['c99_complex']:
564 code.putln("#ifndef _Complex_I")
565 code.putln("#include <complex.h>")
566 code.putln("#endif")
567 code.putln("#define __PYX_USE_C99_COMPLEX defined(_Complex_I)")
568 code.putln('')
569 code.put(Nodes.utility_function_predeclarations)
570 code.put(PyrexTypes.type_conversion_predeclarations)
571 code.put(Nodes.branch_prediction_macros)
572 code.putln('')
573 code.putln('static PyObject *%s;' % env.module_cname)
574 code.putln('static PyObject *%s;' % Naming.builtins_cname)
575 code.putln('static PyObject *%s;' % Naming.empty_tuple)
576 code.putln('static PyObject *%s;' % Naming.empty_bytes)
577 if Options.pre_import is not None:
578 code.putln('static PyObject *%s;' % Naming.preimport_cname)
579 code.putln('static int %s;' % Naming.lineno_cname)
580 code.putln('static int %s = 0;' % Naming.clineno_cname)
581 code.putln('static const char * %s= %s;' % (Naming.cfilenm_cname, Naming.file_c_macro))
582 code.putln('static const char *%s;' % Naming.filename_cname)
583 code.putln('static const char **%s;' % Naming.filetable_cname)
584 if env.doc:
585 docstr = env.doc
586 if not isinstance(docstr, str):
587 docstr = docstr.utf8encode()
588 code.putln('')
589 code.putln('static char %s[] = "%s";' % (
590 env.doc_cname, escape_byte_string(docstr)))
592 # XXX this is a mess
593 for utility_code in PyrexTypes.c_int_from_py_function.specialize_list:
594 env.use_utility_code(utility_code)
595 for utility_code in PyrexTypes.c_long_from_py_function.specialize_list:
596 env.use_utility_code(utility_code)
598 def generate_extern_c_macro_definition(self, code):
599 name = Naming.extern_c_macro
600 code.putln("#ifdef __cplusplus")
601 code.putln('#define %s extern "C"' % name)
602 code.putln("#else")
603 code.putln("#define %s extern" % name)
604 code.putln("#endif")
606 def generate_includes(self, env, cimported_modules, code):
607 includes = []
608 for filename in env.include_files:
609 code.putln('#include "%s"' % filename)
611 def generate_filename_table(self, code):
612 code.putln("")
613 code.putln("static const char *%s[] = {" % Naming.filenames_cname)
614 if code.globalstate.filename_list:
615 for source_desc in code.globalstate.filename_list:
616 filename = os.path.basename(source_desc.get_filenametable_entry())
617 escaped_filename = filename.replace("\\", "\\\\").replace('"', r'\"')
618 code.putln('"%s",' %
619 escaped_filename)
620 else:
621 # Some C compilers don't like an empty array
622 code.putln("0")
623 code.putln("};")
625 def generate_type_predeclarations(self, env, code):
626 pass
628 def generate_type_header_code(self, type_entries, code):
629 # Generate definitions of structs/unions/enums/typedefs/objstructs.
630 #self.generate_gcc33_hack(env, code) # Is this still needed?
631 #for entry in env.type_entries:
632 for entry in type_entries:
633 if not entry.in_cinclude:
634 #print "generate_type_header_code:", entry.name, repr(entry.type) ###
635 type = entry.type
636 if type.is_typedef: # Must test this first!
637 self.generate_typedef(entry, code)
638 elif type.is_struct_or_union:
639 self.generate_struct_union_definition(entry, code)
640 elif type.is_enum:
641 self.generate_enum_definition(entry, code)
642 elif type.is_extension_type:
643 self.generate_obj_struct_definition(type, code)
645 def generate_gcc33_hack(self, env, code):
646 # Workaround for spurious warning generation in gcc 3.3
647 code.putln("")
648 for entry in env.c_class_entries:
649 type = entry.type
650 if not type.typedef_flag:
651 name = type.objstruct_cname
652 if name.startswith("__pyx_"):
653 tail = name[6:]
654 else:
655 tail = name
656 code.putln("typedef struct %s __pyx_gcc33_%s;" % (
657 name, tail))
659 def generate_typedef(self, entry, code):
660 base_type = entry.type.typedef_base_type
661 code.putln("")
662 code.putln("typedef %s;" % base_type.declaration_code(entry.cname))
664 def sue_header_footer(self, type, kind, name):
665 if type.typedef_flag:
666 header = "typedef %s {" % kind
667 footer = "} %s;" % name
668 else:
669 header = "%s %s {" % (kind, name)
670 footer = "};"
671 return header, footer
673 def generate_struct_union_definition(self, entry, code):
674 code.mark_pos(entry.pos)
675 type = entry.type
676 scope = type.scope
677 if scope:
678 kind = type.kind
679 packed = type.is_struct and type.packed
680 if packed:
681 kind = "%s %s" % (type.kind, "__Pyx_PACKED")
682 code.globalstate.use_utility_code(packed_struct_utility_code)
683 header, footer = \
684 self.sue_header_footer(type, kind, type.cname)
685 code.putln("")
686 if packed:
687 code.putln("#if !defined(__GNUC__)")
688 code.putln("#pragma pack(push, 1)")
689 code.putln("#endif")
690 code.putln(header)
691 var_entries = scope.var_entries
692 if not var_entries:
693 error(entry.pos,
694 "Empty struct or union definition not allowed outside a"
695 " 'cdef extern from' block")
696 for attr in var_entries:
697 code.putln(
698 "%s;" %
699 attr.type.declaration_code(attr.cname))
700 code.putln(footer)
701 if packed:
702 code.putln("#if !defined(__GNUC__)")
703 code.putln("#pragma pack(pop)")
704 code.putln("#endif")
706 def generate_enum_definition(self, entry, code):
707 code.mark_pos(entry.pos)
708 type = entry.type
709 name = entry.cname or entry.name or ""
710 header, footer = \
711 self.sue_header_footer(type, "enum", name)
712 code.putln("")
713 code.putln(header)
714 enum_values = entry.enum_values
715 if not enum_values:
716 error(entry.pos,
717 "Empty enum definition not allowed outside a"
718 " 'cdef extern from' block")
719 else:
720 last_entry = enum_values[-1]
721 for value_entry in enum_values:
722 if value_entry.value == value_entry.name:
723 value_code = value_entry.cname
724 else:
725 value_code = ("%s = %s" % (
726 value_entry.cname,
727 value_entry.value))
728 if value_entry is not last_entry:
729 value_code += ","
730 code.putln(value_code)
731 code.putln(footer)
733 def generate_typeobject_predeclaration(self, entry, code):
734 code.putln("")
735 name = entry.type.typeobj_cname
736 if name:
737 if entry.visibility == 'extern' and not entry.in_cinclude:
738 code.putln("%s DL_IMPORT(PyTypeObject) %s;" % (
739 Naming.extern_c_macro,
740 name))
741 elif entry.visibility == 'public':
742 #code.putln("DL_EXPORT(PyTypeObject) %s;" % name)
743 code.putln("%s DL_EXPORT(PyTypeObject) %s;" % (
744 Naming.extern_c_macro,
745 name))
746 # ??? Do we really need the rest of this? ???
747 #else:
748 # code.putln("staticforward PyTypeObject %s;" % name)
750 def generate_exttype_vtable_struct(self, entry, code):
751 code.mark_pos(entry.pos)
752 # Generate struct declaration for an extension type's vtable.
753 type = entry.type
754 scope = type.scope
755 if type.vtabstruct_cname:
756 code.putln("")
757 code.putln(
758 "struct %s {" %
759 type.vtabstruct_cname)
760 if type.base_type and type.base_type.vtabstruct_cname:
761 code.putln("struct %s %s;" % (
762 type.base_type.vtabstruct_cname,
763 Naming.obj_base_cname))
764 for method_entry in scope.cfunc_entries:
765 if not method_entry.is_inherited:
766 code.putln(
767 "%s;" % method_entry.type.declaration_code("(*%s)" % method_entry.name))
768 code.putln(
769 "};")
771 def generate_exttype_vtabptr_declaration(self, entry, code):
772 code.mark_pos(entry.pos)
773 # Generate declaration of pointer to an extension type's vtable.
774 type = entry.type
775 if type.vtabptr_cname:
776 code.putln("static struct %s *%s;" % (
777 type.vtabstruct_cname,
778 type.vtabptr_cname))
780 def generate_obj_struct_definition(self, type, code):
781 code.mark_pos(type.pos)
782 # Generate object struct definition for an
783 # extension type.
784 if not type.scope:
785 return # Forward declared but never defined
786 header, footer = \
787 self.sue_header_footer(type, "struct", type.objstruct_cname)
788 code.putln("")
789 code.putln(header)
790 base_type = type.base_type
791 if base_type:
792 code.putln(
793 "%s%s %s;" % (
794 ("struct ", "")[base_type.typedef_flag],
795 base_type.objstruct_cname,
796 Naming.obj_base_cname))
797 else:
798 code.putln(
799 "PyObject_HEAD")
800 if type.vtabslot_cname and not (type.base_type and type.base_type.vtabslot_cname):
801 code.putln(
802 "struct %s *%s;" % (
803 type.vtabstruct_cname,
804 type.vtabslot_cname))
805 for attr in type.scope.var_entries:
806 code.putln(
807 "%s;" %
808 attr.type.declaration_code(attr.cname))
809 code.putln(footer)
811 def generate_global_declarations(self, env, code, definition):
812 code.putln("")
813 for entry in env.c_class_entries:
814 if definition or entry.defined_in_pxd:
815 code.putln("static PyTypeObject *%s = 0;" %
816 entry.type.typeptr_cname)
817 code.put_var_declarations(env.var_entries, static = 1,
818 dll_linkage = "DL_EXPORT", definition = definition)
819 if definition:
820 code.put_var_declarations(env.default_entries, static = 1,
821 definition = definition)
823 def generate_cfunction_predeclarations(self, env, code, definition):
824 for entry in env.cfunc_entries:
825 if entry.inline_func_in_pxd or (not entry.in_cinclude and (definition
826 or entry.defined_in_pxd or entry.visibility == 'extern')):
827 if entry.visibility in ('public', 'extern'):
828 dll_linkage = "DL_EXPORT"
829 else:
830 dll_linkage = None
831 type = entry.type
832 if not definition and entry.defined_in_pxd:
833 type = CPtrType(type)
834 header = type.declaration_code(entry.cname,
835 dll_linkage = dll_linkage)
836 if entry.visibility == 'private':
837 storage_class = "static "
838 elif entry.visibility == 'public':
839 storage_class = ""
840 else:
841 storage_class = "%s " % Naming.extern_c_macro
842 if entry.func_modifiers:
843 modifiers = '%s ' % ' '.join([
844 modifier.upper() for modifier in entry.func_modifiers])
845 else:
846 modifiers = ''
847 code.putln("%s%s%s; /*proto*/" % (
848 storage_class,
849 modifiers,
850 header))
852 def generate_typeobj_definitions(self, env, code):
853 full_module_name = env.qualified_name
854 for entry in env.c_class_entries:
855 #print "generate_typeobj_definitions:", entry.name
856 #print "...visibility =", entry.visibility
857 if entry.visibility != 'extern':
858 type = entry.type
859 scope = type.scope
860 if scope: # could be None if there was an error
861 self.generate_exttype_vtable(scope, code)
862 self.generate_new_function(scope, code)
863 self.generate_dealloc_function(scope, code)
864 if scope.needs_gc():
865 self.generate_traverse_function(scope, code)
866 self.generate_clear_function(scope, code)
867 if scope.defines_any(["__getitem__"]):
868 self.generate_getitem_int_function(scope, code)
869 if scope.defines_any(["__setitem__", "__delitem__"]):
870 self.generate_ass_subscript_function(scope, code)
871 if scope.defines_any(["__setslice__", "__delslice__"]):
872 warning(self.pos, "__setslice__ and __delslice__ are not supported by Python 3", 1)
873 self.generate_ass_slice_function(scope, code)
874 if scope.defines_any(["__getattr__","__getattribute__"]):
875 self.generate_getattro_function(scope, code)
876 if scope.defines_any(["__setattr__", "__delattr__"]):
877 self.generate_setattro_function(scope, code)
878 if scope.defines_any(["__get__"]):
879 self.generate_descr_get_function(scope, code)
880 if scope.defines_any(["__set__", "__delete__"]):
881 self.generate_descr_set_function(scope, code)
882 self.generate_property_accessors(scope, code)
883 self.generate_method_table(scope, code)
884 self.generate_member_table(scope, code)
885 self.generate_getset_table(scope, code)
886 self.generate_typeobj_definition(full_module_name, entry, code)
888 def generate_exttype_vtable(self, scope, code):
889 # Generate the definition of an extension type's vtable.
890 type = scope.parent_type
891 if type.vtable_cname:
892 code.putln("static struct %s %s;" % (
893 type.vtabstruct_cname,
894 type.vtable_cname))
896 def generate_self_cast(self, scope, code):
897 type = scope.parent_type
898 code.putln(
899 "%s = (%s)o;" % (
900 type.declaration_code("p"),
901 type.declaration_code("")))
903 def generate_new_function(self, scope, code):
904 tp_slot = TypeSlots.ConstructorSlot("tp_new", '__new__')
905 slot_func = scope.mangle_internal("tp_new")
906 type = scope.parent_type
907 base_type = type.base_type
908 py_attrs = []
909 for entry in scope.var_entries:
910 if entry.type.is_pyobject:
911 py_attrs.append(entry)
912 need_self_cast = type.vtabslot_cname or py_attrs
913 code.putln("")
914 code.putln(
915 "static PyObject *%s(PyTypeObject *t, PyObject *a, PyObject *k) {"
916 % scope.mangle_internal("tp_new"))
917 if need_self_cast:
918 code.putln(
919 "%s;"
920 % scope.parent_type.declaration_code("p"))
921 if base_type:
922 tp_new = TypeSlots.get_base_slot_function(scope, tp_slot)
923 if tp_new is None:
924 tp_new = "%s->tp_new" % base_type.typeptr_cname
925 code.putln(
926 "PyObject *o = %s(t, a, k);" % tp_new)
927 else:
928 code.putln(
929 "PyObject *o = (*t->tp_alloc)(t, 0);")
930 code.putln(
931 "if (!o) return 0;")
932 if need_self_cast:
933 code.putln(
934 "p = %s;"
935 % type.cast_code("o"))
936 #if need_self_cast:
937 # self.generate_self_cast(scope, code)
938 if type.vtabslot_cname:
939 vtab_base_type = type
940 while vtab_base_type.base_type and vtab_base_type.base_type.vtabstruct_cname:
941 vtab_base_type = vtab_base_type.base_type
942 if vtab_base_type is not type:
943 struct_type_cast = "(struct %s*)" % vtab_base_type.vtabstruct_cname
944 else:
945 struct_type_cast = ""
946 code.putln("p->%s = %s%s;" % (
947 type.vtabslot_cname,
948 struct_type_cast, type.vtabptr_cname))
949 for entry in py_attrs:
950 if entry.name == "__weakref__":
951 code.putln("p->%s = 0;" % entry.cname)
952 else:
953 code.put_init_var_to_py_none(entry, "p->%s", nanny=False)
954 entry = scope.lookup_here("__new__")
955 if entry and entry.is_special:
956 if entry.trivial_signature:
957 cinit_args = "o, %s, NULL" % Naming.empty_tuple
958 else:
959 cinit_args = "o, a, k"
960 code.putln(
961 "if (%s(%s) < 0) {" %
962 (entry.func_cname, cinit_args))
963 code.put_decref_clear("o", py_object_type, nanny=False);
964 code.putln(
965 "}")
966 code.putln(
967 "return o;")
968 code.putln(
969 "}")
971 def generate_dealloc_function(self, scope, code):
972 tp_slot = TypeSlots.ConstructorSlot("tp_dealloc", '__dealloc__')
973 slot_func = scope.mangle_internal("tp_dealloc")
974 base_type = scope.parent_type.base_type
975 if tp_slot.slot_code(scope) != slot_func:
976 return # never used
977 code.putln("")
978 code.putln(
979 "static void %s(PyObject *o) {"
980 % scope.mangle_internal("tp_dealloc"))
981 py_attrs = []
982 weakref_slot = scope.lookup_here("__weakref__")
983 for entry in scope.var_entries:
984 if entry.type.is_pyobject and entry is not weakref_slot:
985 py_attrs.append(entry)
986 if py_attrs or weakref_slot in scope.var_entries:
987 self.generate_self_cast(scope, code)
988 self.generate_usr_dealloc_call(scope, code)
989 if weakref_slot in scope.var_entries:
990 code.putln("if (p->__weakref__) PyObject_ClearWeakRefs(o);")
991 for entry in py_attrs:
992 code.put_xdecref("p->%s" % entry.cname, entry.type, nanny=False)
993 if base_type:
994 tp_dealloc = TypeSlots.get_base_slot_function(scope, tp_slot)
995 if tp_dealloc is None:
996 tp_dealloc = "%s->tp_dealloc" % base_type.typeptr_cname
997 code.putln(
998 "%s(o);" % tp_dealloc)
999 else:
1000 code.putln(
1001 "(*Py_TYPE(o)->tp_free)(o);")
1002 code.putln(
1003 "}")
1005 def generate_usr_dealloc_call(self, scope, code):
1006 entry = scope.lookup_here("__dealloc__")
1007 if entry:
1008 code.putln(
1009 "{")
1010 code.putln(
1011 "PyObject *etype, *eval, *etb;")
1012 code.putln(
1013 "PyErr_Fetch(&etype, &eval, &etb);")
1014 code.putln(
1015 "++Py_REFCNT(o);")
1016 code.putln(
1017 "%s(o);" %
1018 entry.func_cname)
1019 code.putln(
1020 "if (PyErr_Occurred()) PyErr_WriteUnraisable(o);")
1021 code.putln(
1022 "--Py_REFCNT(o);")
1023 code.putln(
1024 "PyErr_Restore(etype, eval, etb);")
1025 code.putln(
1026 "}")
1028 def generate_traverse_function(self, scope, code):
1029 tp_slot = TypeSlots.GCDependentSlot("tp_traverse")
1030 slot_func = scope.mangle_internal("tp_traverse")
1031 base_type = scope.parent_type.base_type
1032 if tp_slot.slot_code(scope) != slot_func:
1033 return # never used
1034 code.putln("")
1035 code.putln(
1036 "static int %s(PyObject *o, visitproc v, void *a) {"
1037 % slot_func)
1038 py_attrs = []
1039 for entry in scope.var_entries:
1040 if entry.type.is_pyobject and entry.name != "__weakref__":
1041 py_attrs.append(entry)
1042 if base_type or py_attrs:
1043 code.putln("int e;")
1044 if py_attrs:
1045 self.generate_self_cast(scope, code)
1046 if base_type:
1047 # want to call it explicitly if possible so inlining can be performed
1048 static_call = TypeSlots.get_base_slot_function(scope, tp_slot)
1049 if static_call:
1050 code.putln("e = %s(o, v, a); if (e) return e;" % static_call)
1051 else:
1052 code.putln("if (%s->tp_traverse) {" % base_type.typeptr_cname)
1053 code.putln(
1054 "e = %s->tp_traverse(o, v, a); if (e) return e;" %
1055 base_type.typeptr_cname)
1056 code.putln("}")
1057 for entry in py_attrs:
1058 var_code = "p->%s" % entry.cname
1059 code.putln(
1060 "if (%s) {"
1061 % var_code)
1062 if entry.type.is_extension_type:
1063 var_code = "((PyObject*)%s)" % var_code
1064 code.putln(
1065 "e = (*v)(%s, a); if (e) return e;"
1066 % var_code)
1067 code.putln(
1068 "}")
1069 code.putln(
1070 "return 0;")
1071 code.putln(
1072 "}")
1074 def generate_clear_function(self, scope, code):
1075 tp_slot = TypeSlots.GCDependentSlot("tp_clear")
1076 slot_func = scope.mangle_internal("tp_clear")
1077 base_type = scope.parent_type.base_type
1078 if tp_slot.slot_code(scope) != slot_func:
1079 return # never used
1080 code.putln("")
1081 code.putln("static int %s(PyObject *o) {" % slot_func)
1082 py_attrs = []
1083 for entry in scope.var_entries:
1084 if entry.type.is_pyobject and entry.name != "__weakref__":
1085 py_attrs.append(entry)
1086 if py_attrs:
1087 self.generate_self_cast(scope, code)
1088 code.putln("PyObject* tmp;")
1089 if base_type:
1090 # want to call it explicitly if possible so inlining can be performed
1091 static_call = TypeSlots.get_base_slot_function(scope, tp_slot)
1092 if static_call:
1093 code.putln("%s(o);" % static_call)
1094 else:
1095 code.putln("if (%s->tp_clear) {" % base_type.typeptr_cname)
1096 code.putln("%s->tp_clear(o);" % base_type.typeptr_cname)
1097 code.putln("}")
1098 for entry in py_attrs:
1099 name = "p->%s" % entry.cname
1100 code.putln("tmp = ((PyObject*)%s);" % name)
1101 code.put_init_to_py_none(name, entry.type, nanny=False)
1102 code.putln("Py_XDECREF(tmp);")
1103 code.putln(
1104 "return 0;")
1105 code.putln(
1106 "}")
1108 def generate_getitem_int_function(self, scope, code):
1109 # This function is put into the sq_item slot when
1110 # a __getitem__ method is present. It converts its
1111 # argument to a Python integer and calls mp_subscript.
1112 code.putln(
1113 "static PyObject *%s(PyObject *o, Py_ssize_t i) {" %
1114 scope.mangle_internal("sq_item"))
1115 code.putln(
1116 "PyObject *r;")
1117 code.putln(
1118 "PyObject *x = PyInt_FromSsize_t(i); if(!x) return 0;")
1119 code.putln(
1120 "r = Py_TYPE(o)->tp_as_mapping->mp_subscript(o, x);")
1121 code.putln(
1122 "Py_DECREF(x);")
1123 code.putln(
1124 "return r;")
1125 code.putln(
1126 "}")
1128 def generate_ass_subscript_function(self, scope, code):
1129 # Setting and deleting an item are both done through
1130 # the ass_subscript method, so we dispatch to user's __setitem__
1131 # or __delitem__, or raise an exception.
1132 base_type = scope.parent_type.base_type
1133 set_entry = scope.lookup_here("__setitem__")
1134 del_entry = scope.lookup_here("__delitem__")
1135 code.putln("")
1136 code.putln(
1137 "static int %s(PyObject *o, PyObject *i, PyObject *v) {" %
1138 scope.mangle_internal("mp_ass_subscript"))
1139 code.putln(
1140 "if (v) {")
1141 if set_entry:
1142 code.putln(
1143 "return %s(o, i, v);" %
1144 set_entry.func_cname)
1145 else:
1146 self.generate_guarded_basetype_call(
1147 base_type, "tp_as_mapping", "mp_ass_subscript", "o, i, v", code)
1148 code.putln(
1149 "PyErr_Format(PyExc_NotImplementedError,")
1150 code.putln(
1151 ' "Subscript assignment not supported by %s", Py_TYPE(o)->tp_name);')
1152 code.putln(
1153 "return -1;")
1154 code.putln(
1155 "}")
1156 code.putln(
1157 "else {")
1158 if del_entry:
1159 code.putln(
1160 "return %s(o, i);" %
1161 del_entry.func_cname)
1162 else:
1163 self.generate_guarded_basetype_call(
1164 base_type, "tp_as_mapping", "mp_ass_subscript", "o, i, v", code)
1165 code.putln(
1166 "PyErr_Format(PyExc_NotImplementedError,")
1167 code.putln(
1168 ' "Subscript deletion not supported by %s", Py_TYPE(o)->tp_name);')
1169 code.putln(
1170 "return -1;")
1171 code.putln(
1172 "}")
1173 code.putln(
1174 "}")
1176 def generate_guarded_basetype_call(
1177 self, base_type, substructure, slot, args, code):
1178 if base_type:
1179 base_tpname = base_type.typeptr_cname
1180 if substructure:
1181 code.putln(
1182 "if (%s->%s && %s->%s->%s)" % (
1183 base_tpname, substructure, base_tpname, substructure, slot))
1184 code.putln(
1185 " return %s->%s->%s(%s);" % (
1186 base_tpname, substructure, slot, args))
1187 else:
1188 code.putln(
1189 "if (%s->%s)" % (
1190 base_tpname, slot))
1191 code.putln(
1192 " return %s->%s(%s);" % (
1193 base_tpname, slot, args))
1195 def generate_ass_slice_function(self, scope, code):
1196 # Setting and deleting a slice are both done through
1197 # the ass_slice method, so we dispatch to user's __setslice__
1198 # or __delslice__, or raise an exception.
1199 base_type = scope.parent_type.base_type
1200 set_entry = scope.lookup_here("__setslice__")
1201 del_entry = scope.lookup_here("__delslice__")
1202 code.putln("")
1203 code.putln(
1204 "static int %s(PyObject *o, Py_ssize_t i, Py_ssize_t j, PyObject *v) {" %
1205 scope.mangle_internal("sq_ass_slice"))
1206 code.putln(
1207 "if (v) {")
1208 if set_entry:
1209 code.putln(
1210 "return %s(o, i, j, v);" %
1211 set_entry.func_cname)
1212 else:
1213 self.generate_guarded_basetype_call(
1214 base_type, "tp_as_sequence", "sq_ass_slice", "o, i, j, v", code)
1215 code.putln(
1216 "PyErr_Format(PyExc_NotImplementedError,")
1217 code.putln(
1218 ' "2-element slice assignment not supported by %s", Py_TYPE(o)->tp_name);')
1219 code.putln(
1220 "return -1;")
1221 code.putln(
1222 "}")
1223 code.putln(
1224 "else {")
1225 if del_entry:
1226 code.putln(
1227 "return %s(o, i, j);" %
1228 del_entry.func_cname)
1229 else:
1230 self.generate_guarded_basetype_call(
1231 base_type, "tp_as_sequence", "sq_ass_slice", "o, i, j, v", code)
1232 code.putln(
1233 "PyErr_Format(PyExc_NotImplementedError,")
1234 code.putln(
1235 ' "2-element slice deletion not supported by %s", Py_TYPE(o)->tp_name);')
1236 code.putln(
1237 "return -1;")
1238 code.putln(
1239 "}")
1240 code.putln(
1241 "}")
1243 def generate_getattro_function(self, scope, code):
1244 # First try to get the attribute using __getattribute__, if defined, or
1245 # PyObject_GenericGetAttr.
1246 #
1247 # If that raises an AttributeError, call the __getattr__ if defined.
1248 #
1249 # In both cases, defined can be in this class, or any base class.
1250 def lookup_here_or_base(n,type=None):
1251 # Recursive lookup
1252 if type is None:
1253 type = scope.parent_type
1254 r = type.scope.lookup_here(n)
1255 if r is None and \
1256 type.base_type is not None:
1257 return lookup_here_or_base(n,type.base_type)
1258 else:
1259 return r
1260 getattr_entry = lookup_here_or_base("__getattr__")
1261 getattribute_entry = lookup_here_or_base("__getattribute__")
1262 code.putln("")
1263 code.putln(
1264 "static PyObject *%s(PyObject *o, PyObject *n) {"
1265 % scope.mangle_internal("tp_getattro"))
1266 if getattribute_entry is not None:
1267 code.putln(
1268 "PyObject *v = %s(o, n);" %
1269 getattribute_entry.func_cname)
1270 else:
1271 code.putln(
1272 "PyObject *v = PyObject_GenericGetAttr(o, n);")
1273 if getattr_entry is not None:
1274 code.putln(
1275 "if (!v && PyErr_ExceptionMatches(PyExc_AttributeError)) {")
1276 code.putln(
1277 "PyErr_Clear();")
1278 code.putln(
1279 "v = %s(o, n);" %
1280 getattr_entry.func_cname)
1281 code.putln(
1282 "}")
1283 code.putln(
1284 "return v;")
1285 code.putln(
1286 "}")
1288 def generate_setattro_function(self, scope, code):
1289 # Setting and deleting an attribute are both done through
1290 # the setattro method, so we dispatch to user's __setattr__
1291 # or __delattr__ or fall back on PyObject_GenericSetAttr.
1292 base_type = scope.parent_type.base_type
1293 set_entry = scope.lookup_here("__setattr__")
1294 del_entry = scope.lookup_here("__delattr__")
1295 code.putln("")
1296 code.putln(
1297 "static int %s(PyObject *o, PyObject *n, PyObject *v) {" %
1298 scope.mangle_internal("tp_setattro"))
1299 code.putln(
1300 "if (v) {")
1301 if set_entry:
1302 code.putln(
1303 "return %s(o, n, v);" %
1304 set_entry.func_cname)
1305 else:
1306 self.generate_guarded_basetype_call(
1307 base_type, None, "tp_setattro", "o, n, v", code)
1308 code.putln(
1309 "return PyObject_GenericSetAttr(o, n, v);")
1310 code.putln(
1311 "}")
1312 code.putln(
1313 "else {")
1314 if del_entry:
1315 code.putln(
1316 "return %s(o, n);" %
1317 del_entry.func_cname)
1318 else:
1319 self.generate_guarded_basetype_call(
1320 base_type, None, "tp_setattro", "o, n, v", code)
1321 code.putln(
1322 "return PyObject_GenericSetAttr(o, n, 0);")
1323 code.putln(
1324 "}")
1325 code.putln(
1326 "}")
1328 def generate_descr_get_function(self, scope, code):
1329 # The __get__ function of a descriptor object can be
1330 # called with NULL for the second or third arguments
1331 # under some circumstances, so we replace them with
1332 # None in that case.
1333 user_get_entry = scope.lookup_here("__get__")
1334 code.putln("")
1335 code.putln(
1336 "static PyObject *%s(PyObject *o, PyObject *i, PyObject *c) {" %
1337 scope.mangle_internal("tp_descr_get"))
1338 code.putln(
1339 "PyObject *r = 0;")
1340 code.putln(
1341 "if (!i) i = Py_None;")
1342 code.putln(
1343 "if (!c) c = Py_None;")
1344 #code.put_incref("i", py_object_type)
1345 #code.put_incref("c", py_object_type)
1346 code.putln(
1347 "r = %s(o, i, c);" %
1348 user_get_entry.func_cname)
1349 #code.put_decref("i", py_object_type)
1350 #code.put_decref("c", py_object_type)
1351 code.putln(
1352 "return r;")
1353 code.putln(
1354 "}")
1356 def generate_descr_set_function(self, scope, code):
1357 # Setting and deleting are both done through the __set__
1358 # method of a descriptor, so we dispatch to user's __set__
1359 # or __delete__ or raise an exception.
1360 base_type = scope.parent_type.base_type
1361 user_set_entry = scope.lookup_here("__set__")
1362 user_del_entry = scope.lookup_here("__delete__")
1363 code.putln("")
1364 code.putln(
1365 "static int %s(PyObject *o, PyObject *i, PyObject *v) {" %
1366 scope.mangle_internal("tp_descr_set"))
1367 code.putln(
1368 "if (v) {")
1369 if user_set_entry:
1370 code.putln(
1371 "return %s(o, i, v);" %
1372 user_set_entry.func_cname)
1373 else:
1374 self.generate_guarded_basetype_call(
1375 base_type, None, "tp_descr_set", "o, i, v", code)
1376 code.putln(
1377 'PyErr_SetString(PyExc_NotImplementedError, "__set__");')
1378 code.putln(
1379 "return -1;")
1380 code.putln(
1381 "}")
1382 code.putln(
1383 "else {")
1384 if user_del_entry:
1385 code.putln(
1386 "return %s(o, i);" %
1387 user_del_entry.func_cname)
1388 else:
1389 self.generate_guarded_basetype_call(
1390 base_type, None, "tp_descr_set", "o, i, v", code)
1391 code.putln(
1392 'PyErr_SetString(PyExc_NotImplementedError, "__delete__");')
1393 code.putln(
1394 "return -1;")
1395 code.putln(
1396 "}")
1397 code.putln(
1398 "}")
1400 def generate_property_accessors(self, cclass_scope, code):
1401 for entry in cclass_scope.property_entries:
1402 property_scope = entry.scope
1403 if property_scope.defines_any(["__get__"]):
1404 self.generate_property_get_function(entry, code)
1405 if property_scope.defines_any(["__set__", "__del__"]):
1406 self.generate_property_set_function(entry, code)
1408 def generate_property_get_function(self, property_entry, code):
1409 property_scope = property_entry.scope
1410 property_entry.getter_cname = property_scope.parent_scope.mangle(
1411 Naming.prop_get_prefix, property_entry.name)
1412 get_entry = property_scope.lookup_here("__get__")
1413 code.putln("")
1414 code.putln(
1415 "static PyObject *%s(PyObject *o, void *x) {" %
1416 property_entry.getter_cname)
1417 code.putln(
1418 "return %s(o);" %
1419 get_entry.func_cname)
1420 code.putln(
1421 "}")
1423 def generate_property_set_function(self, property_entry, code):
1424 property_scope = property_entry.scope
1425 property_entry.setter_cname = property_scope.parent_scope.mangle(
1426 Naming.prop_set_prefix, property_entry.name)
1427 set_entry = property_scope.lookup_here("__set__")
1428 del_entry = property_scope.lookup_here("__del__")
1429 code.putln("")
1430 code.putln(
1431 "static int %s(PyObject *o, PyObject *v, void *x) {" %
1432 property_entry.setter_cname)
1433 code.putln(
1434 "if (v) {")
1435 if set_entry:
1436 code.putln(
1437 "return %s(o, v);" %
1438 set_entry.func_cname)
1439 else:
1440 code.putln(
1441 'PyErr_SetString(PyExc_NotImplementedError, "__set__");')
1442 code.putln(
1443 "return -1;")
1444 code.putln(
1445 "}")
1446 code.putln(
1447 "else {")
1448 if del_entry:
1449 code.putln(
1450 "return %s(o);" %
1451 del_entry.func_cname)
1452 else:
1453 code.putln(
1454 'PyErr_SetString(PyExc_NotImplementedError, "__del__");')
1455 code.putln(
1456 "return -1;")
1457 code.putln(
1458 "}")
1459 code.putln(
1460 "}")
1462 def generate_typeobj_definition(self, modname, entry, code):
1463 type = entry.type
1464 scope = type.scope
1465 for suite in TypeSlots.substructures:
1466 suite.generate_substructure(scope, code)
1467 code.putln("")
1468 if entry.visibility == 'public':
1469 header = "DL_EXPORT(PyTypeObject) %s = {"
1470 else:
1471 #header = "statichere PyTypeObject %s = {"
1472 header = "PyTypeObject %s = {"
1473 #code.putln(header % scope.parent_type.typeobj_cname)
1474 code.putln(header % type.typeobj_cname)
1475 code.putln(
1476 "PyVarObject_HEAD_INIT(0, 0)")
1477 code.putln(
1478 '__Pyx_NAMESTR("%s.%s"), /*tp_name*/' % (
1479 self.full_module_name, scope.class_name))
1480 if type.typedef_flag:
1481 objstruct = type.objstruct_cname
1482 else:
1483 #objstruct = "struct %s" % scope.parent_type.objstruct_cname
1484 objstruct = "struct %s" % type.objstruct_cname
1485 code.putln(
1486 "sizeof(%s), /*tp_basicsize*/" %
1487 objstruct)
1488 code.putln(
1489 "0, /*tp_itemsize*/")
1490 for slot in TypeSlots.slot_table:
1491 slot.generate(scope, code)
1492 code.putln(
1493 "};")
1495 def generate_method_table(self, env, code):
1496 code.putln("")
1497 code.putln(
1498 "static struct PyMethodDef %s[] = {" %
1499 env.method_table_cname)
1500 for entry in env.pyfunc_entries:
1501 code.put_pymethoddef(entry, ",")
1502 code.putln(
1503 "{0, 0, 0, 0}")
1504 code.putln(
1505 "};")
1507 def generate_member_table(self, env, code):
1508 #print "ModuleNode.generate_member_table: scope =", env ###
1509 if env.public_attr_entries:
1510 code.putln("")
1511 code.putln(
1512 "static struct PyMemberDef %s[] = {" %
1513 env.member_table_cname)
1514 type = env.parent_type
1515 if type.typedef_flag:
1516 objstruct = type.objstruct_cname
1517 else:
1518 objstruct = "struct %s" % type.objstruct_cname
1519 for entry in env.public_attr_entries:
1520 type_code = entry.type.pymemberdef_typecode
1521 if entry.visibility == 'readonly':
1522 flags = "READONLY"
1523 else:
1524 flags = "0"
1525 code.putln('{(char *)"%s", %s, %s, %s, 0},' % (
1526 entry.name,
1527 type_code,
1528 "offsetof(%s, %s)" % (objstruct, entry.cname),
1529 flags))
1530 code.putln(
1531 "{0, 0, 0, 0, 0}")
1532 code.putln(
1533 "};")
1535 def generate_getset_table(self, env, code):
1536 if env.property_entries:
1537 code.putln("")
1538 code.putln(
1539 "static struct PyGetSetDef %s[] = {" %
1540 env.getset_table_cname)
1541 for entry in env.property_entries:
1542 code.putln(
1543 '{(char *)"%s", %s, %s, %s, 0},' % (
1544 entry.name,
1545 entry.getter_cname or "0",
1546 entry.setter_cname or "0",
1547 entry.doc_cname or "0"))
1548 code.putln(
1549 "{0, 0, 0, 0, 0}")
1550 code.putln(
1551 "};")
1553 def generate_filename_init_prototype(self, code):
1554 code.putln("");
1555 code.putln("static void %s(void); /*proto*/" % Naming.fileinit_cname)
1557 def generate_import_star(self, env, code):
1558 env.use_utility_code(streq_utility_code)
1559 code.putln()
1560 code.putln("char* %s_type_names[] = {" % Naming.import_star)
1561 for name, entry in env.entries.items():
1562 if entry.is_type:
1563 code.putln('"%s",' % name)
1564 code.putln("0")
1565 code.putln("};")
1566 code.putln()
1567 code.enter_cfunc_scope() # as we need labels
1568 code.putln("static int %s(PyObject *o, PyObject* py_name, char *name) {" % Naming.import_star_set)
1569 code.putln("char** type_name = %s_type_names;" % Naming.import_star)
1570 code.putln("while (*type_name) {")
1571 code.putln("if (__Pyx_StrEq(name, *type_name)) {")
1572 code.putln('PyErr_Format(PyExc_TypeError, "Cannot overwrite C type %s", name);')
1573 code.putln('goto bad;')
1574 code.putln("}")
1575 code.putln("type_name++;")
1576 code.putln("}")
1577 old_error_label = code.new_error_label()
1578 code.putln("if (0);") # so the first one can be "else if"
1579 for name, entry in env.entries.items():
1580 if entry.is_cglobal and entry.used:
1581 code.putln('else if (__Pyx_StrEq(name, "%s")) {' % name)
1582 if entry.type.is_pyobject:
1583 if entry.type.is_extension_type or entry.type.is_builtin_type:
1584 code.putln("if (!(%s)) %s;" % (
1585 entry.type.type_test_code("o"),
1586 code.error_goto(entry.pos)))
1587 code.put_var_decref(entry)
1588 code.putln("%s = %s;" % (
1589 entry.cname,
1590 PyrexTypes.typecast(entry.type, py_object_type, "o")))
1591 elif entry.type.from_py_function:
1592 rhs = "%s(o)" % entry.type.from_py_function
1593 if entry.type.is_enum:
1594 rhs = typecast(entry.type, c_long_type, rhs)
1595 code.putln("%s = %s; if (%s) %s;" % (
1596 entry.cname,
1597 rhs,
1598 entry.type.error_condition(entry.cname),
1599 code.error_goto(entry.pos)))
1600 code.putln("Py_DECREF(o);")
1601 else:
1602 code.putln('PyErr_Format(PyExc_TypeError, "Cannot convert Python object %s to %s");' % (name, entry.type))
1603 code.putln(code.error_goto(entry.pos))
1604 code.putln("}")
1605 code.putln("else {")
1606 code.putln("if (PyObject_SetAttr(%s, py_name, o) < 0) goto bad;" % Naming.module_cname)
1607 code.putln("}")
1608 code.putln("return 0;")
1609 code.put_label(code.error_label)
1610 # This helps locate the offending name.
1611 code.putln('__Pyx_AddTraceback("%s");' % self.full_module_name);
1612 code.error_label = old_error_label
1613 code.putln("bad:")
1614 code.putln("Py_DECREF(o);")
1615 code.putln("return -1;")
1616 code.putln("}")
1617 code.putln(import_star_utility_code)
1618 code.exit_cfunc_scope() # done with labels
1620 def generate_module_init_func(self, imported_modules, env, code):
1621 # Insert code stream of __Pyx_InitGlobals()
1622 code.globalstate.insert_initcode_into(code)
1624 code.enter_cfunc_scope()
1625 code.putln("")
1626 header2 = "PyMODINIT_FUNC init%s(void)" % env.module_name
1627 header3 = "PyMODINIT_FUNC PyInit_%s(void)" % env.module_name
1628 code.putln("#if PY_MAJOR_VERSION < 3")
1629 code.putln("%s; /*proto*/" % header2)
1630 code.putln(header2)
1631 code.putln("#else")
1632 code.putln("%s; /*proto*/" % header3)
1633 code.putln(header3)
1634 code.putln("#endif")
1635 code.putln("{")
1636 tempdecl_code = code.insertion_point()
1638 self.generate_filename_init_call(code)
1639 code.putln("#ifdef CYTHON_REFNANNY")
1640 code.putln("void* __pyx_refchk = NULL;")
1641 code.putln("__Pyx_Refnanny = __Pyx_ImportRefcountAPI(\"refnanny\");")
1642 code.putln("if (!__Pyx_Refnanny) {")
1643 code.putln(" PyErr_Clear();")
1644 code.putln(" __Pyx_Refnanny = __Pyx_ImportRefcountAPI(\"Cython.Runtime.refnanny\");")
1645 code.putln(" if (!__Pyx_Refnanny)")
1646 code.putln(" Py_FatalError(\"failed to import refnanny module\");")
1647 code.putln("}")
1648 code.putln("__pyx_refchk = __Pyx_Refnanny->NewContext(\"%s\", __LINE__, __FILE__);"% header3)
1649 code.putln("#endif")
1651 code.putln("%s = PyTuple_New(0); %s" % (Naming.empty_tuple, code.error_goto_if_null(Naming.empty_tuple, self.pos)));
1652 code.putln("#if PY_MAJOR_VERSION < 3");
1653 code.putln("%s = PyString_FromStringAndSize(\"\", 0); %s" % (Naming.empty_bytes, code.error_goto_if_null(Naming.empty_bytes, self.pos)));
1654 code.putln("#else");
1655 code.putln("%s = PyBytes_FromStringAndSize(\"\", 0); %s" % (Naming.empty_bytes, code.error_goto_if_null(Naming.empty_bytes, self.pos)));
1656 code.putln("#endif");
1658 code.putln("/*--- Library function declarations ---*/")
1659 env.generate_library_function_declarations(code)
1661 code.putln("/*--- Threads initialization code ---*/")
1662 code.putln("#if defined(__PYX_FORCE_INIT_THREADS) && __PYX_FORCE_INIT_THREADS")
1663 code.putln("#ifdef WITH_THREAD /* Python build with threading support? */")
1664 code.putln("PyEval_InitThreads();")
1665 code.putln("#endif")
1666 code.putln("#endif")
1668 code.putln("/*--- Module creation code ---*/")
1669 self.generate_module_creation_code(env, code)
1671 code.putln("/*--- Initialize various global constants etc. ---*/")
1672 code.putln(code.error_goto_if_neg("__Pyx_InitGlobals()", self.pos))
1674 if Options.cache_builtins:
1675 code.putln("/*--- Builtin init code ---*/")
1676 code.putln(code.error_goto_if_neg("__Pyx_InitCachedBuiltins()",
1677 self.pos))
1679 code.putln("%s = 0;" % Naming.skip_dispatch_cname);
1681 code.putln("/*--- Global init code ---*/")
1682 self.generate_global_init_code(env, code)
1684 code.putln("/*--- Function export code ---*/")
1685 self.generate_c_function_export_code(env, code)
1687 code.putln("/*--- Type init code ---*/")
1688 self.generate_type_init_code(env, code)
1690 code.putln("/*--- Type import code ---*/")
1691 for module in imported_modules:
1692 self.generate_type_import_code_for_module(module, env, code)
1694 code.putln("/*--- Function import code ---*/")
1695 for module in imported_modules:
1696 self.generate_c_function_import_code_for_module(module, env, code)
1698 code.putln("/*--- Execution code ---*/")
1699 code.mark_pos(None)
1701 self.body.generate_execution_code(code)
1703 if Options.generate_cleanup_code:
1704 # this should be replaced by the module's tp_clear in Py3
1705 env.use_utility_code(import_module_utility_code)
1706 code.putln("if (__Pyx_RegisterCleanup()) %s;" % code.error_goto(self.pos))
1708 code.put_goto(code.return_label)
1709 code.put_label(code.error_label)
1710 code.put_var_xdecrefs(env.temp_entries)
1711 for cname, type in code.funcstate.all_managed_temps():
1712 code.put_xdecref(cname, type)
1713 code.putln('if (%s) {' % env.module_cname)
1714 code.putln('__Pyx_AddTraceback("init %s");' % env.qualified_name)
1715 env.use_utility_code(Nodes.traceback_utility_code)
1716 code.put_decref_clear(env.module_cname, py_object_type, nanny=False)
1717 code.putln('} else if (!PyErr_Occurred()) {')
1718 code.putln('PyErr_SetString(PyExc_ImportError, "init %s");' % env.qualified_name)
1719 code.putln('}')
1720 code.put_label(code.return_label)
1722 code.put_finish_refcount_context()
1724 code.putln("#if PY_MAJOR_VERSION < 3")
1725 code.putln("return;")
1726 code.putln("#else")
1727 code.putln("return %s;" % env.module_cname)
1728 code.putln("#endif")
1729 code.putln('}')
1731 tempdecl_code.put_var_declarations(env.temp_entries)
1732 tempdecl_code.put_temp_declarations(code.funcstate)
1734 code.exit_cfunc_scope()
1736 def generate_module_cleanup_func(self, env, code):
1737 if not Options.generate_cleanup_code:
1738 return
1739 env.use_utility_code(register_cleanup_utility_code)
1740 # Insert code stream of __Pyx_CleanupGlobals()
1741 code.globalstate.insert_cleanupcode_into(code)
1742 code.putln()
1743 code.putln('static PyObject* %s(PyObject *self, PyObject *unused) {' % Naming.cleanup_cname)
1744 if Options.generate_cleanup_code >= 2:
1745 code.putln("/*--- Global cleanup code ---*/")
1746 rev_entries = list(env.var_entries)
1747 rev_entries.reverse()
1748 for entry in rev_entries:
1749 if entry.visibility != 'extern':
1750 if entry.type.is_pyobject and entry.used:
1751 code.putln("Py_DECREF(%s); %s = 0;" % (
1752 code.entry_as_pyobject(entry), entry.cname))
1753 code.putln("__Pyx_CleanupGlobals();")
1754 if Options.generate_cleanup_code >= 3:
1755 code.putln("/*--- Type import cleanup code ---*/")
1756 for type, _ in env.types_imported.items():
1757 code.putln("Py_DECREF((PyObject *)%s);" % type.typeptr_cname)
1758 if Options.cache_builtins:
1759 code.putln("/*--- Builtin cleanup code ---*/")
1760 for entry in env.cached_builtins:
1761 code.put_decref_clear(entry.cname,
1762 PyrexTypes.py_object_type,
1763 nanny=False)
1764 code.putln("/*--- Intern cleanup code ---*/")
1765 code.put_decref_clear(Naming.empty_tuple,
1766 PyrexTypes.py_object_type,
1767 nanny=False)
1768 for entry in env.pynum_entries:
1769 code.put_decref_clear(entry.cname,
1770 PyrexTypes.py_object_type,
1771 nanny=False)
1772 for entry in env.all_pystring_entries:
1773 if entry.is_interned:
1774 code.put_decref_clear(entry.pystring_cname,
1775 PyrexTypes.py_object_type,
1776 nanny=False)
1777 for entry in env.default_entries:
1778 if entry.type.is_pyobject and entry.used:
1779 code.putln("Py_DECREF(%s); %s = 0;" % (
1780 code.entry_as_pyobject(entry), entry.cname))
1781 code.putln("Py_INCREF(Py_None); return Py_None;")
1782 code.putln('}')
1784 def generate_main_method(self, env, code):
1785 code.globalstate.use_utility_code(main_method.specialize(module_name=env.module_name))
1787 def generate_filename_init_call(self, code):
1788 code.putln("%s();" % Naming.fileinit_cname)
1790 def generate_pymoduledef_struct(self, env, code):
1791 if env.doc:
1792 doc = "__Pyx_DOCSTR(%s)" % env.doc_cname
1793 else:
1794 doc = "0"
1795 code.putln("")
1796 code.putln("#if PY_MAJOR_VERSION >= 3")
1797 code.putln("static struct PyModuleDef %s = {" % Naming.pymoduledef_cname)
1798 code.putln(" PyModuleDef_HEAD_INIT,")
1799 code.putln(' __Pyx_NAMESTR("%s"),' % env.module_name)
1800 code.putln(" %s, /* m_doc */" % doc)
1801 code.putln(" -1, /* m_size */")
1802 code.putln(" %s /* m_methods */," % env.method_table_cname)
1803 code.putln(" NULL, /* m_reload */")
1804 code.putln(" NULL, /* m_traverse */")
1805 code.putln(" NULL, /* m_clear */")
1806 code.putln(" NULL /* m_free */")
1807 code.putln("};")
1808 code.putln("#endif")
1810 def generate_module_creation_code(self, env, code):
1811 # Generate code to create the module object and
1812 # install the builtins.
1813 if env.doc:
1814 doc = env.doc_cname
1815 else:
1816 doc = "0"
1817 code.putln("#if PY_MAJOR_VERSION < 3")
1818 code.putln(
1819 '%s = Py_InitModule4(__Pyx_NAMESTR("%s"), %s, %s, 0, PYTHON_API_VERSION);' % (
1820 env.module_cname,
1821 env.module_name,
1822 env.method_table_cname,
1823 doc))
1824 code.putln("#else")
1825 code.putln(
1826 "%s = PyModule_Create(&%s);" % (
1827 env.module_cname,
1828 Naming.pymoduledef_cname))
1829 code.putln("#endif")
1830 code.putln(
1831 "if (!%s) %s;" % (
1832 env.module_cname,
1833 code.error_goto(self.pos)));
1834 code.putln("#if PY_MAJOR_VERSION < 3")
1835 code.putln(
1836 "Py_INCREF(%s);" %
1837 env.module_cname)
1838 code.putln("#endif")
1839 code.putln(
1840 '%s = PyImport_AddModule(__Pyx_NAMESTR(__Pyx_BUILTIN_MODULE_NAME));' %
1841 Naming.builtins_cname)
1842 code.putln(
1843 "if (!%s) %s;" % (
1844 Naming.builtins_cname,
1845 code.error_goto(self.pos)));
1846 code.putln(
1847 'if (__Pyx_SetAttrString(%s, "__builtins__", %s) < 0) %s;' % (
1848 env.module_cname,
1849 Naming.builtins_cname,
1850 code.error_goto(self.pos)))
1851 code.putln("if (%s%s) {" % (Naming.module_is_main, self.full_module_name.replace('.', '__')))
1852 code.putln(
1853 'if (__Pyx_SetAttrString(%s, "__name__", %s) < 0) %s;' % (
1854 env.module_cname,
1855 self.__main__cname,
1856 code.error_goto(self.pos)))
1857 code.putln("}")
1858 if Options.pre_import is not None:
1859 code.putln(
1860 '%s = PyImport_AddModule(__Pyx_NAMESTR("%s"));' % (
1861 Naming.preimport_cname,
1862 Options.pre_import))
1863 code.putln(
1864 "if (!%s) %s;" % (
1865 Naming.preimport_cname,
1866 code.error_goto(self.pos)));
1868 def generate_global_init_code(self, env, code):
1869 # Generate code to initialise global PyObject *
1870 # variables to None.
1871 for entry in env.var_entries:
1872 if entry.visibility != 'extern':
1873 if entry.type.is_pyobject and entry.used:
1874 code.put_init_var_to_py_none(entry, nanny=False)
1876 def generate_c_function_export_code(self, env, code):
1877 # Generate code to create PyCFunction wrappers for exported C functions.
1878 for entry in env.cfunc_entries:
1879 if entry.api or entry.defined_in_pxd:
1880 env.use_utility_code(function_export_utility_code)
1881 signature = entry.type.signature_string()
1882 code.putln('if (__Pyx_ExportFunction("%s", (void (*)(void))%s, "%s") < 0) %s' % (
1883 entry.name,
1884 entry.cname,
1885 signature,
1886 code.error_goto(self.pos)))
1888 def generate_type_import_code_for_module(self, module, env, code):
1889 # Generate type import code for all exported extension types in
1890 # an imported module.
1891 #if module.c_class_entries:
1892 for entry in module.c_class_entries:
1893 if entry.defined_in_pxd:
1894 self.generate_type_import_code(env, entry.type, entry.pos, code)
1896 def generate_c_function_import_code_for_module(self, module, env, code):
1897 # Generate import code for all exported C functions in a cimported module.
1898 entries = []
1899 for entry in module.cfunc_entries:
1900 if entry.defined_in_pxd:
1901 entries.append(entry)
1902 if entries:
1903 env.use_utility_code(import_module_utility_code)
1904 env.use_utility_code(function_import_utility_code)
1905 temp = self.module_temp_cname
1906 code.putln(
1907 '%s = __Pyx_ImportModule("%s"); if (!%s) %s' % (
1908 temp,
1909 module.qualified_name,
1910 temp,
1911 code.error_goto(self.pos)))
1912 for entry in entries:
1913 code.putln(
1914 'if (__Pyx_ImportFunction(%s, "%s", (void (**)(void))&%s, "%s") < 0) %s' % (
1915 temp,
1916 entry.name,
1917 entry.cname,
1918 entry.type.signature_string(),
1919 code.error_goto(self.pos)))
1920 code.putln("Py_DECREF(%s); %s = 0;" % (temp, temp))
1922 def generate_type_init_code(self, env, code):
1923 # Generate type import code for extern extension types
1924 # and type ready code for non-extern ones.
1925 for entry in env.c_class_entries:
1926 if entry.visibility == 'extern':
1927 self.generate_type_import_code(env, entry.type, entry.pos, code)
1928 else:
1929 self.generate_base_type_import_code(env, entry, code)
1930 self.generate_exttype_vtable_init_code(entry, code)
1931 self.generate_type_ready_code(env, entry, code)
1932 self.generate_typeptr_assignment_code(entry, code)
1934 def generate_base_type_import_code(self, env, entry, code):
1935 base_type = entry.type.base_type
1936 if base_type and base_type.module_name != env.qualified_name:
1937 self.generate_type_import_code(env, base_type, self.pos, code)
1939 def use_type_import_utility_code(self, env):
1940 env.use_utility_code(type_import_utility_code)
1941 env.use_utility_code(import_module_utility_code)
1943 def generate_type_import_code(self, env, type, pos, code):
1944 # If not already done, generate code to import the typeobject of an
1945 # extension type defined in another module, and extract its C method
1946 # table pointer if any.
1947 if type in env.types_imported:
1948 return
1949 if type.typedef_flag:
1950 objstruct = type.objstruct_cname
1951 else:
1952 objstruct = "struct %s" % type.objstruct_cname
1953 self.generate_type_import_call(type, code,
1954 code.error_goto_if_null(type.typeptr_cname, pos))
1955 self.use_type_import_utility_code(env)
1956 if type.vtabptr_cname:
1957 code.putln(
1958 "if (__Pyx_GetVtable(%s->tp_dict, &%s) < 0) %s" % (
1959 type.typeptr_cname,
1960 type.vtabptr_cname,
1961 code.error_goto(pos)))
1962 env.use_utility_code(Nodes.get_vtable_utility_code)
1963 env.types_imported[type] = 1
1965 py3_type_name_map = {'str' : 'bytes', 'unicode' : 'str'}
1967 def generate_type_import_call(self, type, code, error_code):
1968 if type.typedef_flag:
1969 objstruct = type.objstruct_cname
1970 else:
1971 objstruct = "struct %s" % type.objstruct_cname
1972 module_name = type.module_name
1973 if module_name not in ('__builtin__', 'builtins'):
1974 module_name = '"%s"' % module_name
1975 else:
1976 module_name = '__Pyx_BUILTIN_MODULE_NAME'
1977 if type.name in self.py3_type_name_map:
1978 code.putln("#if PY_MAJOR_VERSION >= 3")
1979 code.putln('%s = __Pyx_ImportType(%s, "%s", sizeof(%s)); %s' % (
1980 type.typeptr_cname,
1981 module_name,
1982 self.py3_type_name_map[type.name],
1983 objstruct,
1984 error_code))
1985 code.putln("#else")
1986 code.putln('%s = __Pyx_ImportType(%s, "%s", sizeof(%s)); %s' % (
1987 type.typeptr_cname,
1988 module_name,
1989 type.name,
1990 objstruct,
1991 error_code))
1992 if type.name in self.py3_type_name_map:
1993 code.putln("#endif")
1995 def generate_type_ready_code(self, env, entry, code):
1996 # Generate a call to PyType_Ready for an extension
1997 # type defined in this module.
1998 type = entry.type
1999 typeobj_cname = type.typeobj_cname
2000 scope = type.scope
2001 if scope: # could be None if there was an error
2002 if entry.visibility != 'extern':
2003 for slot in TypeSlots.slot_table:
2004 slot.generate_dynamic_init_code(scope, code)
2005 code.putln(
2006 "if (PyType_Ready(&%s) < 0) %s" % (
2007 typeobj_cname,
2008 code.error_goto(entry.pos)))
2009 if type.vtable_cname:
2010 code.putln(
2011 "if (__Pyx_SetVtable(%s.tp_dict, %s) < 0) %s" % (
2012 typeobj_cname,
2013 type.vtabptr_cname,
2014 code.error_goto(entry.pos)))
2015 env.use_utility_code(Nodes.set_vtable_utility_code)
2016 code.putln(
2017 'if (__Pyx_SetAttrString(%s, "%s", (PyObject *)&%s) < 0) %s' % (
2018 Naming.module_cname,
2019 scope.class_name,
2020 typeobj_cname,
2021 code.error_goto(entry.pos)))
2022 weakref_entry = scope.lookup_here("__weakref__")
2023 if weakref_entry:
2024 if weakref_entry.type is py_object_type:
2025 tp_weaklistoffset = "%s.tp_weaklistoffset" % typeobj_cname
2026 if type.typedef_flag:
2027 objstruct = type.objstruct_cname
2028 else:
2029 objstruct = "struct %s" % type.objstruct_cname
2030 code.putln("if (%s == 0) %s = offsetof(%s, %s);" % (
2031 tp_weaklistoffset,
2032 tp_weaklistoffset,
2033 objstruct,
2034 weakref_entry.cname))
2035 else:
2036 error(weakref_entry.pos, "__weakref__ slot must be of type 'object'")
2038 def generate_exttype_vtable_init_code(self, entry, code):
2039 # Generate code to initialise the C method table of an
2040 # extension type.
2041 type = entry.type
2042 if type.vtable_cname:
2043 code.putln(
2044 "%s = &%s;" % (
2045 type.vtabptr_cname,
2046 type.vtable_cname))
2047 if type.base_type and type.base_type.vtabptr_cname:
2048 code.putln(
2049 "%s.%s = *%s;" % (
2050 type.vtable_cname,
2051 Naming.obj_base_cname,
2052 type.base_type.vtabptr_cname))
2054 c_method_entries = [
2055 entry for entry in type.scope.cfunc_entries
2056 if entry.func_cname ]
2057 if c_method_entries:
2058 code.putln('#if PY_MAJOR_VERSION >= 3')
2059 for meth_entry in c_method_entries:
2060 cast = meth_entry.type.signature_cast_string()
2061 code.putln(
2062 "%s.%s = %s%s;" % (
2063 type.vtable_cname,
2064 meth_entry.cname,
2065 cast,
2066 meth_entry.func_cname))
2067 code.putln('#else')
2068 for meth_entry in c_method_entries:
2069 code.putln(
2070 "*(void(**)(void))&%s.%s = (void(*)(void))%s;" % (
2071 type.vtable_cname,
2072 meth_entry.cname,
2073 meth_entry.func_cname))
2074 code.putln('#endif')
2076 def generate_typeptr_assignment_code(self, entry, code):
2077 # Generate code to initialise the typeptr of an extension
2078 # type defined in this module to point to its type object.
2079 type = entry.type
2080 if type.typeobj_cname:
2081 code.putln(
2082 "%s = &%s;" % (
2083 type.typeptr_cname, type.typeobj_cname))
2085 #------------------------------------------------------------------------------------
2086 #
2087 # Runtime support code
2088 #
2089 #------------------------------------------------------------------------------------
2091 builtin_module_name_utility_code = UtilityCode(
2092 proto = """\
2093 #if PY_MAJOR_VERSION < 3
2094 #define __Pyx_BUILTIN_MODULE_NAME "__builtin__"
2095 #else
2096 #define __Pyx_BUILTIN_MODULE_NAME "builtins"
2097 #endif
2098 """)
2100 #------------------------------------------------------------------------------------
2102 streq_utility_code = UtilityCode(
2103 proto = """
2104 static INLINE int __Pyx_StrEq(const char *, const char *); /*proto*/
2105 """,
2106 impl = """
2107 static INLINE int __Pyx_StrEq(const char *s1, const char *s2) {
2108 while (*s1 != '\\0' && *s1 == *s2) { s1++; s2++; }
2109 return *s1 == *s2;
2110 }
2111 """)
2113 #------------------------------------------------------------------------------------
2115 import_module_utility_code = UtilityCode(
2116 proto = """
2117 static PyObject *__Pyx_ImportModule(const char *name); /*proto*/
2118 """,
2119 impl = """
2120 #ifndef __PYX_HAVE_RT_ImportModule
2121 #define __PYX_HAVE_RT_ImportModule
2122 static PyObject *__Pyx_ImportModule(const char *name) {
2123 PyObject *py_name = 0;
2124 PyObject *py_module = 0;
2126 #if PY_MAJOR_VERSION < 3
2127 py_name = PyString_FromString(name);
2128 #else
2129 py_name = PyUnicode_FromString(name);
2130 #endif
2131 if (!py_name)
2132 goto bad;
2133 py_module = PyImport_Import(py_name);
2134 Py_DECREF(py_name);
2135 return py_module;
2136 bad:
2137 Py_XDECREF(py_name);
2138 return 0;
2139 }
2140 #endif
2141 """)
2143 #------------------------------------------------------------------------------------
2145 type_import_utility_code = UtilityCode(
2146 proto = """
2147 static PyTypeObject *__Pyx_ImportType(const char *module_name, const char *class_name, long size); /*proto*/
2148 """,
2149 impl = """
2150 #ifndef __PYX_HAVE_RT_ImportType
2151 #define __PYX_HAVE_RT_ImportType
2152 static PyTypeObject *__Pyx_ImportType(const char *module_name, const char *class_name,
2153 long size)
2154 {
2155 PyObject *py_module = 0;
2156 PyObject *result = 0;
2157 PyObject *py_name = 0;
2159 py_module = __Pyx_ImportModule(module_name);
2160 if (!py_module)
2161 goto bad;
2162 #if PY_MAJOR_VERSION < 3
2163 py_name = PyString_FromString(class_name);
2164 #else
2165 py_name = PyUnicode_FromString(class_name);
2166 #endif
2167 if (!py_name)
2168 goto bad;
2169 result = PyObject_GetAttr(py_module, py_name);
2170 Py_DECREF(py_name);
2171 py_name = 0;
2172 Py_DECREF(py_module);
2173 py_module = 0;
2174 if (!result)
2175 goto bad;
2176 if (!PyType_Check(result)) {
2177 PyErr_Format(PyExc_TypeError,
2178 "%s.%s is not a type object",
2179 module_name, class_name);
2180 goto bad;
2181 }
2182 if (((PyTypeObject *)result)->tp_basicsize != size) {
2183 PyErr_Format(PyExc_ValueError,
2184 "%s.%s does not appear to be the correct type object",
2185 module_name, class_name);
2186 goto bad;
2187 }
2188 return (PyTypeObject *)result;
2189 bad:
2190 Py_XDECREF(py_module);
2191 Py_XDECREF(result);
2192 return 0;
2193 }
2194 #endif
2195 """)
2197 #------------------------------------------------------------------------------------
2199 function_export_utility_code = UtilityCode(
2200 proto = """
2201 static int __Pyx_ExportFunction(const char *name, void (*f)(void), const char *sig); /*proto*/
2202 """,
2203 impl = r"""
2204 static int __Pyx_ExportFunction(const char *name, void (*f)(void), const char *sig) {
2205 #if PY_VERSION_HEX < 0x02050000
2206 char *api = (char *)"%(API)s";
2207 #else
2208 const char *api = "%(API)s";
2209 #endif
2210 PyObject *d = 0;
2211 PyObject *cobj = 0;
2212 union {
2213 void (*fp)(void);
2214 void *p;
2215 } tmp;
2218 d = PyObject_GetAttrString(%(MODULE)s, api);
2219 if (!d) {
2220 PyErr_Clear();
2221 d = PyDict_New();
2222 if (!d)
2223 goto bad;
2224 Py_INCREF(d);
2225 if (PyModule_AddObject(%(MODULE)s, api, d) < 0)
2226 goto bad;
2227 }
2228 tmp.fp = f;
2229 cobj = PyCObject_FromVoidPtrAndDesc(tmp.p, (void *)sig, 0);
2230 if (!cobj)
2231 goto bad;
2232 if (PyDict_SetItemString(d, name, cobj) < 0)
2233 goto bad;
2234 Py_DECREF(cobj);
2235 Py_DECREF(d);
2236 return 0;
2237 bad:
2238 Py_XDECREF(cobj);
2239 Py_XDECREF(d);
2240 return -1;
2241 }
2242 """ % {'MODULE': Naming.module_cname, 'API': Naming.api_name}
2243 )
2245 #------------------------------------------------------------------------------------
2247 function_import_utility_code = UtilityCode(
2248 proto = """
2249 static int __Pyx_ImportFunction(PyObject *module, const char *funcname, void (**f)(void), const char *sig); /*proto*/
2250 """,
2251 impl = """
2252 #ifndef __PYX_HAVE_RT_ImportFunction
2253 #define __PYX_HAVE_RT_ImportFunction
2254 static int __Pyx_ImportFunction(PyObject *module, const char *funcname, void (**f)(void), const char *sig) {
2255 #if PY_VERSION_HEX < 0x02050000
2256 char *api = (char *)"%(API)s";
2257 #else
2258 const char *api = "%(API)s";
2259 #endif
2260 PyObject *d = 0;
2261 PyObject *cobj = 0;
2262 const char *desc;
2263 const char *s1, *s2;
2264 union {
2265 void (*fp)(void);
2266 void *p;
2267 } tmp;
2269 d = PyObject_GetAttrString(module, api);
2270 if (!d)
2271 goto bad;
2272 cobj = PyDict_GetItemString(d, funcname);
2273 if (!cobj) {
2274 PyErr_Format(PyExc_ImportError,
2275 "%%s does not export expected C function %%s",
2276 PyModule_GetName(module), funcname);
2277 goto bad;
2278 }
2279 desc = (const char *)PyCObject_GetDesc(cobj);
2280 if (!desc)
2281 goto bad;
2282 s1 = desc; s2 = sig;
2283 while (*s1 != '\\0' && *s1 == *s2) { s1++; s2++; }
2284 if (*s1 != *s2) {
2285 PyErr_Format(PyExc_TypeError,
2286 "C function %%s.%%s has wrong signature (expected %%s, got %%s)",
2287 PyModule_GetName(module), funcname, sig, desc);
2288 goto bad;
2289 }
2290 tmp.p = PyCObject_AsVoidPtr(cobj);
2291 *f = tmp.fp;
2292 Py_DECREF(d);
2293 return 0;
2294 bad:
2295 Py_XDECREF(d);
2296 return -1;
2297 }
2298 #endif
2299 """ % dict(API = Naming.api_name)
2300 )
2302 register_cleanup_utility_code = UtilityCode(
2303 proto = """
2304 static int __Pyx_RegisterCleanup(void); /*proto*/
2305 static PyObject* __pyx_module_cleanup(PyObject *self, PyObject *unused); /*proto*/
2306 static PyMethodDef cleanup_def = {__Pyx_NAMESTR("__cleanup"), (PyCFunction)&__pyx_module_cleanup, METH_NOARGS, 0};
2307 """,
2308 impl = """
2309 static int __Pyx_RegisterCleanup(void) {
2310 /* Don't use Py_AtExit because that has a 32-call limit
2311 * and is called after python finalization.
2312 */
2314 PyObject *cleanup_func = 0;
2315 PyObject *atexit = 0;
2316 PyObject *reg = 0;
2317 PyObject *args = 0;
2318 PyObject *res = 0;
2319 int ret = -1;
2321 cleanup_func = PyCFunction_New(&cleanup_def, 0);
2322 args = PyTuple_New(1);
2323 if (!cleanup_func || !args)
2324 goto bad;
2325 PyTuple_SET_ITEM(args, 0, cleanup_func);
2326 cleanup_func = 0;
2328 atexit = __Pyx_ImportModule("atexit");
2329 if (!atexit)
2330 goto bad;
2331 reg = __Pyx_GetAttrString(atexit, "register");
2332 if (!reg)
2333 goto bad;
2334 res = PyObject_CallObject(reg, args);
2335 if (!res)
2336 goto bad;
2337 ret = 0;
2338 bad:
2339 Py_XDECREF(cleanup_func);
2340 Py_XDECREF(atexit);
2341 Py_XDECREF(reg);
2342 Py_XDECREF(args);
2343 Py_XDECREF(res);
2344 return ret;
2345 }
2346 """)
2348 import_star_utility_code = """
2350 /* import_all_from is an unexposed function from ceval.c */
2352 static int
2353 __Pyx_import_all_from(PyObject *locals, PyObject *v)
2354 {
2355 PyObject *all = __Pyx_GetAttrString(v, "__all__");
2356 PyObject *dict, *name, *value;
2357 int skip_leading_underscores = 0;
2358 int pos, err;
2360 if (all == NULL) {
2361 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
2362 return -1; /* Unexpected error */
2363 PyErr_Clear();
2364 dict = __Pyx_GetAttrString(v, "__dict__");
2365 if (dict == NULL) {
2366 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
2367 return -1;
2368 PyErr_SetString(PyExc_ImportError,
2369 "from-import-* object has no __dict__ and no __all__");
2370 return -1;
2371 }
2372 all = PyMapping_Keys(dict);
2373 Py_DECREF(dict);
2374 if (all == NULL)
2375 return -1;
2376 skip_leading_underscores = 1;
2377 }
2379 for (pos = 0, err = 0; ; pos++) {
2380 name = PySequence_GetItem(all, pos);
2381 if (name == NULL) {
2382 if (!PyErr_ExceptionMatches(PyExc_IndexError))
2383 err = -1;
2384 else
2385 PyErr_Clear();
2386 break;
2387 }
2388 if (skip_leading_underscores &&
2389 #if PY_MAJOR_VERSION < 3
2390 PyString_Check(name) &&
2391 PyString_AS_STRING(name)[0] == '_')
2392 #else
2393 PyUnicode_Check(name) &&
2394 PyUnicode_AS_UNICODE(name)[0] == '_')
2395 #endif
2396 {
2397 Py_DECREF(name);
2398 continue;
2399 }
2400 value = PyObject_GetAttr(v, name);
2401 if (value == NULL)
2402 err = -1;
2403 else if (PyDict_CheckExact(locals))
2404 err = PyDict_SetItem(locals, name, value);
2405 else
2406 err = PyObject_SetItem(locals, name, value);
2407 Py_DECREF(name);
2408 Py_XDECREF(value);
2409 if (err != 0)
2410 break;
2411 }
2412 Py_DECREF(all);
2413 return err;
2414 }
2417 static int %(IMPORT_STAR)s(PyObject* m) {
2419 int i;
2420 int ret = -1;
2421 char* s;
2422 PyObject *locals = 0;
2423 PyObject *list = 0;
2424 PyObject *name;
2425 PyObject *item;
2427 locals = PyDict_New(); if (!locals) goto bad;
2428 if (__Pyx_import_all_from(locals, m) < 0) goto bad;
2429 list = PyDict_Items(locals); if (!list) goto bad;
2431 for(i=0; i<PyList_GET_SIZE(list); i++) {
2432 name = PyTuple_GET_ITEM(PyList_GET_ITEM(list, i), 0);
2433 item = PyTuple_GET_ITEM(PyList_GET_ITEM(list, i), 1);
2434 #if PY_MAJOR_VERSION < 3
2435 s = PyString_AsString(name);
2436 #else
2437 s = PyUnicode_AsString(name);
2438 #endif
2439 if (!s) goto bad;
2440 if (%(IMPORT_STAR_SET)s(item, name, s) < 0) goto bad;
2441 }
2442 ret = 0;
2444 bad:
2445 Py_XDECREF(locals);
2446 Py_XDECREF(list);
2447 return ret;
2448 }
2449 """ % {'IMPORT_STAR' : Naming.import_star,
2450 'IMPORT_STAR_SET' : Naming.import_star_set }
2452 refcount_utility_code = UtilityCode(proto="""
2453 #ifdef CYTHON_REFNANNY
2454 typedef struct {
2455 void (*INCREF)(void*, PyObject*, int);
2456 void (*DECREF)(void*, PyObject*, int);
2457 void (*GOTREF)(void*, PyObject*, int);
2458 void (*GIVEREF)(void*, PyObject*, int);
2459 void* (*NewContext)(const char*, int, const char*);
2460 void (*FinishContext)(void**);
2461 } __Pyx_RefnannyAPIStruct;
2462 static __Pyx_RefnannyAPIStruct *__Pyx_Refnanny = NULL;
2463 #define __Pyx_ImportRefcountAPI(name) \
2464 (__Pyx_RefnannyAPIStruct *) PyCObject_Import((char *)name, (char *)\"RefnannyAPI\")
2465 #define __Pyx_INCREF(r) __Pyx_Refnanny->INCREF(__pyx_refchk, (PyObject *)(r), __LINE__)
2466 #define __Pyx_DECREF(r) __Pyx_Refnanny->DECREF(__pyx_refchk, (PyObject *)(r), __LINE__)
2467 #define __Pyx_GOTREF(r) __Pyx_Refnanny->GOTREF(__pyx_refchk, (PyObject *)(r), __LINE__)
2468 #define __Pyx_GIVEREF(r) __Pyx_Refnanny->GIVEREF(__pyx_refchk, (PyObject *)(r), __LINE__)
2469 #define __Pyx_XDECREF(r) if((r) == NULL) ; else __Pyx_DECREF(r)
2470 #define __Pyx_SetupRefcountContext(name) \
2471 void* __pyx_refchk = __Pyx_Refnanny->NewContext((name), __LINE__, __FILE__)
2472 #define __Pyx_FinishRefcountContext() \
2473 __Pyx_Refnanny->FinishContext(&__pyx_refchk)
2474 #else
2475 #define __Pyx_INCREF(r) Py_INCREF(r)
2476 #define __Pyx_DECREF(r) Py_DECREF(r)
2477 #define __Pyx_GOTREF(r)
2478 #define __Pyx_GIVEREF(r)
2479 #define __Pyx_XDECREF(r) Py_XDECREF(r)
2480 #define __Pyx_SetupRefcountContext(name)
2481 #define __Pyx_FinishRefcountContext()
2482 #endif /* CYTHON_REFNANNY */
2483 #define __Pyx_XGIVEREF(r) if((r) == NULL) ; else __Pyx_GIVEREF(r)
2484 #define __Pyx_XGOTREF(r) if((r) == NULL) ; else __Pyx_GOTREF(r)
2485 """)
2488 main_method = UtilityCode(
2489 impl = """
2490 #if PY_MAJOR_VERSION < 3 || (!defined(WIN32) && !defined(MS_WINDOWS))
2491 int main(int argc, char** argv) {
2492 #else
2493 int wmain(int argc, wchar_t **argv) {
2494 #endif
2495 int r = 0;
2496 PyObject* m = NULL;
2497 Py_SetProgramName(argv[0]);
2498 Py_Initialize();
2499 PySys_SetArgv(argc, argv);
2500 #if PY_MAJOR_VERSION < 3
2501 init%(module_name)s();
2502 #else
2503 m = PyInit_%(module_name)s(name);
2504 #endif
2505 if (PyErr_Occurred() != NULL) {
2506 r = 1;
2507 PyErr_Print(); /* This exits with the right code if SystemExit. */
2508 if (Py_FlushLine()) PyErr_Clear();
2509 }
2510 Py_XDECREF(m);
2511 Py_Finalize();
2512 return r;
2513 }
2514 """)
2516 packed_struct_utility_code = UtilityCode(proto="""
2517 #if defined(__GNUC__)
2518 #define __Pyx_PACKED __attribute__((__packed__))
2519 #else
2520 #define __Pyx_PACKED
2521 #endif
2522 """, impl="")
