# Pyrex - Module parse tree node
#
+import cython
+from cython import set
+cython.declare(Naming=object, Options=object, PyrexTypes=object, TypeSlots=object,
+ error=object, warning=object, py_object_type=object, UtilityCode=object,
+ escape_byte_string=object, EncodedString=object)
+
import os, time
from PyrexTypes import CPtrType
import Future
-try:
- set
-except NameError: # Python 2.3
- from sets import Set as set
-
import Annotate
import Code
import Naming
child_attrs = ["body"]
directives = None
-
+
def analyse_declarations(self, env):
if Options.embed_pos_in_docstring:
env.doc = EncodedString(u'File: %s (starting at line %s)' % Nodes.relative_position(self.pos))
env.doc = self.doc
env.directives = self.directives
self.body.analyse_declarations(env)
-
+
def process_implementation(self, options, result):
env = self.scope
env.return_type = PyrexTypes.c_void_type
self.generate_c_code(env, options, result)
self.generate_h_code(env, options, result)
self.generate_api_code(env, result)
-
+
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_dep_file(self, env, result):
modules = self.referenced_modules
if len(modules) > 1 or env.included_files:
h_code.putln("PyMODINIT_FUNC init%s(void);" % env.module_name)
h_code.putln("")
h_code.putln("#endif")
-
+
h_code.copyto(open_new_file(result.h_file))
-
+
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" %
+ 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 = []
public_extension_types = []
h_code.putln("}")
h_code.putln("")
h_code.putln("#endif")
-
+
h_code.copyto(open_new_file(result.api_file))
-
+
def generate_cclass_header_code(self, type, h_code):
h_code.putln("%s DL_IMPORT(PyTypeObject) %s;" % (
Naming.extern_c_macro,
type.typeobj_cname))
-
+
def generate_cclass_include_code(self, type, i_code):
i_code.putln("cdef extern class %s.%s:" % (
type.module_name, type.name))
var_entries = type.scope.var_entries
if var_entries:
for entry in var_entries:
- i_code.putln("cdef %s" %
+ i_code.putln("cdef %s" %
entry.type.declaration_code(entry.cname, pyrex = 1))
else:
i_code.putln("pass")
i_code.dedent()
-
+
def generate_c_code(self, env, options, result):
modules = self.referenced_modules
globalstate = Code.GlobalState(rootwriter, emit_linenums)
globalstate.initialize_main_c_code()
h_code = globalstate['h_code']
-
+
self.generate_module_preamble(env, modules, h_code)
globalstate.module_pos = self.pos
code = globalstate['before_global_var']
code.putln('#define __Pyx_MODULE_NAME "%s"' % self.full_module_name)
- code.putln("int %s%s = 0;" % (Naming.module_is_main, self.full_module_name.replace('.', '__')))
+ code.putln("static int %s%s = 0;" % (Naming.module_is_main, self.full_module_name.replace('.', '__')))
code.putln("")
code.putln("/* Implementation of %s */" % env.qualified_name)
code = globalstate['all_the_rest']
self.generate_cached_builtins_decls(env, code)
- # generate lambda function definitions
- for node in env.lambda_defs:
- node.generate_function_definitions(env, code)
+ self.generate_lambda_definitions(env, code)
# generate normal function definitions
self.body.generate_function_definitions(env, code)
code.mark_pos(None)
if Options.embed:
self.generate_main_method(env, globalstate['main_method'])
self.generate_filename_table(globalstate['filename_table'])
-
+
self.generate_declarations_for_modules(env, modules, globalstate)
h_code.write('\n')
for utilcode in env.utility_code_list:
globalstate.use_utility_code(utilcode)
globalstate.finalize_main_c_code()
-
+
f = open_new_file(result.c_file)
rootwriter.copyto(f)
+ if options.gdb_debug:
+ self._serialize_lineno_map(env, rootwriter)
f.close()
result.c_file_generated = 1
if Options.annotate or options.annotate:
self.annotate(rootwriter)
rootwriter.save_annotation(result.main_source_file, result.c_file)
-
+
+ def _serialize_lineno_map(self, env, ccodewriter):
+ tb = env.context.gdb_debug_outputwriter
+ markers = ccodewriter.buffer.allmarkers()
+
+ d = {}
+ for c_lineno, cython_lineno in enumerate(markers):
+ if cython_lineno > 0:
+ d.setdefault(cython_lineno, []).append(c_lineno + 1)
+
+ tb.start('LineNumberMapping')
+ for cython_lineno, c_linenos in sorted(d.iteritems()):
+ attrs = {
+ 'c_linenos': ' '.join(map(str, c_linenos)),
+ 'cython_lineno': str(cython_lineno),
+ }
+ tb.start('LineNumber', attrs)
+ tb.end('LineNumber')
+ tb.end('LineNumberMapping')
+ tb.serialize()
+
def find_referenced_modules(self, env, module_list, modules_seen):
if env not in modules_seen:
modules_seen[env] = 1
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
vtab_list = self.sort_types_by_inheritance(
code.putln(" #error Python headers needed to compile C extensions, please install development version of Python.")
code.putln("#else")
code.globalstate["end"].putln("#endif /* Py_PYTHON_H */")
-
+
code.put("""
#include <stddef.h> /* For offsetof */
#ifndef offsetof
#define PyBytes_ConcatAndDel PyString_ConcatAndDel
#endif
+#if PY_VERSION_HEX < 0x02060000
+ #define PySet_Check(obj) PyObject_TypeCheck(obj, &PySet_Type)
+ #define PyFrozenSet_Check(obj) PyObject_TypeCheck(obj, &PyFrozenSet_Type)
+#endif
+#ifndef PySet_CheckExact
+ #define PySet_CheckExact(obj) (Py_TYPE(obj) == &PySet_Type)
+#endif
+
#if PY_MAJOR_VERSION >= 3
+ #define PyIntObject PyLongObject
#define PyInt_Type PyLong_Type
#define PyInt_Check(op) PyLong_Check(op)
#define PyInt_CheckExact(op) PyLong_CheckExact(op)
#define PyInt_AsUnsignedLongMask PyLong_AsUnsignedLongMask
#define PyInt_AsUnsignedLongLongMask PyLong_AsUnsignedLongLongMask
#endif
+
+#if PY_MAJOR_VERSION >= 3
+ #define PyBoolObject PyLongObject
+#endif
+
""")
code.put("""
code.putln("#endif")
code.put("""
+#if (PY_MAJOR_VERSION < 3) || (PY_VERSION_HEX >= 0x03010300)
+ #define __Pyx_PySequence_GetSlice(obj, a, b) PySequence_GetSlice(obj, a, b)
+ #define __Pyx_PySequence_SetSlice(obj, a, b, value) PySequence_SetSlice(obj, a, b, value)
+ #define __Pyx_PySequence_DelSlice(obj, a, b) PySequence_DelSlice(obj, a, b)
+#else
+ #define __Pyx_PySequence_GetSlice(obj, a, b) (unlikely(!(obj)) ? \\
+ (PyErr_SetString(PyExc_SystemError, "null argument to internal routine"), (PyObject*)0) : \\
+ (likely((obj)->ob_type->tp_as_mapping) ? (PySequence_GetSlice(obj, a, b)) : \\
+ (PyErr_Format(PyExc_TypeError, "'%.200s' object is unsliceable", (obj)->ob_type->tp_name), (PyObject*)0)))
+ #define __Pyx_PySequence_SetSlice(obj, a, b, value) (unlikely(!(obj)) ? \\
+ (PyErr_SetString(PyExc_SystemError, "null argument to internal routine"), -1) : \\
+ (likely((obj)->ob_type->tp_as_mapping) ? (PySequence_SetSlice(obj, a, b, value)) : \\
+ (PyErr_Format(PyExc_TypeError, "'%.200s' object doesn't support slice assignment", (obj)->ob_type->tp_name), -1)))
+ #define __Pyx_PySequence_DelSlice(obj, a, b) (unlikely(!(obj)) ? \\
+ (PyErr_SetString(PyExc_SystemError, "null argument to internal routine"), -1) : \\
+ (likely((obj)->ob_type->tp_as_mapping) ? (PySequence_DelSlice(obj, a, b)) : \\
+ (PyErr_Format(PyExc_TypeError, "'%.200s' object doesn't support slice deletion", (obj)->ob_type->tp_name), -1)))
+#endif
+
#if PY_MAJOR_VERSION >= 3
#define PyMethod_New(func, self, klass) ((self) ? PyMethod_New(func, self) : PyInstanceMethod_New(func))
#endif
code.putln("#include <math.h>")
code.putln("#define %s" % Naming.api_guard_prefix + self.api_name(env))
self.generate_includes(env, cimported_modules, code)
+ code.putln("")
+ code.putln("#ifdef PYREX_WITHOUT_ASSERTIONS")
+ code.putln("#define CYTHON_WITHOUT_ASSERTIONS")
+ code.putln("#endif")
+ code.putln("")
if env.directives['ccomplex']:
code.putln("")
code.putln("#if !defined(CYTHON_CCOMPLEX)")
code.putln('#include %s' % byte_decoded_filenname)
else:
code.putln('#include "%s"' % byte_decoded_filenname)
-
+
def generate_filename_table(self, code):
code.putln("")
code.putln("static const char *%s[] = {" % Naming.filetable_cname)
self.generate_enum_definition(entry, code)
elif type.is_extension_type:
self.generate_objstruct_definition(type, code)
-
+
def generate_gcc33_hack(self, env, code):
# Workaround for spurious warning generation in gcc 3.3
code.putln("")
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
if base_type.is_numeric:
header = "%s %s {" % (kind, name)
footer = "};"
return header, footer
-
+
def generate_struct_union_definition(self, entry, code):
code.mark_pos(entry.pos)
type = entry.type
self.sue_header_footer(type, kind, type.cname)
code.putln("")
if packed:
- code.putln("#if !defined(__GNUC__)")
- code.putln("#pragma pack(push, 1)")
+ code.putln("#if defined(__SUNPRO_C)")
+ code.putln(" #pragma pack(1)")
+ code.putln("#elif !defined(__GNUC__)")
+ code.putln(" #pragma pack(push, 1)")
code.putln("#endif")
code.putln(header)
var_entries = scope.var_entries
attr.type.declaration_code(attr.cname))
code.putln(footer)
if packed:
- code.putln("#if !defined(__GNUC__)")
- code.putln("#pragma pack(pop)")
+ code.putln("#if defined(__SUNPRO_C)")
+ code.putln(" #pragma pack()")
+ code.putln("#elif !defined(__GNUC__)")
+ code.putln(" #pragma pack(pop)")
code.putln("#endif")
def generate_enum_definition(self, entry, code):
value_code += ","
code.putln(value_code)
code.putln(footer)
-
+
def generate_typeobject_predeclaration(self, entry, code):
code.putln("")
name = entry.type.typeobj_cname
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):
code.mark_pos(entry.pos)
# Generate struct declaration for an extension type's vtable.
"%s;" % method_entry.type.declaration_code("(*%s)" % method_entry.name))
code.putln(
"};")
-
+
def generate_exttype_vtabptr_declaration(self, entry, code):
code.mark_pos(entry.pos)
# Generate declaration of pointer to an extension type's vtable.
code.putln("static struct %s *%s;" % (
type.vtabstruct_cname,
type.vtabptr_cname))
-
+
def generate_objstruct_definition(self, type, code):
code.mark_pos(type.pos)
# Generate object struct definition for an
code.putln("")
for entry in env.c_class_entries:
if definition or entry.defined_in_pxd:
- code.putln("static PyTypeObject *%s = 0;" %
+ code.putln("static PyTypeObject *%s = 0;" %
entry.type.typeptr_cname)
- code.put_var_declarations(env.var_entries, static = 1,
+ code.put_var_declarations(env.var_entries, static = 1,
dll_linkage = "DL_EXPORT", definition = definition)
-
+
def generate_cfunction_predeclarations(self, env, code, definition):
for entry in env.cfunc_entries:
if entry.inline_func_in_pxd or (not entry.in_cinclude and (definition
type = entry.type
if not definition and entry.defined_in_pxd:
type = CPtrType(type)
- header = type.declaration_code(entry.cname,
+ header = type.declaration_code(entry.cname,
dll_linkage = dll_linkage)
if entry.visibility == 'private':
storage_class = "static "
storage_class,
modifiers,
header))
-
+
def generate_typeobj_definitions(self, env, code):
full_module_name = env.qualified_name
for entry in env.c_class_entries:
self.generate_getitem_int_function(scope, code)
if scope.defines_any(["__setitem__", "__delitem__"]):
self.generate_ass_subscript_function(scope, code)
+ if scope.defines_any(["__getslice__", "__setslice__", "__delslice__"]):
+ warning(self.pos, "__getslice__, __setslice__, and __delslice__ are not supported by Python 3, use __getitem__, __setitem__, and __delitem__ instead", 1)
+ code.putln("#if PY_MAJOR_VERSION >= 3")
+ code.putln("#error __getslice__, __setslice__, and __delslice__ not supported in Python 3.")
+ code.putln("#endif")
if scope.defines_any(["__setslice__", "__delslice__"]):
- warning(self.pos, "__setslice__ and __delslice__ are not supported by Python 3, use __setitem__ and __getitem__ instead", 1)
self.generate_ass_slice_function(scope, code)
if scope.defines_any(["__getattr__","__getattribute__"]):
self.generate_getattro_function(scope, code)
self.generate_method_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
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):
tp_slot = TypeSlots.ConstructorSlot("tp_new", '__new__')
slot_func = scope.mangle_internal("tp_new")
else:
cinit_args = "o, a, k"
code.putln(
- "if (%s(%s) < 0) {" %
+ "if (%s(%s) < 0) {" %
(entry.func_cname, cinit_args))
code.put_decref_clear("o", py_object_type, nanny=False);
code.putln(
"return o;")
code.putln(
"}")
-
+
def generate_dealloc_function(self, scope, code):
tp_slot = TypeSlots.ConstructorSlot("tp_dealloc", '__dealloc__')
slot_func = scope.mangle_internal("tp_dealloc")
"(*Py_TYPE(o)->tp_free)(o);")
code.putln(
"}")
-
+
def generate_usr_dealloc_call(self, scope, code):
entry = scope.lookup_here("__dealloc__")
if entry:
code.putln(
"++Py_REFCNT(o);")
code.putln(
- "%s(o);" %
+ "%s(o);" %
entry.func_cname)
code.putln(
"if (PyErr_Occurred()) PyErr_WriteUnraisable(o);")
"PyErr_Restore(etype, eval, etb);")
code.putln(
"}")
-
+
def generate_traverse_function(self, scope, code):
tp_slot = TypeSlots.GCDependentSlot("tp_traverse")
slot_func = scope.mangle_internal("tp_traverse")
if entry.type.is_extension_type:
var_code = "((PyObject*)%s)" % var_code
code.putln(
- "e = (*v)(%s, a); if (e) return e;"
+ "e = (*v)(%s, a); if (e) return e;"
% var_code)
code.putln(
"}")
"return 0;")
code.putln(
"}")
-
+
def generate_clear_function(self, scope, code):
tp_slot = TypeSlots.GCDependentSlot("tp_clear")
slot_func = scope.mangle_internal("tp_clear")
"return 0;")
code.putln(
"}")
-
+
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
"}")
code.putln(
"}")
-
+
def generate_guarded_basetype_call(
self, base_type, substructure, slot, args, code):
if base_type:
# 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.
- code.putln("#if PY_MAJOR_VERSION >= 3")
- code.putln("#error __setslice__ and __delslice__ not supported in Python 3.")
- code.putln("#endif")
base_type = scope.parent_type.base_type
set_entry = scope.lookup_here("__setslice__")
del_entry = scope.lookup_here("__delslice__")
"return v;")
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__
"}")
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
"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__
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
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(
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(
if entry.visibility == 'public':
header = "DL_EXPORT(PyTypeObject) %s = {"
else:
- #header = "statichere PyTypeObject %s = {"
- header = "PyTypeObject %s = {"
+ header = "static PyTypeObject %s = {"
#code.putln(header % scope.parent_type.typeobj_cname)
code.putln(header % type.typeobj_cname)
code.putln(
slot.generate(scope, code)
code.putln(
"};")
-
+
def generate_method_table(self, env, code):
code.putln("")
code.putln(
- "static PyMethodDef %s[] = {" %
+ "static PyMethodDef %s[] = {" %
env.method_table_cname)
for entry in env.pyfunc_entries:
code.put_pymethoddef(entry, ",")
"{0, 0, 0, 0}")
code.putln(
"};")
-
+
def generate_getset_table(self, env, code):
if env.property_entries:
code.putln("")
code.putln("if (!(%s)) %s;" % (
entry.type.type_test_code("o"),
code.error_goto(entry.pos)))
- code.put_var_decref(entry)
+ code.putln("Py_INCREF(o);")
+ code.put_decref(entry.cname, entry.type, nanny=False)
code.putln("%s = %s;" % (
- entry.cname,
+ entry.cname,
PyrexTypes.typecast(entry.type, py_object_type, "o")))
elif entry.type.from_py_function:
rhs = "%s(o)" % entry.type.from_py_function
if entry.type.is_enum:
- rhs = typecast(entry.type, c_long_type, rhs)
+ rhs = PyrexTypes.typecast(entry.type, PyrexTypes.c_long_type, rhs)
code.putln("%s = %s; if (%s) %s;" % (
entry.cname,
rhs,
entry.type.error_condition(entry.cname),
code.error_goto(entry.pos)))
- code.putln("Py_DECREF(o);")
else:
code.putln('PyErr_Format(PyExc_TypeError, "Cannot convert Python object %s to %s");' % (name, entry.type))
code.putln(code.error_goto(entry.pos))
code.putln("if (PyObject_SetAttr(%s, py_name, o) < 0) goto bad;" % Naming.module_cname)
code.putln("}")
code.putln("return 0;")
- code.put_label(code.error_label)
- # This helps locate the offending name.
- code.putln('__Pyx_AddTraceback("%s");' % self.full_module_name);
+ if code.label_used(code.error_label):
+ code.put_label(code.error_label)
+ # This helps locate the offending name.
+ code.putln('__Pyx_AddTraceback("%s");' % self.full_module_name);
code.error_label = old_error_label
code.putln("bad:")
- code.putln("Py_DECREF(o);")
code.putln("return -1;")
code.putln("}")
code.putln(import_star_utility_code)
if Options.cache_builtins:
code.putln("/*--- Builtin init code ---*/")
- code.putln(code.error_goto_if_neg("__Pyx_InitCachedBuiltins()",
- self.pos))
+ code.putln(code.error_goto_if_neg("__Pyx_InitCachedBuiltins()", self.pos))
+
+ code.putln("/*--- Constants init code ---*/")
+ code.putln(code.error_goto_if_neg("__Pyx_InitCachedConstants()", self.pos))
code.putln("/*--- Global init code ---*/")
self.generate_global_init_code(env, code)
code.putln("/*--- Execution code ---*/")
code.mark_pos(None)
-
+
self.body.generate_execution_code(code)
if Options.generate_cleanup_code:
if not Options.generate_cleanup_code:
return
code.globalstate.use_utility_code(register_cleanup_utility_code)
- code.putln('static PyObject *%s(CYTHON_UNUSED PyObject *self, CYTHON_UNUSED PyObject *unused) {' %
+ code.putln('static PyObject *%s(CYTHON_UNUSED PyObject *self, CYTHON_UNUSED PyObject *unused) {' %
Naming.cleanup_cname)
if Options.generate_cleanup_code >= 2:
code.putln("/*--- Global cleanup code ---*/")
code.putln("#if PY_MAJOR_VERSION < 3")
code.putln(
'%s = Py_InitModule4(__Pyx_NAMESTR("%s"), %s, %s, 0, PYTHON_API_VERSION);' % (
- env.module_cname,
- env.module_name,
- env.method_table_cname,
+ env.module_cname,
+ env.module_name,
+ env.method_table_cname,
doc))
code.putln("#else")
code.putln(
if Options.pre_import is not None:
code.putln(
'%s = PyImport_AddModule(__Pyx_NAMESTR("%s"));' % (
- Naming.preimport_cname,
+ Naming.preimport_cname,
Options.pre_import))
code.putln(
"if (!%s) %s;" % (
code.putln('if (__Pyx_ExportFunction("%s", (void (*)(void))%s, "%s") < 0) %s' % (
entry.name,
entry.cname,
- signature,
+ signature,
code.error_goto(self.pos)))
-
+
def generate_type_import_code_for_module(self, module, env, code):
# Generate type import code for all exported extension types in
# an imported module.
for entry in module.c_class_entries:
if entry.defined_in_pxd:
self.generate_type_import_code(env, entry.type, entry.pos, code)
-
+
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 = []
entry.type.signature_string(),
code.error_goto(self.pos)))
code.putln("Py_DECREF(%s); %s = 0;" % (temp, temp))
-
+
def generate_type_init_code(self, env, code):
# Generate type import code for extern extension types
# and type ready code for non-extern ones.
def generate_base_type_import_code(self, env, entry, code):
base_type = entry.type.base_type
- if base_type and base_type.module_name != env.qualified_name:
+ if base_type and base_type.module_name != env.qualified_name \
+ and not base_type.is_builtin_type:
self.generate_type_import_code(env, base_type, self.pos, code)
-
+
def use_type_import_utility_code(self, env):
env.use_utility_code(type_import_utility_code)
env.use_utility_code(import_module_utility_code)
-
+
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
"if (PyType_Ready(&%s) < 0) %s" % (
typeobj_cname,
code.error_goto(entry.pos)))
+ # Fix special method docstrings. This is a bit of a hack, but
+ # unless we let PyType_Ready create the slot wrappers we have
+ # a significant performance hit. (See trac #561.)
+ for func in entry.type.scope.pyfunc_entries:
+ if func.is_special and Options.docstrings and func.wrapperbase_cname:
+ code.putln("{");
+ code.putln(
+ 'PyObject *wrapper = __Pyx_GetAttrString((PyObject *)&%s, "%s"); %s' % (
+ typeobj_cname,
+ func.name,
+ code.error_goto_if_null('wrapper', entry.pos)));
+ code.putln(
+ "if (Py_TYPE(wrapper) == &PyWrapperDescr_Type) {");
+ code.putln(
+ "%s = *((PyWrapperDescrObject *)wrapper)->d_base;" % (
+ func.wrapperbase_cname));
+ code.putln(
+ "%s.doc = %s;" % (func.wrapperbase_cname, func.doc_cname));
+ code.putln(
+ "((PyWrapperDescrObject *)wrapper)->d_base = &%s;" % (
+ func.wrapperbase_cname));
+ code.putln("}");
+ code.putln("}");
if type.vtable_cname:
code.putln(
"if (__Pyx_SetVtable(%s.tp_dict, %s) < 0) %s" % (
type.vtabptr_cname,
code.error_goto(entry.pos)))
env.use_utility_code(Nodes.set_vtable_utility_code)
- code.putln(
- 'if (__Pyx_SetAttrString(%s, "%s", (PyObject *)&%s) < 0) %s' % (
- Naming.module_cname,
- scope.class_name,
- typeobj_cname,
- code.error_goto(entry.pos)))
+ if not type.scope.is_internal and not type.scope.directives['internal']:
+ # scope.is_internal is set for types defined by
+ # Cython (such as closures), the 'internal'
+ # directive is set by users
+ code.putln(
+ 'if (__Pyx_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:
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.
entry for entry in type.scope.cfunc_entries
if entry.func_cname ]
if c_method_entries:
- code.putln('#if PY_MAJOR_VERSION >= 3')
for meth_entry in c_method_entries:
cast = meth_entry.type.signature_cast_string()
code.putln(
meth_entry.cname,
cast,
meth_entry.func_cname))
- code.putln('#else')
- for meth_entry in c_method_entries:
- code.putln(
- "*(void(**)(void))&%s.%s = (void(*)(void))%s;" % (
- type.vtable_cname,
- meth_entry.cname,
- meth_entry.func_cname))
- code.putln('#endif')
-
+
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.
code.putln(
"%s = &%s;" % (
type.typeptr_cname, type.typeobj_cname))
-
+
#------------------------------------------------------------------------------------
#
# Runtime support code
if (!result)
goto bad;
if (!PyType_Check(result)) {
- PyErr_Format(PyExc_TypeError,
+ PyErr_Format(PyExc_TypeError,
"%s.%s is not a type object",
module_name, class_name);
goto bad;
}
if (!strict && ((PyTypeObject *)result)->tp_basicsize > size) {
- PyOS_snprintf(warning, sizeof(warning),
+ PyOS_snprintf(warning, sizeof(warning),
"%s.%s size changed, may indicate binary incompatibility",
module_name, class_name);
#if PY_VERSION_HEX < 0x02050000
#endif
}
else if (((PyTypeObject *)result)->tp_basicsize != size) {
- PyErr_Format(PyExc_ValueError,
+ PyErr_Format(PyExc_ValueError,
"%s.%s has the wrong size, try recompiling",
module_name, class_name);
goto bad;
""" % {'module_cleanup': Naming.cleanup_cname},
impl = """
static int __Pyx_RegisterCleanup(void) {
- /* Don't use Py_AtExit because that has a 32-call limit
- * and is called after python finalization.
+ /* Don't use Py_AtExit because that has a 32-call limit
+ * and is called after python finalization.
*/
PyObject *cleanup_func = 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)
#endif
PyObject *name;
PyObject *item;
-
+
locals = PyDict_New(); if (!locals) goto bad;
if (__Pyx_import_all_from(locals, m) < 0) goto bad;
list = PyDict_Items(locals); if (!list) goto bad;
-
+
for(i=0; i<PyList_GET_SIZE(list); i++) {
name = PyTuple_GET_ITEM(PyList_GET_ITEM(list, i), 0);
item = PyTuple_GET_ITEM(PyList_GET_ITEM(list, i), 1);
#endif
}
ret = 0;
-
+
bad:
Py_XDECREF(locals);
Py_XDECREF(list);
}
""" % {'IMPORT_STAR' : Naming.import_star,
'IMPORT_STAR_SET' : Naming.import_star_set }
-
+
refnanny_utility_code = UtilityCode(proto="""
#ifndef CYTHON_REFNANNY
#define CYTHON_REFNANNY 0
Py_XDECREF(m);
return (__Pyx_RefNannyAPIStruct *)r;
}
+ #define __Pyx_RefNannyDeclareContext void *__pyx_refnanny;
#define __Pyx_RefNannySetupContext(name) \
- void *__pyx_refnanny = __Pyx_RefNanny->SetupContext((name), __LINE__, __FILE__)
+ __pyx_refnanny = __Pyx_RefNanny->SetupContext((name), __LINE__, __FILE__)
#define __Pyx_RefNannyFinishContext() \
__Pyx_RefNanny->FinishContext(&__pyx_refnanny)
#define __Pyx_INCREF(r) __Pyx_RefNanny->INCREF(__pyx_refnanny, (PyObject *)(r), __LINE__)
#define __Pyx_GIVEREF(r) __Pyx_RefNanny->GIVEREF(__pyx_refnanny, (PyObject *)(r), __LINE__)
#define __Pyx_XDECREF(r) do { if((r) != NULL) {__Pyx_DECREF(r);} } while(0)
#else
+ #define __Pyx_RefNannyDeclareContext
#define __Pyx_RefNannySetupContext(name)
#define __Pyx_RefNannyFinishContext()
#define __Pyx_INCREF(r) Py_INCREF(r)