Commit a2cce2b0 authored by Dag Sverre Seljebotn's avatar Dag Sverre Seljebotn

merge

parents 20178844 85e7bd5a
...@@ -3098,7 +3098,7 @@ class AttributeNode(ExprNode): ...@@ -3098,7 +3098,7 @@ class AttributeNode(ExprNode):
self.put_nonecheck(code) self.put_nonecheck(code)
select_code = self.result() select_code = self.result()
if self.type.is_pyobject: if self.type.is_pyobject and self.use_managed_ref:
rhs.make_owned_reference(code) rhs.make_owned_reference(code)
code.put_giveref(rhs.py_result()) code.put_giveref(rhs.py_result())
code.put_gotref(select_code) code.put_gotref(select_code)
......
...@@ -2510,13 +2510,30 @@ refnanny_utility_code = UtilityCode(proto=""" ...@@ -2510,13 +2510,30 @@ refnanny_utility_code = UtilityCode(proto="""
main_method = UtilityCode( main_method = UtilityCode(
impl = """ impl = """
#if PY_MAJOR_VERSION < 3 || (!defined(WIN32) && !defined(MS_WINDOWS)) #ifdef __FreeBSD__
#include <floatingpoint.h>
#endif
#if PY_MAJOR_VERSION < 3
int main(int argc, char** argv) { int main(int argc, char** argv) {
#else #elif defined(WIN32) || defined(MS_WINDOWS)
int wmain(int argc, wchar_t **argv) { int wmain(int argc, wchar_t **argv) {
#else
static int __Pyx_main(int argc, wchar_t **argv) {
#endif #endif
int r = 0; int r = 0;
PyObject* m = NULL; PyObject* m = NULL;
/* 754 requires that FP exceptions run in "no stop" mode by default,
* and until C vendors implement C99's ways to control FP exceptions,
* Python requires non-stop mode. Alas, some platforms enable FP
* exceptions by default. Here we disable them.
*/
#ifdef __FreeBSD__
fp_except_t m;
m = fpgetmask();
fpsetmask(m & ~FP_X_OFL);
#endif
Py_SetProgramName(argv[0]); Py_SetProgramName(argv[0]);
Py_Initialize(); Py_Initialize();
PySys_SetArgv(argc, argv); PySys_SetArgv(argc, argv);
...@@ -2524,17 +2541,157 @@ int wmain(int argc, wchar_t **argv) { ...@@ -2524,17 +2541,157 @@ int wmain(int argc, wchar_t **argv) {
#if PY_MAJOR_VERSION < 3 #if PY_MAJOR_VERSION < 3
init%(module_name)s(); init%(module_name)s();
#else #else
m = PyInit_%(module_name)s(name); m = PyInit_%(module_name)s();
#endif #endif
if (PyErr_Occurred() != NULL) { if (PyErr_Occurred() != NULL) {
r = 1; r = 1;
PyErr_Print(); /* This exits with the right code if SystemExit. */ PyErr_Print(); /* This exits with the right code if SystemExit. */
#if PY_MAJOR_VERSION < 3
if (Py_FlushLine()) PyErr_Clear(); if (Py_FlushLine()) PyErr_Clear();
#endif
} }
Py_XDECREF(m); Py_XDECREF(m);
Py_Finalize(); Py_Finalize();
return r; return r;
} }
#if PY_MAJOR_VERSION >= 3 && !defined(WIN32) && !defined(MS_WINDOWS)
#include <locale.h>
static wchar_t*
__Pyx_char2wchar(char* arg)
{
wchar_t *res;
#ifdef HAVE_BROKEN_MBSTOWCS
/* Some platforms have a broken implementation of
* mbstowcs which does not count the characters that
* would result from conversion. Use an upper bound.
*/
size_t argsize = strlen(arg);
#else
size_t argsize = mbstowcs(NULL, arg, 0);
#endif
size_t count;
unsigned char *in;
wchar_t *out;
#ifdef HAVE_MBRTOWC
mbstate_t mbs;
#endif
if (argsize != (size_t)-1) {
res = (wchar_t *)PyMem_Malloc((argsize+1)*sizeof(wchar_t));
if (!res)
goto oom;
count = mbstowcs(res, arg, argsize+1);
if (count != (size_t)-1) {
wchar_t *tmp;
/* Only use the result if it contains no
surrogate characters. */
for (tmp = res; *tmp != 0 &&
(*tmp < 0xd800 || *tmp > 0xdfff); tmp++)
;
if (*tmp == 0)
return res;
}
PyMem_Free(res);
}
/* Conversion failed. Fall back to escaping with surrogateescape. */
#ifdef HAVE_MBRTOWC
/* Try conversion with mbrtwoc (C99), and escape non-decodable bytes. */
/* Overallocate; as multi-byte characters are in the argument, the
actual output could use less memory. */
argsize = strlen(arg) + 1;
res = PyMem_Malloc(argsize*sizeof(wchar_t));
if (!res) goto oom;
in = (unsigned char*)arg;
out = res;
memset(&mbs, 0, sizeof mbs);
while (argsize) {
size_t converted = mbrtowc(out, (char*)in, argsize, &mbs);
if (converted == 0)
/* Reached end of string; null char stored. */
break;
if (converted == (size_t)-2) {
/* Incomplete character. This should never happen,
since we provide everything that we have -
unless there is a bug in the C library, or I
misunderstood how mbrtowc works. */
fprintf(stderr, "unexpected mbrtowc result -2\\n");
return NULL;
}
if (converted == (size_t)-1) {
/* Conversion error. Escape as UTF-8b, and start over
in the initial shift state. */
*out++ = 0xdc00 + *in++;
argsize--;
memset(&mbs, 0, sizeof mbs);
continue;
}
if (*out >= 0xd800 && *out <= 0xdfff) {
/* Surrogate character. Escape the original
byte sequence with surrogateescape. */
argsize -= converted;
while (converted--)
*out++ = 0xdc00 + *in++;
continue;
}
/* successfully converted some bytes */
in += converted;
argsize -= converted;
out++;
}
#else
/* Cannot use C locale for escaping; manually escape as if charset
is ASCII (i.e. escape all bytes > 128. This will still roundtrip
correctly in the locale's charset, which must be an ASCII superset. */
res = PyMem_Malloc((strlen(arg)+1)*sizeof(wchar_t));
if (!res) goto oom;
in = (unsigned char*)arg;
out = res;
while(*in)
if(*in < 128)
*out++ = *in++;
else
*out++ = 0xdc00 + *in++;
*out = 0;
#endif
return res;
oom:
fprintf(stderr, "out of memory\\n");
return NULL;
}
int
main(int argc, char **argv)
{
wchar_t **argv_copy = (wchar_t **)PyMem_Malloc(sizeof(wchar_t*)*argc);
/* We need a second copies, as Python might modify the first one. */
wchar_t **argv_copy2 = (wchar_t **)PyMem_Malloc(sizeof(wchar_t*)*argc);
int i, res;
char *oldloc;
if (!argv_copy || !argv_copy2) {
fprintf(stderr, "out of memory\\n");
return 1;
}
oldloc = strdup(setlocale(LC_ALL, NULL));
setlocale(LC_ALL, "");
for (i = 0; i < argc; i++) {
argv_copy2[i] = argv_copy[i] = __Pyx_char2wchar(argv[i]);
if (!argv_copy[i])
return 1;
}
setlocale(LC_ALL, oldloc);
free(oldloc);
res = __Pyx_main(argc, argv_copy);
for (i = 0; i < argc; i++) {
PyMem_Free(argv_copy2[i]);
}
PyMem_Free(argv_copy);
PyMem_Free(argv_copy2);
return res;
}
#endif
""") """)
packed_struct_utility_code = UtilityCode(proto=""" packed_struct_utility_code = UtilityCode(proto="""
......
...@@ -634,8 +634,8 @@ class DropRefcountingTransform(Visitor.VisitorTransform): ...@@ -634,8 +634,8 @@ class DropRefcountingTransform(Visitor.VisitorTransform):
if left_names or right_names: if left_names or right_names:
# lhs/rhs names must be a non-redundant permutation # lhs/rhs names must be a non-redundant permutation
lnames = [n.name for n in left_names] lnames = [ path for path, n in left_names ]
rnames = [n.name for n in right_names] rnames = [ path for path, n in right_names ]
if set(lnames) != set(rnames): if set(lnames) != set(rnames):
return node return node
if len(set(lnames)) != len(right_names): if len(set(lnames)) != len(right_names):
...@@ -670,7 +670,7 @@ class DropRefcountingTransform(Visitor.VisitorTransform): ...@@ -670,7 +670,7 @@ class DropRefcountingTransform(Visitor.VisitorTransform):
for temp in temps: for temp in temps:
temp.use_managed_ref = False temp.use_managed_ref = False
for name_node in left_names + right_names: for _, name_node in left_names + right_names:
if name_node not in temp_args: if name_node not in temp_args:
name_node.use_managed_ref = False name_node.use_managed_ref = False
...@@ -686,10 +686,16 @@ class DropRefcountingTransform(Visitor.VisitorTransform): ...@@ -686,10 +686,16 @@ class DropRefcountingTransform(Visitor.VisitorTransform):
if isinstance(node, ExprNodes.CoerceToTempNode): if isinstance(node, ExprNodes.CoerceToTempNode):
temps.append(node) temps.append(node)
node = node.arg node = node.arg
if isinstance(node, ExprNodes.NameNode): name_path = []
if node.entry.is_builtin or node.entry.is_pyglobal: obj_node = node
while isinstance(obj_node, ExprNodes.AttributeNode):
if obj_node.is_py_attr:
return False return False
names.append(node) name_path.append(obj_node.member)
obj_node = obj_node.obj
if isinstance(obj_node, ExprNodes.NameNode):
name_path.append(obj_node.name)
names.append( ('.'.join(name_path[::-1]), node) )
elif isinstance(node, ExprNodes.IndexNode): elif isinstance(node, ExprNodes.IndexNode):
if node.base.type != Builtin.list_type: if node.base.type != Builtin.list_type:
return False return False
......
...@@ -4,11 +4,11 @@ CYTHON_FREEZE = ../../bin/cython_freeze ...@@ -4,11 +4,11 @@ CYTHON_FREEZE = ../../bin/cython_freeze
PYTHON = python PYTHON = python
RST2HTML = rst2html RST2HTML = rst2html
PY_LDFLAGS = $(shell $(PYTHON) -c 'from distutils.sysconfig import get_config_var as g; print " ".join([g("LINKFORSHARED"), "-L"+g("LIBPL")])') PY_LDFLAGS = $(shell $(PYTHON) -c 'from distutils.sysconfig import get_config_var as g; import sys; sys.stdout.write(" ".join([g("LINKFORSHARED"), "-L"+g("LIBPL")]) + "\n")')
PY_CPPFLAGS = $(shell $(PYTHON) -c 'from distutils.sysconfig import *; print "-I"+get_python_inc()') PY_CPPFLAGS = $(shell $(PYTHON) -c 'from distutils.sysconfig import *; import sys; sys.stdout.write("-I"+get_python_inc() + "\n")')
PY_LDLIBS = $(shell $(PYTHON) -c 'from distutils.sysconfig import get_config_var as g; print " ".join(["-lpython"+g("VERSION"), g("SYSLIBS"), g("LIBS"), g("LOCALMODLIBS")])') PY_LDLIBS = $(shell $(PYTHON) -c 'from distutils.sysconfig import get_config_var as g; import sys; sys.stdout.write(" ".join(["-lpython"+g("VERSION"), g("SYSLIBS"), g("LIBS"), g("LOCALMODLIBS")]) + "\n")')
CFLAGS = -fPIC -g -O2 -Wall -Wextra CFLAGS = -fPIC -fno-strict-aliasing -g -O2 -Wall -Wextra
CPPFLAGS = $(PY_CPPFLAGS) CPPFLAGS = $(PY_CPPFLAGS)
LDFLAGS = $(PY_LDFLAGS) LDFLAGS = $(PY_LDFLAGS)
LDLIBS = $(PY_LDLIBS) LDLIBS = $(PY_LDLIBS)
......
...@@ -19,6 +19,6 @@ if __name__ == "__main__": ...@@ -19,6 +19,6 @@ if __name__ == "__main__":
import sys import sys
if len(sys.argv) != 2: if len(sys.argv) != 2:
sys.stderr.write("USAGE: %s n\nPrints n!.\n" % sys.argv[0]) sys.stderr.write("USAGE: %s n\nPrints n!.\n" % sys.argv[0])
sys.exit(1) sys.exit(2)
n, = map(float, sys.argv[1:]) n, = map(float, sys.argv[1:])
print factorial(n) print factorial(n)
...@@ -9,6 +9,6 @@ if __name__ == "__main__": ...@@ -9,6 +9,6 @@ if __name__ == "__main__":
import sys import sys
if len(sys.argv) != 3: if len(sys.argv) != 3:
sys.stderr.write("USAGE: %s n r\nPrints n-choose-r.\n" % sys.argv[0]) sys.stderr.write("USAGE: %s n r\nPrints n-choose-r.\n" % sys.argv[0])
sys.exit(1) sys.exit(2)
n, r = map(float, sys.argv[1:]) n, r = map(float, sys.argv[1:])
print nCr(n, r) print nCr(n, r)
This diff is collapsed.
...@@ -38,9 +38,14 @@ modules = [format_modname(x) for x in args] ...@@ -38,9 +38,14 @@ modules = [format_modname(x) for x in args]
print """\ print """\
#include <Python.h> #include <Python.h>
#include <locale.h>
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
#ifdef __FreeBSD__
#include <floatingpoint.h>
#endif
#if PY_MAJOR_VERSION < 3 #if PY_MAJOR_VERSION < 3
# define MODINIT(name) init ## name # define MODINIT(name) init ## name
#else #else
...@@ -65,10 +70,12 @@ if not options.pymain: ...@@ -65,10 +70,12 @@ if not options.pymain:
print "\nextern int __pyx_module_is_main_%s;" % modules[0] print "\nextern int __pyx_module_is_main_%s;" % modules[0]
print """ print """
#if PY_MAJOR_VERSION < 3 || (!defined(WIN32) && !defined(MS_WINDOWS)) #if PY_MAJOR_VERSION < 3
int main(int argc, char** argv) { int main(int argc, char** argv) {
#else #elif defined(WIN32) || defined(MS_WINDOWS)
int wmain(int argc, wchar_t **argv) { int wmain(int argc, wchar_t **argv) {
#else
static int python_main(int argc, wchar_t **argv) {
#endif #endif
""", """,
if not options.pymain: if not options.pymain:
...@@ -77,6 +84,17 @@ if not options.pymain: ...@@ -77,6 +84,17 @@ if not options.pymain:
int r = 0; int r = 0;
""", """,
print """\ print """\
/* 754 requires that FP exceptions run in "no stop" mode by default,
* and until C vendors implement C99's ways to control FP exceptions,
* Python requires non-stop mode. Alas, some platforms enable FP
* exceptions by default. Here we disable them.
*/
#ifdef __FreeBSD__
fp_except_t m;
m = fpgetmask();
fpsetmask(m & ~FP_X_OFL);
#endif
if (PyImport_ExtendInittab(inittab)) { if (PyImport_ExtendInittab(inittab)) {
fprintf(stderr, "No memory\\n"); fprintf(stderr, "No memory\\n");
exit(1); exit(1);
...@@ -97,11 +115,149 @@ else: ...@@ -97,11 +115,149 @@ else:
if (!m) { if (!m) {
r = 1; r = 1;
PyErr_Print(); /* This exits with the right code if SystemExit. */ PyErr_Print(); /* This exits with the right code if SystemExit. */
#if PY_MAJOR_VERSION < 3
if (Py_FlushLine()) if (Py_FlushLine())
PyErr_Clear(); PyErr_Clear();
#endif
} }
Py_XDECREF(m); Py_XDECREF(m);
Py_Finalize(); Py_Finalize();
return r; return r;
} }
""" % {'main' : modules[0]}, """ % {'main' : modules[0]},
print r"""
#if PY_MAJOR_VERSION >= 3 && !defined(WIN32) && !defined(MS_WINDOWS)
static wchar_t*
char2wchar(char* arg)
{
wchar_t *res;
#ifdef HAVE_BROKEN_MBSTOWCS
/* Some platforms have a broken implementation of
* mbstowcs which does not count the characters that
* would result from conversion. Use an upper bound.
*/
size_t argsize = strlen(arg);
#else
size_t argsize = mbstowcs(NULL, arg, 0);
#endif
size_t count;
unsigned char *in;
wchar_t *out;
#ifdef HAVE_MBRTOWC
mbstate_t mbs;
#endif
if (argsize != (size_t)-1) {
res = (wchar_t *)PyMem_Malloc((argsize+1)*sizeof(wchar_t));
if (!res)
goto oom;
count = mbstowcs(res, arg, argsize+1);
if (count != (size_t)-1) {
wchar_t *tmp;
/* Only use the result if it contains no
surrogate characters. */
for (tmp = res; *tmp != 0 &&
(*tmp < 0xd800 || *tmp > 0xdfff); tmp++)
;
if (*tmp == 0)
return res;
}
PyMem_Free(res);
}
/* Conversion failed. Fall back to escaping with surrogateescape. */
#ifdef HAVE_MBRTOWC
/* Try conversion with mbrtwoc (C99), and escape non-decodable bytes. */
/* Overallocate; as multi-byte characters are in the argument, the
actual output could use less memory. */
argsize = strlen(arg) + 1;
res = PyMem_Malloc(argsize*sizeof(wchar_t));
if (!res) goto oom;
in = (unsigned char*)arg;
out = res;
memset(&mbs, 0, sizeof mbs);
while (argsize) {
size_t converted = mbrtowc(out, (char*)in, argsize, &mbs);
if (converted == 0)
/* Reached end of string; null char stored. */
break;
if (converted == (size_t)-2) {
/* Incomplete character. This should never happen,
since we provide everything that we have -
unless there is a bug in the C library, or I
misunderstood how mbrtowc works. */
fprintf(stderr, "unexpected mbrtowc result -2\n");
return NULL;
}
if (converted == (size_t)-1) {
/* Conversion error. Escape as UTF-8b, and start over
in the initial shift state. */
*out++ = 0xdc00 + *in++;
argsize--;
memset(&mbs, 0, sizeof mbs);
continue;
}
if (*out >= 0xd800 && *out <= 0xdfff) {
/* Surrogate character. Escape the original
byte sequence with surrogateescape. */
argsize -= converted;
while (converted--)
*out++ = 0xdc00 + *in++;
continue;
}
/* successfully converted some bytes */
in += converted;
argsize -= converted;
out++;
}
#else
/* Cannot use C locale for escaping; manually escape as if charset
is ASCII (i.e. escape all bytes > 128. This will still roundtrip
correctly in the locale's charset, which must be an ASCII superset. */
res = PyMem_Malloc((strlen(arg)+1)*sizeof(wchar_t));
if (!res) goto oom;
in = (unsigned char*)arg;
out = res;
while(*in)
if(*in < 128)
*out++ = *in++;
else
*out++ = 0xdc00 + *in++;
*out = 0;
#endif
return res;
oom:
fprintf(stderr, "out of memory\n");
return NULL;
}
int
main(int argc, char **argv)
{
wchar_t **argv_copy = (wchar_t **)PyMem_Malloc(sizeof(wchar_t*)*argc);
/* We need a second copies, as Python might modify the first one. */
wchar_t **argv_copy2 = (wchar_t **)PyMem_Malloc(sizeof(wchar_t*)*argc);
int i, res;
char *oldloc;
if (!argv_copy || !argv_copy2) {
fprintf(stderr, "out of memory\n");
return 1;
}
oldloc = strdup(setlocale(LC_ALL, NULL));
setlocale(LC_ALL, "");
for (i = 0; i < argc; i++) {
argv_copy2[i] = argv_copy[i] = char2wchar(argv[i]);
if (!argv_copy[i])
return 1;
}
setlocale(LC_ALL, oldloc);
free(oldloc);
res = python_main(argc, argv_copy);
for (i = 0; i < argc; i++) {
PyMem_Free(argv_copy2[i]);
}
PyMem_Free(argv_copy);
PyMem_Free(argv_copy2);
return res;
}
#endif"""
cdef f(void=None):
pass
cdef struct foo:
int void
cdef class Foo:
cdef int void
cdef extern void spam(char *s)
cdef struct Grail:
char silly[42]
cdef void eggs():
cdef char silly[42]
cdef Grail grail
spam(silly)
spam(grail.silly)
eggs()
cdef cf(default=None):
return default
cpdef cpf(default=None):
"""
>>> cpf()
None
>>> cpf(1)
1
>>> cpf(default=2)
2
"""
default = cf(default)
return default
def pf(default=None):
"""
>>> pf()
None
>>> pf(1)
1
>>> pf(default=2)
2
"""
return default
cdef struct foo:
int void
int default
def test_struct():
"""
>>> test_struct()
(1, 2)
"""
cdef foo foo_struct
foo_struct.void = 1
foo_struct.default = 2
return foo_struct.void, foo_struct.default
cdef class Foo:
cdef int void
cdef int default
def test_class():
"""
>>> test_class()
(1, 2)
"""
cdef Foo foo_instance = Foo()
foo_instance.void = 1
foo_instance.default = 2
return foo_instance.void, foo_instance.default
...@@ -8,7 +8,7 @@ cdef char* cstring = "abcABCqtp" ...@@ -8,7 +8,7 @@ cdef char* cstring = "abcABCqtp"
def slice_charptr_end(): def slice_charptr_end():
""" """
>>> print str(slice_charptr_end()).replace("b'", "'") >>> print(str(slice_charptr_end()).replace("b'", "'"))
('a', 'abc', 'abcABCqtp') ('a', 'abc', 'abcABCqtp')
""" """
return cstring[:1], cstring[:3], cstring[:9] return cstring[:1], cstring[:3], cstring[:9]
...@@ -17,7 +17,7 @@ def slice_charptr_end(): ...@@ -17,7 +17,7 @@ def slice_charptr_end():
@cython.test_fail_if_path_exists("//AttributeNode") @cython.test_fail_if_path_exists("//AttributeNode")
def slice_charptr_decode(): def slice_charptr_decode():
""" """
>>> print str(slice_charptr_decode()).replace("u'", "'") >>> print(str(slice_charptr_decode()).replace("u'", "'"))
('a', 'abc', 'abcABCqtp') ('a', 'abc', 'abcABCqtp')
""" """
return (cstring[:1].decode('UTF-8'), return (cstring[:1].decode('UTF-8'),
...@@ -28,7 +28,7 @@ def slice_charptr_decode(): ...@@ -28,7 +28,7 @@ def slice_charptr_decode():
@cython.test_fail_if_path_exists("//AttributeNode") @cython.test_fail_if_path_exists("//AttributeNode")
def slice_charptr_decode_unbound(): def slice_charptr_decode_unbound():
""" """
>>> print str(slice_charptr_decode_unbound()).replace("u'", "'") >>> print(str(slice_charptr_decode_unbound()).replace("u'", "'"))
('a', 'abc', 'abcABCqtp') ('a', 'abc', 'abcABCqtp')
""" """
return (bytes.decode(cstring[:1], 'UTF-8'), return (bytes.decode(cstring[:1], 'UTF-8'),
...@@ -39,7 +39,7 @@ def slice_charptr_decode_unbound(): ...@@ -39,7 +39,7 @@ def slice_charptr_decode_unbound():
@cython.test_fail_if_path_exists("//AttributeNode") @cython.test_fail_if_path_exists("//AttributeNode")
def slice_charptr_decode_errormode(): def slice_charptr_decode_errormode():
""" """
>>> print str(slice_charptr_decode_errormode()).replace("u'", "'") >>> print(str(slice_charptr_decode_errormode()).replace("u'", "'"))
('a', 'abc', 'abcABCqtp') ('a', 'abc', 'abcABCqtp')
""" """
return (cstring[:1].decode('UTF-8', 'strict'), return (cstring[:1].decode('UTF-8', 'strict'),
...@@ -56,9 +56,9 @@ def slice_charptr_for_loop_py(): ...@@ -56,9 +56,9 @@ def slice_charptr_for_loop_py():
['b', 'c', 'A', 'B'] ['b', 'c', 'A', 'B']
['B', 'C', 'q', 't', 'p'] ['B', 'C', 'q', 't', 'p']
""" """
print str([ c for c in cstring[:3] ]).replace(" b'", "'").replace("[b'", "'") print str([ c for c in cstring[:3] ]).replace(" b'", " '").replace("[b'", "['")
print str([ c for c in cstring[1:5] ]).replace(" b'", "'").replace("[b'", "'") print str([ c for c in cstring[1:5] ]).replace(" b'", " '").replace("[b'", "['")
print str([ c for c in cstring[4:9] ]).replace(" b'", "'") print str([ c for c in cstring[4:9] ]).replace(" b'", " '").replace("[b'", "['")
@cython.test_assert_path_exists("//ForFromStatNode", @cython.test_assert_path_exists("//ForFromStatNode",
"//ForFromStatNode//IndexNode") "//ForFromStatNode//IndexNode")
...@@ -71,9 +71,9 @@ def slice_charptr_for_loop_c(): ...@@ -71,9 +71,9 @@ def slice_charptr_for_loop_c():
['B', 'C', 'q', 't', 'p'] ['B', 'C', 'q', 't', 'p']
""" """
cdef char c cdef char c
print map(chr, [ c for c in cstring[:3] ]) print [ chr(c) for c in cstring[:3] ]
print map(chr, [ c for c in cstring[1:5] ]) print [ chr(c) for c in cstring[1:5] ]
print map(chr, [ c for c in cstring[4:9] ]) print [ chr(c) for c in cstring[4:9] ]
@cython.test_assert_path_exists("//ForFromStatNode", @cython.test_assert_path_exists("//ForFromStatNode",
"//ForFromStatNode//SliceIndexNode") "//ForFromStatNode//SliceIndexNode")
...@@ -85,9 +85,9 @@ def slice_charptr_for_loop_py_enumerate(): ...@@ -85,9 +85,9 @@ def slice_charptr_for_loop_py_enumerate():
[(0, 'b'), (1, 'c'), (2, 'A'), (3, 'B')] [(0, 'b'), (1, 'c'), (2, 'A'), (3, 'B')]
[(0, 'B'), (1, 'C'), (2, 'q'), (3, 't'), (4, 'p')] [(0, 'B'), (1, 'C'), (2, 'q'), (3, 't'), (4, 'p')]
""" """
print [ (i,c) for i,c in enumerate(cstring[:3]) ] print str([ (i,c) for i,c in enumerate(cstring[:3]) ]).replace(" b'", " '")
print [ (i,c) for i,c in enumerate(cstring[1:5]) ] print str([ (i,c) for i,c in enumerate(cstring[1:5]) ]).replace(" b'", " '")
print [ (i,c) for i,c in enumerate(cstring[4:9]) ] print str([ (i,c) for i,c in enumerate(cstring[4:9]) ]).replace(" b'", " '")
@cython.test_assert_path_exists("//ForFromStatNode", @cython.test_assert_path_exists("//ForFromStatNode",
"//ForFromStatNode//IndexNode") "//ForFromStatNode//IndexNode")
......
...@@ -76,6 +76,18 @@ Traceback (most recent call last): ...@@ -76,6 +76,18 @@ Traceback (most recent call last):
OverflowError: value too large to perform division OverflowError: value too large to perform division
""" """
def _all(seq):
for x in seq:
if not x:
return False
return True
try:
all
except NameError:
all = _all
cimport cython cimport cython
@cython.cdivision(False) @cython.cdivision(False)
......
cdef char* cstring = "abcdefg"
cdef void spam(char *target):
cdef char* s = cstring
while s[0]:
target[0] = s[0]
s += 1
target += 1
target[0] = c'\0'
cdef struct Grail:
char silly[42]
def eggs():
"""
>>> print(str(eggs()).replace("b'", "'"))
('abcdefg', 'abcdefg')
"""
cdef char silly[42]
cdef Grail grail
spam(silly)
spam(grail.silly)
return silly, grail.silly
...@@ -5,7 +5,7 @@ __doc__ = u""" ...@@ -5,7 +5,7 @@ __doc__ = u"""
>>> print(sys.exc_info()[0]) # 0 >>> print(sys.exc_info()[0]) # 0
None None
>>> exc = test_c() >>> exc = test_c()
>>> type(exc) is TestException >>> isinstance(exc, TestException) or exc
True True
>>> print(sys.exc_info()[0]) # test_c() >>> print(sys.exc_info()[0]) # test_c()
None None
......
...@@ -51,7 +51,8 @@ TypeError: 'int' object is unsubscriptable ...@@ -51,7 +51,8 @@ TypeError: 'int' object is unsubscriptable
import sys import sys
if sys.version_info[0] >= 3: if sys.version_info[0] >= 3:
__doc__ = __doc__.replace(u'is unsubscriptable', u'is not subscriptable') __doc__ = __doc__.replace(u'is unsubscriptable', u'is not subscriptable')
elif sys.version_info < (2,5):
__doc__ = __doc__.replace(u"'int' object is unsubscriptable", u'unsubscriptable object')
def index_tuple(tuple t, int i): def index_tuple(tuple t, int i):
return t[i] return t[i]
......
...@@ -68,10 +68,46 @@ def swap_cmp5(a,b,c,d,e): ...@@ -68,10 +68,46 @@ def swap_cmp5(a,b,c,d,e):
"//ParallelAssignmentNode/SingleAssignmentNode//CoerceToTempNode[@use_managed_ref=False]", "//ParallelAssignmentNode/SingleAssignmentNode//CoerceToTempNode[@use_managed_ref=False]",
) )
def swap_py(a,b): def swap_py(a,b):
"""
>>> swap_py(1,2)
(1, 2)
"""
a,a = b,a a,a = b,a
return a,b return a,b
cdef class A:
cdef readonly object x
cdef readonly object y
def __init__(self, x, y):
self.x, self.y = x, y
@cython.test_assert_path_exists(
"//ParallelAssignmentNode",
"//ParallelAssignmentNode/SingleAssignmentNode",
"//ParallelAssignmentNode/SingleAssignmentNode/CoerceToTempNode",
"//ParallelAssignmentNode/SingleAssignmentNode/CoerceToTempNode[@use_managed_ref=False]",
"//ParallelAssignmentNode/SingleAssignmentNode//AttributeNode/NameNode",
"//ParallelAssignmentNode/SingleAssignmentNode//AttributeNode[@use_managed_ref=False]/NameNode",
)
@cython.test_fail_if_path_exists(
"//ParallelAssignmentNode/SingleAssignmentNode/CoerceToTempNode[@use_managed_ref=True]",
"//ParallelAssignmentNode/SingleAssignmentNode/AttributeNode[@use_managed_ref=True]",
)
def swap_attr_values(A a, A b):
"""
>>> a, b = A(1,2), A(3,4)
>>> a.x, a.y, b.x, b.y
(1, 2, 3, 4)
>>> swap_attr_values(a,b)
>>> a.x, a.y, b.x, b.y
(3, 2, 1, 4)
"""
a.x, a.y, b.x, b.y = a.y, b.x, b.y, a.x # shift by one
a.x, a.y, b.x, b.y = b.x, b.y, a.x, a.y # shift by two
a.x, a.y, b.x, b.y = b.y, b.x, a.y, a.x # reverse
@cython.test_assert_path_exists( @cython.test_assert_path_exists(
# "//ParallelAssignmentNode", # "//ParallelAssignmentNode",
# "//ParallelAssignmentNode/SingleAssignmentNode", # "//ParallelAssignmentNode/SingleAssignmentNode",
......
...@@ -23,6 +23,13 @@ __doc__ = u""" ...@@ -23,6 +23,13 @@ __doc__ = u"""
>>> os.unlink(statsfile) >>> os.unlink(statsfile)
""" """
import sys
if sys.version_info < (2,5):
# disable in earlier versions
__doc__ = """
>>> # nothing to test here ...
"""
cimport cython cimport cython
def test_profile(long N): def test_profile(long N):
......
...@@ -36,8 +36,7 @@ True ...@@ -36,8 +36,7 @@ True
""" """
# recoding/escaping is required to properly pass the literals to doctest # recoding/escaping is required to properly pass the literals to doctest
).encode('unicode_escape').decode('ASCII') ).encode('unicode_escape').decode('ASCII').replace(u'\\n', u'\n')
a = 'abc' a = 'abc'
s = 'ao' s = 'ao'
......
...@@ -19,6 +19,12 @@ __doc__ = u""" ...@@ -19,6 +19,12 @@ __doc__ = u"""
TypeError: 'NoneType' object is not iterable TypeError: 'NoneType' object is not iterable
""" """
import sys
if sys.version_info < (2,5):
__doc__ = __doc__.replace(
u"'NoneType' object is not iterable\n >>> tuple_none_list()",
u'iteration over non-sequence\n >>> tuple_none_list()')
def f(obj1, obj2, obj3, obj4, obj5): def f(obj1, obj2, obj3, obj4, obj5):
obj1 = () obj1 = ()
return obj1 return obj1
......
...@@ -38,6 +38,11 @@ enter ...@@ -38,6 +38,11 @@ enter
exit <type 'NoneType'> <type 'NoneType'> <type 'NoneType'> exit <type 'NoneType'> <type 'NoneType'> <type 'NoneType'>
""" """
import sys
if sys.version_info < (2,5):
__doc__ = __doc__.replace(u"exit <type 'type'> <type 'MyException'>",
u"exit <type 'classobj'> <type 'instance'>")
def typename(t): def typename(t):
return u"<type '%s'>" % type(t).__name__ return u"<type '%s'>" % type(t).__name__
......
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