Commit 36c54dda authored by Stefan Behnel's avatar Stefan Behnel

merge with latest cython-devel

parents 9d84198a 5ef8c817
...@@ -3957,8 +3957,7 @@ class TypecastNode(ExprNode): ...@@ -3957,8 +3957,7 @@ class TypecastNode(ExprNode):
if from_py and not to_py and self.operand.is_ephemeral() and not self.type.is_numeric: if from_py and not to_py and self.operand.is_ephemeral() and not self.type.is_numeric:
error(self.pos, "Casting temporary Python object to non-numeric non-Python type") error(self.pos, "Casting temporary Python object to non-numeric non-Python type")
if to_py and not from_py: if to_py and not from_py:
if (self.operand.type.to_py_function and if self.operand.type.create_to_py_utility_code(env):
self.operand.type.create_to_py_utility_code(env)):
self.result_ctype = py_object_type self.result_ctype = py_object_type
self.operand = self.operand.coerce_to_pyobject(env) self.operand = self.operand.coerce_to_pyobject(env)
else: else:
...@@ -3966,7 +3965,7 @@ class TypecastNode(ExprNode): ...@@ -3966,7 +3965,7 @@ class TypecastNode(ExprNode):
warning(self.pos, "No conversion from %s to %s, python object pointer used." % (self.operand.type, self.type)) warning(self.pos, "No conversion from %s to %s, python object pointer used." % (self.operand.type, self.type))
self.operand = self.operand.coerce_to_simple(env) self.operand = self.operand.coerce_to_simple(env)
elif from_py and not to_py: elif from_py and not to_py:
if self.type.from_py_function: if self.type.create_from_py_utility_code(env):
self.operand = self.operand.coerce_to(self.type, env) self.operand = self.operand.coerce_to(self.type, env)
elif self.type.is_ptr and not (self.type.base_type.is_void or self.type.base_type.is_struct): elif self.type.is_ptr and not (self.type.base_type.is_void or self.type.base_type.is_struct):
error(self.pos, "Python objects cannot be casted to pointers of primitive types") error(self.pos, "Python objects cannot be casted to pointers of primitive types")
......
...@@ -35,6 +35,12 @@ def dumptree(t): ...@@ -35,6 +35,12 @@ def dumptree(t):
print t.dump() print t.dump()
return t return t
def abort_on_errors(node):
# Stop the pipeline if there are any errors.
if Errors.num_errors != 0:
raise InternalError, "abort"
return node
class CompilationData(object): class CompilationData(object):
# Bundles the information that is passed from transform to transform. # Bundles the information that is passed from transform to transform.
# (For now, this is only) # (For now, this is only)
...@@ -86,7 +92,7 @@ class Context(object): ...@@ -86,7 +92,7 @@ class Context(object):
from Optimize import FlattenInListTransform, SwitchTransform, IterationTransform from Optimize import FlattenInListTransform, SwitchTransform, IterationTransform
from Optimize import OptimizeBuiltinCalls, ConstantFolding, FinalOptimizePhase from Optimize import OptimizeBuiltinCalls, ConstantFolding, FinalOptimizePhase
from Buffer import IntroduceBufferAuxiliaryVars from Buffer import IntroduceBufferAuxiliaryVars
from ModuleNode import check_c_declarations from ModuleNode import check_c_declarations, check_c_declarations_pxd
# Temporary hack that can be used to ensure that all result_code's # Temporary hack that can be used to ensure that all result_code's
# are generated at code generation time. # are generated at code generation time.
...@@ -98,7 +104,7 @@ class Context(object): ...@@ -98,7 +104,7 @@ class Context(object):
return node return node
if pxd: if pxd:
_check_c_declarations = None _check_c_declarations = check_c_declarations_pxd
_specific_post_parse = PxdPostParse(self) _specific_post_parse = PxdPostParse(self)
else: else:
_check_c_declarations = check_c_declarations _check_c_declarations = check_c_declarations
...@@ -160,6 +166,7 @@ class Context(object): ...@@ -160,6 +166,7 @@ class Context(object):
create_parse(self), create_parse(self),
] + self.create_pipeline(pxd=False, py=py) + [ ] + self.create_pipeline(pxd=False, py=py) + [
inject_pxd_code, inject_pxd_code,
abort_on_errors,
generate_pyx_code, generate_pyx_code,
]) ])
......
...@@ -28,6 +28,10 @@ from Code import UtilityCode ...@@ -28,6 +28,10 @@ from Code import UtilityCode
from StringEncoding import escape_byte_string, EncodedString from StringEncoding import escape_byte_string, EncodedString
def check_c_declarations_pxd(module_node):
module_node.scope.check_c_classes_pxd()
return module_node
def check_c_declarations(module_node): def check_c_declarations(module_node):
module_node.scope.check_c_classes() module_node.scope.check_c_classes()
module_node.scope.check_c_functions() module_node.scope.check_c_functions()
...@@ -799,6 +803,9 @@ class ModuleNode(Nodes.Node, Nodes.BlockNode): ...@@ -799,6 +803,9 @@ class ModuleNode(Nodes.Node, Nodes.BlockNode):
"%s;" % "%s;" %
attr.type.declaration_code(attr.cname)) attr.type.declaration_code(attr.cname))
code.putln(footer) code.putln(footer)
if type.objtypedef_cname is not None:
# Only for exposing public typedef name.
code.putln("typedef struct %s %s;" % (type.objstruct_cname, type.objtypedef_cname))
def generate_global_declarations(self, env, code, definition): def generate_global_declarations(self, env, code, definition):
code.putln("") code.putln("")
...@@ -1625,6 +1632,7 @@ class ModuleNode(Nodes.Node, Nodes.BlockNode): ...@@ -1625,6 +1632,7 @@ class ModuleNode(Nodes.Node, Nodes.BlockNode):
code.putln("{") code.putln("{")
tempdecl_code = code.insertion_point() tempdecl_code = code.insertion_point()
self.generate_filename_init_call(code)
code.putln("#ifdef CYTHON_REFNANNY") code.putln("#ifdef CYTHON_REFNANNY")
code.putln("void* __pyx_refchk = NULL;") code.putln("void* __pyx_refchk = NULL;")
code.putln("__Pyx_Refnanny = __Pyx_ImportRefcountAPI(\"refnanny\");") code.putln("__Pyx_Refnanny = __Pyx_ImportRefcountAPI(\"refnanny\");")
...@@ -1646,7 +1654,6 @@ class ModuleNode(Nodes.Node, Nodes.BlockNode): ...@@ -1646,7 +1654,6 @@ class ModuleNode(Nodes.Node, Nodes.BlockNode):
code.putln("/*--- Library function declarations ---*/") code.putln("/*--- Library function declarations ---*/")
env.generate_library_function_declarations(code) env.generate_library_function_declarations(code)
self.generate_filename_init_call(code)
code.putln("/*--- Threads initialization code ---*/") code.putln("/*--- Threads initialization code ---*/")
code.putln("#if defined(__PYX_FORCE_INIT_THREADS) && __PYX_FORCE_INIT_THREADS") code.putln("#if defined(__PYX_FORCE_INIT_THREADS) && __PYX_FORCE_INIT_THREADS")
...@@ -1655,12 +1662,12 @@ class ModuleNode(Nodes.Node, Nodes.BlockNode): ...@@ -1655,12 +1662,12 @@ class ModuleNode(Nodes.Node, Nodes.BlockNode):
code.putln("#endif") code.putln("#endif")
code.putln("#endif") code.putln("#endif")
code.putln("/*--- Initialize various global constants etc. ---*/")
code.putln(code.error_goto_if_neg("__Pyx_InitGlobals()", self.pos))
code.putln("/*--- Module creation code ---*/") code.putln("/*--- Module creation code ---*/")
self.generate_module_creation_code(env, code) self.generate_module_creation_code(env, code)
code.putln("/*--- Initialize various global constants etc. ---*/")
code.putln(code.error_goto_if_neg("__Pyx_InitGlobals()", self.pos))
if Options.cache_builtins: if Options.cache_builtins:
code.putln("/*--- Builtin init code ---*/") code.putln("/*--- Builtin init code ---*/")
code.putln(code.error_goto_if_neg("__Pyx_InitCachedBuiltins()", code.putln(code.error_goto_if_neg("__Pyx_InitCachedBuiltins()",
...@@ -1699,9 +1706,13 @@ class ModuleNode(Nodes.Node, Nodes.BlockNode): ...@@ -1699,9 +1706,13 @@ class ModuleNode(Nodes.Node, Nodes.BlockNode):
code.put_label(code.error_label) code.put_label(code.error_label)
for cname, type in code.funcstate.all_managed_temps(): for cname, type in code.funcstate.all_managed_temps():
code.put_xdecref(cname, type) code.put_xdecref(cname, type)
code.putln('__Pyx_AddTraceback("%s");' % env.qualified_name) code.putln('if (%s) {' % env.module_cname)
code.putln('__Pyx_AddTraceback("init %s");' % env.qualified_name)
env.use_utility_code(Nodes.traceback_utility_code) env.use_utility_code(Nodes.traceback_utility_code)
code.put_decref_clear(env.module_cname, py_object_type, nanny=False) code.put_decref_clear(env.module_cname, py_object_type, nanny=False)
code.putln('} else if (!PyErr_Occurred()) {')
code.putln('PyErr_SetString(PyExc_ImportError, "init %s");' % env.qualified_name)
code.putln('}')
code.put_label(code.return_label) code.put_label(code.return_label)
code.put_finish_refcount_context() code.put_finish_refcount_context()
......
...@@ -983,8 +983,10 @@ class FuncDefNode(StatNode, BlockNode): ...@@ -983,8 +983,10 @@ class FuncDefNode(StatNode, BlockNode):
def analyse_default_values(self, env): def analyse_default_values(self, env):
genv = env.global_scope() genv = env.global_scope()
default_seen = 0
for arg in self.args: for arg in self.args:
if arg.default: if arg.default:
default_seen = 1
if arg.is_generic: if arg.is_generic:
arg.default.analyse_types(env) arg.default.analyse_types(env)
arg.default = arg.default.coerce_to(arg.type, genv) arg.default = arg.default.coerce_to(arg.type, genv)
...@@ -992,6 +994,10 @@ class FuncDefNode(StatNode, BlockNode): ...@@ -992,6 +994,10 @@ class FuncDefNode(StatNode, BlockNode):
error(arg.pos, error(arg.pos,
"This argument cannot have a default value") "This argument cannot have a default value")
arg.default = None arg.default = None
elif arg.kw_only:
default_seen = 1
elif default_seen:
error(arg.pos, "Non-default argument following default argument")
def need_gil_acquisition(self, lenv): def need_gil_acquisition(self, lenv):
return 0 return 0
...@@ -1064,7 +1070,7 @@ class FuncDefNode(StatNode, BlockNode): ...@@ -1064,7 +1070,7 @@ class FuncDefNode(StatNode, BlockNode):
# ----- Extern library function declarations # ----- Extern library function declarations
lenv.generate_library_function_declarations(code) lenv.generate_library_function_declarations(code)
# ----- GIL acquisition # ----- GIL acquisition
acquire_gil = self.need_gil_acquisition(lenv) acquire_gil = self.acquire_gil
if acquire_gil: if acquire_gil:
env.use_utility_code(force_init_threads_utility_code) env.use_utility_code(force_init_threads_utility_code)
code.putln("PyGILState_STATE _save = PyGILState_Ensure();") code.putln("PyGILState_STATE _save = PyGILState_Ensure();")
...@@ -1403,6 +1409,7 @@ class CFuncDefNode(FuncDefNode): ...@@ -1403,6 +1409,7 @@ class CFuncDefNode(FuncDefNode):
self.py_func.analyse_expressions(env) self.py_func.analyse_expressions(env)
else: else:
self.analyse_default_values(env) self.analyse_default_values(env)
self.acquire_gil = self.need_gil_acquisition(self.local_scope)
def generate_function_header(self, code, with_pymethdef, with_opt_args = 1, with_dispatch = 1, cname = None): def generate_function_header(self, code, with_pymethdef, with_opt_args = 1, with_dispatch = 1, cname = None):
arg_decls = [] arg_decls = []
...@@ -1576,6 +1583,7 @@ class DefNode(FuncDefNode): ...@@ -1576,6 +1583,7 @@ class DefNode(FuncDefNode):
is_wrapper = 0 is_wrapper = 0
decorators = None decorators = None
entry = None entry = None
acquire_gil = 0
def __init__(self, pos, **kwds): def __init__(self, pos, **kwds):
...@@ -1911,8 +1919,9 @@ class DefNode(FuncDefNode): ...@@ -1911,8 +1919,9 @@ class DefNode(FuncDefNode):
or self.starstar_arg is not None or has_kwonly_args or self.starstar_arg is not None or has_kwonly_args
for arg in self.args: for arg in self.args:
if not arg.type.is_pyobject and arg.type.from_py_function is None: if not arg.type.is_pyobject:
arg.type.create_from_py_utility_code(env) done = arg.type.create_from_py_utility_code(env)
if not done: pass # will fail later
if not self.signature_has_generic_args(): if not self.signature_has_generic_args():
if has_star_or_kw_args: if has_star_or_kw_args:
...@@ -1926,12 +1935,10 @@ class DefNode(FuncDefNode): ...@@ -1926,12 +1935,10 @@ class DefNode(FuncDefNode):
else: else:
positional_args = [] positional_args = []
kw_only_args = [] kw_only_args = []
default_seen = 0
for arg in self.args: for arg in self.args:
arg_entry = arg.entry arg_entry = arg.entry
if arg.is_generic: if arg.is_generic:
if arg.default: if arg.default:
default_seen = 1
if not arg.is_self_arg: if not arg.is_self_arg:
if arg.kw_only: if arg.kw_only:
kw_only_args.append(arg) kw_only_args.append(arg)
...@@ -1939,9 +1946,6 @@ class DefNode(FuncDefNode): ...@@ -1939,9 +1946,6 @@ class DefNode(FuncDefNode):
positional_args.append(arg) positional_args.append(arg)
elif arg.kw_only: elif arg.kw_only:
kw_only_args.append(arg) kw_only_args.append(arg)
default_seen = 1
elif default_seen:
error(arg.pos, "Non-default argument following default argument")
elif not arg.is_self_arg: elif not arg.is_self_arg:
positional_args.append(arg) positional_args.append(arg)
......
...@@ -703,6 +703,9 @@ property NAME: ...@@ -703,6 +703,9 @@ property NAME:
return None return None
def visit_CEnumDefNode(self, node): def visit_CEnumDefNode(self, node):
if node.visibility == 'public':
return node
else:
return None return None
def visit_CStructOrUnionDefNode(self, node): def visit_CStructOrUnionDefNode(self, node):
......
...@@ -31,7 +31,6 @@ class PyrexType(BaseType): ...@@ -31,7 +31,6 @@ class PyrexType(BaseType):
# is_extension_type boolean Is a Python extension type # is_extension_type boolean Is a Python extension type
# is_numeric boolean Is a C numeric type # is_numeric boolean Is a C numeric type
# is_int boolean Is a C integer type # is_int boolean Is a C integer type
# is_longlong boolean Is a long long or unsigned long long.
# is_float boolean Is a C floating point type # is_float boolean Is a C floating point type
# is_complex boolean Is a C complex type # is_complex boolean Is a C complex type
# is_void boolean Is the C void type # is_void boolean Is the C void type
...@@ -82,7 +81,6 @@ class PyrexType(BaseType): ...@@ -82,7 +81,6 @@ class PyrexType(BaseType):
is_builtin_type = 0 is_builtin_type = 0
is_numeric = 0 is_numeric = 0
is_int = 0 is_int = 0
is_longlong = 0
is_float = 0 is_float = 0
is_complex = 0 is_complex = 0
is_void = 0 is_void = 0
...@@ -166,11 +164,14 @@ class CTypedefType(BaseType): ...@@ -166,11 +164,14 @@ class CTypedefType(BaseType):
is_typedef = 1 is_typedef = 1
typedef_is_external = 0 typedef_is_external = 0
to_py_utility_code = None
from_py_utility_code = None
def __init__(self, cname, base_type, is_external=0): def __init__(self, cname, base_type, is_external=0):
self.typedef_cname = cname self.typedef_cname = cname
self.typedef_base_type = base_type self.typedef_base_type = base_type
self.typedef_is_external = is_external self.typedef_is_external = is_external
# Make typecodes in external typedefs use typesize-neutral macros # Make typecodes in external typedefs use typesize-neutral macros
if is_external: if is_external:
typecode = None typecode = None
...@@ -215,6 +216,63 @@ class CTypedefType(BaseType): ...@@ -215,6 +216,63 @@ class CTypedefType(BaseType):
def __str__(self): def __str__(self):
return self.declaration_name(for_display = 1) return self.declaration_name(for_display = 1)
def _create_utility_code(self, template_utility_code,
template_function_name):
type_name = self.typedef_cname.replace(" ","_")
utility_code = template_utility_code.specialize(
type = self.typedef_cname,
TypeName = type_name)
function_name = template_function_name % type_name
return utility_code, function_name
def create_to_py_utility_code(self, env):
if self.typedef_is_external:
if not self.to_py_utility_code:
base_type = self.typedef_base_type
if base_type.is_int:
self.to_py_utility_code, self.to_py_function = \
self._create_utility_code(c_typedef_int_to_py_function,
'__Pyx_PyInt_to_py_%s')
elif base_type.is_float:
pass # XXX implement!
elif base_type.is_complex:
pass # XXX implement!
pass
if self.to_py_utility_code:
env.use_utility_code(self.to_py_utility_code)
return True
# delegation
return self.typedef_base_type.create_to_py_utility_code(env)
def create_from_py_utility_code(self, env):
if self.typedef_is_external:
if not self.from_py_utility_code:
base_type = self.typedef_base_type
if base_type.is_int:
self.from_py_utility_code, self.from_py_function = \
self._create_utility_code(c_typedef_int_from_py_function,
'__Pyx_PyInt_from_py_%s')
elif base_type.is_float:
pass # XXX implement!
elif base_type.is_complex:
pass # XXX implement!
if self.from_py_utility_code:
env.use_utility_code(self.from_py_utility_code)
return True
# delegation
return self.typedef_base_type.create_from_py_utility_code(env)
def error_condition(self, result_code):
if self.typedef_is_external:
if self.exception_value:
condition = "(%s == (%s)%s)" % (
result_code, self.typedef_cname, self.exception_value)
if self.exception_check:
condition += " && PyErr_Occurred()"
return condition
# delegation
return self.typedef_base_type.error_condition(result_code)
def __getattr__(self, name): def __getattr__(self, name):
return getattr(self.typedef_base_type, name) return getattr(self.typedef_base_type, name)
...@@ -371,6 +429,7 @@ class PyExtensionType(PyObjectType): ...@@ -371,6 +429,7 @@ class PyExtensionType(PyObjectType):
# base_type PyExtensionType or None # base_type PyExtensionType or None
# module_name string or None Qualified name of defining module # module_name string or None Qualified name of defining module
# objstruct_cname string Name of PyObject struct # objstruct_cname string Name of PyObject struct
# objtypedef_cname string Name of PyObject struct typedef
# typeobj_cname string or None C code fragment referring to type object # typeobj_cname string or None C code fragment referring to type object
# typeptr_cname string or None Name of pointer to external type object # typeptr_cname string or None Name of pointer to external type object
# vtabslot_cname string Name of C method table member # vtabslot_cname string Name of C method table member
...@@ -381,6 +440,8 @@ class PyExtensionType(PyObjectType): ...@@ -381,6 +440,8 @@ class PyExtensionType(PyObjectType):
is_extension_type = 1 is_extension_type = 1
has_attributes = 1 has_attributes = 1
objtypedef_cname = None
def __init__(self, name, typedef_flag, base_type): def __init__(self, name, typedef_flag, base_type):
self.name = name self.name = name
self.scope = None self.scope = None
...@@ -522,7 +583,7 @@ class CNumericType(CType): ...@@ -522,7 +583,7 @@ class CNumericType(CType):
def declaration_code(self, entity_code, def declaration_code(self, entity_code,
for_display = 0, dll_linkage = None, pyrex = 0): for_display = 0, dll_linkage = None, pyrex = 0):
base = public_decl(self.sign_and_name(), dll_linkage) base = public_decl(self.sign_and_name(), dll_linkage)
if for_display and self.is_longlong: if for_display:
base = base.replace('PY_LONG_LONG', 'long long') base = base.replace('PY_LONG_LONG', 'long long')
return self.base_declaration_code(base, entity_code) return self.base_declaration_code(base, entity_code)
...@@ -539,12 +600,12 @@ static INLINE %(type)s __Pyx_PyInt_As%(SignWord)s%(TypeName)s(PyObject* x) { ...@@ -539,12 +600,12 @@ static INLINE %(type)s __Pyx_PyInt_As%(SignWord)s%(TypeName)s(PyObject* x) {
if (sizeof(%(type)s) < sizeof(long)) { if (sizeof(%(type)s) < sizeof(long)) {
long val = __Pyx_PyInt_AsLong(x); long val = __Pyx_PyInt_AsLong(x);
if (unlikely(val != (long)(%(type)s)val)) { if (unlikely(val != (long)(%(type)s)val)) {
if (unlikely(val == -1 && PyErr_Occurred())) if (!unlikely(val == -1 && PyErr_Occurred())) {
return (%(type)s)-1;""" + \
"%(IntValSignTest)s" + \
"""
PyErr_SetString(PyExc_OverflowError, PyErr_SetString(PyExc_OverflowError,
(((%(type)s)-1) > ((%(type)s)0) && unlikely(val < 0)) ?
"can't convert negative value to %(type)s" :
"value too large to convert to %(type)s"); "value too large to convert to %(type)s");
}
return (%(type)s)-1; return (%(type)s)-1;
} }
return (%(type)s)val; return (%(type)s)val;
...@@ -552,12 +613,6 @@ static INLINE %(type)s __Pyx_PyInt_As%(SignWord)s%(TypeName)s(PyObject* x) { ...@@ -552,12 +613,6 @@ static INLINE %(type)s __Pyx_PyInt_As%(SignWord)s%(TypeName)s(PyObject* x) {
return (%(type)s)__Pyx_PyInt_As%(SignWord)sLong(x); return (%(type)s)__Pyx_PyInt_As%(SignWord)sLong(x);
} }
""") """)
intval_signtest = """
if (unlikely(%(var)s < 0)) {
PyErr_SetString(PyExc_OverflowError,
"can't convert negative value to %(type)s");
return (%(type)s)-1;
}"""
c_long_from_py_function = UtilityCode( c_long_from_py_function = UtilityCode(
proto=""" proto="""
...@@ -566,17 +621,25 @@ static INLINE %(type)s __Pyx_PyInt_As%(SignWord)s%(TypeName)s(PyObject *); ...@@ -566,17 +621,25 @@ static INLINE %(type)s __Pyx_PyInt_As%(SignWord)s%(TypeName)s(PyObject *);
impl=""" impl="""
static INLINE %(type)s __Pyx_PyInt_As%(SignWord)s%(TypeName)s(PyObject* x) { static INLINE %(type)s __Pyx_PyInt_As%(SignWord)s%(TypeName)s(PyObject* x) {
#if PY_VERSION_HEX < 0x03000000 #if PY_VERSION_HEX < 0x03000000
if (likely(PyInt_CheckExact(x) || PyInt_Check(x))) { if (likely(PyInt_Check(x))) {
long val = PyInt_AS_LONG(x);""" + \ long val = PyInt_AS_LONG(x);
"%(IntValSignTest)s" + \ if (((%(type)s)-1) > ((%(type)s)0) && unlikely(val < 0)) {
""" PyErr_SetString(PyExc_OverflowError,
"can't convert negative value to %(type)s");
return (%(type)s)-1;
}
return (%(type)s)val; return (%(type)s)val;
} else } else
#endif #endif
if (likely(PyLong_CheckExact(x) || PyLong_Check(x))) {""" +\ if (likely(PyLong_Check(x))) {
"%(PyLongSignTest)s" + \ if (((%(type)s)-1) > ((%(type)s)0) && unlikely(Py_SIZE(x) < 0)) {
""" PyErr_SetString(PyExc_OverflowError,
return %(PyLongConvert)s(x); "can't convert negative value to %(type)s");
return (%(type)s)-1;
}
return (((%(type)s)-1) < ((%(type)s)0)) ?
PyLong_As%(TypeName)s(x) :
PyLong_AsUnsigned%(TypeName)s(x);
} else { } else {
%(type)s val; %(type)s val;
PyObject *tmp = __Pyx_PyNumber_Int(x); PyObject *tmp = __Pyx_PyNumber_Int(x);
...@@ -587,14 +650,63 @@ static INLINE %(type)s __Pyx_PyInt_As%(SignWord)s%(TypeName)s(PyObject* x) { ...@@ -587,14 +650,63 @@ static INLINE %(type)s __Pyx_PyInt_As%(SignWord)s%(TypeName)s(PyObject* x) {
} }
} }
""") """)
pylong_signtest = """
if (unlikely(Py_SIZE(%(var)s) < 0)) {
PyErr_SetString(PyExc_OverflowError,
"can't convert negative value to %(type)s");
return (%(type)s)-1;
}"""
c_typedef_int_from_py_function = UtilityCode(
proto="""
static INLINE %(type)s __Pyx_PyInt_from_py_%(TypeName)s(PyObject *);
""",
impl="""
static INLINE %(type)s __Pyx_PyInt_from_py_%(TypeName)s(PyObject* x) {
/**/ if (sizeof(%(type)s) == sizeof(char))
return (((%(type)s)-1) < ((%(type)s)0)) ?
(%(type)s)__Pyx_PyInt_AsSignedChar(x) :
(%(type)s)__Pyx_PyInt_AsUnsignedChar(x);
else if (sizeof(%(type)s) == sizeof(short))
return (((%(type)s)-1) < ((%(type)s)0)) ?
(%(type)s)__Pyx_PyInt_AsSignedShort(x) :
(%(type)s)__Pyx_PyInt_AsUnsignedShort(x);
else if (sizeof(%(type)s) == sizeof(int))
return (((%(type)s)-1) < ((%(type)s)0)) ?
(%(type)s)__Pyx_PyInt_AsSignedInt(x) :
(%(type)s)__Pyx_PyInt_AsUnsignedInt(x);
else if (sizeof(%(type)s) == sizeof(long))
return (((%(type)s)-1) < ((%(type)s)0)) ?
(%(type)s)__Pyx_PyInt_AsSignedLong(x) :
(%(type)s)__Pyx_PyInt_AsUnsignedLong(x);
else if (sizeof(%(type)s) == sizeof(PY_LONG_LONG))
return (((%(type)s)-1) < ((%(type)s)0)) ?
(%(type)s)__Pyx_PyInt_AsSignedLongLong(x) :
(%(type)s)__Pyx_PyInt_AsUnsignedLongLong(x);
#if 0
else if (sizeof(%(type)s) > sizeof(short) &&
sizeof(%(type)s) < sizeof(int)) /* __int32 ILP64 ? */
return (((%(type)s)-1) < ((%(type)s)0)) ?
(%(type)s)__Pyx_PyInt_AsSignedInt(x) :
(%(type)s)__Pyx_PyInt_AsUnsignedInt(x);
#endif
PyErr_SetString(PyExc_TypeError, "%(TypeName)s");
return (%(type)s)-1;
}
""")
c_typedef_int_to_py_function = UtilityCode(
proto="""
static INLINE PyObject *__Pyx_PyInt_to_py_%(TypeName)s(%(type)s);
""",
impl="""
static INLINE PyObject *__Pyx_PyInt_to_py_%(TypeName)s(%(type)s val) {
/**/ if (sizeof(%(type)s) < sizeof(long))
return PyInt_FromLong((long)val);
else if (sizeof(%(type)s) == sizeof(long))
return (((%(type)s)-1) < ((%(type)s)0)) ?
PyInt_FromLong((long)val) :
PyLong_FromUnsignedLong((unsigned long)val);
else /* (sizeof(%(type)s) > sizeof(long)) */
return (((%(type)s)-1) < ((%(type)s)0)) ?
PyLong_FromLongLong((PY_LONG_LONG)val) :
PyLong_FromUnsignedLongLong((unsigned PY_LONG_LONG)val);
}
""")
class CIntType(CNumericType): class CIntType(CNumericType):
...@@ -620,27 +732,13 @@ class CIntType(CNumericType): ...@@ -620,27 +732,13 @@ class CIntType(CNumericType):
type_name = type_name.replace("PY_LONG_LONG","long long") type_name = type_name.replace("PY_LONG_LONG","long long")
SignWord = sign_word.title() SignWord = sign_word.title()
TypeName = type_name.title().replace(" ", "") TypeName = type_name.title().replace(" ", "")
data = {'IntValSignTest' : "",
'PyLongSignTest' : "",
'PyLongConvert' : "",
}
if not self.signed:
data['IntValSignTest'] = intval_signtest % {'var':"val", 'type':ctype}
data['PyLongSignTest'] = pylong_signtest % {'var':"x", 'type':ctype}
if "Long" in TypeName: if "Long" in TypeName:
data['PyLongConvert'] = \
"PyLong_As" + SignWord.replace("Signed", "") + TypeName
# the replaces below are just for generating well indented C code
data['IntValSignTest'] = "\n".join(
[ln.replace(" "*4, "", 1) for ln in data['IntValSignTest'].split('\n')]
)
utility_code = c_long_from_py_function utility_code = c_long_from_py_function
else: else:
utility_code = c_int_from_py_function utility_code = c_int_from_py_function
utility_code.specialize(self, utility_code.specialize(self,
SignWord=SignWord, SignWord=SignWord,
TypeName=TypeName, TypeName=TypeName)
**data)
func_name = "__Pyx_PyInt_As%s%s" % (SignWord, TypeName) func_name = "__Pyx_PyInt_As%s%s" % (SignWord, TypeName)
return func_name return func_name
...@@ -681,13 +779,11 @@ class CULongType(CUIntType): ...@@ -681,13 +779,11 @@ class CULongType(CUIntType):
class CLongLongType(CIntType): class CLongLongType(CIntType):
is_longlong = 1
to_py_function = "PyLong_FromLongLong" to_py_function = "PyLong_FromLongLong"
class CULongLongType(CUIntType): class CULongLongType(CUIntType):
is_longlong = 1
to_py_function = "PyLong_FromUnsignedLongLong" to_py_function = "PyLong_FromUnsignedLongLong"
......
...@@ -243,6 +243,7 @@ class Scope(object): ...@@ -243,6 +243,7 @@ class Scope(object):
self.pystring_entries = [] self.pystring_entries = []
self.buffer_entries = [] self.buffer_entries = []
self.control_flow = ControlFlow.LinearControlFlow() self.control_flow = ControlFlow.LinearControlFlow()
self.return_type = None
def start_branching(self, pos): def start_branching(self, pos):
self.control_flow = self.control_flow.start_branch(pos) self.control_flow = self.control_flow.start_branch(pos)
...@@ -837,6 +838,17 @@ class ModuleScope(Scope): ...@@ -837,6 +838,17 @@ class ModuleScope(Scope):
module_name = None, base_type = None, objstruct_cname = None, module_name = None, base_type = None, objstruct_cname = None,
typeobj_cname = None, visibility = 'private', typedef_flag = 0, api = 0, typeobj_cname = None, visibility = 'private', typedef_flag = 0, api = 0,
buffer_defaults = None): buffer_defaults = None):
# If this is a non-extern typedef class, expose the typedef, but use
# the non-typedef struct internally to avoid needing forward
# declarations for anonymous structs.
if typedef_flag and visibility != 'extern':
if visibility != 'public':
warning(pos, "ctypedef only valid for public and extern classes", 2)
objtypedef_cname = objstruct_cname
objstruct_cname = None
typedef_flag = 0
else:
objtypedef_cname = None
# #
# Look for previous declaration as a type # Look for previous declaration as a type
# #
...@@ -861,6 +873,8 @@ class ModuleScope(Scope): ...@@ -861,6 +873,8 @@ class ModuleScope(Scope):
type = PyrexTypes.PyExtensionType(name, typedef_flag, base_type) type = PyrexTypes.PyExtensionType(name, typedef_flag, base_type)
type.pos = pos type.pos = pos
type.buffer_defaults = buffer_defaults type.buffer_defaults = buffer_defaults
if objtypedef_cname is not None:
type.objtypedef_cname = objtypedef_cname
if visibility == 'extern': if visibility == 'extern':
type.module_name = module_name type.module_name = module_name
else: else:
...@@ -941,6 +955,22 @@ class ModuleScope(Scope): ...@@ -941,6 +955,22 @@ class ModuleScope(Scope):
type.vtabstruct_cname = self.mangle(Naming.vtabstruct_prefix, entry.name) type.vtabstruct_cname = self.mangle(Naming.vtabstruct_prefix, entry.name)
type.vtabptr_cname = self.mangle(Naming.vtabptr_prefix, entry.name) type.vtabptr_cname = self.mangle(Naming.vtabptr_prefix, entry.name)
def check_c_classes_pxd(self):
# Performs post-analysis checking and finishing up of extension types
# being implemented in this module. This is called only for the .pxd.
#
# Checks all extension types declared in this scope to
# make sure that:
#
# * The extension type is fully declared
#
# Also allocates a name for the vtable if needed.
#
for entry in self.c_class_entries:
# Check defined
if not entry.type.scope:
error(entry.pos, "C class '%s' is declared but not defined" % entry.name)
def check_c_classes(self): def check_c_classes(self):
# Performs post-analysis checking and finishing up of extension types # Performs post-analysis checking and finishing up of extension types
# being implemented in this module. This is called only for the main # being implemented in this module. This is called only for the main
...@@ -1204,7 +1234,8 @@ class CClassScope(ClassScope): ...@@ -1204,7 +1234,8 @@ class CClassScope(ClassScope):
# If the type or any of its base types have Python-valued # If the type or any of its base types have Python-valued
# C attributes, then it needs to participate in GC. # C attributes, then it needs to participate in GC.
return self.has_pyobject_attrs or \ return self.has_pyobject_attrs or \
(self.parent_type.base_type and \ (self.parent_type.base_type and
self.parent_type.base_type.scope is not None and
self.parent_type.base_type.scope.needs_gc()) self.parent_type.base_type.scope.needs_gc())
def declare_var(self, name, type, pos, def declare_var(self, name, type, pos,
...@@ -1214,7 +1245,7 @@ class CClassScope(ClassScope): ...@@ -1214,7 +1245,7 @@ class CClassScope(ClassScope):
if self.defined: if self.defined:
error(pos, error(pos,
"C attributes cannot be added in implementation part of" "C attributes cannot be added in implementation part of"
" extension type") " extension type defined in a pxd")
if get_special_method_signature(name): if get_special_method_signature(name):
error(pos, error(pos,
"The name '%s' is reserved for a special method." "The name '%s' is reserved for a special method."
......
...@@ -87,7 +87,7 @@ cdef extern from "Python.h": ...@@ -87,7 +87,7 @@ cdef extern from "Python.h":
# needs to handle exceptions or by code that needs to save and # needs to handle exceptions or by code that needs to save and
# restore the error indicator temporarily. # restore the error indicator temporarily.
void PyErr_Restore(object type, object value, object traceback) void PyErr_Restore(PyObject* type, PyObject* value, PyObject* traceback)
# Set the error indicator from the three objects. If the error # Set the error indicator from the three objects. If the error
# indicator is already set, it is cleared first. If the objects # indicator is already set, it is cleared first. If the objects
# are NULL, the error indicator is cleared. Do not pass a NULL # are NULL, the error indicator is cleared. Do not pass a NULL
......
...@@ -59,7 +59,7 @@ class Context(object): ...@@ -59,7 +59,7 @@ class Context(object):
else: else:
return None return None
cpdef report_unraisable(e): cdef void report_unraisable(object e):
try: try:
print "refnanny raised an exception: %s" % e print "refnanny raised an exception: %s" % e
except: except:
...@@ -84,7 +84,7 @@ cdef PyObject* NewContext(char* funcname, int lineno, char* filename) except NUL ...@@ -84,7 +84,7 @@ cdef PyObject* NewContext(char* funcname, int lineno, char* filename) except NUL
result = <PyObject*>ctx result = <PyObject*>ctx
except Exception, e: except Exception, e:
report_unraisable(e) report_unraisable(e)
PyErr_Restore(<object>type, <object>value, <object>tb) PyErr_Restore(type, value, tb)
return result return result
cdef void GOTREF(PyObject* ctx, PyObject* p_obj, int lineno): cdef void GOTREF(PyObject* ctx, PyObject* p_obj, int lineno):
...@@ -98,7 +98,7 @@ cdef void GOTREF(PyObject* ctx, PyObject* p_obj, int lineno): ...@@ -98,7 +98,7 @@ cdef void GOTREF(PyObject* ctx, PyObject* p_obj, int lineno):
(<object>ctx).regref(<object>p_obj, lineno, False) (<object>ctx).regref(<object>p_obj, lineno, False)
except Exception, e: except Exception, e:
report_unraisable(e) report_unraisable(e)
PyErr_Restore(<object>type, <object>value, <object>tb) PyErr_Restore(type, value, tb)
cdef int GIVEREF_and_report(PyObject* ctx, PyObject* p_obj, int lineno): cdef int GIVEREF_and_report(PyObject* ctx, PyObject* p_obj, int lineno):
if ctx == NULL: return 1 if ctx == NULL: return 1
...@@ -112,7 +112,7 @@ cdef int GIVEREF_and_report(PyObject* ctx, PyObject* p_obj, int lineno): ...@@ -112,7 +112,7 @@ cdef int GIVEREF_and_report(PyObject* ctx, PyObject* p_obj, int lineno):
decref_ok = (<object>ctx).delref(<object>p_obj, lineno, False) decref_ok = (<object>ctx).delref(<object>p_obj, lineno, False)
except Exception, e: except Exception, e:
report_unraisable(e) report_unraisable(e)
PyErr_Restore(<object>type, <object>value, <object>tb) PyErr_Restore(type, value, tb)
return decref_ok return decref_ok
cdef void GIVEREF(PyObject* ctx, PyObject* p_obj, int lineno): cdef void GIVEREF(PyObject* ctx, PyObject* p_obj, int lineno):
...@@ -141,7 +141,7 @@ cdef void FinishContext(PyObject** ctx): ...@@ -141,7 +141,7 @@ cdef void FinishContext(PyObject** ctx):
report_unraisable(e) report_unraisable(e)
Py_DECREF(<object>ctx[0]) Py_DECREF(<object>ctx[0])
ctx[0] = NULL ctx[0] = NULL
PyErr_Restore(<object>type, <object>value, <object>tb) PyErr_Restore(type, value, tb)
cdef extern from "Python.h": cdef extern from "Python.h":
object PyCObject_FromVoidPtr(void*, void (*)(void*)) object PyCObject_FromVoidPtr(void*, void (*)(void*))
......
...@@ -3,7 +3,6 @@ ...@@ -3,7 +3,6 @@
methodmangling_T5 methodmangling_T5
class_attribute_init_values_T18 class_attribute_init_values_T18
return_outside_function_T135
builtin_types_none_T166 builtin_types_none_T166
numpy_ValueError_T172 numpy_ValueError_T172
unsignedbehaviour_T184 unsignedbehaviour_T184
......
ctypedef public class Time [type MyTime_Type, object MyTimeObject]:
cdef public double seconds
ctypedef public class Event [type MyEvent_Type, object MyEventObject]:
cdef public Time time
ctypedef public class Time [type MyTime_Type, object MyTimeObject]:
def __init__(self, seconds):
self.seconds = seconds
ctypedef public class Event [type MyEvent_Type, object MyEventObject]:
def __init__(self, Time time):
self.time = time
...@@ -11,6 +11,7 @@ cdef class Grail: ...@@ -11,6 +11,7 @@ cdef class Grail:
_ERRORS = u""" _ERRORS = u"""
1:10: Non-default argument follows default argument 1:10: Non-default argument follows default argument
9:16: This argument cannot have a default value 1:36: Non-default argument following default argument
4:23: Non-default argument following default argument 4:23: Non-default argument following default argument
9:16: This argument cannot have a default value
""" """
ctypedef struct Spam ctypedef struct Spam
ctypedef class Eggs
cdef extern from *: cdef extern from *:
ctypedef struct Ham ctypedef struct Ham
...@@ -7,12 +6,7 @@ cdef extern from *: ...@@ -7,12 +6,7 @@ cdef extern from *:
ctypedef struct Spam: ctypedef struct Spam:
int i int i
ctypedef class Eggs:
pass
ctypedef struct Spam ctypedef struct Spam
ctypedef class Eggs
_ERRORS = u""" _ERRORS = u"""
1:0: Forward-referenced type must use 'cdef', not 'ctypedef' 1:0: Forward-referenced type must use 'cdef', not 'ctypedef'
2:0: Forward-referenced type must use 'cdef', not 'ctypedef'
""" """
...@@ -8,16 +8,10 @@ ctypedef struct Blarg: ...@@ -8,16 +8,10 @@ ctypedef struct Blarg:
cdef struct Blarg cdef struct Blarg
cdef class Spam
ctypedef class Spam:
pass
cdef Foo f cdef Foo f
cdef Blarg b cdef Blarg b
_ERRORS = u""" _ERRORS = u"""
3:0: 'Foo' previously declared using 'cdef' 3:0: 'Foo' previously declared using 'cdef'
9:5: 'Blarg' previously declared using 'ctypedef' 9:5: 'Blarg' previously declared using 'ctypedef'
13:0: 'Spam' previously declared using 'cdef'
""" """
...@@ -8,13 +8,11 @@ def f(a): ...@@ -8,13 +8,11 @@ def f(a):
del f() # error del f() # error
del i # error: deletion of non-Python object del i # error: deletion of non-Python object
del j # error: deletion of non-Python object del j # error: deletion of non-Python object
del a # error: deletion of local name not supported
del x[i] # error: deletion of non-Python object del x[i] # error: deletion of non-Python object
del s.m # error: deletion of non-Python object del s.m # error: deletion of non-Python object
_ERRORS = u""" _ERRORS = u"""
8:6: Cannot assign to or delete this 8:6: Cannot assign to or delete this
9:45: Deletion of non-Python object 9:45: Deletion of non-Python object
11:6: Deletion of non-Python object
12:6: Deletion of non-Python object 12:6: Deletion of non-Python object
13:6: Deletion of non-Python object
11:52: Deletion of local or C global name not supported
""" """
# Errors reported during code generation.
cdef int i
def f(a):
del a # error: deletion of local name not supported
del i # error: deletion of local name not supported
_ERRORS = u"""
6:52: Deletion of local or C global name not supported
7:52: Deletion of local or C global name not supported
"""
...@@ -109,9 +109,9 @@ _ERRORS = u""" ...@@ -109,9 +109,9 @@ _ERRORS = u"""
37:15: Converting to Python object not allowed without gil 37:15: Converting to Python object not allowed without gil
37:17: Converting to Python object not allowed without gil 37:17: Converting to Python object not allowed without gil
38:11: Accessing Python attribute not allowed without gil 38:11: Accessing Python attribute not allowed without gil
39:9: Constructing Python tuple not allowed without gil 39: 9: Constructing Python tuple not allowed without gil
40:8: Constructing Python list not allowed without gil 40: 8: Constructing Python list not allowed without gil
41:8: Constructing Python dict not allowed without gil 41: 8: Constructing Python dict not allowed without gil
42:12: Truth-testing Python object not allowed without gil 42:12: Truth-testing Python object not allowed without gil
43:13: Python type test not allowed without gil 43:13: Python type test not allowed without gil
45:10: Operation not allowed without gil 45:10: Operation not allowed without gil
......
cdef class A:
pass
_ERRORS = u"""
1:5: C class 'A' is declared but not defined
"""
__doc__ = u""
# -------------------------------------------------------------------
cdef extern from "ctypedef_int_types_chdr_T333.h":
ctypedef int SChar ## "signed char"
ctypedef int UChar ## "unsigned char"
ctypedef int SShort ## "signed short"
ctypedef int UShort ## "unsigned short"
ctypedef int SInt ## "signed int"
ctypedef int UInt ## "unsigned int"
ctypedef int SLong ## "signed long"
ctypedef int ULong ## "unsigned long"
ctypedef int SLongLong ## "signed PY_LONG_LONG"
ctypedef int ULongLong ## "unsigned PY_LONG_LONG"
# -------------------------------------------------------------------
SCHAR_MAX = <SChar>((<UChar>-1)>>1)
SCHAR_MIN = (-SCHAR_MAX-1)
def test_schar(SChar x):
u"""
>>> test_schar(-129) #doctest: +ELLIPSIS
Traceback (most recent call last):
...
OverflowError: ...
>>> test_schar(-128)
-128
>>> test_schar(0)
0
>>> test_schar(127)
127
>>> test_schar(128) #doctest: +ELLIPSIS
Traceback (most recent call last):
...
OverflowError: ...
"""
return x
def test_add_schar(x, y):
u"""
>>> test_add_schar(SCHAR_MIN, -1) #doctest: +ELLIPSIS
Traceback (most recent call last):
...
OverflowError: ...
>>> test_add_schar(SCHAR_MIN, 0) == SCHAR_MIN
True
>>> test_add_schar(SCHAR_MIN, 1) == SCHAR_MIN+1
True
>>> test_add_schar(SCHAR_MAX, -1) == SCHAR_MAX-1
True
>>> test_add_schar(SCHAR_MAX, 0) == SCHAR_MAX
True
>>> test_add_schar(SCHAR_MAX, 1) #doctest: +ELLIPSIS
Traceback (most recent call last):
...
OverflowError: ...
"""
cdef SChar r = x + y
return r
UCHAR_MAX = <UChar>((<UChar>-1))
def test_uchar(UChar x):
u"""
>>> test_uchar(-1) #doctest: +ELLIPSIS
Traceback (most recent call last):
...
OverflowError: ...
>>> test_uchar(0)
0
>>> test_uchar(1)
1
>>> test_uchar(UCHAR_MAX) == UCHAR_MAX
True
>>> test_uchar(UCHAR_MAX+1) #doctest: +ELLIPSIS
Traceback (most recent call last):
...
OverflowError: ...
"""
return x
def test_add_uchar(x, y):
u"""
>>> test_add_uchar(UCHAR_MAX, 0) == UCHAR_MAX
True
>>> test_add_uchar(UCHAR_MAX, 1) #doctest: +ELLIPSIS
Traceback (most recent call last):
...
OverflowError: ...
"""
cdef UChar r = x + y
return r
# -------------------------------------------------------------------
SSHORT_MAX = <SShort>((<UShort>-1)>>1)
SSHORT_MIN = (-SSHORT_MAX-1)
def test_sshort(short x):
u"""
>>> test_sshort(SSHORT_MIN-1) #doctest: +ELLIPSIS
Traceback (most recent call last):
...
OverflowError: ...
>>> test_sshort(SSHORT_MIN) == SSHORT_MIN
True
>>> test_sshort(-1)
-1
>>> test_sshort(0)
0
>>> test_sshort(1)
1
>>> test_sshort(SSHORT_MAX) == SSHORT_MAX
True
>>> test_sshort(SSHORT_MAX+1) #doctest: +ELLIPSIS
Traceback (most recent call last):
...
OverflowError: ...
"""
return x
def test_add_sshort(x, y):
u"""
>>> test_add_sshort(SSHORT_MIN, -1) #doctest: +ELLIPSIS
Traceback (most recent call last):
...
OverflowError: ...
>>> test_add_sshort(SSHORT_MIN, 0) == SSHORT_MIN
True
>>> test_add_sshort(SSHORT_MIN, 1) == SSHORT_MIN+1
True
>>> test_add_sshort(SSHORT_MAX, -1) == SSHORT_MAX-1
True
>>> test_add_sshort(SSHORT_MAX, 0) == SSHORT_MAX
True
>>> test_add_sshort(SSHORT_MAX, 1) #doctest: +ELLIPSIS
Traceback (most recent call last):
...
OverflowError: ...
"""
cdef SShort r = x + y
return r
USHORT_MAX = <UShort>((<UShort>-1))
def test_ushort(UShort x):
u"""
>>> test_ushort(-1) #doctest: +ELLIPSIS
Traceback (most recent call last):
...
OverflowError: ...
>>> test_ushort(0)
0
>>> test_ushort(1)
1
>>> test_ushort(USHORT_MAX) == USHORT_MAX
True
>>> test_ushort(USHORT_MAX+1) #doctest: +ELLIPSIS
Traceback (most recent call last):
...
OverflowError: ...
"""
return x
def test_add_ushort(x, y):
u"""
>>> test_add_ushort(USHORT_MAX, 0) == USHORT_MAX
True
>>> test_add_ushort(USHORT_MAX, 1) #doctest: +ELLIPSIS
Traceback (most recent call last):
...
OverflowError: ...
"""
cdef UShort r = x + y
return r
# -------------------------------------------------------------------
SINT_MAX = <SInt>((<UInt>-1)>>1)
SINT_MIN = (-SINT_MAX-1)
def test_sint(int x):
u"""
>>> test_sint(SINT_MIN-1) #doctest: +ELLIPSIS
Traceback (most recent call last):
...
OverflowError: ...
>>> test_sint(SINT_MIN) == SINT_MIN
True
>>> test_sint(-1)
-1
>>> test_sint(0)
0
>>> test_sint(1)
1
>>> test_sint(SINT_MAX) == SINT_MAX
True
>>> test_sint(SINT_MAX+1) #doctest: +ELLIPSIS
Traceback (most recent call last):
...
OverflowError: ...
"""
return x
def test_add_sint(x, y):
u"""
>>> test_add_sint(SINT_MIN, -1) #doctest: +ELLIPSIS
Traceback (most recent call last):
...
OverflowError: ...
>>> test_add_sint(SINT_MIN, 0) == SINT_MIN
True
>>> test_add_sint(SINT_MIN, 1) == SINT_MIN+1
True
>>> test_add_sint(SINT_MAX, -1) == SINT_MAX-1
True
>>> test_add_sint(SINT_MAX, 0) == SINT_MAX
True
>>> test_add_sint(SINT_MAX, 1) #doctest: +ELLIPSIS
Traceback (most recent call last):
...
OverflowError: ...
"""
cdef SInt r = x + y
return r
UINT_MAX = <UInt>(<UInt>-1)
def test_uint(UInt x):
u"""
>>> test_uint(-1) #doctest: +ELLIPSIS
Traceback (most recent call last):
...
OverflowError: ...
>>> print(test_uint(0))
0
>>> print(test_uint(1))
1
>>> test_uint(UINT_MAX) == UINT_MAX
True
>>> test_uint(UINT_MAX+1) #doctest: +ELLIPSIS
Traceback (most recent call last):
...
OverflowError: ...
"""
return x
def test_add_uint(x, y):
u"""
>>> test_add_uint(UINT_MAX, 0) == UINT_MAX
True
>>> test_add_uint(UINT_MAX, 1) #doctest: +ELLIPSIS
Traceback (most recent call last):
...
OverflowError: ...
"""
cdef UInt r = x + y
return r
# -------------------------------------------------------------------
SLONG_MAX = <SLong>((<ULong>-1)>>1)
SLONG_MIN = (-SLONG_MAX-1)
def test_slong(long x):
u"""
>>> test_slong(SLONG_MIN-1) #doctest: +ELLIPSIS
Traceback (most recent call last):
...
OverflowError: ...
>>> test_slong(SLONG_MIN) == SLONG_MIN
True
>>> test_slong(-1)
-1
>>> test_slong(0)
0
>>> test_slong(1)
1
>>> test_slong(SLONG_MAX) == SLONG_MAX
True
>>> test_slong(SLONG_MAX+1) #doctest: +ELLIPSIS
Traceback (most recent call last):
...
OverflowError: ...
"""
return x
def test_add_slong(x, y):
u"""
>>> test_add_slong(SLONG_MIN, -1) #doctest: +ELLIPSIS
Traceback (most recent call last):
...
OverflowError: ...
>>> test_add_slong(SLONG_MIN, 0) == SLONG_MIN
True
>>> test_add_slong(SLONG_MIN, 1) == SLONG_MIN+1
True
>>> test_add_slong(SLONG_MAX, -1) == SLONG_MAX-1
True
>>> test_add_slong(SLONG_MAX, 0) == SLONG_MAX
True
>>> test_add_slong(SLONG_MAX, 1) #doctest: +ELLIPSIS
Traceback (most recent call last):
...
OverflowError: ...
"""
cdef SLong r = x + y
return r
ULONG_MAX = <ULong>(<ULong>-1)
def test_ulong(ULong x):
u"""
>>> test_ulong(-1) #doctest: +ELLIPSIS
Traceback (most recent call last):
...
OverflowError: ...
>>> print(test_ulong(0))
0
>>> print(test_ulong(1))
1
>>> test_ulong(ULONG_MAX) == ULONG_MAX
True
>>> test_ulong(ULONG_MAX+1) #doctest: +ELLIPSIS
Traceback (most recent call last):
...
OverflowError: ...
"""
return x
def test_add_ulong(x, y):
u"""
>>> test_add_ulong(ULONG_MAX, 0) == ULONG_MAX
True
>>> test_add_ulong(ULONG_MAX, 1) #doctest: +ELLIPSIS
Traceback (most recent call last):
...
OverflowError: ...
"""
cdef ULong r = x + y
return r
# -------------------------------------------------------------------
SLONGLONG_MAX = <SLongLong>((<ULongLong>-1)>>1)
SLONGLONG_MIN = (-SLONGLONG_MAX-1)
def test_slonglong(long long x):
u"""
>>> test_slonglong(SLONGLONG_MIN-1) #doctest: +ELLIPSIS
Traceback (most recent call last):
...
OverflowError: ...
>>> test_slonglong(SLONGLONG_MIN) == SLONGLONG_MIN
True
>>> print(test_slonglong(-1))
-1
>>> print(test_slonglong(0))
0
>>> print(test_slonglong(1))
1
>>> test_slonglong(SLONGLONG_MAX) == SLONGLONG_MAX
True
>>> test_slonglong(SLONGLONG_MAX+1) #doctest: +ELLIPSIS
Traceback (most recent call last):
...
OverflowError: ...
"""
return x
def test_add_slonglong(x, y):
u"""
>>> test_add_slonglong(SLONGLONG_MIN, -1) #doctest: +ELLIPSIS
Traceback (most recent call last):
...
OverflowError: ...
>>> test_add_slonglong(SLONGLONG_MIN, 0) == SLONGLONG_MIN
True
>>> test_add_slonglong(SLONGLONG_MIN, 1) == SLONGLONG_MIN+1
True
>>> test_add_slonglong(SLONGLONG_MAX, -1) == SLONGLONG_MAX-1
True
>>> test_add_slonglong(SLONGLONG_MAX, 0) == SLONGLONG_MAX
True
>>> test_add_slonglong(SLONGLONG_MAX, 1) #doctest: +ELLIPSIS
Traceback (most recent call last):
...
OverflowError: ...
"""
cdef SLongLong r = x + y
return r
ULONGLONG_MAX = <ULongLong>(<ULongLong>-1)
def test_ulonglong(ULongLong x):
u"""
>>> test_ulonglong(-1) #doctest: +ELLIPSIS
Traceback (most recent call last):
...
OverflowError: ...
>>> print(test_ulonglong(0))
0
>>> print(test_ulonglong(1))
1
>>> test_ulonglong(ULONGLONG_MAX) == ULONGLONG_MAX
True
>>> test_ulonglong(ULONGLONG_MAX+1) #doctest: +ELLIPSIS
Traceback (most recent call last):
...
OverflowError: ...
"""
return x
def test_add_ulonglong(x, y):
u"""
>>> test_add_ulonglong(ULONGLONG_MAX, 0) == ULONGLONG_MAX
True
>>> test_add_ulonglong(ULONGLONG_MAX, 1) #doctest: +ELLIPSIS
Traceback (most recent call last):
...
OverflowError: ...
"""
cdef ULongLong r = x + y
return r
# -------------------------------------------------------------------
cdef class MyClass:
"""
>>> a = MyClass()
>>> vals = (SCHAR_MIN, UCHAR_MAX,
... SSHORT_MIN, USHORT_MAX,
... SINT_MIN, UINT_MAX,
... SLONG_MIN, ULONG_MAX,
... SLONGLONG_MIN, ULONGLONG_MAX)
>>> a.setvalues(*vals)
>>> a.getvalues() == vals
True
>>> vals = (SCHAR_MAX, UCHAR_MAX,
... SSHORT_MAX, USHORT_MAX,
... SINT_MAX, UINT_MAX,
... SLONG_MAX, ULONG_MAX,
... SLONGLONG_MAX, ULONGLONG_MAX)
>>> a.setvalues(*vals)
>>> a.getvalues() == vals
True
>>> vals = (0,) * 10
>>> a.setvalues(*vals)
>>> a.getvalues() == vals
True
"""
cdef:
SChar attr_schar
UChar attr_uchar
SShort attr_sshort
UShort attr_ushort
SInt attr_sint
UInt attr_uint
SLong attr_slong
ULong attr_ulong
SLongLong attr_slonglong
ULongLong attr_ulonglong
cpdef setvalues(self,
SChar arg_schar ,
UChar arg_uchar ,
SShort arg_sshort ,
UShort arg_ushort ,
SInt arg_sint ,
UInt arg_uint ,
SLong arg_slong ,
ULong arg_ulong ,
SLongLong arg_slonglong ,
ULongLong arg_ulonglong ):
self.attr_schar = arg_schar
self.attr_uchar = arg_uchar
self.attr_sshort = arg_sshort
self.attr_ushort = arg_ushort
self.attr_sint = arg_sint
self.attr_uint = arg_uint
self.attr_slong = arg_slong
self.attr_ulong = arg_ulong
self.attr_slonglong = arg_slonglong
self.attr_ulonglong = arg_ulonglong
cpdef getvalues(self):
return (self.attr_schar ,
self.attr_uchar ,
self.attr_sshort ,
self.attr_ushort ,
self.attr_sint ,
self.attr_uint ,
self.attr_slong ,
self.attr_ulong ,
self.attr_slonglong ,
self.attr_ulonglong )
# -------------------------------------------------------------------
cdef extern from *:
ctypedef signed MySInt1 "signed short"
ctypedef unsigned MyUInt1 "unsigned short"
def test_MySInt1(MySInt1 x):
u"""
>>> test_MySInt1(-1)
-1
>>> test_MySInt1(0)
0
>>> test_MySInt1(1)
1
"""
return x
def test_MyUInt1(MyUInt1 x):
u"""
>>> test_MyUInt1(-1) #doctest: +ELLIPSIS
Traceback (most recent call last):
...
OverflowError: ...
>>> test_MyUInt1(0)
0
>>> test_MyUInt1(1)
1
"""
return x
cdef extern from *:
ctypedef signed MySInt2 "signed short"
ctypedef unsigned MyUInt2 "unsigned short"
def test_MySInt2(MySInt2 x):
u"""
>>> test_MySInt2(-1)
-1
>>> test_MySInt2(0)
0
>>> test_MySInt2(1)
1
"""
return x
def test_MyUInt2(MyUInt2 x):
u"""
>>> test_MyUInt2(-1) #doctest: +ELLIPSIS
Traceback (most recent call last):
...
OverflowError: ...
>>> test_MyUInt2(0)
0
>>> test_MyUInt2(1)
1
"""
return x
# -------------------------------------------------------------------
cimport ctypedef_int_types_defs_T333 as defs
def test_DefSInt(defs.SInt x):
u"""
>>> test_DeftSInt(-1)
-1
>>> test_DefSInt(0)
0
>>> test_DefSInt(1)
1
"""
return x
def test_DefUInt(defs.UInt x):
u"""
>>> test_DefUInt(-1) #doctest: +ELLIPSIS
Traceback (most recent call last):
...
OverflowError: ...
>>> test_DefUInt(0)
0
>>> test_DefUInt(1)
1
"""
return x
def test_ExtSInt(defs.ExtSInt x):
u"""
>>> test_ExtSInt(-1)
-1
>>> test_ExtSInt(0)
0
>>> test_ExtSInt(1)
1
"""
return x
def test_ExtUInt(defs.ExtUInt x):
u"""
>>> test_ExtUInt(-1) #doctest: +ELLIPSIS
Traceback (most recent call last):
...
OverflowError: ...
>>> test_ExtUInt(0)
0
>>> test_ExtUInt(1)
1
"""
return x
ctypedef defs.SShort LocSInt
ctypedef defs.UShort LocUInt
def test_LocSInt(LocSInt x):
u"""
>>> test_LocSInt(-1)
-1
>>> test_LocSInt(0)
0
>>> test_LocSInt(1)
1
"""
return x
def test_LocUInt(LocUInt x):
u"""
>>> test_LocUInt(-1) #doctest: +ELLIPSIS
Traceback (most recent call last):
...
OverflowError: ...
>>> test_LocUInt(0)
0
>>> test_LocUInt(1)
1
"""
return x
# -------------------------------------------------------------------
__doc__ = u"".join([
f.__doc__ for f in (
#
test_schar, test_add_schar,
test_uchar, test_add_uchar,
#
test_sshort, test_add_sshort,
test_ushort, test_add_ushort,
#
test_sint, test_add_sint,
test_uint, test_add_uint,
#
test_slong, test_add_slong,
test_ulong, test_add_ulong,
#
test_slonglong, test_add_slonglong,
test_ulonglong, test_add_ulonglong,
#
MyClass,
#
test_MySInt1, test_MyUInt1,
test_MySInt2, test_MyUInt2,
#
test_ExtSInt, test_ExtUInt,
test_LocSInt, test_LocUInt,
)
])
# -------------------------------------------------------------------
typedef signed char SChar;
typedef unsigned char UChar;
typedef signed short SShort;
typedef unsigned short UShort;
typedef signed int SInt;
typedef unsigned int UInt;
typedef signed long SLong;
typedef unsigned long ULong;
typedef signed long long SLongLong;
typedef unsigned long long ULongLong;
cdef extern from "ctypedef_int_types_chdr_T333.h":
ctypedef int SChar ## "signed char"
ctypedef int UChar ## "unsigned char"
ctypedef int SShort ## "signed short"
ctypedef int UShort ## "unsigned short"
ctypedef int SInt ## "signed int"
ctypedef int UInt ## "unsigned int"
ctypedef int SLong ## "signed long"
ctypedef int ULong ## "unsigned long"
ctypedef int SLongLong ## "signed PY_LONG_LONG"
ctypedef int ULongLong ## "unsigned PY_LONG_LONG"
cdef extern from *:
ctypedef int ExtSInt "signed short"
ctypedef int ExtUInt "unsigned short"
__doc__ = u"""
>>> BAR
3
"""
cdef public enum FOO:
BAR = 3
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment