You can subscribe to this list here.
2000 |
Jan
|
Feb
|
Mar
|
Apr
|
May
|
Jun
|
Jul
|
Aug
|
Sep
|
Oct
(1) |
Nov
(107) |
Dec
(67) |
---|---|---|---|---|---|---|---|---|---|---|---|---|
2001 |
Jan
(76) |
Feb
(125) |
Mar
(72) |
Apr
(13) |
May
(18) |
Jun
(12) |
Jul
(129) |
Aug
(47) |
Sep
(1) |
Oct
(36) |
Nov
(128) |
Dec
(124) |
2002 |
Jan
(59) |
Feb
|
Mar
(14) |
Apr
(14) |
May
(72) |
Jun
(9) |
Jul
(3) |
Aug
(5) |
Sep
(18) |
Oct
(65) |
Nov
(28) |
Dec
(12) |
2003 |
Jan
(10) |
Feb
(2) |
Mar
(4) |
Apr
(33) |
May
(21) |
Jun
(9) |
Jul
(29) |
Aug
(34) |
Sep
(4) |
Oct
(8) |
Nov
(15) |
Dec
(4) |
2004 |
Jan
(26) |
Feb
(12) |
Mar
(11) |
Apr
(9) |
May
(7) |
Jun
|
Jul
(5) |
Aug
|
Sep
(3) |
Oct
(7) |
Nov
(1) |
Dec
(10) |
2005 |
Jan
(2) |
Feb
(72) |
Mar
(16) |
Apr
(39) |
May
(48) |
Jun
(97) |
Jul
(57) |
Aug
(13) |
Sep
(16) |
Oct
(24) |
Nov
(100) |
Dec
(24) |
2006 |
Jan
(15) |
Feb
(34) |
Mar
(33) |
Apr
(31) |
May
(79) |
Jun
(64) |
Jul
(41) |
Aug
(64) |
Sep
(31) |
Oct
(46) |
Nov
(55) |
Dec
(37) |
2007 |
Jan
(32) |
Feb
(61) |
Mar
(11) |
Apr
(58) |
May
(46) |
Jun
(30) |
Jul
(94) |
Aug
(93) |
Sep
(86) |
Oct
(69) |
Nov
(125) |
Dec
(177) |
2008 |
Jan
(169) |
Feb
(97) |
Mar
(74) |
Apr
(113) |
May
(120) |
Jun
(334) |
Jul
(215) |
Aug
(237) |
Sep
(72) |
Oct
(189) |
Nov
(126) |
Dec
(160) |
2009 |
Jan
(180) |
Feb
(45) |
Mar
(98) |
Apr
(140) |
May
(151) |
Jun
(71) |
Jul
(107) |
Aug
(119) |
Sep
(73) |
Oct
(121) |
Nov
(14) |
Dec
(6) |
2010 |
Jan
(13) |
Feb
(9) |
Mar
(10) |
Apr
(64) |
May
(3) |
Jun
(16) |
Jul
(7) |
Aug
(23) |
Sep
(17) |
Oct
(37) |
Nov
(5) |
Dec
(8) |
2011 |
Jan
(10) |
Feb
(11) |
Mar
(77) |
Apr
(11) |
May
(2) |
Jun
|
Jul
|
Aug
|
Sep
|
Oct
|
Nov
|
Dec
|
From: <fwi...@us...> - 2008-07-08 10:00:07
|
Revision: 4873 http://jython.svn.sourceforge.net/jython/?rev=4873&view=rev Author: fwierzbicki Date: 2008-07-08 03:00:05 -0700 (Tue, 08 Jul 2008) Log Message: ----------- new example files for django demo. Added Paths: ----------- trunk/sandbox/wierzbicki/javaone2008/mysite/templates/world/ trunk/sandbox/wierzbicki/javaone2008/mysite/templates/world/city.html trunk/sandbox/wierzbicki/javaone2008/mysite/templates/world/index.html trunk/sandbox/wierzbicki/javaone2008/mysite/world/urls.py Added: trunk/sandbox/wierzbicki/javaone2008/mysite/templates/world/city.html =================================================================== --- trunk/sandbox/wierzbicki/javaone2008/mysite/templates/world/city.html (rev 0) +++ trunk/sandbox/wierzbicki/javaone2008/mysite/templates/world/city.html 2008-07-08 10:00:05 UTC (rev 4873) @@ -0,0 +1 @@ +{{ city.name }} Added: trunk/sandbox/wierzbicki/javaone2008/mysite/templates/world/index.html =================================================================== --- trunk/sandbox/wierzbicki/javaone2008/mysite/templates/world/index.html (rev 0) +++ trunk/sandbox/wierzbicki/javaone2008/mysite/templates/world/index.html 2008-07-08 10:00:05 UTC (rev 4873) @@ -0,0 +1,9 @@ +{% if five_cities %} + <ul> + {% for c in five_cities %} + <li>{{ c.name }}</li> + {% endfor %} + </ul> +{% else %} + <p>No cities are available.</p> +{% endif %} Added: trunk/sandbox/wierzbicki/javaone2008/mysite/world/urls.py =================================================================== --- trunk/sandbox/wierzbicki/javaone2008/mysite/world/urls.py (rev 0) +++ trunk/sandbox/wierzbicki/javaone2008/mysite/world/urls.py 2008-07-08 10:00:05 UTC (rev 4873) @@ -0,0 +1,6 @@ +from django.conf.urls.defaults import * + +urlpatterns = patterns('mysite.world.views', + (r'^world/$', 'index'), + (r'^world/(?P<city_id>\d+)/$', 'city'), +) This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <fwi...@us...> - 2008-07-08 09:57:26
|
Revision: 4872 http://jython.svn.sourceforge.net/jython/?rev=4872&view=rev Author: fwierzbicki Date: 2008-07-08 02:57:24 -0700 (Tue, 08 Jul 2008) Log Message: ----------- example code updates Modified Paths: -------------- trunk/sandbox/wierzbicki/javaone2008/countries.py trunk/sandbox/wierzbicki/javaone2008/mysite/world/models.py Modified: trunk/sandbox/wierzbicki/javaone2008/countries.py =================================================================== --- trunk/sandbox/wierzbicki/javaone2008/countries.py 2008-07-08 09:00:26 UTC (rev 4871) +++ trunk/sandbox/wierzbicki/javaone2008/countries.py 2008-07-08 09:57:24 UTC (rev 4872) @@ -288,7 +288,7 @@ MUS.save() MYT = Country(code='MYT', name='Mayotte',continent=Africa, region='Eastern Africa', surface_area=373.00, indep_year=None, population=149000, life_expectancy=59.5, gnp=0.00, gnp_old=None, local_name='Mayotte', government_form='Territorial Collectivity of France', head_of_state='Jacques Chirac',capital=None,code2='YT') MYT.save() -MEX = Country(code='MEX', name='Mexico',continent=North_America, region='Central America', surface_area=1958201.00, indep_year=1810, population=98881000, life_expectancy=71.5, gnp=414972.00, gnp_old=401461.00, local_name='México', government_form='Federal Republic', head_of_state='Vicente Fox Quesada',capital=None,code2='MX') +MEX = Country(code='MEX', name='Mexico',continent=North_America, region='Central America', surface_area=1958201.00, indep_year=1810, population=98881000, life_expectancy=71.5, gnp=414972.00, gnp_old=401461.00, local_name='Mexico', government_form='Federal Republic', head_of_state='Vicente Fox Quesada',capital=None,code2='MX') MEX.save() FSM = Country(code='FSM', name='Micronesia, Federated States of',continent=Oceania, region='Micronesia', surface_area=702.00, indep_year=1990, population=119000, life_expectancy=68.6, gnp=212.00, gnp_old=None, local_name='Micronesia', government_form='Federal Republic', head_of_state='Leo A. Falcam',capital=None,code2='FM') FSM.save() Modified: trunk/sandbox/wierzbicki/javaone2008/mysite/world/models.py =================================================================== --- trunk/sandbox/wierzbicki/javaone2008/mysite/world/models.py 2008-07-08 09:00:26 UTC (rev 4871) +++ trunk/sandbox/wierzbicki/javaone2008/mysite/world/models.py 2008-07-08 09:57:24 UTC (rev 4872) @@ -66,7 +66,7 @@ list_display = ('name', 'country', 'district', - 'population', + #'population', ) list_filter = ('country', This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <fwi...@us...> - 2008-07-08 09:00:27
|
Revision: 4871 http://jython.svn.sourceforge.net/jython/?rev=4871&view=rev Author: fwierzbicki Date: 2008-07-08 02:00:26 -0700 (Tue, 08 Jul 2008) Log Message: ----------- depend on jython-complete.jar now. Modified Paths: -------------- branches/installer25/src/java/org/python/util/install/JarInstaller.java Modified: branches/installer25/src/java/org/python/util/install/JarInstaller.java =================================================================== --- branches/installer25/src/java/org/python/util/install/JarInstaller.java 2008-07-08 08:59:37 UTC (rev 4870) +++ branches/installer25/src/java/org/python/util/install/JarInstaller.java 2008-07-08 09:00:26 UTC (rev 4871) @@ -17,7 +17,7 @@ * moment). */ public class JarInstaller { - public static final String JYTHON_JAR = "jython.jar"; + public static final String JYTHON_JAR = "jython-complete.jar"; private static final String PATH_SEPARATOR = "/"; private static final String LIB_NAME_SEP = "Lib" + PATH_SEPARATOR; @@ -258,4 +258,4 @@ return exclude; } -} \ No newline at end of file +} This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <fwi...@us...> - 2008-07-08 08:59:39
|
Revision: 4870 http://jython.svn.sourceforge.net/jython/?rev=4870&view=rev Author: fwierzbicki Date: 2008-07-08 01:59:37 -0700 (Tue, 08 Jul 2008) Log Message: ----------- some tweaks to help the install task. Modified Paths: -------------- branches/asm/build.xml Modified: branches/asm/build.xml =================================================================== --- branches/asm/build.xml 2008-07-08 07:27:03 UTC (rev 4869) +++ branches/asm/build.xml 2008-07-08 08:59:37 UTC (rev 4870) @@ -202,7 +202,7 @@ <property name="PY_RELEASE_LEVEL_SNAPSHOT" value="170"/> <!-- 0xAA --> <!-- The current version info --> - <property name="jython.version" value="2.5a0+" /> + <property name="jython.version" value="2.5a0" /> <property name="jython.major_version" value="2"/> <property name="jython.minor_version" value="5"/> <property name="jython.micro_version" value="0"/> @@ -515,7 +515,7 @@ destdir="${exposed.dir}" includesfile="${jython.base.dir}/CoreExposed.includes"/> </target> - <target name="jarjar" depends="init" unless="jarjar.notneeded"> + <target name="jarjar" depends="init" > <taskdef name="jarjar" classname="com.tonicsystems.jarjar.JarJarTask" classpath="extlibs/jarjar-0.7.jar"/> <jarjar destfile="${output.dir}/jarjar.jar"> <zipfileset src="extlibs/antlr-runtime-3.1b1.jar"/> @@ -535,7 +535,7 @@ </unjar> </target> - <target name="jar-complete" depends="compile,expose,jarjar"> + <target name="jar-complete" depends="jarjar,compile,expose"> <jar destfile="${dist.dir}/jython-complete.jar"> <fileset dir="${compile.dir}"/> <fileset dir="${exposed.dir}"/> @@ -697,8 +697,8 @@ </target> <!-- wrap the build into the installer --> - <target name="install" depends="brand-readme-version, doc, jar, javadoc, copy-full"> - <property name="install.src.dir" value="${jython.base.dir}/../installer/src/java" /> + <target name="install" depends="brand-readme-version, doc, jar-complete, javadoc, copy-full"> + <property name="install.src.dir" value="${jython.base.dir}/../installer25/src/java" /> <echo>compiling installer from ${install.src.dir}</echo> <javac srcdir="${install.src.dir}" includes="org/**" This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <pj...@us...> - 2008-07-08 07:27:07
|
Revision: 4869 http://jython.svn.sourceforge.net/jython/?rev=4869&view=rev Author: pjenvey Date: 2008-07-08 00:27:03 -0700 (Tue, 08 Jul 2008) Log Message: ----------- o workaround jython issues in test_richcmp and test_repr o our custom test_operations isn't really necessary and we pass stdlib's. also now pass stdlib's test_long Modified Paths: -------------- branches/asm/Lib/test/test_repr.py branches/asm/Lib/test/test_richcmp.py Removed Paths: ------------- branches/asm/Lib/test/output/test_operations branches/asm/Lib/test/test_long.py branches/asm/Lib/test/test_operations.py Deleted: branches/asm/Lib/test/output/test_operations =================================================================== --- branches/asm/Lib/test/output/test_operations 2008-07-08 06:20:46 UTC (rev 4868) +++ branches/asm/Lib/test/output/test_operations 2008-07-08 07:27:03 UTC (rev 4869) @@ -1,28 +0,0 @@ -test_operations -Operations (test_operations.py) -Numeric -+ -- -* -/ -** -% -Binary -| -^ -& -<< ->> -Comparison -< -> -== -<= ->= -and -or -Indexing -[i] -[i:j] -in -not in Deleted: branches/asm/Lib/test/test_long.py =================================================================== --- branches/asm/Lib/test/test_long.py 2008-07-08 06:20:46 UTC (rev 4868) +++ branches/asm/Lib/test/test_long.py 2008-07-08 07:27:03 UTC (rev 4869) @@ -1,486 +0,0 @@ -import unittest -from test import test_support - -import random - -# Used for lazy formatting of failure messages -class Frm(object): - def __init__(self, format, *args): - self.format = format - self.args = args - - def __str__(self): - return self.format % self.args - -# SHIFT should match the value in longintrepr.h for best testing. -SHIFT = 15 -BASE = 2 ** SHIFT -MASK = BASE - 1 -KARATSUBA_CUTOFF = 70 # from longobject.c - -# Max number of base BASE digits to use in test cases. Doubling -# this will more than double the runtime. -MAXDIGITS = 15 - -# build some special values -special = map(long, [0, 1, 2, BASE, BASE >> 1]) -special.append(0x5555555555555555L) -special.append(0xaaaaaaaaaaaaaaaaL) -# some solid strings of one bits -p2 = 4L # 0 and 1 already added -for i in range(2*SHIFT): - special.append(p2 - 1) - p2 = p2 << 1 -del p2 -# add complements & negations -special = special + map(lambda x: ~x, special) + \ - map(lambda x: -x, special) - - -class LongTest(unittest.TestCase): - - # Get quasi-random long consisting of ndigits digits (in base BASE). - # quasi == the most-significant digit will not be 0, and the number - # is constructed to contain long strings of 0 and 1 bits. These are - # more likely than random bits to provoke digit-boundary errors. - # The sign of the number is also random. - - def getran(self, ndigits): - self.assert_(ndigits > 0) - nbits_hi = ndigits * SHIFT - nbits_lo = nbits_hi - SHIFT + 1 - answer = 0L - nbits = 0 - r = int(random.random() * (SHIFT * 2)) | 1 # force 1 bits to start - while nbits < nbits_lo: - bits = (r >> 1) + 1 - bits = min(bits, nbits_hi - nbits) - self.assert_(1 <= bits <= SHIFT) - nbits = nbits + bits - answer = answer << bits - if r & 1: - answer = answer | ((1 << bits) - 1) - r = int(random.random() * (SHIFT * 2)) - self.assert_(nbits_lo <= nbits <= nbits_hi) - if random.random() < 0.5: - answer = -answer - return answer - - # Get random long consisting of ndigits random digits (relative to base - # BASE). The sign bit is also random. - - def getran2(ndigits): - answer = 0L - for i in xrange(ndigits): - answer = (answer << SHIFT) | random.randint(0, MASK) - if random.random() < 0.5: - answer = -answer - return answer - - def check_division(self, x, y): - eq = self.assertEqual - q, r = divmod(x, y) - q2, r2 = x//y, x%y - pab, pba = x*y, y*x - eq(pab, pba, Frm("multiplication does not commute for %r and %r", x, y)) - eq(q, q2, Frm("divmod returns different quotient than / for %r and %r", x, y)) - eq(r, r2, Frm("divmod returns different mod than %% for %r and %r", x, y)) - eq(x, q*y + r, Frm("x != q*y + r after divmod on x=%r, y=%r", x, y)) - if y > 0: - self.assert_(0 <= r < y, Frm("bad mod from divmod on %r and %r", x, y)) - else: - self.assert_(y < r <= 0, Frm("bad mod from divmod on %r and %r", x, y)) - - def test_division(self): - digits = range(1, MAXDIGITS+1) + range(KARATSUBA_CUTOFF, - KARATSUBA_CUTOFF + 14) - digits.append(KARATSUBA_CUTOFF * 3) - for lenx in digits: - x = self.getran(lenx) - for leny in digits: - y = self.getran(leny) or 1L - self.check_division(x, y) - - def test_karatsuba(self): - digits = range(1, 5) + range(KARATSUBA_CUTOFF, KARATSUBA_CUTOFF + 10) - digits.extend([KARATSUBA_CUTOFF * 10, KARATSUBA_CUTOFF * 100]) - - bits = [digit * SHIFT for digit in digits] - - # Test products of long strings of 1 bits -- (2**x-1)*(2**y-1) == - # 2**(x+y) - 2**x - 2**y + 1, so the proper result is easy to check. - for abits in bits: - a = (1L << abits) - 1 - for bbits in bits: - if bbits < abits: - continue - b = (1L << bbits) - 1 - x = a * b - y = ((1L << (abits + bbits)) - - (1L << abits) - - (1L << bbits) + - 1) - self.assertEqual(x, y, - Frm("bad result for a*b: a=%r, b=%r, x=%r, y=%r", a, b, x, y)) - - def check_bitop_identities_1(self, x): - eq = self.assertEqual - eq(x & 0, 0, Frm("x & 0 != 0 for x=%r", x)) - eq(x | 0, x, Frm("x | 0 != x for x=%r", x)) - eq(x ^ 0, x, Frm("x ^ 0 != x for x=%r", x)) - eq(x & -1, x, Frm("x & -1 != x for x=%r", x)) - eq(x | -1, -1, Frm("x | -1 != -1 for x=%r", x)) - eq(x ^ -1, ~x, Frm("x ^ -1 != ~x for x=%r", x)) - eq(x, ~~x, Frm("x != ~~x for x=%r", x)) - eq(x & x, x, Frm("x & x != x for x=%r", x)) - eq(x | x, x, Frm("x | x != x for x=%r", x)) - eq(x ^ x, 0, Frm("x ^ x != 0 for x=%r", x)) - eq(x & ~x, 0, Frm("x & ~x != 0 for x=%r", x)) - eq(x | ~x, -1, Frm("x | ~x != -1 for x=%r", x)) - eq(x ^ ~x, -1, Frm("x ^ ~x != -1 for x=%r", x)) - eq(-x, 1 + ~x, Frm("not -x == 1 + ~x for x=%r", x)) - eq(-x, ~(x-1), Frm("not -x == ~(x-1) forx =%r", x)) - for n in xrange(2*SHIFT): - p2 = 2L ** n - eq(x << n >> n, x, - Frm("x << n >> n != x for x=%r, n=%r", (x, n))) - eq(x // p2, x >> n, - Frm("x // p2 != x >> n for x=%r n=%r p2=%r", (x, n, p2))) - eq(x * p2, x << n, - Frm("x * p2 != x << n for x=%r n=%r p2=%r", (x, n, p2))) - eq(x & -p2, x >> n << n, - Frm("not x & -p2 == x >> n << n for x=%r n=%r p2=%r", (x, n, p2))) - eq(x & -p2, x & ~(p2 - 1), - Frm("not x & -p2 == x & ~(p2 - 1) for x=%r n=%r p2=%r", (x, n, p2))) - - def check_bitop_identities_2(self, x, y): - eq = self.assertEqual - eq(x & y, y & x, Frm("x & y != y & x for x=%r, y=%r", (x, y))) - eq(x | y, y | x, Frm("x | y != y | x for x=%r, y=%r", (x, y))) - eq(x ^ y, y ^ x, Frm("x ^ y != y ^ x for x=%r, y=%r", (x, y))) - eq(x ^ y ^ x, y, Frm("x ^ y ^ x != y for x=%r, y=%r", (x, y))) - eq(x & y, ~(~x | ~y), Frm("x & y != ~(~x | ~y) for x=%r, y=%r", (x, y))) - eq(x | y, ~(~x & ~y), Frm("x | y != ~(~x & ~y) for x=%r, y=%r", (x, y))) - eq(x ^ y, (x | y) & ~(x & y), - Frm("x ^ y != (x | y) & ~(x & y) for x=%r, y=%r", (x, y))) - eq(x ^ y, (x & ~y) | (~x & y), - Frm("x ^ y == (x & ~y) | (~x & y) for x=%r, y=%r", (x, y))) - eq(x ^ y, (x | y) & (~x | ~y), - Frm("x ^ y == (x | y) & (~x | ~y) for x=%r, y=%r", (x, y))) - - def check_bitop_identities_3(self, x, y, z): - eq = self.assertEqual - eq((x & y) & z, x & (y & z), - Frm("(x & y) & z != x & (y & z) for x=%r, y=%r, z=%r", (x, y, z))) - eq((x | y) | z, x | (y | z), - Frm("(x | y) | z != x | (y | z) for x=%r, y=%r, z=%r", (x, y, z))) - eq((x ^ y) ^ z, x ^ (y ^ z), - Frm("(x ^ y) ^ z != x ^ (y ^ z) for x=%r, y=%r, z=%r", (x, y, z))) - eq(x & (y | z), (x & y) | (x & z), - Frm("x & (y | z) != (x & y) | (x & z) for x=%r, y=%r, z=%r", (x, y, z))) - eq(x | (y & z), (x | y) & (x | z), - Frm("x | (y & z) != (x | y) & (x | z) for x=%r, y=%r, z=%r", (x, y, z))) - - def test_bitop_identities(self): - for x in special: - self.check_bitop_identities_1(x) - digits = xrange(1, MAXDIGITS+1) - for lenx in digits: - x = self.getran(lenx) - self.check_bitop_identities_1(x) - for leny in digits: - y = self.getran(leny) - self.check_bitop_identities_2(x, y) - self.check_bitop_identities_3(x, y, self.getran((lenx + leny)//2)) - - def slow_format(self, x, base): - if (x, base) == (0, 8): - # this is an oddball! - return "0L" - digits = [] - sign = 0 - if x < 0: - sign, x = 1, -x - while x: - x, r = divmod(x, base) - digits.append(int(r)) - digits.reverse() - digits = digits or [0] - return '-'[:sign] + \ - {8: '0', 10: '', 16: '0x'}[base] + \ - "".join(map(lambda i: "0123456789abcdef"[i], digits)) + "L" - - def check_format_1(self, x): - for base, mapper in (8, oct), (10, repr), (16, hex): - got = mapper(x) - expected = self.slow_format(x, base) - msg = Frm("%s returned %r but expected %r for %r", - mapper.__name__, got, expected, x) - self.assertEqual(got, expected, msg) - self.assertEqual(long(got, 0), x, Frm('long("%s", 0) != %r', got, x)) - # str() has to be checked a little differently since there's no - # trailing "L" - got = str(x) - expected = self.slow_format(x, 10)[:-1] - msg = Frm("%s returned %r but expected %r for %r", - mapper.__name__, got, expected, x) - self.assertEqual(got, expected, msg) - - def test_format(self): - for x in special: - self.check_format_1(x) - for i in xrange(10): - for lenx in xrange(1, MAXDIGITS+1): - x = self.getran(lenx) - self.check_format_1(x) - - def test_misc(self): - import sys - - # check the extremes in int<->long conversion - hugepos = sys.maxint - hugeneg = -hugepos - 1 - hugepos_aslong = long(hugepos) - hugeneg_aslong = long(hugeneg) - self.assertEqual(hugepos, hugepos_aslong, "long(sys.maxint) != sys.maxint") - self.assertEqual(hugeneg, hugeneg_aslong, - "long(-sys.maxint-1) != -sys.maxint-1") - - # long -> int should not fail for hugepos_aslong or hugeneg_aslong - try: - self.assertEqual(int(hugepos_aslong), hugepos, - "converting sys.maxint to long and back to int fails") - except OverflowError: - self.fail("int(long(sys.maxint)) overflowed!") - try: - self.assertEqual(int(hugeneg_aslong), hugeneg, - "converting -sys.maxint-1 to long and back to int fails") - except OverflowError: - self.fail("int(long(-sys.maxint-1)) overflowed!") - - # but long -> int should overflow for hugepos+1 and hugeneg-1 - x = hugepos_aslong + 1 - try: - y = int(x) - except OverflowError: - self.fail("int(long(sys.maxint) + 1) mustn't overflow") - self.assert_(isinstance(y, long), - "int(long(sys.maxint) + 1) should have returned long") - - x = hugeneg_aslong - 1 - try: - y = int(x) - except OverflowError: - self.fail("int(long(-sys.maxint-1) - 1) mustn't overflow") - self.assert_(isinstance(y, long), - "int(long(-sys.maxint-1) - 1) should have returned long") - - class long2(long): - pass - x = long2(1L<<100) - y = int(x) - self.assert_(type(y) is long, - "overflowing int conversion must return long not long subtype") - -# ----------------------------------- tests of auto int->long conversion - - def test_auto_overflow(self): - import math, sys - - special = [0, 1, 2, 3, sys.maxint-1, sys.maxint, sys.maxint+1] - sqrt = int(math.sqrt(sys.maxint)) - special.extend([sqrt-1, sqrt, sqrt+1]) - special.extend([-i for i in special]) - - def checkit(*args): - # Heavy use of nested scopes here! - self.assertEqual(got, expected, - Frm("for %r expected %r got %r", args, expected, got)) - - for x in special: - longx = long(x) - - expected = -longx - got = -x - checkit('-', x) - - for y in special: - longy = long(y) - - expected = longx + longy - got = x + y - checkit(x, '+', y) - - expected = longx - longy - got = x - y - checkit(x, '-', y) - - expected = longx * longy - got = x * y - checkit(x, '*', y) - - if y: - expected = longx / longy - got = x / y - checkit(x, '/', y) - - expected = longx // longy - got = x // y - checkit(x, '//', y) - - expected = divmod(longx, longy) - got = divmod(longx, longy) - checkit(x, 'divmod', y) - - if abs(y) < 5 and not (x == 0 and y < 0): - expected = longx ** longy - got = x ** y - checkit(x, '**', y) - - for z in special: - if z != 0 : - if y >= 0: - expected = pow(longx, longy, long(z)) - got = pow(x, y, z) - checkit('pow', x, y, '%', z) - else: - self.assertRaises(TypeError, pow,longx, longy, long(z)) - - def test_float_overflow(self): - import math - - for x in -2.0, -1.0, 0.0, 1.0, 2.0: - self.assertEqual(float(long(x)), x) - - shuge = '12345' * 120 - huge = 1L << 30000 - mhuge = -huge - namespace = {'huge': huge, 'mhuge': mhuge, 'shuge': shuge, 'math': math} - for test in ["float(huge)", "float(mhuge)", - "complex(huge)", "complex(mhuge)", - "complex(huge, 1)", "complex(mhuge, 1)", - "complex(1, huge)", "complex(1, mhuge)", - "1. + huge", "huge + 1.", "1. + mhuge", "mhuge + 1.", - "1. - huge", "huge - 1.", "1. - mhuge", "mhuge - 1.", - "1. * huge", "huge * 1.", "1. * mhuge", "mhuge * 1.", - "1. // huge", "huge // 1.", "1. // mhuge", "mhuge // 1.", - "1. / huge", "huge / 1.", "1. / mhuge", "mhuge / 1.", - "1. ** huge", "huge ** 1.", "1. ** mhuge", "mhuge ** 1.", - "math.sin(huge)", "math.sin(mhuge)", - "math.sqrt(huge)", "math.sqrt(mhuge)", # should do better - "math.floor(huge)", "math.floor(mhuge)"]: - - self.assertRaises(OverflowError, eval, test, namespace) - - # XXX Perhaps float(shuge) can raise OverflowError on some box? - # The comparison should not. - self.assertNotEqual(float(shuge), int(shuge), - "float(shuge) should not equal int(shuge)") - - def test_logs(self): - import math - - LOG10E = math.log10(math.e) - - for exp in range(10) + [100, 1000, 10000]: - value = 10 ** exp - log10 = math.log10(value) - self.assertAlmostEqual(log10, exp) - - # log10(value) == exp, so log(value) == log10(value)/log10(e) == - # exp/LOG10E - expected = exp / LOG10E - log = math.log(value) - self.assertAlmostEqual(log, expected) - - for bad in -(1L << 10000), -2L, 0L: - self.assertRaises(ValueError, math.log, bad) - self.assertRaises(ValueError, math.log10, bad) - - def test_mixed_compares(self): - eq = self.assertEqual - import math - import sys - - # We're mostly concerned with that mixing floats and longs does the - # right stuff, even when longs are too large to fit in a float. - # The safest way to check the results is to use an entirely different - # method, which we do here via a skeletal rational class (which - # represents all Python ints, longs and floats exactly). - class Rat: - def __init__(self, value): - if isinstance(value, (int, long)): - self.n = value - self.d = 1 - elif isinstance(value, float): - # Convert to exact rational equivalent. - f, e = math.frexp(abs(value)) - assert f == 0 or 0.5 <= f < 1.0 - # |value| = f * 2**e exactly - - # Suck up CHUNK bits at a time; 28 is enough so that we suck - # up all bits in 2 iterations for all known binary double- - # precision formats, and small enough to fit in an int. - CHUNK = 28 - top = 0 - # invariant: |value| = (top + f) * 2**e exactly - while f: - f = math.ldexp(f, CHUNK) - digit = int(f) - assert digit >> CHUNK == 0 - top = (top << CHUNK) | digit - f -= digit - assert 0.0 <= f < 1.0 - e -= CHUNK - - # Now |value| = top * 2**e exactly. - if e >= 0: - n = top << e - d = 1 - else: - n = top - d = 1 << -e - if value < 0: - n = -n - self.n = n - self.d = d - assert float(n) / float(d) == value - else: - raise TypeError("can't deal with %r" % val) - - def __cmp__(self, other): - if not isinstance(other, Rat): - other = Rat(other) - return cmp(self.n * other.d, self.d * other.n) - - cases = [0, 0.001, 0.99, 1.0, 1.5, 1e20, 1e200] - # 2**48 is an important boundary in the internals. 2**53 is an - # important boundary for IEEE double precision. - for t in 2.0**48, 2.0**50, 2.0**53: - cases.extend([t - 1.0, t - 0.3, t, t + 0.3, t + 1.0, - long(t-1), long(t), long(t+1)]) - cases.extend([0, 1, 2, sys.maxint, float(sys.maxint)]) - # 1L<<20000 should exceed all double formats. long(1e200) is to - # check that we get equality with 1e200 above. - t = long(1e200) - cases.extend([0L, 1L, 2L, 1L << 20000, t-1, t, t+1]) - cases.extend([-x for x in cases]) - for x in cases: - Rx = Rat(x) - for y in cases: - Ry = Rat(y) - Rcmp = cmp(Rx, Ry) - xycmp = cmp(x, y) - eq(Rcmp, xycmp, Frm("%r %r %d %d", x, y, Rcmp, xycmp)) - eq(x == y, Rcmp == 0, Frm("%r == %r %d", x, y, Rcmp)) - eq(x != y, Rcmp != 0, Frm("%r != %r %d", x, y, Rcmp)) - eq(x < y, Rcmp < 0, Frm("%r < %r %d", x, y, Rcmp)) - eq(x <= y, Rcmp <= 0, Frm("%r <= %r %d", x, y, Rcmp)) - eq(x > y, Rcmp > 0, Frm("%r > %r %d", x, y, Rcmp)) - eq(x >= y, Rcmp >= 0, Frm("%r >= %r %d", x, y, Rcmp)) - -def test_main(): - test_support.run_unittest(LongTest) - -if __name__ == "__main__": - test_main() Deleted: branches/asm/Lib/test/test_operations.py =================================================================== --- branches/asm/Lib/test/test_operations.py 2008-07-08 06:20:46 UTC (rev 4868) +++ branches/asm/Lib/test/test_operations.py 2008-07-08 07:27:03 UTC (rev 4869) @@ -1,475 +0,0 @@ -# Python test set -- part 3, built-in operations. - -from test_support import * - -print 'Operations (test_operations.py)' - -print 'Numeric' -print '+' -assert 0 + 0 == 0 -assert 0 + 3 == 3 -assert 0 + 42 == 42 -assert 3 + 0 == 3 -assert 3 + 3 == 6 -assert 3 + 42 == 45 -assert 42 + 0 == 42 -assert 42 + 3 == 45 -assert 42 + 42 == 84 -assert 0.0 + 0.0 == 0.0 -assert 0.0 + 3.0 == 3.0 -assert 0.0 + 42.0 == 42.0 -assert 3.0 + 0.0 == 3.0 -assert 3.0 + 3.0 == 6.0 -assert 3.0 + 42.0 == 45.0 -assert 42.0 + 0.0 == 42.0 -assert 42.0 + 3.0 == 45.0 -assert 42.0 + 42.0 == 84.0 -assert 0L + 0L == 0L -assert 0L + 3L == 3L -assert 0L + 42L == 42L -assert 3L + 0L == 3L -assert 3L + 3L == 6L -assert 3L + 42L == 45L -assert 42L + 0L == 42L -assert 42L + 3L == 45L -assert 42L + 42L == 84L -print '-' -assert 0 - 0 == 0 -assert 0 - 3 == -3 -assert 0 - 42 == -42 -assert 3 - 0 == 3 -assert 3 - 3 == 0 -assert 3 - 42 == -39 -assert 42 - 0 == 42 -assert 42 - 3 == 39 -assert 42 - 42 == 0 -assert 0.0 - 0.0 == 0.0 -assert 0.0 - 3.0 == -3.0 -assert 0.0 - 42.0 == -42.0 -assert 3.0 - 0.0 == 3.0 -assert 3.0 - 3.0 == 0.0 -assert 3.0 - 42.0 == -39.0 -assert 42.0 - 0.0 == 42.0 -assert 42.0 - 3.0 == 39.0 -assert 42.0 - 42.0 == 0.0 -assert 0L - 0L == 0L -assert 0L - 3L == -3L -assert 0L - 42L == -42L -assert 3L - 0L == 3L -assert 3L - 3L == 0L -assert 3L - 42L == -39L -assert 42L - 0L == 42L -assert 42L - 3L == 39L -assert 42L - 42L == 0L -print '*' -assert 0 * 0 == 0 -assert 0 * 3 == 0 -assert 0 * 42 == 0 -assert 3 * 0 == 0 -assert 3 * 3 == 9 -assert 3 * 42 == 126 -assert 42 * 0 == 0 -assert 42 * 3 == 126 -assert 42 * 42 == 1764 -assert 0.0 * 0.0 == 0.0 -assert 0.0 * 3.0 == 0.0 -assert 0.0 * 42.0 == 0.0 -assert 3.0 * 0.0 == 0.0 -assert 3.0 * 3.0 == 9.0 -assert 3.0 * 42.0 == 126.0 -assert 42.0 * 0.0 == 0.0 -assert 42.0 * 3.0 == 126.0 -assert 42.0 * 42.0 == 1764.0 -assert 0L * 0L == 0L -assert 0L * 3L == 0L -assert 0L * 42L == 0L -assert 3L * 0L == 0L -assert 3L * 3L == 9L -assert 3L * 42L == 126L -assert 42L * 0L == 0L -assert 42L * 3L == 126L -assert 42L * 42L == 1764L -print '/' -assert 0 / 3 == 0 -assert 0 / 42 == 0 -assert 3 / 3 == 1 -assert 3 / 42 == 0 -assert 42 / 3 == 14 -assert 42 / 42 == 1 -assert 0.0 / 3.0 == 0.0 -assert 0.0 / 42.0 == 0.0 -assert 3.0 / 3.0 == 1.0 -assert abs(3.0 / 42.0 - 0.0714285714286) < 0.000001 -assert 42.0 / 3.0 == 14.0 -assert 42.0 / 42.0 == 1.0 -assert 0L / 3L == 0L -assert 0L / 42L == 0L -assert 3L / 3L == 1L -assert 3L / 42L == 0L -assert 42L / 3L == 14L -assert 42L / 42L == 1L -print '**' -assert 0 ** 0 == 1 -assert 0 ** 3 == 0 -assert 0 ** 42 == 0 -assert 3 ** 0 == 1 -assert 3 ** 3 == 27 -assert 42 ** 0 == 1 -assert 42 ** 3 == 74088 -assert 0.0 ** 0.0 == 1.0 -assert 0.0 ** 3.0 == 0.0 -assert 0.0 ** 42.0 == 0.0 -assert 3.0 ** 0.0 == 1.0 -assert 3.0 ** 3.0 == 27.0 -assert abs(3.0 ** 42.0 - 1.0941898913151237e+020) < 1e10 -assert 42.0 ** 0.0 == 1.0 -assert 42.0 ** 3.0 == 74088.0 -assert abs(42.0 ** 42.0 - 1.5013093754529659e+068) < 1e58 -assert 0L ** 0L == 1L -assert 0L ** 3L == 0L -assert 0L ** 42L == 0L -assert 3L ** 0L == 1L -assert 3L ** 3L == 27L -assert 3L ** 42L == 109418989131512359209L -assert 42L ** 0L == 1L -assert 42L ** 3L == 74088L -assert 42L ** 42L == 150130937545296572356771972164254457814047970568738777235893533016064L -print '%' -assert 0 % 3 == 0 -assert 0 % 42 == 0 -assert 3 % 3 == 0 -assert 3 % 42 == 3 -assert 42 % 3 == 0 -assert 42 % 42 == 0 -assert 0.0 % 3.0 == 0.0 -assert 0.0 % 42.0 == 0.0 -assert 3.0 % 3.0 == 0.0 -assert 3.0 % 42.0 == 3.0 -assert 42.0 % 3.0 == 0.0 -assert 42.0 % 42.0 == 0.0 -assert 0L % 3L == 0L -assert 0L % 42L == 0L -assert 3L % 3L == 0L -assert 3L % 42L == 3L -assert 42L % 3L == 0L -assert 42L % 42L == 0L - -print 'Binary' -print '|' -assert 0 | 0 == 0 -assert 0 | 3 == 3 -assert 0 | 42 == 42 -assert 3 | 0 == 3 -assert 3 | 3 == 3 -assert 3 | 42 == 43 -assert 42 | 0 == 42 -assert 42 | 3 == 43 -assert 42 | 42 == 42 -assert 0L | 0L == 0L -assert 0L | 3L == 3L -assert 0L | 42L == 42L -assert 3L | 0L == 3L -assert 3L | 3L == 3L -assert 3L | 42L == 43L -assert 42L | 0L == 42L -assert 42L | 3L == 43L -assert 42L | 42L == 42L -print '^' -assert 0 ^ 0 == 0 -assert 0 ^ 3 == 3 -assert 0 ^ 42 == 42 -assert 3 ^ 0 == 3 -assert 3 ^ 3 == 0 -assert 3 ^ 42 == 41 -assert 42 ^ 0 == 42 -assert 42 ^ 3 == 41 -assert 42 ^ 42 == 0 -assert 0L ^ 0L == 0L -assert 0L ^ 3L == 3L -assert 0L ^ 42L == 42L -assert 3L ^ 0L == 3L -assert 3L ^ 3L == 0L -assert 3L ^ 42L == 41L -assert 42L ^ 0L == 42L -assert 42L ^ 3L == 41L -assert 42L ^ 42L == 0L -print '&' -assert 0 & 0 == 0 -assert 0 & 3 == 0 -assert 0 & 42 == 0 -assert 3 & 0 == 0 -assert 3 & 3 == 3 -assert 3 & 42 == 2 -assert 42 & 0 == 0 -assert 42 & 3 == 2 -assert 42 & 42 == 42 -assert 0L & 0L == 0L -assert 0L & 3L == 0L -assert 0L & 42L == 0L -assert 3L & 0L == 0L -assert 3L & 3L == 3L -assert 3L & 42L == 2L -assert 42L & 0L == 0L -assert 42L & 3L == 2L -assert 42L & 42L == 42L -print '<<' -assert 0 << 0 == 0 -assert 0 << 3 == 0 -assert 0 << 42 == 0 -assert 3 << 0 == 3 -assert 3 << 3 == 24 -assert 3 << 42 == 13194139533312L -assert 42 << 0 == 42 -assert 42 << 3 == 336 -assert 42 << 42 == 184717953466368L -assert 0L << 0L == 0L -assert 0L << 3L == 0L -assert 0L << 42L == 0L -assert 3L << 0L == 3L -assert 3L << 3L == 24L -assert 3L << 42L == 13194139533312L -assert 42L << 0L == 42L -assert 42L << 3L == 336L -assert 42L << 42L == 184717953466368L -print '>>' -assert 0 >> 0 == 0 -assert 0 >> 3 == 0 -assert 0 >> 42 == 0 -assert 3 >> 0 == 3 -assert 3 >> 3 == 0 -assert 3 >> 42 == 0 -assert 42 >> 0 == 42 -assert 42 >> 3 == 5 -assert 42 >> 42 == 0 -assert 0L >> 0L == 0L -assert 0L >> 3L == 0L -assert 0L >> 42L == 0L -assert 3L >> 0L == 3L -assert 3L >> 3L == 0L -assert 3L >> 42L == 0L -assert 42L >> 0L == 42L -assert 42L >> 3L == 5L -assert 42L >> 42L == 0L - -print 'Comparison' -print '<' -assert (0 < 0) == 0 -assert (0 < 3) == 1 -assert (0 < 42) == 1 -assert (3 < 0) == 0 -assert (3 < 3) == 0 -assert (3 < 42) == 1 -assert (42 < 0) == 0 -assert (42 < 3) == 0 -assert (42 < 42) == 0 -assert (0.0 < 0.0) == 0 -assert (0.0 < 3.0) == 1 -assert (0.0 < 42.0) == 1 -assert (3.0 < 0.0) == 0 -assert (3.0 < 3.0) == 0 -assert (3.0 < 42.0) == 1 -assert (42.0 < 0.0) == 0 -assert (42.0 < 3.0) == 0 -assert (42.0 < 42.0) == 0 -assert (0L < 0L) == 0 -assert (0L < 3L) == 1 -assert (0L < 42L) == 1 -assert (3L < 0L) == 0 -assert (3L < 3L) == 0 -assert (3L < 42L) == 1 -assert (42L < 0L) == 0 -assert (42L < 3L) == 0 -assert (42L < 42L) == 0 -print '>' -assert (0 > 0) == 0 -assert (0 > 3) == 0 -assert (0 > 42) == 0 -assert (3 > 0) == 1 -assert (3 > 3) == 0 -assert (3 > 42) == 0 -assert (42 > 0) == 1 -assert (42 > 3) == 1 -assert (42 > 42) == 0 -assert (0.0 > 0.0) == 0 -assert (0.0 > 3.0) == 0 -assert (0.0 > 42.0) == 0 -assert (3.0 > 0.0) == 1 -assert (3.0 > 3.0) == 0 -assert (3.0 > 42.0) == 0 -assert (42.0 > 0.0) == 1 -assert (42.0 > 3.0) == 1 -assert (42.0 > 42.0) == 0 -assert (0L > 0L) == 0 -assert (0L > 3L) == 0 -assert (0L > 42L) == 0 -assert (3L > 0L) == 1 -assert (3L > 3L) == 0 -assert (3L > 42L) == 0 -assert (42L > 0L) == 1 -assert (42L > 3L) == 1 -assert (42L > 42L) == 0 -print '==' -assert (0 == 0) == 1 -assert (0 == 3) == 0 -assert (0 == 42) == 0 -assert (3 == 0) == 0 -assert (3 == 3) == 1 -assert (3 == 42) == 0 -assert (42 == 0) == 0 -assert (42 == 3) == 0 -assert (42 == 42) == 1 -assert (0.0 == 0.0) == 1 -assert (0.0 == 3.0) == 0 -assert (0.0 == 42.0) == 0 -assert (3.0 == 0.0) == 0 -assert (3.0 == 3.0) == 1 -assert (3.0 == 42.0) == 0 -assert (42.0 == 0.0) == 0 -assert (42.0 == 3.0) == 0 -assert (42.0 == 42.0) == 1 -assert (0L == 0L) == 1 -assert (0L == 3L) == 0 -assert (0L == 42L) == 0 -assert (3L == 0L) == 0 -assert (3L == 3L) == 1 -assert (3L == 42L) == 0 -assert (42L == 0L) == 0 -assert (42L == 3L) == 0 -assert (42L == 42L) == 1 -print '<=' -assert (0 <= 0) == 1 -assert (0 <= 3) == 1 -assert (0 <= 42) == 1 -assert (3 <= 0) == 0 -assert (3 <= 3) == 1 -assert (3 <= 42) == 1 -assert (42 <= 0) == 0 -assert (42 <= 3) == 0 -assert (42 <= 42) == 1 -assert (0.0 <= 0.0) == 1 -assert (0.0 <= 3.0) == 1 -assert (0.0 <= 42.0) == 1 -assert (3.0 <= 0.0) == 0 -assert (3.0 <= 3.0) == 1 -assert (3.0 <= 42.0) == 1 -assert (42.0 <= 0.0) == 0 -assert (42.0 <= 3.0) == 0 -assert (42.0 <= 42.0) == 1 -assert (0L <= 0L) == 1 -assert (0L <= 3L) == 1 -assert (0L <= 42L) == 1 -assert (3L <= 0L) == 0 -assert (3L <= 3L) == 1 -assert (3L <= 42L) == 1 -assert (42L <= 0L) == 0 -assert (42L <= 3L) == 0 -assert (42L <= 42L) == 1 -print '>=' -assert (0 >= 0) == 1 -assert (0 >= 3) == 0 -assert (0 >= 42) == 0 -assert (3 >= 0) == 1 -assert (3 >= 3) == 1 -assert (3 >= 42) == 0 -assert (42 >= 0) == 1 -assert (42 >= 3) == 1 -assert (42 >= 42) == 1 -assert (0.0 >= 0.0) == 1 -assert (0.0 >= 3.0) == 0 -assert (0.0 >= 42.0) == 0 -assert (3.0 >= 0.0) == 1 -assert (3.0 >= 3.0) == 1 -assert (3.0 >= 42.0) == 0 -assert (42.0 >= 0.0) == 1 -assert (42.0 >= 3.0) == 1 -assert (42.0 >= 42.0) == 1 -assert (0L >= 0L) == 1 -assert (0L >= 3L) == 0 -assert (0L >= 42L) == 0 -assert (3L >= 0L) == 1 -assert (3L >= 3L) == 1 -assert (3L >= 42L) == 0 -assert (42L >= 0L) == 1 -assert (42L >= 3L) == 1 -assert (42L >= 42L) == 1 -print 'and' -assert (0 and 0) == 0 -assert (0 and 3) == 0 -assert (0 and 42) == 0 -assert (3 and 0) == 0 -assert (3 and 3) == 3 -assert (3 and 42) == 42 -assert (42 and 0) == 0 -assert (42 and 3) == 3 -assert (42 and 42) == 42 -assert (0.0 and 0.0) == 0.0 -assert (0.0 and 3.0) == 0.0 -assert (0.0 and 42.0) == 0.0 -assert (3.0 and 0.0) == 0.0 -assert (3.0 and 3.0) == 3.0 -assert (3.0 and 42.0) == 42.0 -assert (42.0 and 0.0) == 0.0 -assert (42.0 and 3.0) == 3.0 -assert (42.0 and 42.0) == 42.0 -assert (0L and 0L) == 0L -assert (0L and 3L) == 0L -assert (0L and 42L) == 0L -assert (3L and 0L) == 0L -assert (3L and 3L) == 3L -assert (3L and 42L) == 42L -assert (42L and 0L) == 0L -assert (42L and 3L) == 3L -assert (42L and 42L) == 42L -print 'or' -assert (0 or 0) == 0 -assert (0 or 3) == 3 -assert (0 or 42) == 42 -assert (3 or 0) == 3 -assert (3 or 3) == 3 -assert (3 or 42) == 3 -assert (42 or 0) == 42 -assert (42 or 3) == 42 -assert (42 or 42) == 42 -assert (0.0 or 0.0) == 0.0 -assert (0.0 or 3.0) == 3.0 -assert (0.0 or 42.0) == 42.0 -assert (3.0 or 0.0) == 3.0 -assert (3.0 or 3.0) == 3.0 -assert (3.0 or 42.0) == 3.0 -assert (42.0 or 0.0) == 42.0 -assert (42.0 or 3.0) == 42.0 -assert (42.0 or 42.0) == 42.0 -assert (0L or 0L) == 0L -assert (0L or 3L) == 3L -assert (0L or 42L) == 42L -assert (3L or 0L) == 3L -assert (3L or 3L) == 3L -assert (3L or 42L) == 3L -assert (42L or 0L) == 42L -assert (42L or 3L) == 42L -assert (42L or 42L) == 42L - -print 'Indexing' -lst = range(5) - -print '[i]' -assert lst[0] == 0 -assert lst[3] == 3 -lst[3] = 99 -assert lst[3] == 99 -lst[3] = 3 - -print '[i:j]' -assert lst[:2] == [0,1] -assert lst[-3:] == [2,3,4] -assert lst[2:] == [2,3,4] -assert lst[0:2] == [0,1] -assert lst[1:3] == [1,2] - -print 'in' -assert 2 in lst -assert not (8 in lst) - -print 'not in' -assert 8 not in lst -assert not (2 not in lst) Modified: branches/asm/Lib/test/test_repr.py =================================================================== --- branches/asm/Lib/test/test_repr.py 2008-07-08 06:20:46 UTC (rev 4868) +++ branches/asm/Lib/test/test_repr.py 2008-07-08 07:27:03 UTC (rev 4869) @@ -130,10 +130,13 @@ def test_file(self): fp = open(unittest.__file__) self.failUnless(repr(fp).startswith( - "<open file '%s', mode 'r' at 0x" % unittest.__file__)) + # XXX: Jython doesn't use hex ids + # "<open file '%s', mode 'r' at 0x" % unittest.__file__)) + "<open file '%s', mode 'r' at " % unittest.__file__)) fp.close() self.failUnless(repr(fp).startswith( - "<closed file '%s', mode 'r' at 0x" % unittest.__file__)) + # "<closed file '%s', mode 'r' at 0x" % unittest.__file__)) + "<closed file '%s', mode 'r' at " % unittest.__file__)) def test_lambda(self): self.failUnless(repr(lambda x: x).startswith( @@ -146,7 +149,8 @@ eq(repr(hash), '<built-in function hash>') # Methods self.failUnless(repr(''.split).startswith( - '<built-in method split of str object at 0x')) + # '<built-in method split of str object at 0x')) + '<built-in method split of str object at ')) def test_xrange(self): import warnings @@ -193,9 +197,11 @@ class C: def foo(cls): pass x = staticmethod(C.foo) - self.failUnless(repr(x).startswith('<staticmethod object at 0x')) + #self.failUnless(repr(x).startswith('<staticmethod object at 0x')) + self.failUnless(repr(x).startswith('<staticmethod object at ')) x = classmethod(C.foo) - self.failUnless(repr(x).startswith('<classmethod object at 0x')) + #self.failUnless(repr(x).startswith('<classmethod object at 0x')) + self.failUnless(repr(x).startswith('<classmethod object at ')) def test_unsortable(self): # Repr.repr() used to call sorted() on sets, frozensets and dicts @@ -251,7 +257,8 @@ from areallylongpackageandmodulenametotestreprtruncation.areallylongpackageandmodulenametotestreprtruncation import areallylongpackageandmodulenametotestreprtruncation eq(repr(areallylongpackageandmodulenametotestreprtruncation), "<module '%s' from '%s'>" % (areallylongpackageandmodulenametotestreprtruncation.__name__, areallylongpackageandmodulenametotestreprtruncation.__file__)) - eq(repr(sys), "<module 'sys' (built-in)>") + # XXX: Jython sys module is not a real module + #eq(repr(sys), "<module 'sys' (built-in)>") def test_type(self): eq = self.assertEquals @@ -276,7 +283,8 @@ from areallylongpackageandmodulenametotestreprtruncation.areallylongpackageandmodulenametotestreprtruncation import bar # Module name may be prefixed with "test.", depending on how run. self.failUnless(repr(bar.bar).startswith( - "<class %s.bar at 0x" % bar.__name__)) + # "<class %s.bar at 0x" % bar.__name__)) + "<class %s.bar at " % bar.__name__)) def test_instance(self): touch(os.path.join(self.subpkgname, 'baz'+os.extsep+'py'), '''\ @@ -286,7 +294,8 @@ from areallylongpackageandmodulenametotestreprtruncation.areallylongpackageandmodulenametotestreprtruncation import baz ibaz = baz.baz() self.failUnless(repr(ibaz).startswith( - "<%s.baz instance at 0x" % baz.__name__)) + # "<%s.baz instance at 0x" % baz.__name__)) + "<%s.baz instance at " % baz.__name__)) def test_method(self): eq = self.assertEquals @@ -301,7 +310,8 @@ # Bound method next iqux = qux.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa() self.failUnless(repr(iqux.amethod).startswith( - '<bound method aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.amethod of <%s.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa instance at 0x' \ + # '<bound method aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.amethod of <%s.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa instance at 0x' \ + '<bound method aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.amethod of <%s.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa instance at ' \ % (qux.__name__,) )) def test_builtin_function(self): @@ -321,6 +331,10 @@ def test_main(): + from test import test_support + if test_support.is_jython: + # XXX: Jython lacks the buffer type + del ReprTests.test_buffer run_unittest(ReprTests) if os.name != 'mac': run_unittest(LongReprTest) Modified: branches/asm/Lib/test/test_richcmp.py =================================================================== --- branches/asm/Lib/test/test_richcmp.py 2008-07-08 06:20:46 UTC (rev 4868) +++ branches/asm/Lib/test/test_richcmp.py 2008-07-08 07:27:03 UTC (rev 4869) @@ -331,6 +331,10 @@ self.assertIs(op(x, y), True) def test_main(): + if test_support.is_jython: + # A circular implementation of __eq__ returns False instead of + # True: http://jython.org/bugs/1758280 + del MiscTest.test_recursion test_support.run_unittest(VectorTest, NumberTest, MiscTest, DictTest, ListTest) if __name__ == "__main__": This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <pj...@us...> - 2008-07-08 06:20:49
|
Revision: 4868 http://jython.svn.sourceforge.net/jython/?rev=4868&view=rev Author: pjenvey Date: 2008-07-07 23:20:46 -0700 (Mon, 07 Jul 2008) Log Message: ----------- from: http://svn.python.org/projects/python/branches/release25-maint/Lib/test/test_repr.py@58123 http://svn.python.org/projects/python/branches/release25-maint/Lib/test/test_richcmp.py@43274 Modified Paths: -------------- branches/asm/Lib/test/test_repr.py branches/asm/Lib/test/test_richcmp.py Modified: branches/asm/Lib/test/test_repr.py =================================================================== --- branches/asm/Lib/test/test_repr.py 2008-07-08 05:37:05 UTC (rev 4867) +++ branches/asm/Lib/test/test_repr.py 2008-07-08 06:20:46 UTC (rev 4868) @@ -5,10 +5,12 @@ import sys import os +import shutil import unittest -from test_support import run_unittest +from test.test_support import run_unittest from repr import repr as r # Don't shadow builtin repr +from repr import Repr def nestedTuple(nesting): @@ -25,15 +27,30 @@ eq(r("abcdefghijklmnop"),"'abcdefghijklmnop'") s = "a"*30+"b"*30 - expected = `s`[:13] + "..." + `s`[-14:] + expected = repr(s)[:13] + "..." + repr(s)[-14:] eq(r(s), expected) eq(r("\"'"), repr("\"'")) s = "\""*30+"'"*100 - expected = `s`[:13] + "..." + `s`[-14:] + expected = repr(s)[:13] + "..." + repr(s)[-14:] eq(r(s), expected) + def test_tuple(self): + eq = self.assertEquals + eq(r((1,)), "(1,)") + + t3 = (1, 2, 3) + eq(r(t3), "(1, 2, 3)") + + r2 = Repr() + r2.maxtuple = 2 + expected = repr(t3)[:-2] + "...)" + eq(r2.repr(t3), expected) + def test_container(self): + from array import array + from collections import deque + eq = self.assertEquals # Tuples give up after 6 elements eq(r(()), "()") @@ -49,6 +66,23 @@ eq(r([1, 2, 3, 4, 5, 6]), "[1, 2, 3, 4, 5, 6]") eq(r([1, 2, 3, 4, 5, 6, 7]), "[1, 2, 3, 4, 5, 6, ...]") + # Sets give up after 6 as well + eq(r(set([])), "set([])") + eq(r(set([1])), "set([1])") + eq(r(set([1, 2, 3])), "set([1, 2, 3])") + eq(r(set([1, 2, 3, 4, 5, 6])), "set([1, 2, 3, 4, 5, 6])") + eq(r(set([1, 2, 3, 4, 5, 6, 7])), "set([1, 2, 3, 4, 5, 6, ...])") + + # Frozensets give up after 6 as well + eq(r(frozenset([])), "frozenset([])") + eq(r(frozenset([1])), "frozenset([1])") + eq(r(frozenset([1, 2, 3])), "frozenset([1, 2, 3])") + eq(r(frozenset([1, 2, 3, 4, 5, 6])), "frozenset([1, 2, 3, 4, 5, 6])") + eq(r(frozenset([1, 2, 3, 4, 5, 6, 7])), "frozenset([1, 2, 3, 4, 5, 6, ...])") + + # collections.deque after 6 + eq(r(deque([1, 2, 3, 4, 5, 6, 7])), "deque([1, 2, 3, 4, 5, 6, ...])") + # Dictionaries give up after 4. eq(r({}), "{}") d = {'alice': 1, 'bob': 2, 'charles': 3, 'dave': 4} @@ -56,6 +90,16 @@ d['arthur'] = 1 eq(r(d), "{'alice': 1, 'arthur': 1, 'bob': 2, 'charles': 3, ...}") + # array.array after 5. + eq(r(array('i')), "array('i', [])") + eq(r(array('i', [1])), "array('i', [1])") + eq(r(array('i', [1, 2])), "array('i', [1, 2])") + eq(r(array('i', [1, 2, 3])), "array('i', [1, 2, 3])") + eq(r(array('i', [1, 2, 3, 4])), "array('i', [1, 2, 3, 4])") + eq(r(array('i', [1, 2, 3, 4, 5])), "array('i', [1, 2, 3, 4, 5])") + eq(r(array('i', [1, 2, 3, 4, 5, 6])), + "array('i', [1, 2, 3, 4, 5, ...])") + def test_numbers(self): eq = self.assertEquals eq(r(123), repr(123)) @@ -63,7 +107,7 @@ eq(r(1.0/3), repr(1.0/3)) n = 10L**100 - expected = `n`[:18] + "..." + `n`[-19:] + expected = repr(n)[:18] + "..." + repr(n)[-19:] eq(r(n), expected) def test_instance(self): @@ -72,7 +116,7 @@ eq(r(i1), repr(i1)) i2 = ClassWithRepr("x"*1000) - expected = `i2`[:13] + "..." + `i2`[-14:] + expected = repr(i2)[:13] + "..." + repr(i2)[-14:] eq(r(i2), expected) i3 = ClassWithFailingRepr() @@ -86,10 +130,10 @@ def test_file(self): fp = open(unittest.__file__) self.failUnless(repr(fp).startswith( - "<open file '%s', mode 'r'" % unittest.__file__)) + "<open file '%s', mode 'r' at 0x" % unittest.__file__)) fp.close() self.failUnless(repr(fp).startswith( - "<closed file '%s', mode 'r'" % unittest.__file__)) + "<closed file '%s', mode 'r' at 0x" % unittest.__file__)) def test_lambda(self): self.failUnless(repr(lambda x: x).startswith( @@ -102,19 +146,14 @@ eq(repr(hash), '<built-in function hash>') # Methods self.failUnless(repr(''.split).startswith( - '<built-in method split of str object')) + '<built-in method split of str object at 0x')) def test_xrange(self): + import warnings eq = self.assertEquals eq(repr(xrange(1)), 'xrange(1)') eq(repr(xrange(1, 2)), 'xrange(1, 2)') eq(repr(xrange(1, 2, 3)), 'xrange(1, 4, 3)') - #commented out for jython since this is deprecated. - # Turn off warnings for deprecated multiplication - #import warnings - #warnings.filterwarnings('ignore', category=DeprecationWarning, - # module=ReprTests.__module__) - #eq(repr(xrange(1) * 3), '(xrange(1) * 3)') def test_nesting(self): eq = self.assertEquals @@ -133,12 +172,11 @@ eq(r([[[[[[{}]]]]]]), "[[[[[[{}]]]]]]") eq(r([[[[[[[{}]]]]]]]), "[[[[[[[...]]]]]]]") - #XXX: no buffer in jython. - #def test_buffer(self): + def test_buffer(self): # XXX doesn't test buffers with no b_base or read-write buffers (see # bufferobject.c). The test is fairly incomplete too. Sigh. - # x = buffer('foo') - # self.failUnless(repr(x).startswith('<read-only buffer')) + x = buffer('foo') + self.failUnless(repr(x).startswith('<read-only buffer for 0x')) def test_cell(self): # XXX Hmm? How to get at a cell object? @@ -155,10 +193,20 @@ class C: def foo(cls): pass x = staticmethod(C.foo) - self.failUnless(repr(x).startswith('<staticmethod object')) + self.failUnless(repr(x).startswith('<staticmethod object at 0x')) x = classmethod(C.foo) - self.failUnless(repr(x).startswith('<classmethod object')) + self.failUnless(repr(x).startswith('<classmethod object at 0x')) + def test_unsortable(self): + # Repr.repr() used to call sorted() on sets, frozensets and dicts + # without taking into account that not all objects are comparable + x = set([1j, 2j, 3j]) + y = frozenset(x) + z = {1j: 1, 2j: 2} + r(x) + r(y) + r(z) + def touch(path, text=''): fp = open(path, 'w') fp.write(text) @@ -168,15 +216,16 @@ for name in names: actions.append(os.path.join(dirname, name)) -# class LongReprTest(unittest.TestCase): def setUp(self): longname = 'areallylongpackageandmodulenametotestreprtruncation' self.pkgname = os.path.join(longname) self.subpkgname = os.path.join(longname, longname) # Make the package and subpackage + shutil.rmtree(self.pkgname, ignore_errors=True) os.mkdir(self.pkgname) touch(os.path.join(self.pkgname, '__init__'+os.extsep+'py')) + shutil.rmtree(self.subpkgname, ignore_errors=True) os.mkdir(self.subpkgname) touch(os.path.join(self.subpkgname, '__init__'+os.extsep+'py')) # Remember where we are @@ -201,7 +250,8 @@ touch(os.path.join(self.subpkgname, self.pkgname + os.extsep + 'py')) from areallylongpackageandmodulenametotestreprtruncation.areallylongpackageandmodulenametotestreprtruncation import areallylongpackageandmodulenametotestreprtruncation eq(repr(areallylongpackageandmodulenametotestreprtruncation), - "<module 'areallylongpackageandmodulenametotestreprtruncation.areallylongpackageandmodulenametotestreprtruncation.areallylongpackageandmodulenametotestreprtruncation' from '%s'>" % areallylongpackageandmodulenametotestreprtruncation.__file__) + "<module '%s' from '%s'>" % (areallylongpackageandmodulenametotestreprtruncation.__name__, areallylongpackageandmodulenametotestreprtruncation.__file__)) + eq(repr(sys), "<module 'sys' (built-in)>") def test_type(self): eq = self.assertEquals @@ -211,7 +261,7 @@ ''') from areallylongpackageandmodulenametotestreprtruncation.areallylongpackageandmodulenametotestreprtruncation import foo eq(repr(foo.foo), - "<class 'areallylongpackageandmodulenametotestreprtruncation.areallylongpackageandmodulenametotestreprtruncation.foo.foo'>") + "<class '%s.foo'>" % foo.__name__) def test_object(self): # XXX Test the repr of a type with a really long tp_name but with no @@ -224,8 +274,9 @@ pass ''') from areallylongpackageandmodulenametotestreprtruncation.areallylongpackageandmodulenametotestreprtruncation import bar + # Module name may be prefixed with "test.", depending on how run. self.failUnless(repr(bar.bar).startswith( - "<class areallylongpackageandmodulenametotestreprtruncation.areallylongpackageandmodulenametotestreprtruncation.bar.bar")) + "<class %s.bar at 0x" % bar.__name__)) def test_instance(self): touch(os.path.join(self.subpkgname, 'baz'+os.extsep+'py'), '''\ @@ -235,7 +286,7 @@ from areallylongpackageandmodulenametotestreprtruncation.areallylongpackageandmodulenametotestreprtruncation import baz ibaz = baz.baz() self.failUnless(repr(ibaz).startswith( - "<areallylongpackageandmodulenametotestreprtruncation.areallylongpackageandmodulenametotestreprtruncation.baz.baz instance")) + "<%s.baz instance at 0x" % baz.__name__)) def test_method(self): eq = self.assertEquals @@ -250,7 +301,8 @@ # Bound method next iqux = qux.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa() self.failUnless(repr(iqux.amethod).startswith( - '<bound method aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.amethod of <areallylongpackageandmodulenametotestreprtruncation.areallylongpackageandmodulenametotestreprtruncation.qux.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa instance')) + '<bound method aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.amethod of <%s.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa instance at 0x' \ + % (qux.__name__,) )) def test_builtin_function(self): # XXX test built-in functions and methods with really long names @@ -270,7 +322,7 @@ def test_main(): run_unittest(ReprTests) - if os.name != 'mac' and not os.name.startswith('java'): + if os.name != 'mac': run_unittest(LongReprTest) Modified: branches/asm/Lib/test/test_richcmp.py =================================================================== --- branches/asm/Lib/test/test_richcmp.py 2008-07-08 05:37:05 UTC (rev 4867) +++ branches/asm/Lib/test/test_richcmp.py 2008-07-08 06:20:46 UTC (rev 4868) @@ -211,7 +211,7 @@ # Check that exceptions in __nonzero__ are properly # propagated by the not operator import operator - class Exc: + class Exc(Exception): pass class Bad: def __nonzero__(self): @@ -224,64 +224,43 @@ self.assertRaises(Exc, func, Bad()) def test_recursion(self): - # Check comparison for recursive objects + # Check that comparison for recursive objects fails gracefully from UserList import UserList - a = UserList(); a.append(a) - b = UserList(); b.append(b) - - self.assert_(a == b) - self.assert_(not a != b) - a.append(1) - self.assert_(a == a[0]) - self.assert_(not a != a[0]) - self.assert_(a != b) - self.assert_(not a == b) - b.append(0) - self.assert_(a != b) - self.assert_(not a == b) - a[1] = -1 - self.assert_(a != b) - self.assert_(not a == b) - a = UserList() b = UserList() a.append(b) b.append(a) - self.assert_(a == b) - self.assert_(not a != b) + self.assertRaises(RuntimeError, operator.eq, a, b) + self.assertRaises(RuntimeError, operator.ne, a, b) + self.assertRaises(RuntimeError, operator.lt, a, b) + self.assertRaises(RuntimeError, operator.le, a, b) + self.assertRaises(RuntimeError, operator.gt, a, b) + self.assertRaises(RuntimeError, operator.ge, a, b) b.append(17) + # Even recursive lists of different lengths are different, + # but they cannot be ordered + self.assert_(not (a == b)) self.assert_(a != b) - self.assert_(not a == b) + self.assertRaises(RuntimeError, operator.lt, a, b) + self.assertRaises(RuntimeError, operator.le, a, b) + self.assertRaises(RuntimeError, operator.gt, a, b) + self.assertRaises(RuntimeError, operator.ge, a, b) a.append(17) - self.assert_(a == b) - self.assert_(not a != b) + self.assertRaises(RuntimeError, operator.eq, a, b) + self.assertRaises(RuntimeError, operator.ne, a, b) + a.insert(0, 11) + b.insert(0, 12) + self.assert_(not (a == b)) + self.assert_(a != b) + self.assert_(a < b) - def test_recursion2(self): - # This test exercises the circular structure handling code - # in PyObject_RichCompare() - class Weird(object): - def __eq__(self, other): - return self != other - def __ne__(self, other): - return self == other - def __lt__(self, other): - return self > other - def __gt__(self, other): - return self < other - - self.assert_(Weird() == Weird()) - self.assert_(not (Weird() != Weird())) - - for op in opmap["lt"]: - self.assertRaises(ValueError, op, Weird(), Weird()) - class DictTest(unittest.TestCase): def test_dicts(self): # Verify that __eq__ and __ne__ work for dicts even if the keys and - # values don't support anything other than __eq__ and __ne__. Complex - # numbers are a fine example of that. + # values don't support anything other than __eq__ and __ne__ (and + # __hash__). Complex numbers are a fine example of that. import random imag1a = {} for i in range(50): @@ -326,7 +305,7 @@ def test_badentry(self): # make sure that exceptions for item comparison are properly # propagated in list comparisons - class Exc: + class Exc(Exception): pass class Bad: def __eq__(self, other): @@ -351,10 +330,6 @@ for op in opmap["lt"]: self.assertIs(op(x, y), True) -# A circular implementation of __eq__ returns False instead of True -# http://jython.org/bugs/1758280 -del MiscTest.test_recursion2 - def test_main(): test_support.run_unittest(VectorTest, NumberTest, MiscTest, DictTest, ListTest) This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <pj...@us...> - 2008-07-08 05:37:09
|
Revision: 4867 http://jython.svn.sourceforge.net/jython/?rev=4867&view=rev Author: pjenvey Date: 2008-07-07 22:37:05 -0700 (Mon, 07 Jul 2008) Log Message: ----------- o wrap the fstat usage in is_jython instead of commenting it out o "sync" with: http://svn.python.org/projects/python/branches/release25-maint/Lib/test/test_largefile.py@33923 (no changes; equiv to 2.3's) Modified Paths: -------------- branches/asm/Lib/test/test_largefile.py Modified: branches/asm/Lib/test/test_largefile.py =================================================================== --- branches/asm/Lib/test/test_largefile.py 2008-07-08 05:24:17 UTC (rev 4866) +++ branches/asm/Lib/test/test_largefile.py 2008-07-08 05:37:05 UTC (rev 4867) @@ -75,10 +75,10 @@ f.seek(size) f.write('a') f.flush() - # XXX: Jython doesn't have fstat - #if test_support.verbose: - # print 'check file size with os.fstat' - #expect(os.fstat(f.fileno())[stat.ST_SIZE], size+1) + if not test_support.is_jython: + if test_support.verbose: + print 'check file size with os.fstat' + expect(os.fstat(f.fileno())[stat.ST_SIZE], size+1) finally: f.close() if test_support.verbose: This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <pj...@us...> - 2008-07-08 05:24:18
|
Revision: 4866 http://jython.svn.sourceforge.net/jython/?rev=4866&view=rev Author: pjenvey Date: 2008-07-07 22:24:17 -0700 (Mon, 07 Jul 2008) Log Message: ----------- o make StopIteration (and the like) a 'sink state' in iter and call-iter, to fix the test_iter test_sinkstate_* tests o workaround test_iter test_unpack_iter GC related issues Modified Paths: -------------- branches/asm/Lib/test/test_iter.py branches/asm/src/org/python/core/PyCallIter.java branches/asm/src/org/python/core/PySequenceIter.java Modified: branches/asm/Lib/test/test_iter.py =================================================================== --- branches/asm/Lib/test/test_iter.py 2008-07-08 05:20:37 UTC (rev 4865) +++ branches/asm/Lib/test/test_iter.py 2008-07-08 05:24:17 UTC (rev 4866) @@ -780,11 +780,16 @@ # Test reference count behavior - class C(object): + # XXX: Jython new style objects don't support __del__ yet + from test_weakref import extra_collect + #class C(object): + class C: count = 0 - def __new__(cls): + #def __new__(cls): + def __init__(self): + cls = C cls.count += 1 - return object.__new__(cls) + #return object.__new__(cls) def __del__(self): cls = self.__class__ assert cls.count > 0 @@ -792,6 +797,7 @@ x = C() self.assertEqual(C.count, 1) del x + extra_collect() self.assertEqual(C.count, 0) l = [C(), C(), C()] self.assertEqual(C.count, 3) @@ -800,6 +806,7 @@ except ValueError: pass del l + extra_collect() self.assertEqual(C.count, 0) Modified: branches/asm/src/org/python/core/PyCallIter.java =================================================================== --- branches/asm/src/org/python/core/PyCallIter.java 2008-07-08 05:20:37 UTC (rev 4865) +++ branches/asm/src/org/python/core/PyCallIter.java 2008-07-08 05:24:17 UTC (rev 4866) @@ -15,19 +15,25 @@ } public PyObject __iternext__() { - PyObject val = null; + if (callable == null) { + return null; + } + + PyObject result; try { - val = callable.__call__(); + result = callable.__call__(); } catch (PyException exc) { if (Py.matchException(exc, Py.StopIteration)) { + callable = null; stopException = exc; return null; } throw exc; } - if (val._eq(sentinel).__nonzero__()) { + if (result._eq(sentinel).__nonzero__()) { + callable = null; return null; } - return val; + return result; } } Modified: branches/asm/src/org/python/core/PySequenceIter.java =================================================================== --- branches/asm/src/org/python/core/PySequenceIter.java 2008-07-08 05:20:37 UTC (rev 4865) +++ branches/asm/src/org/python/core/PySequenceIter.java 2008-07-08 05:24:17 UTC (rev 4866) @@ -10,14 +10,24 @@ } public PyObject __iternext__() { + if (seq == null) { + return null; + } + + PyObject result; try { - return seq.__finditem__(idx++); + result = seq.__finditem__(idx++); } catch (PyException exc) { - if (Py.matchException(exc, Py.StopIteration)) + if (Py.matchException(exc, Py.StopIteration)) { + seq = null; return null; + } throw exc; } + if (result == null) { + seq = null; + } + return result; } - } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <pj...@us...> - 2008-07-08 05:20:40
|
Revision: 4865 http://jython.svn.sourceforge.net/jython/?rev=4865&view=rev Author: pjenvey Date: 2008-07-07 22:20:37 -0700 (Mon, 07 Jul 2008) Log Message: ----------- from: http://svn.python.org/projects/python/branches/release25-maint/Lib/test/test_iter.py@33742 Modified Paths: -------------- branches/asm/Lib/test/test_iter.py Modified: branches/asm/Lib/test/test_iter.py =================================================================== --- branches/asm/Lib/test/test_iter.py 2008-07-08 01:15:40 UTC (rev 4864) +++ branches/asm/Lib/test/test_iter.py 2008-07-08 05:20:37 UTC (rev 4865) @@ -1,12 +1,7 @@ # Test iterators. -''' -Commented out features specific to the JVM platform. - - reference counting -''' - import unittest -from test_support import run_unittest, TESTFN, unlink, have_unicode +from test.test_support import run_unittest, TESTFN, unlink, have_unicode # Test result of triple loop (too big to inline) TRIPLETS = [(0, 0, 0), (0, 0, 1), (0, 0, 2), @@ -274,7 +269,7 @@ try: self.assertEqual(list(f), ["0\n", "1\n", "2\n", "3\n", "4\n"]) f.seek(0, 0) - self.assertEqual(list(f.xreadlines()), + self.assertEqual(list(f), ["0\n", "1\n", "2\n", "3\n", "4\n"]) finally: f.close() @@ -307,7 +302,7 @@ try: self.assertEqual(tuple(f), ("0\n", "1\n", "2\n", "3\n", "4\n")) f.seek(0, 0) - self.assertEqual(tuple(f.xreadlines()), + self.assertEqual(tuple(f), ("0\n", "1\n", "2\n", "3\n", "4\n")) finally: f.close() @@ -334,8 +329,8 @@ self.truth = truth def __nonzero__(self): return self.truth - True = Boolean(1) - False = Boolean(0) + bTrue = Boolean(1) + bFalse = Boolean(0) class Seq: def __init__(self, *args): @@ -356,9 +351,9 @@ raise StopIteration return SeqIter(self.vals) - seq = Seq(*([True, False] * 25)) - self.assertEqual(filter(lambda x: not x, seq), [False]*25) - self.assertEqual(filter(lambda x: not x, iter(seq)), [False]*25) + seq = Seq(*([bTrue, bFalse] * 25)) + self.assertEqual(filter(lambda x: not x, seq), [bFalse]*25) + self.assertEqual(filter(lambda x: not x, iter(seq)), [bFalse]*25) # Test max() and min()'s use of iterators. def test_builtin_max_min(self): @@ -428,8 +423,10 @@ # Test zip()'s use of iterators. def test_builtin_zip(self): - # no longer true as of 2.4 - # self.assertRaises(TypeError, zip) + self.assertEqual(zip(), []) + self.assertEqual(zip(*[]), []) + self.assertEqual(zip(*[(1, 2), 'ab']), [(1, 'a'), (2, 'b')]) + self.assertRaises(TypeError, zip, None) self.assertRaises(TypeError, zip, range(10), 42) self.assertRaises(TypeError, zip, range(10), zip) @@ -473,6 +470,34 @@ except OSError: pass + self.assertEqual(zip(xrange(5)), [(i,) for i in range(5)]) + + # Classes that lie about their lengths. + class NoGuessLen5: + def __getitem__(self, i): + if i >= 5: + raise IndexError + return i + + class Guess3Len5(NoGuessLen5): + def __len__(self): + return 3 + + class Guess30Len5(NoGuessLen5): + def __len__(self): + return 30 + + self.assertEqual(len(Guess3Len5()), 3) + self.assertEqual(len(Guess30Len5()), 30) + self.assertEqual(zip(NoGuessLen5()), zip(range(5))) + self.assertEqual(zip(Guess3Len5()), zip(range(5))) + self.assertEqual(zip(Guess30Len5()), zip(range(5))) + + expected = [(i, i) for i in range(5)] + for x in NoGuessLen5(), Guess3Len5(), Guess30Len5(): + for y in NoGuessLen5(), Guess3Len5(), Guess30Len5(): + self.assertEqual(zip(x, y), expected) + # Test reduces()'s use of iterators. def test_builtin_reduce(self): from operator import add @@ -764,19 +789,95 @@ cls = self.__class__ assert cls.count > 0 cls.count -= 1 - #x = C() - #self.assertEqual(C.count, 1) - #del x - #self.assertEqual(C.count, 0) - #l = [C(), C(), C()] - #self.assertEqual(C.count, 3) - #try: - # a, b = iter(l) - #except ValueError: - # pass - #del l - #self.assertEqual(C.count, 0) + x = C() + self.assertEqual(C.count, 1) + del x + self.assertEqual(C.count, 0) + l = [C(), C(), C()] + self.assertEqual(C.count, 3) + try: + a, b = iter(l) + except ValueError: + pass + del l + self.assertEqual(C.count, 0) + + # Make sure StopIteration is a "sink state". + # This tests various things that weren't sink states in Python 2.2.1, + # plus various things that always were fine. + + def test_sinkstate_list(self): + # This used to fail + a = range(5) + b = iter(a) + self.assertEqual(list(b), range(5)) + a.extend(range(5, 10)) + self.assertEqual(list(b), []) + + def test_sinkstate_tuple(self): + a = (0, 1, 2, 3, 4) + b = iter(a) + self.assertEqual(list(b), range(5)) + self.assertEqual(list(b), []) + + def test_sinkstate_string(self): + a = "abcde" + b = iter(a) + self.assertEqual(list(b), ['a', 'b', 'c', 'd', 'e']) + self.assertEqual(list(b), []) + + def test_sinkstate_sequence(self): + # This used to fail + a = SequenceClass(5) + b = iter(a) + self.assertEqual(list(b), range(5)) + a.n = 10 + self.assertEqual(list(b), []) + + def test_sinkstate_callable(self): + # This used to fail + def spam(state=[0]): + i = state[0] + state[0] = i+1 + if i == 10: + raise AssertionError, "shouldn't have gotten this far" + return i + b = iter(spam, 5) + self.assertEqual(list(b), range(5)) + self.assertEqual(list(b), []) + + def test_sinkstate_dict(self): + # XXX For a more thorough test, see towards the end of: + # http://mail.python.org/pipermail/python-dev/2002-July/026512.html + a = {1:1, 2:2, 0:0, 4:4, 3:3} + for b in iter(a), a.iterkeys(), a.iteritems(), a.itervalues(): + b = iter(a) + self.assertEqual(len(list(b)), 5) + self.assertEqual(list(b), []) + + def test_sinkstate_yield(self): + def gen(): + for i in range(5): + yield i + b = gen() + self.assertEqual(list(b), range(5)) + self.assertEqual(list(b), []) + + def test_sinkstate_range(self): + a = xrange(5) + b = iter(a) + self.assertEqual(list(b), range(5)) + self.assertEqual(list(b), []) + + def test_sinkstate_enumerate(self): + a = range(5) + e = enumerate(a) + b = iter(e) + self.assertEqual(list(b), zip(range(5), range(5))) + self.assertEqual(list(b), []) + + def test_main(): run_unittest(TestCase) This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <pj...@us...> - 2008-07-08 01:15:42
|
Revision: 4864 http://jython.svn.sourceforge.net/jython/?rev=4864&view=rev Author: pjenvey Date: 2008-07-07 18:15:40 -0700 (Mon, 07 Jul 2008) Log Message: ----------- avoid implementation detail tests Modified Paths: -------------- branches/asm/Lib/test/test_enumerate.py Modified: branches/asm/Lib/test/test_enumerate.py =================================================================== --- branches/asm/Lib/test/test_enumerate.py 2008-07-08 01:14:55 UTC (rev 4863) +++ branches/asm/Lib/test/test_enumerate.py 2008-07-08 01:15:40 UTC (rev 4864) @@ -197,6 +197,11 @@ def test_main(verbose=None): + if test_support.is_jython: + # XXX: CPython implementation details + del EnumerateTestCase.test_tuple_reuse + del TestReversed.test_len + del TestReversed.test_xrange_optimization testclasses = (EnumerateTestCase, SubclassTestCase, TestEmpty, TestBig, TestReversed) test_support.run_unittest(*testclasses) This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <pj...@us...> - 2008-07-08 01:14:56
|
Revision: 4863 http://jython.svn.sourceforge.net/jython/?rev=4863&view=rev Author: pjenvey Date: 2008-07-07 18:14:55 -0700 (Mon, 07 Jul 2008) Log Message: ----------- from: http://svn.python.org/projects/python/branches/release25-maint/Lib/test/test_enumerate.py@39608 Modified Paths: -------------- branches/asm/Lib/test/test_enumerate.py Modified: branches/asm/Lib/test/test_enumerate.py =================================================================== --- branches/asm/Lib/test/test_enumerate.py 2008-07-08 01:14:04 UTC (rev 4862) +++ branches/asm/Lib/test/test_enumerate.py 2008-07-08 01:14:55 UTC (rev 4863) @@ -1,9 +1,5 @@ -# Taken from Python 2.3.5 - -from __future__ import generators - import unittest -from sets import Set +import sys from test import test_support @@ -55,7 +51,7 @@ def __iter__(self): return self def next(self): - 3/0 + 3 // 0 class N: 'Iterator missing next()' @@ -71,9 +67,7 @@ seq, res = 'abc', [(0,'a'), (1,'b'), (2,'c')] def test_basicfunction(self): - # This one fails. - #self.assertEqual(type(self.enum(self.seq)), self.enum) - # + self.assertEqual(type(self.enum(self.seq)), self.enum) e = self.enum(self.seq) self.assertEqual(iter(e), e) self.assertEqual(list(self.enum(self.seq)), self.res) @@ -111,9 +105,8 @@ def test_tuple_reuse(self): # Tests an implementation detail where tuple is reused # whenever nothing else holds a reference to it - #self.assertEqual(len(Set(map(id, list(enumerate(self.seq))))), len(self.seq)) - #self.assertEqual(len(Set(map(id, enumerate(self.seq)))), min(1,len(self.seq))) - pass + self.assertEqual(len(set(map(id, list(enumerate(self.seq))))), len(self.seq)) + self.assertEqual(len(set(map(id, enumerate(self.seq)))), min(1,len(self.seq))) class MyEnum(enumerate): pass @@ -141,15 +134,72 @@ raise StopIteration def __len__(self): return 5 - for data in 'abc', range(5), tuple(enumerate('abc')), A(): + for data in 'abc', range(5), tuple(enumerate('abc')), A(), xrange(1,17,5): self.assertEqual(list(data)[::-1], list(reversed(data))) self.assertRaises(TypeError, reversed, {}) + def test_xrange_optimization(self): + x = xrange(1) + self.assertEqual(type(reversed(x)), type(iter(x))) + + def test_len(self): + # This is an implementation detail, not an interface requirement + from test.test_iterlen import len + for s in ('hello', tuple('hello'), list('hello'), xrange(5)): + self.assertEqual(len(reversed(s)), len(s)) + r = reversed(s) + list(r) + self.assertEqual(len(r), 0) + class SeqWithWeirdLen: + called = False + def __len__(self): + if not self.called: + self.called = True + return 10 + raise ZeroDivisionError + def __getitem__(self, index): + return index + r = reversed(SeqWithWeirdLen()) + self.assertRaises(ZeroDivisionError, len, r) + + + def test_gc(self): + class Seq: + def __len__(self): + return 10 + def __getitem__(self, index): + return index + s = Seq() + r = reversed(s) + s.r = r + + def test_args(self): + self.assertRaises(TypeError, reversed) + self.assertRaises(TypeError, reversed, [], 'extra') + + def test_bug1229429(self): + # this bug was never in reversed, it was in + # PyObject_CallMethod, and reversed_new calls that sometimes. + if not hasattr(sys, "getrefcount"): + return + def f(): + pass + r = f.__reversed__ = object() + rc = sys.getrefcount(r) + for i in range(10): + try: + reversed(f) + except TypeError: + pass + else: + self.fail("non-callable __reversed__ didn't raise!") + self.assertEqual(rc, sys.getrefcount(r)) + + def test_main(verbose=None): testclasses = (EnumerateTestCase, SubclassTestCase, TestEmpty, TestBig, TestReversed) - for test in testclasses: - test_support.run_unittest(test) + test_support.run_unittest(*testclasses) # verify reference counting import sys This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <pj...@us...> - 2008-07-08 01:14:11
|
Revision: 4862 http://jython.svn.sourceforge.net/jython/?rev=4862&view=rev Author: pjenvey Date: 2008-07-07 18:14:04 -0700 (Mon, 07 Jul 2008) Log Message: ----------- Merged revisions 4851-4861 via svnmerge from https://jython.svn.sourceforge.net/svnroot/jython/trunk/jython ........ r4858 | pjenvey | 2008-07-07 13:58:37 -0700 (Mon, 07 Jul 2008) | 3 lines revert most of r4811: call file___iternext__ instead of __iternext__ which the deriveds override to call next (causing an endless loop) ........ r4860 | pjenvey | 2008-07-07 18:00:51 -0700 (Mon, 07 Jul 2008) | 3 lines allow subclassing of enumerate. avoid an endless loop in an enumerate subclass's next() ........ r4861 | pjenvey | 2008-07-07 18:10:27 -0700 (Mon, 07 Jul 2008) | 1 line coding standards ........ Modified Paths: -------------- branches/asm/src/org/python/core/PyEnumerate.java branches/asm/src/org/python/core/PyFile.java branches/asm/src/org/python/core/PyIterator.java branches/asm/src/templates/mappings Added Paths: ----------- branches/asm/src/org/python/core/PyEnumerateDerived.java branches/asm/src/templates/enumerate.derived Property Changed: ---------------- branches/asm/ Property changes on: branches/asm ___________________________________________________________________ Name: svnmerge-integrated - /trunk/jython:1-4850 + /trunk/jython:1-4861 Modified: branches/asm/src/org/python/core/PyEnumerate.java =================================================================== --- branches/asm/src/org/python/core/PyEnumerate.java 2008-07-08 01:10:27 UTC (rev 4861) +++ branches/asm/src/org/python/core/PyEnumerate.java 2008-07-08 01:14:04 UTC (rev 4862) @@ -1,3 +1,4 @@ +/* Copyright (c) Jython Developers */ package org.python.core; import org.python.expose.ExposedMethod; @@ -4,56 +5,77 @@ import org.python.expose.ExposedNew; import org.python.expose.ExposedType; +/** + * The Python builtin enumerate type. + */ @ExposedType(name = "enumerate", base = PyObject.class) public class PyEnumerate extends PyIterator { - + public static final PyType TYPE = PyType.fromClass(PyEnumerate.class); - private long en_index; /* current index of enumeration */ - private PyObject en_sit; /* secondary iterator of enumeration */ + /** Current index of enumeration. */ + private long index; + /** Secondary iterator of enumeration. */ + private PyObject sit; + + public PyEnumerate(PyType subType) { + super(subType); + } + + public PyEnumerate(PyType subType, PyObject seq) { + super(subType); + index = 0; + sit = seq.__iter__(); + } + + public PyEnumerate(PyObject seq) { + this(TYPE, seq); + } + + public PyObject next() { + return enumerate_next(); + } + @ExposedMethod - public PyObject enumerate_next() { - return next(); + final PyObject enumerate_next() { + return doNext(enumerate___iternext__()); } - + @ExposedMethod - public PyObject enumerate___iter__() { - return __iter__(); + final PyObject enumerate___iter__() { + return super.__iter__(); } @ExposedNew - public final static PyObject enumerate_new(PyNewWrapper new_, - boolean init, - PyType subtype, - PyObject[] args, - String[] keywords) { + public final static PyObject enumerate_new(PyNewWrapper new_, boolean init, PyType subtype, + PyObject[] args, String[] keywords) { if (args.length != 1) { - throw PyBuiltinFunction.DefaultInfo.unexpectedCall(args.length, - false, - "enumerate", - 0, + throw PyBuiltinFunction.DefaultInfo.unexpectedCall(args.length, false, "enumerate", 0, 1); } - return new PyEnumerate(args[0]); + if (new_.for_type == subtype) { + return new PyEnumerate(args[0]); + } else { + return new PyEnumerateDerived(subtype, args[0]); + } } - - public PyEnumerate(PyObject seq) { - en_index = 0; - en_sit = seq.__iter__(); + + public PyObject __iternext__() { + return enumerate___iternext__(); } - - public PyObject __iternext__() { - PyObject next_item; - next_item = en_sit.__iternext__(); - if(next_item == null){ - if(en_sit instanceof PyIterator && ((PyIterator)en_sit).stopException != null){ - stopException = ((PyIterator)en_sit).stopException; + final PyObject enumerate___iternext__() { + PyObject nextItem; + + nextItem = sit.__iternext__(); + if (nextItem == null) { + if (sit instanceof PyIterator && ((PyIterator)sit).stopException != null) { + stopException = ((PyIterator)sit).stopException; } return null; } - return new PyTuple(new PyInteger((int)en_index++), next_item); + return new PyTuple(new PyInteger((int)index++), nextItem); } } Copied: branches/asm/src/org/python/core/PyEnumerateDerived.java (from rev 4861, trunk/jython/src/org/python/core/PyEnumerateDerived.java) =================================================================== --- branches/asm/src/org/python/core/PyEnumerateDerived.java (rev 0) +++ branches/asm/src/org/python/core/PyEnumerateDerived.java 2008-07-08 01:14:04 UTC (rev 4862) @@ -0,0 +1,1005 @@ +/* Generated file, do not modify. See jython/src/templates/gderived.py. */ +package org.python.core; + +public class PyEnumerateDerived extends PyEnumerate implements Slotted { + + public PyObject getSlot(int index) { + return slots[index]; + } + + public void setSlot(int index,PyObject value) { + slots[index]=value; + } + + private PyObject[]slots; + + private PyObject dict; + + public PyObject fastGetDict() { + return dict; + } + + public PyObject getDict() { + return dict; + } + + public void setDict(PyObject newDict) { + if (newDict instanceof PyStringMap||newDict instanceof PyDictionary) { + dict=newDict; + } else { + throw Py.TypeError("__dict__ must be set to a Dictionary "+newDict.getClass().getName()); + } + } + + public void delDict() { + // deleting an object's instance dict makes it grow a new one + dict=new PyStringMap(); + } + + public PyEnumerateDerived(PyType subtype,PyObject seq) { + super(subtype,seq); + slots=new PyObject[subtype.getNumSlots()]; + dict=subtype.instDict(); + } + + public PyString __str__() { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__str__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(); + if (res instanceof PyString) + return(PyString)res; + throw Py.TypeError("__str__"+" returned non-"+"string"+" (type "+res.getType().fastGetName()+")"); + } + return super.__str__(); + } + + public PyString __repr__() { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__repr__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(); + if (res instanceof PyString) + return(PyString)res; + throw Py.TypeError("__repr__"+" returned non-"+"string"+" (type "+res.getType().fastGetName()+")"); + } + return super.__repr__(); + } + + public PyString __hex__() { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__hex__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(); + if (res instanceof PyString) + return(PyString)res; + throw Py.TypeError("__hex__"+" returned non-"+"string"+" (type "+res.getType().fastGetName()+")"); + } + return super.__hex__(); + } + + public PyString __oct__() { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__oct__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(); + if (res instanceof PyString) + return(PyString)res; + throw Py.TypeError("__oct__"+" returned non-"+"string"+" (type "+res.getType().fastGetName()+")"); + } + return super.__oct__(); + } + + public PyFloat __float__() { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__float__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(); + if (res instanceof PyFloat) + return(PyFloat)res; + throw Py.TypeError("__float__"+" returned non-"+"float"+" (type "+res.getType().fastGetName()+")"); + } + return super.__float__(); + } + + public PyComplex __complex__() { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__complex__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(); + if (res instanceof PyComplex) + return(PyComplex)res; + throw Py.TypeError("__complex__"+" returned non-"+"complex"+" (type "+res.getType().fastGetName()+")"); + } + return super.__complex__(); + } + + public PyObject __pos__() { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__pos__"); + if (impl!=null) + return impl.__get__(this,self_type).__call__(); + return super.__pos__(); + } + + public PyObject __neg__() { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__neg__"); + if (impl!=null) + return impl.__get__(this,self_type).__call__(); + return super.__neg__(); + } + + public PyObject __abs__() { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__abs__"); + if (impl!=null) + return impl.__get__(this,self_type).__call__(); + return super.__abs__(); + } + + public PyObject __invert__() { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__invert__"); + if (impl!=null) + return impl.__get__(this,self_type).__call__(); + return super.__invert__(); + } + + public PyObject __reduce__() { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__reduce__"); + if (impl!=null) + return impl.__get__(this,self_type).__call__(); + return super.__reduce__(); + } + + public PyObject __add__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__add__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res==Py.NotImplemented) + return null; + return res; + } + return super.__add__(other); + } + + public PyObject __radd__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__radd__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res==Py.NotImplemented) + return null; + return res; + } + return super.__radd__(other); + } + + public PyObject __sub__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__sub__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res==Py.NotImplemented) + return null; + return res; + } + return super.__sub__(other); + } + + public PyObject __rsub__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__rsub__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res==Py.NotImplemented) + return null; + return res; + } + return super.__rsub__(other); + } + + public PyObject __mul__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__mul__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res==Py.NotImplemented) + return null; + return res; + } + return super.__mul__(other); + } + + public PyObject __rmul__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__rmul__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res==Py.NotImplemented) + return null; + return res; + } + return super.__rmul__(other); + } + + public PyObject __div__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__div__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res==Py.NotImplemented) + return null; + return res; + } + return super.__div__(other); + } + + public PyObject __rdiv__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__rdiv__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res==Py.NotImplemented) + return null; + return res; + } + return super.__rdiv__(other); + } + + public PyObject __floordiv__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__floordiv__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res==Py.NotImplemented) + return null; + return res; + } + return super.__floordiv__(other); + } + + public PyObject __rfloordiv__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__rfloordiv__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res==Py.NotImplemented) + return null; + return res; + } + return super.__rfloordiv__(other); + } + + public PyObject __truediv__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__truediv__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res==Py.NotImplemented) + return null; + return res; + } + return super.__truediv__(other); + } + + public PyObject __rtruediv__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__rtruediv__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res==Py.NotImplemented) + return null; + return res; + } + return super.__rtruediv__(other); + } + + public PyObject __mod__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__mod__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res==Py.NotImplemented) + return null; + return res; + } + return super.__mod__(other); + } + + public PyObject __rmod__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__rmod__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res==Py.NotImplemented) + return null; + return res; + } + return super.__rmod__(other); + } + + public PyObject __divmod__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__divmod__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res==Py.NotImplemented) + return null; + return res; + } + return super.__divmod__(other); + } + + public PyObject __rdivmod__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__rdivmod__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res==Py.NotImplemented) + return null; + return res; + } + return super.__rdivmod__(other); + } + + public PyObject __rpow__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__rpow__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res==Py.NotImplemented) + return null; + return res; + } + return super.__rpow__(other); + } + + public PyObject __lshift__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__lshift__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res==Py.NotImplemented) + return null; + return res; + } + return super.__lshift__(other); + } + + public PyObject __rlshift__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__rlshift__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res==Py.NotImplemented) + return null; + return res; + } + return super.__rlshift__(other); + } + + public PyObject __rshift__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__rshift__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res==Py.NotImplemented) + return null; + return res; + } + return super.__rshift__(other); + } + + public PyObject __rrshift__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__rrshift__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res==Py.NotImplemented) + return null; + return res; + } + return super.__rrshift__(other); + } + + public PyObject __and__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__and__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res==Py.NotImplemented) + return null; + return res; + } + return super.__and__(other); + } + + public PyObject __rand__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__rand__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res==Py.NotImplemented) + return null; + return res; + } + return super.__rand__(other); + } + + public PyObject __or__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__or__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res==Py.NotImplemented) + return null; + return res; + } + return super.__or__(other); + } + + public PyObject __ror__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__ror__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res==Py.NotImplemented) + return null; + return res; + } + return super.__ror__(other); + } + + public PyObject __xor__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__xor__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res==Py.NotImplemented) + return null; + return res; + } + return super.__xor__(other); + } + + public PyObject __rxor__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__rxor__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res==Py.NotImplemented) + return null; + return res; + } + return super.__rxor__(other); + } + + public PyObject __lt__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__lt__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res==Py.NotImplemented) + return null; + return res; + } + return super.__lt__(other); + } + + public PyObject __le__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__le__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res==Py.NotImplemented) + return null; + return res; + } + return super.__le__(other); + } + + public PyObject __gt__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__gt__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res==Py.NotImplemented) + return null; + return res; + } + return super.__gt__(other); + } + + public PyObject __ge__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__ge__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res==Py.NotImplemented) + return null; + return res; + } + return super.__ge__(other); + } + + public PyObject __eq__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__eq__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res==Py.NotImplemented) + return null; + return res; + } + return super.__eq__(other); + } + + public PyObject __ne__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__ne__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res==Py.NotImplemented) + return null; + return res; + } + return super.__ne__(other); + } + + public PyObject __iadd__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__iadd__"); + if (impl!=null) + return impl.__get__(this,self_type).__call__(other); + return super.__iadd__(other); + } + + public PyObject __isub__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__isub__"); + if (impl!=null) + return impl.__get__(this,self_type).__call__(other); + return super.__isub__(other); + } + + public PyObject __imul__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__imul__"); + if (impl!=null) + return impl.__get__(this,self_type).__call__(other); + return super.__imul__(other); + } + + public PyObject __idiv__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__idiv__"); + if (impl!=null) + return impl.__get__(this,self_type).__call__(other); + return super.__idiv__(other); + } + + public PyObject __ifloordiv__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__ifloordiv__"); + if (impl!=null) + return impl.__get__(this,self_type).__call__(other); + return super.__ifloordiv__(other); + } + + public PyObject __itruediv__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__itruediv__"); + if (impl!=null) + return impl.__get__(this,self_type).__call__(other); + return super.__itruediv__(other); + } + + public PyObject __imod__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__imod__"); + if (impl!=null) + return impl.__get__(this,self_type).__call__(other); + return super.__imod__(other); + } + + public PyObject __ipow__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__ipow__"); + if (impl!=null) + return impl.__get__(this,self_type).__call__(other); + return super.__ipow__(other); + } + + public PyObject __ilshift__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__ilshift__"); + if (impl!=null) + return impl.__get__(this,self_type).__call__(other); + return super.__ilshift__(other); + } + + public PyObject __irshift__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__irshift__"); + if (impl!=null) + return impl.__get__(this,self_type).__call__(other); + return super.__irshift__(other); + } + + public PyObject __iand__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__iand__"); + if (impl!=null) + return impl.__get__(this,self_type).__call__(other); + return super.__iand__(other); + } + + public PyObject __ior__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__ior__"); + if (impl!=null) + return impl.__get__(this,self_type).__call__(other); + return super.__ior__(other); + } + + public PyObject __ixor__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__ixor__"); + if (impl!=null) + return impl.__get__(this,self_type).__call__(other); + return super.__ixor__(other); + } + + public PyObject __int__() { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__int__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(); + if (res instanceof PyInteger||res instanceof PyLong) + return(PyObject)res; + throw Py.TypeError("__int__"+" should return an integer"); + } + return super.__int__(); + } + + public PyObject __long__() { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__long__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(); + if (res instanceof PyLong||res instanceof PyInteger) + return res; + throw Py.TypeError("__long__"+" returned non-"+"long"+" (type "+res.getType().fastGetName()+")"); + } + return super.__long__(); + } + + public int hashCode() { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__hash__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(); + if (res instanceof PyInteger) + return((PyInteger)res).getValue(); + throw Py.TypeError("__hash__ should return a int"); + } + if (self_type.lookup("__eq__")!=null||self_type.lookup("__cmp__")!=null) + throw Py.TypeError("unhashable type"); + return super.hashCode(); + } + + public PyUnicode __unicode__() { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__unicode__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(); + if (res instanceof PyUnicode) + return(PyUnicode)res; + if (res instanceof PyString) + return new PyUnicode((PyString)res); + throw Py.TypeError("__unicode__"+" should return a "+"unicode"); + } + return super.__unicode__(); + } + + public int __cmp__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__cmp__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res instanceof PyInteger) { + int v=((PyInteger)res).getValue(); + return v<0?-1:v>0?1:0; + } + throw Py.TypeError("__cmp__ should return a int"); + } + return super.__cmp__(other); + } + + public boolean __nonzero__() { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__nonzero__"); + if (impl==null) { + impl=self_type.lookup("__len__"); + if (impl==null) + return super.__nonzero__(); + } + return impl.__get__(this,self_type).__call__().__nonzero__(); + } + + public boolean __contains__(PyObject o) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__contains__"); + if (impl==null) + return super.__contains__(o); + return impl.__get__(this,self_type).__call__(o).__nonzero__(); + } + + public int __len__() { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__len__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(); + if (res instanceof PyInteger) + return((PyInteger)res).getValue(); + throw Py.TypeError("__len__ should return a int"); + } + return super.__len__(); + } + + public PyObject __iter__() { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__iter__"); + if (impl!=null) + return impl.__get__(this,self_type).__call__(); + impl=self_type.lookup("__getitem__"); + if (impl==null) + return super.__iter__(); + return new PySequenceIter(this); + } + + public PyObject __iternext__() { + PyType self_type=getType(); + PyObject impl=self_type.lookup("next"); + if (impl!=null) { + try { + return impl.__get__(this,self_type).__call__(); + } catch (PyException exc) { + if (Py.matchException(exc,Py.StopIteration)) + return null; + throw exc; + } + } + return super.__iternext__(); // ??? + } + + public PyObject __finditem__(PyObject key) { // ??? + PyType self_type=getType(); + PyObject impl=self_type.lookup("__getitem__"); + if (impl!=null) + try { + return impl.__get__(this,self_type).__call__(key); + } catch (PyException exc) { + if (Py.matchException(exc,Py.LookupError)) + return null; + throw exc; + } + return super.__finditem__(key); + } + + public PyObject __getitem__(PyObject key) { + // Same as __finditem__, without swallowing LookupErrors. This allows + // __getitem__ implementations written in Python to raise custom + // exceptions (such as subclasses of KeyError). + // + // We are forced to duplicate the code, instead of defining __finditem__ + // in terms of __getitem__. That's because PyObject defines __getitem__ + // in terms of __finditem__. Therefore, we would end with an infinite + // loop when self_type.lookup("__getitem__") returns null: + // + // __getitem__ -> super.__getitem__ -> __finditem__ -> __getitem__ + // + // By duplicating the (short) lookup and call code, we are safe, because + // the call chains will be: + // + // __finditem__ -> super.__finditem__ + // + // __getitem__ -> super.__getitem__ -> __finditem__ -> super.__finditem__ + + PyType self_type=getType(); + PyObject impl=self_type.lookup("__getitem__"); + if (impl!=null) + return impl.__get__(this,self_type).__call__(key); + return super.__getitem__(key); + } + + public void __setitem__(PyObject key,PyObject value) { // ??? + PyType self_type=getType(); + PyObject impl=self_type.lookup("__setitem__"); + if (impl!=null) { + impl.__get__(this,self_type).__call__(key,value); + return; + } + super.__setitem__(key,value); + } + + public PyObject __getslice__(PyObject start,PyObject stop,PyObject step) { // ??? + PyType self_type=getType(); + PyObject impl=self_type.lookup("__getslice__"); + if (impl!=null) { + return impl.__get__(this,self_type).__call__(start,stop); + } + return super.__getslice__(start,stop,step); + } + + public void __setslice__(PyObject start,PyObject stop,PyObject step,PyObject value) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__setslice__"); + if (impl!=null) { + impl.__get__(this,self_type).__call__(start,stop,value); + return; + } + super.__setslice__(start,stop,step,value); + } + + public void __delslice__(PyObject start,PyObject stop,PyObject step) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__delslice__"); + if (impl!=null) { + impl.__get__(this,self_type).__call__(start,stop); + return; + } + super.__delslice__(start,stop,step); + } + + public void __delitem__(PyObject key) { // ??? + PyType self_type=getType(); + PyObject impl=self_type.lookup("__delitem__"); + if (impl!=null) { + impl.__get__(this,self_type).__call__(key); + return; + } + super.__delitem__(key); + } + + public PyObject __call__(PyObject args[],String keywords[]) { + ThreadState ts=Py.getThreadState(); + if (ts.recursion_depth++>ts.systemState.getrecursionlimit()) + throw Py.RuntimeError("maximum __call__ recursion depth exceeded"); + try { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__call__"); + if (impl!=null) + return impl.__get__(this,self_type).__call__(args,keywords); + return super.__call__(args,keywords); + } finally { + --ts.recursion_depth; + } + } + + public PyObject __findattr__(String name) { + PyType self_type=getType(); + PyObject getattribute=self_type.lookup("__getattribute__"); + PyString py_name=null; + try { + if (getattribute!=null) { + return getattribute.__get__(this,self_type).__call__(py_name=PyString.fromInterned(name)); + } else { + return super.__findattr__(name); + } + } catch (PyException e) { + if (Py.matchException(e,Py.AttributeError)) { + PyObject getattr=self_type.lookup("__getattr__"); + if (getattr!=null) + try { + return getattr.__get__(this,self_type).__call__(py_name!=null?py_name:PyString.fromInterned(name)); + } catch (PyException e1) { + if (!Py.matchException(e1,Py.AttributeError)) + throw e1; + } + return null; + } + throw e; + } + } + + public void __setattr__(String name,PyObject value) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__setattr__"); + if (impl!=null) { + impl.__get__(this,self_type).__call__(PyString.fromInterned(name),value); + return; + } + super.__setattr__(name,value); + } + + public void __delattr__(String name) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__delattr__"); + if (impl!=null) { + impl.__get__(this,self_type).__call__(PyString.fromInterned(name)); + return; + } + super.__delattr__(name); + } + + public PyObject __get__(PyObject obj,PyObject type) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__get__"); + if (impl!=null) { + if (obj==null) + obj=Py.None; + if (type==null) + type=Py.None; + return impl.__get__(this,self_type).__call__(obj,type); + } + return super.__get__(obj,type); + } + + public void __set__(PyObject obj,PyObject value) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__set__"); + if (impl!=null) { + impl.__get__(this,self_type).__call__(obj,value); + return; + } + super.__set__(obj,value); + } + + public void __delete__(PyObject obj) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__delete__"); + if (impl!=null) { + impl.__get__(this,self_type).__call__(obj); + return; + } + super.__delete__(obj); + } + + public PyObject __pow__(PyObject other,PyObject modulo) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__pow__"); + if (impl!=null) { + PyObject res; + if (modulo==null) { + res=impl.__get__(this,self_type).__call__(other); + } else { + res=impl.__get__(this,self_type).__call__(other,modulo); + } + if (res==Py.NotImplemented) + return null; + return res; + } + return super.__pow__(other,modulo); + } + + public void dispatch__init__(PyType type,PyObject[]args,String[]keywords) { + PyType self_type=getType(); + if (self_type.isSubType(type)) { + PyObject impl=self_type.lookup("__init__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(args,keywords); + if (res!=Py.None) { + throw Py.TypeError(String.format("__init__() should return None, not '%.200s'",res.getType().fastGetName())); + } + } + } + } + + public String toString() { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__repr__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(); + if (!(res instanceof PyString)) + throw Py.TypeError("__repr__ returned non-string (type "+res.getType().fastGetName()+")"); + return((PyString)res).toString(); + } + return super.toString(); + } + +} Modified: branches/asm/src/org/python/core/PyFile.java =================================================================== --- branches/asm/src/org/python/core/PyFile.java 2008-07-08 01:10:27 UTC (rev 4861) +++ branches/asm/src/org/python/core/PyFile.java 2008-07-08 01:14:04 UTC (rev 4862) @@ -360,6 +360,10 @@ } public PyObject __iternext__() { + return file___iternext__(); + } + + final synchronized PyObject file___iternext__() { checkClosed(); String next = file.readline(-1); if (next.length() == 0) { @@ -370,7 +374,7 @@ @ExposedMethod final PyObject file_next() { - PyObject ret = __iternext__(); + PyObject ret = file___iternext__(); if (ret == null) { throw Py.StopIteration(""); } Modified: branches/asm/src/org/python/core/PyIterator.java =================================================================== --- branches/asm/src/org/python/core/PyIterator.java 2008-07-08 01:10:27 UTC (rev 4861) +++ branches/asm/src/org/python/core/PyIterator.java 2008-07-08 01:14:04 UTC (rev 4862) @@ -1,5 +1,4 @@ // Copyright 2000 Finn Bock - package org.python.core; /** @@ -7,12 +6,24 @@ * implementation supply a correct __iter__() and a next() method based on the * __iternext__() implementation. The __iternext__() method must be supplied by * the subclass. - * + * * If the implementation raises a StopIteration exception, it should be stored * in stopException so the correct exception can be thrown to preserve the line * numbers in the traceback. */ public abstract class PyIterator extends PyObject { + + protected PyException stopException; + + public PyIterator() { + } + + public PyIterator(PyType subType) { + super(subType); + } + + public abstract PyObject __iternext__(); + public PyObject __iter__() { return this; } @@ -21,10 +32,21 @@ "x.next() -> the next value, or raise StopIteration" ); + /** + * The exposed next method. + * + * Note that exposed derivable subclasses of PyIterator should override next to call + * doNext(custom___iternext__), as __iternext__ is overridden by the Derived classes. + * + * @return a PyObject result + */ public PyObject next() { - PyObject ret = __iternext__(); - if(ret == null) { - if(stopException != null) { + return doNext(__iternext__()); + } + + protected final PyObject doNext(PyObject ret) { + if (ret == null) { + if (stopException != null) { PyException toThrow = stopException; stopException = null; throw toThrow; @@ -33,8 +55,4 @@ } return ret; } - - public abstract PyObject __iternext__(); - - protected PyException stopException; -} +} Copied: branches/asm/src/templates/enumerate.derived (from rev 4861, trunk/jython/src/templates/enumerate.derived) =================================================================== --- branches/asm/src/templates/enumerate.derived (rev 0) +++ branches/asm/src/templates/enumerate.derived 2008-07-08 01:14:04 UTC (rev 4862) @@ -0,0 +1,4 @@ +base_class: PyEnumerate +want_dict: true +ctr: PyObject seq +incl: object Modified: branches/asm/src/templates/mappings =================================================================== --- branches/asm/src/templates/mappings 2008-07-08 01:10:27 UTC (rev 4861) +++ branches/asm/src/templates/mappings 2008-07-08 01:14:04 UTC (rev 4862) @@ -14,6 +14,7 @@ defaultdict.derived:org.python.modules.collections.PyDefaultDictDerived deque.derived:org.python.modules.collections.PyDequeDerived dict.derived:org.python.core.PyDictionaryDerived +enumerate.derived:org.python.core.PyEnumerateDerived file.derived:org.python.core.PyFileDerived float.derived:org.python.core.PyFloatDerived frozenset.derived:org.python.core.PyFrozenSetDerived This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <pj...@us...> - 2008-07-08 01:10:29
|
Revision: 4861 http://jython.svn.sourceforge.net/jython/?rev=4861&view=rev Author: pjenvey Date: 2008-07-07 18:10:27 -0700 (Mon, 07 Jul 2008) Log Message: ----------- coding standards Modified Paths: -------------- trunk/jython/src/org/python/core/PyEnumerate.java trunk/jython/src/org/python/core/PyIterator.java Modified: trunk/jython/src/org/python/core/PyEnumerate.java =================================================================== --- trunk/jython/src/org/python/core/PyEnumerate.java 2008-07-08 01:00:51 UTC (rev 4860) +++ trunk/jython/src/org/python/core/PyEnumerate.java 2008-07-08 01:10:27 UTC (rev 4861) @@ -1,3 +1,4 @@ +/* Copyright (c) Jython Developers */ package org.python.core; import org.python.expose.ExposedMethod; @@ -4,14 +5,34 @@ import org.python.expose.ExposedNew; import org.python.expose.ExposedType; +/** + * The Python builtin enumerate type. + */ @ExposedType(name = "enumerate", base = PyObject.class) public class PyEnumerate extends PyIterator { - + public static final PyType TYPE = PyType.fromClass(PyEnumerate.class); - private long en_index; /* current index of enumeration */ - private PyObject en_sit; /* secondary iterator of enumeration */ + /** Current index of enumeration. */ + private long index; + /** Secondary iterator of enumeration. */ + private PyObject sit; + + public PyEnumerate(PyType subType) { + super(subType); + } + + public PyEnumerate(PyType subType, PyObject seq) { + super(subType); + index = 0; + sit = seq.__iter__(); + } + + public PyEnumerate(PyObject seq) { + this(TYPE, seq); + } + public PyObject next() { return enumerate_next(); } @@ -27,16 +48,10 @@ } @ExposedNew - public final static PyObject enumerate_new(PyNewWrapper new_, - boolean init, - PyType subtype, - PyObject[] args, - String[] keywords) { + public final static PyObject enumerate_new(PyNewWrapper new_, boolean init, PyType subtype, + PyObject[] args, String[] keywords) { if (args.length != 1) { - throw PyBuiltinFunction.DefaultInfo.unexpectedCall(args.length, - false, - "enumerate", - 0, + throw PyBuiltinFunction.DefaultInfo.unexpectedCall(args.length, false, "enumerate", 0, 1); } if (new_.for_type == subtype) { @@ -45,36 +60,22 @@ return new PyEnumerateDerived(subtype, args[0]); } } - - public PyEnumerate(PyType subType) { - super(subType); - } - - public PyEnumerate(PyType subType, PyObject seq) { - super(subType); - en_index = 0; - en_sit = seq.__iter__(); - } - - public PyEnumerate(PyObject seq) { - this(TYPE, seq); - } - + public PyObject __iternext__() { return enumerate___iternext__(); } final PyObject enumerate___iternext__() { - PyObject next_item; + PyObject nextItem; - next_item = en_sit.__iternext__(); - if(next_item == null){ - if(en_sit instanceof PyIterator && ((PyIterator)en_sit).stopException != null){ - stopException = ((PyIterator)en_sit).stopException; + nextItem = sit.__iternext__(); + if (nextItem == null) { + if (sit instanceof PyIterator && ((PyIterator)sit).stopException != null) { + stopException = ((PyIterator)sit).stopException; } return null; } - return new PyTuple(new PyInteger((int)en_index++), next_item); + return new PyTuple(new PyInteger((int)index++), nextItem); } } Modified: trunk/jython/src/org/python/core/PyIterator.java =================================================================== --- trunk/jython/src/org/python/core/PyIterator.java 2008-07-08 01:00:51 UTC (rev 4860) +++ trunk/jython/src/org/python/core/PyIterator.java 2008-07-08 01:10:27 UTC (rev 4861) @@ -1,5 +1,4 @@ // Copyright 2000 Finn Bock - package org.python.core; /** @@ -7,13 +6,15 @@ * implementation supply a correct __iter__() and a next() method based on the * __iternext__() implementation. The __iternext__() method must be supplied by * the subclass. - * + * * If the implementation raises a StopIteration exception, it should be stored * in stopException so the correct exception can be thrown to preserve the line * numbers in the traceback. */ public abstract class PyIterator extends PyObject { + protected PyException stopException; + public PyIterator() { } @@ -21,6 +22,8 @@ super(subType); } + public abstract PyObject __iternext__(); + public PyObject __iter__() { return this; } @@ -42,8 +45,8 @@ } protected final PyObject doNext(PyObject ret) { - if(ret == null) { - if(stopException != null) { + if (ret == null) { + if (stopException != null) { PyException toThrow = stopException; stopException = null; throw toThrow; @@ -52,8 +55,4 @@ } return ret; } - - public abstract PyObject __iternext__(); - - protected PyException stopException; -} +} This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <pj...@us...> - 2008-07-08 01:00:53
|
Revision: 4860 http://jython.svn.sourceforge.net/jython/?rev=4860&view=rev Author: pjenvey Date: 2008-07-07 18:00:51 -0700 (Mon, 07 Jul 2008) Log Message: ----------- allow subclassing of enumerate. avoid an endless loop in an enumerate subclass's next() Modified Paths: -------------- trunk/jython/src/org/python/core/PyEnumerate.java trunk/jython/src/org/python/core/PyIterator.java trunk/jython/src/templates/mappings Added Paths: ----------- trunk/jython/src/org/python/core/PyEnumerateDerived.java trunk/jython/src/templates/enumerate.derived Modified: trunk/jython/src/org/python/core/PyEnumerate.java =================================================================== --- trunk/jython/src/org/python/core/PyEnumerate.java 2008-07-07 23:21:43 UTC (rev 4859) +++ trunk/jython/src/org/python/core/PyEnumerate.java 2008-07-08 01:00:51 UTC (rev 4860) @@ -12,14 +12,18 @@ private long en_index; /* current index of enumeration */ private PyObject en_sit; /* secondary iterator of enumeration */ + public PyObject next() { + return enumerate_next(); + } + @ExposedMethod - public PyObject enumerate_next() { - return next(); + final PyObject enumerate_next() { + return doNext(enumerate___iternext__()); } - + @ExposedMethod - public PyObject enumerate___iter__() { - return __iter__(); + final PyObject enumerate___iter__() { + return super.__iter__(); } @ExposedNew @@ -35,15 +39,32 @@ 0, 1); } - return new PyEnumerate(args[0]); + if (new_.for_type == subtype) { + return new PyEnumerate(args[0]); + } else { + return new PyEnumerateDerived(subtype, args[0]); + } } - public PyEnumerate(PyObject seq) { + public PyEnumerate(PyType subType) { + super(subType); + } + + public PyEnumerate(PyType subType, PyObject seq) { + super(subType); en_index = 0; en_sit = seq.__iter__(); } + public PyEnumerate(PyObject seq) { + this(TYPE, seq); + } + public PyObject __iternext__() { + return enumerate___iternext__(); + } + + final PyObject enumerate___iternext__() { PyObject next_item; next_item = en_sit.__iternext__(); Added: trunk/jython/src/org/python/core/PyEnumerateDerived.java =================================================================== --- trunk/jython/src/org/python/core/PyEnumerateDerived.java (rev 0) +++ trunk/jython/src/org/python/core/PyEnumerateDerived.java 2008-07-08 01:00:51 UTC (rev 4860) @@ -0,0 +1,1005 @@ +/* Generated file, do not modify. See jython/src/templates/gderived.py. */ +package org.python.core; + +public class PyEnumerateDerived extends PyEnumerate implements Slotted { + + public PyObject getSlot(int index) { + return slots[index]; + } + + public void setSlot(int index,PyObject value) { + slots[index]=value; + } + + private PyObject[]slots; + + private PyObject dict; + + public PyObject fastGetDict() { + return dict; + } + + public PyObject getDict() { + return dict; + } + + public void setDict(PyObject newDict) { + if (newDict instanceof PyStringMap||newDict instanceof PyDictionary) { + dict=newDict; + } else { + throw Py.TypeError("__dict__ must be set to a Dictionary "+newDict.getClass().getName()); + } + } + + public void delDict() { + // deleting an object's instance dict makes it grow a new one + dict=new PyStringMap(); + } + + public PyEnumerateDerived(PyType subtype,PyObject seq) { + super(subtype,seq); + slots=new PyObject[subtype.getNumSlots()]; + dict=subtype.instDict(); + } + + public PyString __str__() { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__str__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(); + if (res instanceof PyString) + return(PyString)res; + throw Py.TypeError("__str__"+" returned non-"+"string"+" (type "+res.getType().fastGetName()+")"); + } + return super.__str__(); + } + + public PyString __repr__() { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__repr__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(); + if (res instanceof PyString) + return(PyString)res; + throw Py.TypeError("__repr__"+" returned non-"+"string"+" (type "+res.getType().fastGetName()+")"); + } + return super.__repr__(); + } + + public PyString __hex__() { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__hex__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(); + if (res instanceof PyString) + return(PyString)res; + throw Py.TypeError("__hex__"+" returned non-"+"string"+" (type "+res.getType().fastGetName()+")"); + } + return super.__hex__(); + } + + public PyString __oct__() { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__oct__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(); + if (res instanceof PyString) + return(PyString)res; + throw Py.TypeError("__oct__"+" returned non-"+"string"+" (type "+res.getType().fastGetName()+")"); + } + return super.__oct__(); + } + + public PyFloat __float__() { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__float__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(); + if (res instanceof PyFloat) + return(PyFloat)res; + throw Py.TypeError("__float__"+" returned non-"+"float"+" (type "+res.getType().fastGetName()+")"); + } + return super.__float__(); + } + + public PyComplex __complex__() { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__complex__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(); + if (res instanceof PyComplex) + return(PyComplex)res; + throw Py.TypeError("__complex__"+" returned non-"+"complex"+" (type "+res.getType().fastGetName()+")"); + } + return super.__complex__(); + } + + public PyObject __pos__() { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__pos__"); + if (impl!=null) + return impl.__get__(this,self_type).__call__(); + return super.__pos__(); + } + + public PyObject __neg__() { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__neg__"); + if (impl!=null) + return impl.__get__(this,self_type).__call__(); + return super.__neg__(); + } + + public PyObject __abs__() { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__abs__"); + if (impl!=null) + return impl.__get__(this,self_type).__call__(); + return super.__abs__(); + } + + public PyObject __invert__() { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__invert__"); + if (impl!=null) + return impl.__get__(this,self_type).__call__(); + return super.__invert__(); + } + + public PyObject __reduce__() { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__reduce__"); + if (impl!=null) + return impl.__get__(this,self_type).__call__(); + return super.__reduce__(); + } + + public PyObject __add__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__add__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res==Py.NotImplemented) + return null; + return res; + } + return super.__add__(other); + } + + public PyObject __radd__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__radd__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res==Py.NotImplemented) + return null; + return res; + } + return super.__radd__(other); + } + + public PyObject __sub__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__sub__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res==Py.NotImplemented) + return null; + return res; + } + return super.__sub__(other); + } + + public PyObject __rsub__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__rsub__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res==Py.NotImplemented) + return null; + return res; + } + return super.__rsub__(other); + } + + public PyObject __mul__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__mul__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res==Py.NotImplemented) + return null; + return res; + } + return super.__mul__(other); + } + + public PyObject __rmul__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__rmul__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res==Py.NotImplemented) + return null; + return res; + } + return super.__rmul__(other); + } + + public PyObject __div__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__div__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res==Py.NotImplemented) + return null; + return res; + } + return super.__div__(other); + } + + public PyObject __rdiv__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__rdiv__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res==Py.NotImplemented) + return null; + return res; + } + return super.__rdiv__(other); + } + + public PyObject __floordiv__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__floordiv__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res==Py.NotImplemented) + return null; + return res; + } + return super.__floordiv__(other); + } + + public PyObject __rfloordiv__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__rfloordiv__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res==Py.NotImplemented) + return null; + return res; + } + return super.__rfloordiv__(other); + } + + public PyObject __truediv__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__truediv__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res==Py.NotImplemented) + return null; + return res; + } + return super.__truediv__(other); + } + + public PyObject __rtruediv__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__rtruediv__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res==Py.NotImplemented) + return null; + return res; + } + return super.__rtruediv__(other); + } + + public PyObject __mod__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__mod__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res==Py.NotImplemented) + return null; + return res; + } + return super.__mod__(other); + } + + public PyObject __rmod__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__rmod__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res==Py.NotImplemented) + return null; + return res; + } + return super.__rmod__(other); + } + + public PyObject __divmod__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__divmod__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res==Py.NotImplemented) + return null; + return res; + } + return super.__divmod__(other); + } + + public PyObject __rdivmod__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__rdivmod__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res==Py.NotImplemented) + return null; + return res; + } + return super.__rdivmod__(other); + } + + public PyObject __rpow__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__rpow__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res==Py.NotImplemented) + return null; + return res; + } + return super.__rpow__(other); + } + + public PyObject __lshift__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__lshift__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res==Py.NotImplemented) + return null; + return res; + } + return super.__lshift__(other); + } + + public PyObject __rlshift__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__rlshift__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res==Py.NotImplemented) + return null; + return res; + } + return super.__rlshift__(other); + } + + public PyObject __rshift__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__rshift__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res==Py.NotImplemented) + return null; + return res; + } + return super.__rshift__(other); + } + + public PyObject __rrshift__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__rrshift__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res==Py.NotImplemented) + return null; + return res; + } + return super.__rrshift__(other); + } + + public PyObject __and__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__and__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res==Py.NotImplemented) + return null; + return res; + } + return super.__and__(other); + } + + public PyObject __rand__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__rand__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res==Py.NotImplemented) + return null; + return res; + } + return super.__rand__(other); + } + + public PyObject __or__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__or__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res==Py.NotImplemented) + return null; + return res; + } + return super.__or__(other); + } + + public PyObject __ror__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__ror__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res==Py.NotImplemented) + return null; + return res; + } + return super.__ror__(other); + } + + public PyObject __xor__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__xor__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res==Py.NotImplemented) + return null; + return res; + } + return super.__xor__(other); + } + + public PyObject __rxor__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__rxor__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res==Py.NotImplemented) + return null; + return res; + } + return super.__rxor__(other); + } + + public PyObject __lt__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__lt__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res==Py.NotImplemented) + return null; + return res; + } + return super.__lt__(other); + } + + public PyObject __le__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__le__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res==Py.NotImplemented) + return null; + return res; + } + return super.__le__(other); + } + + public PyObject __gt__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__gt__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res==Py.NotImplemented) + return null; + return res; + } + return super.__gt__(other); + } + + public PyObject __ge__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__ge__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res==Py.NotImplemented) + return null; + return res; + } + return super.__ge__(other); + } + + public PyObject __eq__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__eq__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res==Py.NotImplemented) + return null; + return res; + } + return super.__eq__(other); + } + + public PyObject __ne__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__ne__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res==Py.NotImplemented) + return null; + return res; + } + return super.__ne__(other); + } + + public PyObject __iadd__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__iadd__"); + if (impl!=null) + return impl.__get__(this,self_type).__call__(other); + return super.__iadd__(other); + } + + public PyObject __isub__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__isub__"); + if (impl!=null) + return impl.__get__(this,self_type).__call__(other); + return super.__isub__(other); + } + + public PyObject __imul__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__imul__"); + if (impl!=null) + return impl.__get__(this,self_type).__call__(other); + return super.__imul__(other); + } + + public PyObject __idiv__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__idiv__"); + if (impl!=null) + return impl.__get__(this,self_type).__call__(other); + return super.__idiv__(other); + } + + public PyObject __ifloordiv__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__ifloordiv__"); + if (impl!=null) + return impl.__get__(this,self_type).__call__(other); + return super.__ifloordiv__(other); + } + + public PyObject __itruediv__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__itruediv__"); + if (impl!=null) + return impl.__get__(this,self_type).__call__(other); + return super.__itruediv__(other); + } + + public PyObject __imod__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__imod__"); + if (impl!=null) + return impl.__get__(this,self_type).__call__(other); + return super.__imod__(other); + } + + public PyObject __ipow__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__ipow__"); + if (impl!=null) + return impl.__get__(this,self_type).__call__(other); + return super.__ipow__(other); + } + + public PyObject __ilshift__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__ilshift__"); + if (impl!=null) + return impl.__get__(this,self_type).__call__(other); + return super.__ilshift__(other); + } + + public PyObject __irshift__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__irshift__"); + if (impl!=null) + return impl.__get__(this,self_type).__call__(other); + return super.__irshift__(other); + } + + public PyObject __iand__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__iand__"); + if (impl!=null) + return impl.__get__(this,self_type).__call__(other); + return super.__iand__(other); + } + + public PyObject __ior__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__ior__"); + if (impl!=null) + return impl.__get__(this,self_type).__call__(other); + return super.__ior__(other); + } + + public PyObject __ixor__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__ixor__"); + if (impl!=null) + return impl.__get__(this,self_type).__call__(other); + return super.__ixor__(other); + } + + public PyObject __int__() { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__int__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(); + if (res instanceof PyInteger||res instanceof PyLong) + return(PyObject)res; + throw Py.TypeError("__int__"+" should return an integer"); + } + return super.__int__(); + } + + public PyObject __long__() { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__long__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(); + if (res instanceof PyLong||res instanceof PyInteger) + return res; + throw Py.TypeError("__long__"+" returned non-"+"long"+" (type "+res.getType().fastGetName()+")"); + } + return super.__long__(); + } + + public int hashCode() { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__hash__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(); + if (res instanceof PyInteger) + return((PyInteger)res).getValue(); + throw Py.TypeError("__hash__ should return a int"); + } + if (self_type.lookup("__eq__")!=null||self_type.lookup("__cmp__")!=null) + throw Py.TypeError("unhashable type"); + return super.hashCode(); + } + + public PyUnicode __unicode__() { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__unicode__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(); + if (res instanceof PyUnicode) + return(PyUnicode)res; + if (res instanceof PyString) + return new PyUnicode((PyString)res); + throw Py.TypeError("__unicode__"+" should return a "+"unicode"); + } + return super.__unicode__(); + } + + public int __cmp__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__cmp__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res instanceof PyInteger) { + int v=((PyInteger)res).getValue(); + return v<0?-1:v>0?1:0; + } + throw Py.TypeError("__cmp__ should return a int"); + } + return super.__cmp__(other); + } + + public boolean __nonzero__() { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__nonzero__"); + if (impl==null) { + impl=self_type.lookup("__len__"); + if (impl==null) + return super.__nonzero__(); + } + return impl.__get__(this,self_type).__call__().__nonzero__(); + } + + public boolean __contains__(PyObject o) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__contains__"); + if (impl==null) + return super.__contains__(o); + return impl.__get__(this,self_type).__call__(o).__nonzero__(); + } + + public int __len__() { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__len__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(); + if (res instanceof PyInteger) + return((PyInteger)res).getValue(); + throw Py.TypeError("__len__ should return a int"); + } + return super.__len__(); + } + + public PyObject __iter__() { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__iter__"); + if (impl!=null) + return impl.__get__(this,self_type).__call__(); + impl=self_type.lookup("__getitem__"); + if (impl==null) + return super.__iter__(); + return new PySequenceIter(this); + } + + public PyObject __iternext__() { + PyType self_type=getType(); + PyObject impl=self_type.lookup("next"); + if (impl!=null) { + try { + return impl.__get__(this,self_type).__call__(); + } catch (PyException exc) { + if (Py.matchException(exc,Py.StopIteration)) + return null; + throw exc; + } + } + return super.__iternext__(); // ??? + } + + public PyObject __finditem__(PyObject key) { // ??? + PyType self_type=getType(); + PyObject impl=self_type.lookup("__getitem__"); + if (impl!=null) + try { + return impl.__get__(this,self_type).__call__(key); + } catch (PyException exc) { + if (Py.matchException(exc,Py.LookupError)) + return null; + throw exc; + } + return super.__finditem__(key); + } + + public PyObject __getitem__(PyObject key) { + // Same as __finditem__, without swallowing LookupErrors. This allows + // __getitem__ implementations written in Python to raise custom + // exceptions (such as subclasses of KeyError). + // + // We are forced to duplicate the code, instead of defining __finditem__ + // in terms of __getitem__. That's because PyObject defines __getitem__ + // in terms of __finditem__. Therefore, we would end with an infinite + // loop when self_type.lookup("__getitem__") returns null: + // + // __getitem__ -> super.__getitem__ -> __finditem__ -> __getitem__ + // + // By duplicating the (short) lookup and call code, we are safe, because + // the call chains will be: + // + // __finditem__ -> super.__finditem__ + // + // __getitem__ -> super.__getitem__ -> __finditem__ -> super.__finditem__ + + PyType self_type=getType(); + PyObject impl=self_type.lookup("__getitem__"); + if (impl!=null) + return impl.__get__(this,self_type).__call__(key); + return super.__getitem__(key); + } + + public void __setitem__(PyObject key,PyObject value) { // ??? + PyType self_type=getType(); + PyObject impl=self_type.lookup("__setitem__"); + if (impl!=null) { + impl.__get__(this,self_type).__call__(key,value); + return; + } + super.__setitem__(key,value); + } + + public PyObject __getslice__(PyObject start,PyObject stop,PyObject step) { // ??? + PyType self_type=getType(); + PyObject impl=self_type.lookup("__getslice__"); + if (impl!=null) { + return impl.__get__(this,self_type).__call__(start,stop); + } + return super.__getslice__(start,stop,step); + } + + public void __setslice__(PyObject start,PyObject stop,PyObject step,PyObject value) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__setslice__"); + if (impl!=null) { + impl.__get__(this,self_type).__call__(start,stop,value); + return; + } + super.__setslice__(start,stop,step,value); + } + + public void __delslice__(PyObject start,PyObject stop,PyObject step) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__delslice__"); + if (impl!=null) { + impl.__get__(this,self_type).__call__(start,stop); + return; + } + super.__delslice__(start,stop,step); + } + + public void __delitem__(PyObject key) { // ??? + PyType self_type=getType(); + PyObject impl=self_type.lookup("__delitem__"); + if (impl!=null) { + impl.__get__(this,self_type).__call__(key); + return; + } + super.__delitem__(key); + } + + public PyObject __call__(PyObject args[],String keywords[]) { + ThreadState ts=Py.getThreadState(); + if (ts.recursion_depth++>ts.systemState.getrecursionlimit()) + throw Py.RuntimeError("maximum __call__ recursion depth exceeded"); + try { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__call__"); + if (impl!=null) + return impl.__get__(this,self_type).__call__(args,keywords); + return super.__call__(args,keywords); + } finally { + --ts.recursion_depth; + } + } + + public PyObject __findattr__(String name) { + PyType self_type=getType(); + PyObject getattribute=self_type.lookup("__getattribute__"); + PyString py_name=null; + try { + if (getattribute!=null) { + return getattribute.__get__(this,self_type).__call__(py_name=PyString.fromInterned(name)); + } else { + return super.__findattr__(name); + } + } catch (PyException e) { + if (Py.matchException(e,Py.AttributeError)) { + PyObject getattr=self_type.lookup("__getattr__"); + if (getattr!=null) + try { + return getattr.__get__(this,self_type).__call__(py_name!=null?py_name:PyString.fromInterned(name)); + } catch (PyException e1) { + if (!Py.matchException(e1,Py.AttributeError)) + throw e1; + } + return null; + } + throw e; + } + } + + public void __setattr__(String name,PyObject value) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__setattr__"); + if (impl!=null) { + impl.__get__(this,self_type).__call__(PyString.fromInterned(name),value); + return; + } + super.__setattr__(name,value); + } + + public void __delattr__(String name) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__delattr__"); + if (impl!=null) { + impl.__get__(this,self_type).__call__(PyString.fromInterned(name)); + return; + } + super.__delattr__(name); + } + + public PyObject __get__(PyObject obj,PyObject type) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__get__"); + if (impl!=null) { + if (obj==null) + obj=Py.None; + if (type==null) + type=Py.None; + return impl.__get__(this,self_type).__call__(obj,type); + } + return super.__get__(obj,type); + } + + public void __set__(PyObject obj,PyObject value) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__set__"); + if (impl!=null) { + impl.__get__(this,self_type).__call__(obj,value); + return; + } + super.__set__(obj,value); + } + + public void __delete__(PyObject obj) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__delete__"); + if (impl!=null) { + impl.__get__(this,self_type).__call__(obj); + return; + } + super.__delete__(obj); + } + + public PyObject __pow__(PyObject other,PyObject modulo) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__pow__"); + if (impl!=null) { + PyObject res; + if (modulo==null) { + res=impl.__get__(this,self_type).__call__(other); + } else { + res=impl.__get__(this,self_type).__call__(other,modulo); + } + if (res==Py.NotImplemented) + return null; + return res; + } + return super.__pow__(other,modulo); + } + + public void dispatch__init__(PyType type,PyObject[]args,String[]keywords) { + PyType self_type=getType(); + if (self_type.isSubType(type)) { + PyObject impl=self_type.lookup("__init__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(args,keywords); + if (res!=Py.None) { + throw Py.TypeError(String.format("__init__() should return None, not '%.200s'",res.getType().fastGetName())); + } + } + } + } + + public String toString() { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__repr__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(); + if (!(res instanceof PyString)) + throw Py.TypeError("__repr__ returned non-string (type "+res.getType().fastGetName()+")"); + return((PyString)res).toString(); + } + return super.toString(); + } + +} Modified: trunk/jython/src/org/python/core/PyIterator.java =================================================================== --- trunk/jython/src/org/python/core/PyIterator.java 2008-07-07 23:21:43 UTC (rev 4859) +++ trunk/jython/src/org/python/core/PyIterator.java 2008-07-08 01:00:51 UTC (rev 4860) @@ -13,6 +13,14 @@ * numbers in the traceback. */ public abstract class PyIterator extends PyObject { + + public PyIterator() { + } + + public PyIterator(PyType subType) { + super(subType); + } + public PyObject __iter__() { return this; } @@ -21,8 +29,19 @@ "x.next() -> the next value, or raise StopIteration" ); + /** + * The exposed next method. + * + * Note that exposed derivable subclasses of PyIterator should override next to call + * doNext(custom___iternext__), as __iternext__ is overridden by the Derived classes. + * + * @return a PyObject result + */ public PyObject next() { - PyObject ret = __iternext__(); + return doNext(__iternext__()); + } + + protected final PyObject doNext(PyObject ret) { if(ret == null) { if(stopException != null) { PyException toThrow = stopException; Added: trunk/jython/src/templates/enumerate.derived =================================================================== --- trunk/jython/src/templates/enumerate.derived (rev 0) +++ trunk/jython/src/templates/enumerate.derived 2008-07-08 01:00:51 UTC (rev 4860) @@ -0,0 +1,4 @@ +base_class: PyEnumerate +want_dict: true +ctr: PyObject seq +incl: object Modified: trunk/jython/src/templates/mappings =================================================================== --- trunk/jython/src/templates/mappings 2008-07-07 23:21:43 UTC (rev 4859) +++ trunk/jython/src/templates/mappings 2008-07-08 01:00:51 UTC (rev 4860) @@ -13,6 +13,7 @@ defaultdict.derived:org.python.modules.collections.PyDefaultDictDerived deque.derived:org.python.modules.collections.PyDequeDerived dict.derived:org.python.core.PyDictionaryDerived +enumerate.derived:org.python.core.PyEnumerateDerived file.derived:org.python.core.PyFileDerived float.derived:org.python.core.PyFloatDerived frozenset.derived:org.python.core.PyFrozenSetDerived This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <pj...@us...> - 2008-07-07 23:21:44
|
Revision: 4859 http://jython.svn.sourceforge.net/jython/?rev=4859&view=rev Author: pjenvey Date: 2008-07-07 16:21:43 -0700 (Mon, 07 Jul 2008) Log Message: ----------- simplify Modified Paths: -------------- branches/asm/src/org/python/core/PyException.java Modified: branches/asm/src/org/python/core/PyException.java =================================================================== --- branches/asm/src/org/python/core/PyException.java 2008-07-07 20:58:37 UTC (rev 4858) +++ branches/asm/src/org/python/core/PyException.java 2008-07-07 23:21:43 UTC (rev 4859) @@ -203,7 +203,7 @@ * @return true if an exception instance */ public static boolean isExceptionInstance(PyObject obj) { - return obj instanceof PyInstance || obj.getType().isSubType((PyType)Py.BaseException); + return obj instanceof PyInstance || obj instanceof PyBaseException; } /** This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <pj...@us...> - 2008-07-07 20:58:47
|
Revision: 4858 http://jython.svn.sourceforge.net/jython/?rev=4858&view=rev Author: pjenvey Date: 2008-07-07 13:58:37 -0700 (Mon, 07 Jul 2008) Log Message: ----------- revert most of r4811: call file___iternext__ instead of __iternext__ which the deriveds override to call next (causing an endless loop) Modified Paths: -------------- trunk/jython/src/org/python/core/PyFile.java Modified: trunk/jython/src/org/python/core/PyFile.java =================================================================== --- trunk/jython/src/org/python/core/PyFile.java 2008-07-07 19:59:32 UTC (rev 4857) +++ trunk/jython/src/org/python/core/PyFile.java 2008-07-07 20:58:37 UTC (rev 4858) @@ -360,6 +360,10 @@ } public PyObject __iternext__() { + return file___iternext__(); + } + + final synchronized PyObject file___iternext__() { checkClosed(); String next = file.readline(-1); if (next.length() == 0) { @@ -370,7 +374,7 @@ @ExposedMethod final PyObject file_next() { - PyObject ret = __iternext__(); + PyObject ret = file___iternext__(); if (ret == null) { throw Py.StopIteration(""); } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <pj...@us...> - 2008-07-07 19:59:42
|
Revision: 4857 http://jython.svn.sourceforge.net/jython/?rev=4857&view=rev Author: pjenvey Date: 2008-07-07 12:59:32 -0700 (Mon, 07 Jul 2008) Log Message: ----------- no need to go through __builtin__ for issubclass Modified Paths: -------------- branches/asm/src/org/python/core/PyException.java Modified: branches/asm/src/org/python/core/PyException.java =================================================================== --- branches/asm/src/org/python/core/PyException.java 2008-07-07 11:22:16 UTC (rev 4856) +++ branches/asm/src/org/python/core/PyException.java 2008-07-07 19:59:32 UTC (rev 4857) @@ -108,7 +108,7 @@ } if (isExceptionClass(type)) { - if (inClass == null || !__builtin__.issubclass(inClass, type)) { + if (inClass == null || !Py.isSubClass(inClass, type)) { PyObject[] args; // Don't decouple a tuple into args when it's a This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <zy...@us...> - 2008-07-07 11:22:19
|
Revision: 4856 http://jython.svn.sourceforge.net/jython/?rev=4856&view=rev Author: zyasoft Date: 2008-07-07 04:22:16 -0700 (Mon, 07 Jul 2008) Log Message: ----------- Removed double-checked locking used to init ThreadStateMap; didn't make sense to do any locking here anyway. Moved trycatch emit in visitWith to be where it ahappens (doesn't change output, but makes it easier to follow code). Modified Paths: -------------- branches/asm/src/org/python/compiler/CodeCompiler.java branches/asm/src/org/python/core/Py.java branches/asm/src/org/python/core/ThreadStateMapping.java Modified: branches/asm/src/org/python/compiler/CodeCompiler.java =================================================================== --- branches/asm/src/org/python/compiler/CodeCompiler.java 2008-07-07 09:08:22 UTC (rev 4855) +++ branches/asm/src/org/python/compiler/CodeCompiler.java 2008-07-07 11:22:16 UTC (rev 4856) @@ -2021,8 +2021,6 @@ Method call = Method.getMethod("org.python.core.PyObject __call__ ()"); Method call3 = Method.getMethod("org.python.core.PyObject __call__ (org.python.core.PyObject,org.python.core.PyObject,org.python.core.PyObject)"); - code.trycatch(label_body_start, label_body_end, label_catch, "java/lang/Throwable"); - setline(node); // mgr = (EXPR) @@ -2044,6 +2042,7 @@ // exc = True # not necessary, since we don't exec finally if exception // try-catch block here + code.trycatch(label_body_start, label_body_end, label_catch, "java/lang/Throwable"); // VAR = value # Only if "as VAR" is present code.label(label_body_start); Modified: branches/asm/src/org/python/core/Py.java =================================================================== --- branches/asm/src/org/python/core/Py.java 2008-07-07 09:08:22 UTC (rev 4855) +++ branches/asm/src/org/python/core/Py.java 2008-07-07 11:22:16 UTC (rev 4856) @@ -1168,20 +1168,14 @@ } Py.runCode(code, locals, globals); } - private static ThreadStateMapping threadStateMapping = null; + + private final static ThreadStateMapping threadStateMapping = new ThreadStateMapping(); public static final ThreadState getThreadState() { return getThreadState(null); } public static final ThreadState getThreadState(PySystemState newSystemState) { - if (threadStateMapping == null) { - synchronized (Py.class) { - if (threadStateMapping == null) { - threadStateMapping = new ThreadStateMapping(); - } - } - } return threadStateMapping.getThreadState(newSystemState); } Modified: branches/asm/src/org/python/core/ThreadStateMapping.java =================================================================== --- branches/asm/src/org/python/core/ThreadStateMapping.java 2008-07-07 09:08:22 UTC (rev 4855) +++ branches/asm/src/org/python/core/ThreadStateMapping.java 2008-07-07 11:22:16 UTC (rev 4856) @@ -1,7 +1,7 @@ package org.python.core; class ThreadStateMapping { - private static ThreadLocal<ThreadState> cachedThreadState = new ThreadLocal<ThreadState>(); + private static final ThreadLocal<ThreadState> cachedThreadState = new ThreadLocal<ThreadState>(); public ThreadState getThreadState(PySystemState newSystemState) { ThreadState ts = cachedThreadState.get(); This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <fwi...@us...> - 2008-07-07 09:08:23
|
Revision: 4855 http://jython.svn.sourceforge.net/jython/?rev=4855&view=rev Author: fwierzbicki Date: 2008-07-07 02:08:22 -0700 (Mon, 07 Jul 2008) Log Message: ----------- Create a jython-complete.jar to make it easier to put out a 2.5 alpha. Modified Paths: -------------- branches/asm/build.xml Modified: branches/asm/build.xml =================================================================== --- branches/asm/build.xml 2008-07-07 08:40:01 UTC (rev 4854) +++ branches/asm/build.xml 2008-07-07 09:08:22 UTC (rev 4855) @@ -518,6 +518,7 @@ <target name="jarjar" depends="init" unless="jarjar.notneeded"> <taskdef name="jarjar" classname="com.tonicsystems.jarjar.JarJarTask" classpath="extlibs/jarjar-0.7.jar"/> <jarjar destfile="${output.dir}/jarjar.jar"> + <zipfileset src="extlibs/antlr-runtime-3.1b1.jar"/> <zipfileset src="extlibs/asm-3.1.jar"/> <zipfileset src="extlibs/asm-commons-3.1.jar"/> <zipfileset src="extlibs/asm-util-3.1.jar"/> @@ -534,6 +535,30 @@ </unjar> </target> + <target name="jar-complete" depends="compile,expose,jarjar"> + <jar destfile="${dist.dir}/jython-complete.jar"> + <fileset dir="${compile.dir}"/> + <fileset dir="${exposed.dir}"/> + <fileset dir="${jarjar.dir}"> + </fileset> + <manifest> + <attribute name="Main-Class" value="org.python.util.jython" /> + <attribute name="Built-By" value="${user.name}" /> + <!-- info section. ATTN: no blanks, no '.' in the names --> + <section name="Build-Info"> + <attribute name="version" value="${jython.version}" /> + <attribute name="svn-build" value="${do.checkout}" /> + <attribute name="oracle" value="${oracle.present}" /> + <attribute name="informix" value="${informix.present}" /> + <attribute name="build-compiler" value="${build.compiler}" /> + <attribute name="jdk-target-version" value="${jdk.target.version}" /> + <attribute name="debug" value="${debug}" /> + <attribute name="optimize" value="${optimize}" /> + </section> + </manifest> + </jar> + </target> + <target name="jar" depends="compile,expose,jarjar"> <jar destfile="${dist.dir}/jython.jar"> <fileset dir="${compile.dir}"/> This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <fwi...@us...> - 2008-07-07 08:40:03
|
Revision: 4854 http://jython.svn.sourceforge.net/jython/?rev=4854&view=rev Author: fwierzbicki Date: 2008-07-07 01:40:01 -0700 (Mon, 07 Jul 2008) Log Message: ----------- creating a branch of the installer to see what is needed to roll a 2.5 alpha. Added Paths: ----------- branches/installer25/ Copied: branches/installer25 (from rev 4648, trunk/installer) This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <pj...@us...> - 2008-07-06 01:51:22
|
Revision: 4853 http://jython.svn.sourceforge.net/jython/?rev=4853&view=rev Author: pjenvey Date: 2008-07-05 18:51:20 -0700 (Sat, 05 Jul 2008) Log Message: ----------- always recompile bytecode from zipimporter too Modified Paths: -------------- branches/asm/src/org/python/core/imp.java branches/asm/src/org/python/modules/zipimport/zipimporter.java Modified: branches/asm/src/org/python/core/imp.java =================================================================== --- branches/asm/src/org/python/core/imp.java 2008-07-06 00:37:12 UTC (rev 4852) +++ branches/asm/src/org/python/core/imp.java 2008-07-06 01:51:20 UTC (rev 4853) @@ -127,7 +127,9 @@ } } */ - // XXX: always re-generate byte code until APIVersion is fixed + // XXX: always re-generate byte code until APIVersion is fixed. Note that + // zipimporter.isOutdatedBytecode is also disabled so that all zipimported + // bytecode is also always re-generated //return data; return null; } Modified: branches/asm/src/org/python/modules/zipimport/zipimporter.java =================================================================== --- branches/asm/src/org/python/modules/zipimport/zipimporter.java 2008-07-06 00:37:12 UTC (rev 4852) +++ branches/asm/src/org/python/modules/zipimport/zipimporter.java 2008-07-06 01:51:20 UTC (rev 4853) @@ -437,6 +437,9 @@ * @return boolean whether or not the byte code is older */ private boolean isOutdatedBytecode(String path, PyObject tocEntry) { + // XXX: Always recompile bytecode until bytecode APIVersion is fixed + return true; + /* String sourcePath = path.substring(0, path.length() - 9) + ".py"; PyObject sourceTocEntry = files.__finditem__(sourcePath); if (sourceTocEntry == null) { @@ -452,6 +455,7 @@ catch (PyObject.ConversionException ce) { return false; } + */ } /** This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <le...@us...> - 2008-07-06 00:37:14
|
Revision: 4852 http://jython.svn.sourceforge.net/jython/?rev=4852&view=rev Author: leosoto Date: 2008-07-05 17:37:12 -0700 (Sat, 05 Jul 2008) Log Message: ----------- StringFormatter: '%d' and '%f' support for the __int__ and __float__ protocol respectively. The implementation is more convulted than it should be, because we have PyString implementing __float__ and __int__ at the "java level" but not at the "python level". For string formatting, only "python level" __float__ and __int__ must be supported. Also, considering that __int__ can return a PyLong, this case needs special care. Basically formatInteger now can call formatLong if a PyLong is found as the result of calling __int__. Then, as formatLong can also be called from formatInteger, __hex__, __oct__ and __str__ conversions were moved inside formatLong. Finally, test_format_jy was changed to stop checking that we don't support big floats on '%d' (CPython doesn't, but that seems a limitation of the specific implementation and I can't imagine a program that could break on Jython because we *support* it). Modified Paths: -------------- branches/asm/Lib/test/test_format_jy.py branches/asm/src/org/python/core/PyString.java Modified: branches/asm/Lib/test/test_format_jy.py =================================================================== --- branches/asm/Lib/test/test_format_jy.py 2008-07-05 15:55:14 UTC (rev 4851) +++ branches/asm/Lib/test/test_format_jy.py 2008-07-06 00:37:12 UTC (rev 4852) @@ -2,20 +2,24 @@ Made for Jython. """ -import test_support +from test import test_support import unittest class FormatTestCase(unittest.TestCase): + # Tests that %d converts values for custom classes implementing __int__ + def test_int_conversion_support(self): + class Foo(object): + def __init__(self, x): self.x = x + def __int__(self): return self. x + self.assertEqual('1', '%d' % Foo(1)) + self.assertEqual('1', '%d' % Foo(1L)) # __int__ can return a long, but + # it should be accepted too - def test_overflow(self): - # Ensure a float that would convert to a long isn't accepted - for format in 'i', 'd', 'u', 'o', 'x', 'X': - try: - ('%%%s' % format) % 3.7517675036461267e17 - except TypeError, te: - self.assertEqual(str(te), 'int argument required') - else: - self.fail('Expected TypeError') + def test_float_conversion_support(self): + class Foo(object): + def __init__(self, x): self.x = x + def __float__(self): return self. x + self.assertEqual('1.0', '%.1f' % Foo(1.0)) def test_main(): Modified: branches/asm/src/org/python/core/PyString.java =================================================================== --- branches/asm/src/org/python/core/PyString.java 2008-07-05 15:55:14 UTC (rev 4851) +++ branches/asm/src/org/python/core/PyString.java 2008-07-06 00:37:12 UTC (rev 4852) @@ -2322,9 +2322,22 @@ } - private String formatLong(PyString arg, char type, boolean altFlag) { + private String formatLong(PyObject arg, char type, boolean altFlag) { + PyString argAsString; + switch (type) { + case 'o': + argAsString = arg.__oct__(); + break; + case 'x': + case 'X': + argAsString = arg.__hex__(); + break; + default: + argAsString = arg.__str__(); + break; + } checkPrecision("long"); - String s = arg.toString(); + String s = argAsString.toString(); int end = s.length(); int ptr = 0; @@ -2376,18 +2389,46 @@ return s; } - private String formatInteger(PyObject arg, int radix, boolean unsigned) { - PyObject x; + /** + * Formats arg as an integer, with the specified radix + * + * type and altFlag are needed to be passed to {@link #formatLong(PyObject, char, boolean)} + * in case the result of <code>arg.__int__()</code> is a PyLong. + */ + private String formatInteger(PyObject arg, int radix, boolean unsigned, char type, boolean altFlag) { + PyObject argAsInt; + if (arg instanceof PyInteger || arg instanceof PyLong) { + argAsInt = arg; + } else { + // use __int__ to get an int (or long) + if (arg instanceof PyFloat) { + // safe to call __int__: + argAsInt = arg.__int__(); + } else { + // Same case noted on formatFloatDecimal: + // We can't simply call arg.__int__() because PyString implements + // it without exposing it to python (i.e, str instances has no + // __int__ attribute). So, we would support strings as arguments + // for %d format, which is forbidden by CPython tests (on + // test_format.py). try { - x = arg.__int__(); - } catch (PyException pye) { + argAsInt = arg.__getattr__("__int__").__call__(); + } catch (PyException e) { + // XXX: Swallow customs AttributeError throws from __float__ methods + // No better alternative for the moment + if (Py.matchException(e, Py.AttributeError)) { throw Py.TypeError("int argument required"); } - if (!(x instanceof PyInteger)) { - throw Py.TypeError("int argument required"); + throw e; } - return formatInteger(((PyInteger)x).getValue(), radix, unsigned); } + } + if (argAsInt instanceof PyInteger) { + return formatInteger(((PyInteger)argAsInt).getValue(), radix, unsigned); + } else { // must be a PyLong (as per __int__ contract) + return formatLong(argAsInt, type, altFlag); + } + } private String formatInteger(long v, int radix, boolean unsigned) { checkPrecision("integer"); @@ -2408,11 +2449,35 @@ } private String formatFloatDecimal(PyObject arg, boolean truncate) { - if (!(arg instanceof PyFloat || arg instanceof PyInteger || arg instanceof PyLong)) { + PyFloat argAsFloat; + if (arg instanceof PyFloat) { + // Fast path + argAsFloat = (PyFloat)arg; + } else { + // Use __float__ + if (arg instanceof PyInteger || arg instanceof PyLong) { + // Typical cases, safe to call __float__: + argAsFloat = arg.__float__(); + } else { + try { + // We can't simply call arg.__float__() because PyString implements + // it without exposing it to python (i.e, str instances has no + // __float__ attribute). So, we would support strings as arguments + // for %g format, which is forbidden by CPython tests (on + // test_format.py). + argAsFloat = (PyFloat)arg.__getattr__("__float__").__call__(); + } catch (PyException e) { + // XXX: Swallow customs AttributeError throws from __float__ methods + // No better alternative for the moment + if (Py.matchException(e, Py.AttributeError)) { throw Py.TypeError("float argument required"); } - return formatFloatDecimal(arg.__float__().getValue(), truncate); + throw e; } + } + } + return formatFloatDecimal(argAsFloat.getValue(), truncate); + } private String formatFloatDecimal(double v, boolean truncate) { checkPrecision("decimal"); @@ -2591,23 +2656,22 @@ case 'i': case 'd': if (arg instanceof PyLong) - string = formatLong(arg.__str__(), c, altFlag); - else if (arg instanceof PyInteger || arg instanceof PyFloat) - string = formatInteger(arg, 10, false); - else throw Py.TypeError("int argument required"); + string = formatLong(arg, c, altFlag); + else + string = formatInteger(arg, 10, false, c, altFlag); break; case 'u': if (arg instanceof PyLong) - string = formatLong(arg.__str__(), c, altFlag); + string = formatLong(arg, c, altFlag); else if (arg instanceof PyInteger || arg instanceof PyFloat) - string = formatInteger(arg, 10, false); + string = formatInteger(arg, 10, false, c, altFlag); else throw Py.TypeError("int argument required"); break; case 'o': if (arg instanceof PyLong) - string = formatLong(arg.__oct__(), c, altFlag); + string = formatLong(arg, c, altFlag); else if (arg instanceof PyInteger || arg instanceof PyFloat) { - string = formatInteger(arg, 8, false); + string = formatInteger(arg, 8, false, c, altFlag); if (altFlag && string.charAt(0) != '0') { string = "0" + string; } @@ -2616,9 +2680,9 @@ break; case 'x': if (arg instanceof PyLong) - string = formatLong(arg.__hex__(), c, altFlag); + string = formatLong(arg, c, altFlag); else if (arg instanceof PyInteger || arg instanceof PyFloat) { - string = formatInteger(arg, 16, false); + string = formatInteger(arg, 16, false, c, altFlag); string = string.toLowerCase(); if (altFlag) { string = "0x" + string; @@ -2628,9 +2692,9 @@ break; case 'X': if (arg instanceof PyLong) - string = formatLong(arg.__hex__(), c, altFlag); + string = formatLong(arg, c, altFlag); else if (arg instanceof PyInteger || arg instanceof PyFloat) { - string = formatInteger(arg, 16, false); + string = formatInteger(arg, 16, false, c, altFlag); string = string.toUpperCase(); if (altFlag) { string = "0X" + string; This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <fwi...@us...> - 2008-07-05 15:55:16
|
Revision: 4851 http://jython.svn.sourceforge.net/jython/?rev=4851&view=rev Author: fwierzbicki Date: 2008-07-05 08:55:14 -0700 (Sat, 05 Jul 2008) Log Message: ----------- Merged revisions 4780,4803-4805,4811 via svnmerge from https://jython.svn.sourceforge.net/svnroot/jython/trunk/jython ........ r4780 | pjenvey | 2008-06-25 21:31:47 -0400 (Wed, 25 Jun 2008) | 4 lines o move Jython specific complex tests into test_complex_jy o test_cmath -> test_cmath_jy o test_atexit, test_contains test_heapq are in sync with stdlib's ........ r4803 | pjenvey | 2008-06-27 00:41:24 -0400 (Fri, 27 Jun 2008) | 1 line we pass stock test_datetime now with this small fix ........ r4804 | pjenvey | 2008-06-27 00:42:37 -0400 (Fri, 27 Jun 2008) | 2 lines from: http://svn.python.org/projects/python/branches/release25-maint/Lib/test/test_cpickle.py@43289 ........ r4805 | pjenvey | 2008-06-27 00:43:07 -0400 (Fri, 27 Jun 2008) | 1 line re-integrate Jython workaround for lack of list based picklers ........ r4811 | pjenvey | 2008-06-27 15:02:36 -0400 (Fri, 27 Jun 2008) | 1 line __iternext__ shouldn't be exposed ........ Modified Paths: -------------- branches/asm/Lib/datetime.py branches/asm/Lib/test/test_cpickle.py branches/asm/src/org/python/core/PyFile.java Added Paths: ----------- branches/asm/Lib/test/test_cmath_jy.py branches/asm/Lib/test/test_complex_jy.py Removed Paths: ------------- branches/asm/Lib/test/test_complex.py branches/asm/Lib/test/test_datetime.py Property Changed: ---------------- branches/asm/ Property changes on: branches/asm ___________________________________________________________________ Name: svnmerge-integrated - /trunk/jython:1-4738 + /trunk/jython:1-4850 Modified: branches/asm/Lib/datetime.py =================================================================== --- branches/asm/Lib/datetime.py 2008-07-04 21:25:24 UTC (rev 4850) +++ branches/asm/Lib/datetime.py 2008-07-05 15:55:14 UTC (rev 4851) @@ -575,9 +575,9 @@ def __add__(self, other): if isinstance(other, timedelta): - return self.__class__(self.__days + other.__days, - self.__seconds + other.__seconds, - self.__microseconds + other.__microseconds) + return timedelta(self.__days + other.__days, + self.__seconds + other.__seconds, + self.__microseconds + other.__microseconds) return NotImplemented __radd__ = __add__ Copied: branches/asm/Lib/test/test_cmath_jy.py (from rev 4811, trunk/jython/Lib/test/test_cmath_jy.py) =================================================================== --- branches/asm/Lib/test/test_cmath_jy.py (rev 0) +++ branches/asm/Lib/test/test_cmath_jy.py 2008-07-05 15:55:14 UTC (rev 4851) @@ -0,0 +1,109 @@ +#! /usr/bin/env python +""" Simple test script for cmathmodule.c + Roger E. Masse +""" +import cmath +import unittest +from test import test_support +from test.test_support import verbose + +p = cmath.pi +e = cmath.e +if verbose: + print 'PI = ', abs(p) + print 'E = ', abs(e) + + +class CmathTestCase(unittest.TestCase): + def assertAlmostEqual(self, x, y, places=5, msg=None): + unittest.TestCase.assertAlmostEqual(self, x.real, y.real, places, msg) + unittest.TestCase.assertAlmostEqual(self, x.imag, y.imag, places, msg) + + def test_acos(self): + self.assertAlmostEqual(complex(0.936812, -2.30551), + cmath.acos(complex(3, 4))) + + def test_acosh(self): + self.assertAlmostEqual(complex(2.30551, 0.93681), + cmath.acosh(complex(3, 4))) + + def test_asin(self): + self.assertAlmostEqual(complex(0.633984, 2.30551), + cmath.asin(complex(3, 4))) + + def test_asinh(self): + self.assertAlmostEqual(complex(2.29991, 0.917617), + cmath.asinh(complex(3, 4))) + + def test_atan(self): + self.assertAlmostEqual(complex(1.44831, 0.158997), + cmath.atan(complex(3, 4))) + + def test_atanh(self): + self.assertAlmostEqual(complex(0.11750, 1.40992), + cmath.atanh(complex(3, 4))) + + def test_cos(self): + self.assertAlmostEqual(complex(-27.03495, -3.851153), + cmath.cos(complex(3, 4))) + + def test_cosh(self): + self.assertAlmostEqual(complex(-6.58066, -7.58155), + cmath.cosh(complex(3, 4))) + + def test_exp(self): + self.assertAlmostEqual(complex(-13.12878, -15.20078), + cmath.exp(complex(3, 4))) + + def test_log(self): + self.assertAlmostEqual(complex(1.60944, 0.927295), + cmath.log(complex(3, 4))) + + def test_log10(self): + self.assertAlmostEqual(complex(0.69897, 0.40272), + cmath.log10(complex(3, 4))) + + def test_sin(self): + self.assertAlmostEqual(complex(3.853738, -27.01681), + cmath.sin(complex(3, 4))) + + def test_sinh(self): + self.assertAlmostEqual(complex(-6.54812, -7.61923), + cmath.sinh(complex(3, 4))) + + def test_sqrt_real_positive(self): + self.assertAlmostEqual(complex(2, 1), + cmath.sqrt(complex(3, 4))) + + def test_sqrt_real_zero(self): + self.assertAlmostEqual(complex(1.41421, 1.41421), + cmath.sqrt(complex(0, 4))) + + def test_sqrt_real_negative(self): + self.assertAlmostEqual(complex(1, 2), + cmath.sqrt(complex(-3, 4))) + + def test_sqrt_imaginary_zero(self): + self.assertAlmostEqual(complex(0.0, 1.73205), + cmath.sqrt(complex(-3, 0))) + + def test_sqrt_imaginary_negative(self): + self.assertAlmostEqual(complex(1.0, -2.0), + cmath.sqrt(complex(-3, -4))) + + def test_tan(self): + self.assertAlmostEqual(complex(-0.000187346, 0.999356), + cmath.tan(complex(3, 4))) + + def test_tanh(self): + self.assertAlmostEqual(complex(1.00071, 0.00490826), + cmath.tanh(complex(3, 4))) + +def test_main(): + test_support.run_unittest(CmathTestCase) + +if __name__ == "__main__": + test_main() + + + Deleted: branches/asm/Lib/test/test_complex.py =================================================================== --- branches/asm/Lib/test/test_complex.py 2008-07-04 21:25:24 UTC (rev 4850) +++ branches/asm/Lib/test/test_complex.py 2008-07-05 15:55:14 UTC (rev 4851) @@ -1,318 +0,0 @@ -import unittest, os -from test import test_support - -import warnings -warnings.filterwarnings( - "ignore", - category=DeprecationWarning, - message=".*complex divmod.*are deprecated" -) - -from random import random - -# These tests ensure that complex math does the right thing - -class ComplexTest(unittest.TestCase): - - def assertAlmostEqual(self, a, b): - if isinstance(a, complex): - if isinstance(b, complex): - unittest.TestCase.assertAlmostEqual(self, a.real, b.real) - unittest.TestCase.assertAlmostEqual(self, a.imag, b.imag) - else: - unittest.TestCase.assertAlmostEqual(self, a.real, b) - unittest.TestCase.assertAlmostEqual(self, a.imag, 0.) - else: - if isinstance(b, complex): - unittest.TestCase.assertAlmostEqual(self, a, b.real) - unittest.TestCase.assertAlmostEqual(self, 0., b.imag) - else: - unittest.TestCase.assertAlmostEqual(self, a, b) - - def assertCloseAbs(self, x, y, eps=1e-9): - """Return true iff floats x and y "are close\"""" - # put the one with larger magnitude second - if abs(x) > abs(y): - x, y = y, x - if y == 0: - return abs(x) < eps - if x == 0: - return abs(y) < eps - # check that relative difference < eps - self.assert_(abs((x-y)/y) < eps) - - def assertClose(self, x, y, eps=1e-9): - """Return true iff complexes x and y "are close\"""" - self.assertCloseAbs(x.real, y.real, eps) - self.assertCloseAbs(x.imag, y.imag, eps) - - def assertIs(self, a, b): - self.assert_(a is b) - - def check_div(self, x, y): - """Compute complex z=x*y, and check that z/x==y and z/y==x.""" - z = x * y - if x != 0: - q = z / x - self.assertClose(q, y) - q = z.__div__(x) - self.assertClose(q, y) - q = z.__truediv__(x) - self.assertClose(q, y) - if y != 0: - q = z / y - self.assertClose(q, x) - q = z.__div__(y) - self.assertClose(q, x) - q = z.__truediv__(y) - self.assertClose(q, x) - - def test_div(self): - simple_real = [float(i) for i in xrange(-5, 6)] - simple_complex = [complex(x, y) for x in simple_real for y in simple_real] - for x in simple_complex: - for y in simple_complex: - self.check_div(x, y) - - # A naive complex division algorithm (such as in 2.0) is very prone to - # nonsense errors for these (overflows and underflows). - self.check_div(complex(1e200, 1e200), 1+0j) - self.check_div(complex(1e-200, 1e-200), 1+0j) - - # Just for fun. - for i in xrange(100): - self.check_div(complex(random(), random()), - complex(random(), random())) - - self.assertRaises(ZeroDivisionError, complex.__div__, 1+1j, 0+0j) - # FIXME: The following currently crashes on Alpha - # self.assertRaises(OverflowError, pow, 1e200+1j, 1e200+1j) - - def test_truediv(self): - self.assertAlmostEqual(complex.__truediv__(2+0j, 1+1j), 1-1j) - self.assertRaises(ZeroDivisionError, complex.__truediv__, 1+1j, 0+0j) - - def test_floordiv(self): - self.assertAlmostEqual(complex.__floordiv__(3+0j, 1.5+0j), 2) - self.assertRaises(ZeroDivisionError, complex.__floordiv__, 3+0j, 0+0j) - - def test_coerce(self): - self.assertRaises(OverflowError, complex.__coerce__, 1+1j, 1L<<10000) - self.assertEqual(complex.__coerce__(1+1j, None), NotImplemented) - self.assertRaises(TypeError, complex.__coerce__, None, 1+2j) - - def test_richcompare(self): - self.assertRaises(OverflowError, complex.__eq__, 1+1j, 1L<<10000) - self.assertEqual(complex.__lt__(1+1j, None), NotImplemented) - self.assertIs(complex.__eq__(1+1j, 1+1j), True) - self.assertIs(complex.__eq__(1+1j, 2+2j), False) - self.assertIs(complex.__ne__(1+1j, 1+1j), False) - self.assertIs(complex.__ne__(1+1j, 2+2j), True) - self.assertRaises(TypeError, complex.__lt__, 1+1j, 2+2j) - self.assertRaises(TypeError, complex.__le__, 1+1j, 2+2j) - self.assertRaises(TypeError, complex.__gt__, 1+1j, 2+2j) - self.assertRaises(TypeError, complex.__ge__, 1+1j, 2+2j) - - def test_mod(self): - self.assertRaises(ZeroDivisionError, (1+1j).__mod__, 0+0j) - - a = 3.33+4.43j - try: - a % 0 - except ZeroDivisionError: - pass - else: - self.fail("modulo parama can't be 0") - - def test_divmod(self): - self.assertRaises(ZeroDivisionError, divmod, 1+1j, 0+0j) - - def test_pow(self): - self.assertAlmostEqual(pow(1+1j, 0+0j), 1.0) - self.assertAlmostEqual(pow(0+0j, 2+0j), 0.0) - self.assertRaises(ZeroDivisionError, pow, 0+0j, 1j) - self.assertAlmostEqual(pow(1j, -1), 1/1j) - self.assertAlmostEqual(pow(1j, 200), 1) - self.assertRaises(ValueError, pow, 1+1j, 1+1j, 1+1j) - - a = 3.33+4.43j - self.assertEqual(a ** 0j, 1) - self.assertEqual(a ** 0.+0.j, 1) - - self.assertEqual(3j ** 0j, 1) - self.assertEqual(3j ** 0, 1) - - try: - 0j ** a - except ZeroDivisionError: - pass - else: - self.fail("should fail 0.0 to negative or complex power") - - try: - 0j ** (3-2j) - except ZeroDivisionError: - pass - else: - self.fail("should fail 0.0 to negative or complex power") - - # The following is used to exercise certain code paths - self.assertEqual(a ** 105, a ** 105) - self.assertEqual(a ** -105, a ** -105) - self.assertEqual(a ** -30, a ** -30) - - self.assertEqual(0.0j ** 0, 1) - - b = 5.1+2.3j - self.assertRaises(ValueError, pow, a, b, 0) - - def test_boolcontext(self): - for i in xrange(100): - self.assert_(complex(random() + 1e-6, random() + 1e-6)) - self.assert_(not complex(0.0, 0.0)) - - def test_conjugate(self): - self.assertClose(complex(5.3, 9.8).conjugate(), 5.3-9.8j) - - def test_constructor(self): - class OS: - def __init__(self, value): self.value = value - def __complex__(self): return self.value - class NS(object): - def __init__(self, value): self.value = value - def __complex__(self): return self.value - self.assertEqual(complex(OS(1+10j)), 1+10j) - self.assertEqual(complex(NS(1+10j)), 1+10j) - self.assertRaises(TypeError, complex, OS(None)) - self.assertRaises(TypeError, complex, NS(None)) - - self.assertAlmostEqual(complex("1+10j"), 1+10j) - self.assertAlmostEqual(complex(10), 10+0j) - self.assertAlmostEqual(complex(10.0), 10+0j) - self.assertAlmostEqual(complex(10L), 10+0j) - self.assertAlmostEqual(complex(10+0j), 10+0j) - self.assertAlmostEqual(complex(1,10), 1+10j) - self.assertAlmostEqual(complex(1,10L), 1+10j) - self.assertAlmostEqual(complex(1,10.0), 1+10j) - self.assertAlmostEqual(complex(1L,10), 1+10j) - self.assertAlmostEqual(complex(1L,10L), 1+10j) - self.assertAlmostEqual(complex(1L,10.0), 1+10j) - self.assertAlmostEqual(complex(1.0,10), 1+10j) - self.assertAlmostEqual(complex(1.0,10L), 1+10j) - self.assertAlmostEqual(complex(1.0,10.0), 1+10j) - self.assertAlmostEqual(complex(3.14+0j), 3.14+0j) - self.assertAlmostEqual(complex(3.14), 3.14+0j) - self.assertAlmostEqual(complex(314), 314.0+0j) - self.assertAlmostEqual(complex(314L), 314.0+0j) - self.assertAlmostEqual(complex(3.14+0j, 0j), 3.14+0j) - self.assertAlmostEqual(complex(3.14, 0.0), 3.14+0j) - self.assertAlmostEqual(complex(314, 0), 314.0+0j) - self.assertAlmostEqual(complex(314L, 0L), 314.0+0j) - self.assertAlmostEqual(complex(0j, 3.14j), -3.14+0j) - self.assertAlmostEqual(complex(0.0, 3.14j), -3.14+0j) - self.assertAlmostEqual(complex(0j, 3.14), 3.14j) - self.assertAlmostEqual(complex(0.0, 3.14), 3.14j) - self.assertAlmostEqual(complex("1"), 1+0j) - self.assertAlmostEqual(complex("1j"), 1j) - self.assertAlmostEqual(complex(), 0) - self.assertAlmostEqual(complex("-1"), -1) - self.assertAlmostEqual(complex("+1"), +1) - - class complex2(complex): pass - self.assertAlmostEqual(complex(complex2(1+1j)), 1+1j) - self.assertAlmostEqual(complex(real=17, imag=23), 17+23j) - self.assertAlmostEqual(complex(real=17+23j), 17+23j) - self.assertAlmostEqual(complex(real=17+23j, imag=23), 17+46j) - self.assertAlmostEqual(complex(real=1+2j, imag=3+4j), -3+5j) - - c = 3.14 + 1j - self.assert_(complex(c) is c) - del c - - self.assertRaises(TypeError, complex, "1", "1") - self.assertRaises(TypeError, complex, 1, "1") - - self.assertEqual(complex(" 3.14+J "), 3.14+1j) - if test_support.have_unicode: - self.assertEqual(complex(unicode(" 3.14+J ")), 3.14+1j) - - # SF bug 543840: complex(string) accepts strings with \0 - # Fixed in 2.3. - self.assertRaises(ValueError, complex, '1+1j\0j') - - self.assertRaises(TypeError, int, 5+3j) - self.assertRaises(TypeError, long, 5+3j) - self.assertRaises(TypeError, float, 5+3j) - self.assertRaises(ValueError, complex, "") - self.assertRaises(TypeError, complex, None) - self.assertRaises(ValueError, complex, "\0") - self.assertRaises(TypeError, complex, "1", "2") - self.assertRaises(TypeError, complex, "1", 42) - self.assertRaises(TypeError, complex, 1, "2") - self.assertRaises(ValueError, complex, "1+") - self.assertRaises(ValueError, complex, "1+1j+1j") - self.assertRaises(ValueError, complex, "--") - if test_support.have_unicode: - self.assertRaises(ValueError, complex, unicode("1"*500)) - self.assertRaises(ValueError, complex, unicode("x")) - - class EvilExc(Exception): - pass - - class evilcomplex: - def __complex__(self): - raise EvilExc - - self.assertRaises(EvilExc, complex, evilcomplex()) - - class float2: - def __init__(self, value): - self.value = value - def __float__(self): - return self.value - - self.assertAlmostEqual(complex(float2(42.)), 42) - self.assertAlmostEqual(complex(real=float2(17.), imag=float2(23.)), 17+23j) - self.assertRaises(TypeError, complex, float2(None)) - - def test_hash(self): - for x in xrange(-30, 30): - self.assertEqual(hash(x), hash(complex(x, 0))) - x /= 3.0 # now check against floating point - self.assertEqual(hash(x), hash(complex(x, 0.))) - - def test_abs(self): - nums = [complex(x/3., y/7.) for x in xrange(-9,9) for y in xrange(-9,9)] - for num in nums: - self.assertAlmostEqual((num.real**2 + num.imag**2) ** 0.5, abs(num)) - - def test_repr(self): - self.assertEqual(repr(1+6j), '(1+6j)') - - def test_neg(self): - self.assertEqual(-(1+6j), -1-6j) - - def test_file(self): - a = 3.33+4.43j - b = 5.1+2.3j - - fo = None - try: - fo = open(test_support.TESTFN, "wb") - print >>fo, a, b - fo.close() - fo = open(test_support.TESTFN, "rb") - self.assertEqual(fo.read(), "%s %s\n" % (a, b)) - finally: - if (fo is not None) and (not fo.closed): - fo.close() - try: - os.remove(test_support.TESTFN) - except (OSError, IOError): - pass - -def test_main(): - test_support.run_unittest(ComplexTest) - -if __name__ == "__main__": - test_main() Copied: branches/asm/Lib/test/test_complex_jy.py (from rev 4811, trunk/jython/Lib/test/test_complex_jy.py) =================================================================== --- branches/asm/Lib/test/test_complex_jy.py (rev 0) +++ branches/asm/Lib/test/test_complex_jy.py 2008-07-05 15:55:14 UTC (rev 4851) @@ -0,0 +1,19 @@ +"""Misc complex tests + +Made for Jython. +""" +import unittest +from test import test_support + +class ComplexTest(unittest.TestCase): + + def test_dunder_coerce(self): + self.assertEqual(complex.__coerce__(1+1j, None), NotImplemented) + self.assertRaises(TypeError, complex.__coerce__, None, 1+2j) + + +def test_main(): + test_support.run_unittest(ComplexTest) + +if __name__ == "__main__": + test_main() Modified: branches/asm/Lib/test/test_cpickle.py =================================================================== --- branches/asm/Lib/test/test_cpickle.py 2008-07-04 21:25:24 UTC (rev 4850) +++ branches/asm/Lib/test/test_cpickle.py 2008-07-05 15:55:14 UTC (rev 4851) @@ -1,8 +1,8 @@ import cPickle -import test_support import unittest from cStringIO import StringIO -from pickletester import AbstractPickleTests, AbstractPickleModuleTests +from test.pickletester import AbstractPickleTests, AbstractPickleModuleTests +from test import test_support class cPickleTests(AbstractPickleTests, AbstractPickleModuleTests): @@ -15,9 +15,9 @@ class cPicklePicklerTests(AbstractPickleTests): - def dumps(self, arg, bin=0): + def dumps(self, arg, proto=0): f = StringIO() - p = cPickle.Pickler(f, bin) + p = cPickle.Pickler(f, proto) p.dump(arg) f.seek(0) return f.read() @@ -31,8 +31,8 @@ class cPickleListPicklerTests(AbstractPickleTests): - def dumps(self, arg, bin=0): - p = cPickle.Pickler(bin) + def dumps(self, arg, proto=0): + p = cPickle.Pickler(proto) p.dump(arg) return p.getvalue() @@ -45,9 +45,9 @@ class cPickleFastPicklerTests(AbstractPickleTests): - def dumps(self, arg, bin=0): + def dumps(self, arg, proto=0): f = StringIO() - p = cPickle.Pickler(f, bin) + p = cPickle.Pickler(f, proto) p.fast = 1 p.dump(arg) f.seek(0) @@ -60,22 +60,53 @@ error = cPickle.BadPickleGet + def test_recursive_list(self): + self.assertRaises(ValueError, + AbstractPickleTests.test_recursive_list, + self) + + def test_recursive_inst(self): + self.assertRaises(ValueError, + AbstractPickleTests.test_recursive_inst, + self) + + def test_recursive_dict(self): + self.assertRaises(ValueError, + AbstractPickleTests.test_recursive_dict, + self) + + def test_recursive_multi(self): + self.assertRaises(ValueError, + AbstractPickleTests.test_recursive_multi, + self) + def test_nonrecursive_deep(self): + # If it's not cyclic, it should pickle OK even if the nesting + # depth exceeds PY_CPICKLE_FAST_LIMIT. That happens to be + # 50 today. Jack Jansen reported stack overflow on Mac OS 9 + # at 64. a = [] - for i in range(100): + for i in range(60): a = [a] b = self.loads(self.dumps(a)) self.assertEqual(a, b) def test_main(): - loader = unittest.TestLoader() - suite = unittest.TestSuite() - suite.addTest(loader.loadTestsFromTestCase(cPickleTests)) - suite.addTest(loader.loadTestsFromTestCase(cPicklePicklerTests)) - #Jython doesn't support list based picklers - #suite.addTest(loader.loadTestsFromTestCase(cPickleListPicklerTests)) - suite.addTest(loader.loadTestsFromTestCase(cPickleFastPicklerTests)) - test_support.run_suite(suite) + tests = [ + cPickleTests, + cPicklePicklerTests, + cPickleListPicklerTests, + cPickleFastPicklerTests + ] + if test_support.is_jython: + # XXX: Jython doesn't support list based picklers + tests.remove(cPickleListPicklerTests) + # XXX: These don't cause exceptions on Jython + del cPickleFastPicklerTests.test_recursive_list + del cPickleFastPicklerTests.test_recursive_inst + del cPickleFastPicklerTests.test_recursive_dict + del cPickleFastPicklerTests.test_recursive_multi + test_support.run_unittest(*tests) if __name__ == "__main__": test_main() Deleted: branches/asm/Lib/test/test_datetime.py =================================================================== --- branches/asm/Lib/test/test_datetime.py 2008-07-04 21:25:24 UTC (rev 4850) +++ branches/asm/Lib/test/test_datetime.py 2008-07-05 15:55:14 UTC (rev 4851) @@ -1,2947 +0,0 @@ -"""Test date/time type. - -See http://www.zope.org/Members/fdrake/DateTimeWiki/TestCases -""" - -import sys -import pickle -import cPickle -import unittest - -from datetime import MINYEAR, MAXYEAR -from datetime import timedelta -from datetime import tzinfo -from datetime import time -from datetime import date, datetime -from test import test_support - -pickle_choices = [(pickler, unpickler, proto) - for pickler in pickle, cPickle - for unpickler in pickle, cPickle - for proto in range(3)] -assert len(pickle_choices) == 2*2*3 - -# An arbitrary collection of objects of non-datetime types, for testing -# mixed-type comparisons. -OTHERSTUFF = (10, 10L, 34.5, "abc", {}, [], ()) - - -############################################################################# -# module tests - -class TestModule(unittest.TestCase): - - def test_constants(self): - import datetime - self.assertEqual(datetime.MINYEAR, 1) - self.assertEqual(datetime.MAXYEAR, 9999) - -############################################################################# -# tzinfo tests - -class FixedOffset(tzinfo): - def __init__(self, offset, name, dstoffset=42): - if isinstance(offset, int): - offset = timedelta(minutes=offset) - if isinstance(dstoffset, int): - dstoffset = timedelta(minutes=dstoffset) - self.__offset = offset - self.__name = name - self.__dstoffset = dstoffset - def __repr__(self): - return self.__name.lower() - def utcoffset(self, dt): - return self.__offset - def tzname(self, dt): - return self.__name - def dst(self, dt): - return self.__dstoffset - -class PicklableFixedOffset(FixedOffset): - def __init__(self, offset=None, name=None, dstoffset=None): - FixedOffset.__init__(self, offset, name, dstoffset) - -class TestTZInfo(unittest.TestCase): - - def test_non_abstractness(self): - # In order to allow subclasses to get pickled, the C implementation - # wasn't able to get away with having __init__ raise - # NotImplementedError. - useless = tzinfo() - dt = datetime.max - self.assertRaises(NotImplementedError, useless.tzname, dt) - self.assertRaises(NotImplementedError, useless.utcoffset, dt) - self.assertRaises(NotImplementedError, useless.dst, dt) - - def test_subclass_must_override(self): - class NotEnough(tzinfo): - def __init__(self, offset, name): - self.__offset = offset - self.__name = name - self.failUnless(issubclass(NotEnough, tzinfo)) - ne = NotEnough(3, "NotByALongShot") - self.failUnless(isinstance(ne, tzinfo)) - - dt = datetime.now() - self.assertRaises(NotImplementedError, ne.tzname, dt) - self.assertRaises(NotImplementedError, ne.utcoffset, dt) - self.assertRaises(NotImplementedError, ne.dst, dt) - - def test_normal(self): - fo = FixedOffset(3, "Three") - self.failUnless(isinstance(fo, tzinfo)) - for dt in datetime.now(), None: - self.assertEqual(fo.utcoffset(dt), timedelta(minutes=3)) - self.assertEqual(fo.tzname(dt), "Three") - self.assertEqual(fo.dst(dt), timedelta(minutes=42)) - - def test_pickling_base(self): - # There's no point to pickling tzinfo objects on their own (they - # carry no data), but they need to be picklable anyway else - # concrete subclasses can't be pickled. - orig = tzinfo.__new__(tzinfo) - self.failUnless(type(orig) is tzinfo) - for pickler, unpickler, proto in pickle_choices: - green = pickler.dumps(orig, proto) - derived = unpickler.loads(green) - self.failUnless(type(derived) is tzinfo) - - def test_pickling_subclass(self): - # Make sure we can pickle/unpickle an instance of a subclass. - offset = timedelta(minutes=-300) - orig = PicklableFixedOffset(offset, 'cookie') - self.failUnless(isinstance(orig, tzinfo)) - self.failUnless(type(orig) is PicklableFixedOffset) - self.assertEqual(orig.utcoffset(None), offset) - self.assertEqual(orig.tzname(None), 'cookie') - for pickler, unpickler, proto in pickle_choices: - green = pickler.dumps(orig, proto) - derived = unpickler.loads(green) - self.failUnless(isinstance(derived, tzinfo)) - self.failUnless(type(derived) is PicklableFixedOffset) - self.assertEqual(derived.utcoffset(None), offset) - self.assertEqual(derived.tzname(None), 'cookie') - -############################################################################# -# Base clase for testing a particular aspect of timedelta, time, date and -# datetime comparisons. - -class HarmlessMixedComparison(unittest.TestCase): - # Test that __eq__ and __ne__ don't complain for mixed-type comparisons. - - # Subclasses must define 'theclass', and theclass(1, 1, 1) must be a - # legit constructor. - - def test_harmless_mixed_comparison(self): - me = self.theclass(1, 1, 1) - - self.failIf(me == ()) - self.failUnless(me != ()) - self.failIf(() == me) - self.failUnless(() != me) - - self.failUnless(me in [1, 20L, [], me]) - self.failIf(me not in [1, 20L, [], me]) - - self.failUnless([] in [me, 1, 20L, []]) - self.failIf([] not in [me, 1, 20L, []]) - - def test_harmful_mixed_comparison(self): - me = self.theclass(1, 1, 1) - - self.assertRaises(TypeError, lambda: me < ()) - self.assertRaises(TypeError, lambda: me <= ()) - self.assertRaises(TypeError, lambda: me > ()) - self.assertRaises(TypeError, lambda: me >= ()) - - self.assertRaises(TypeError, lambda: () < me) - self.assertRaises(TypeError, lambda: () <= me) - self.assertRaises(TypeError, lambda: () > me) - self.assertRaises(TypeError, lambda: () >= me) - - self.assertRaises(TypeError, cmp, (), me) - self.assertRaises(TypeError, cmp, me, ()) - -############################################################################# -# timedelta tests - -class TestTimeDelta(HarmlessMixedComparison): - - theclass = timedelta - - def test_constructor(self): - eq = self.assertEqual - td = timedelta - - # Check keyword args to constructor - eq(td(), td(weeks=0, days=0, hours=0, minutes=0, seconds=0, - milliseconds=0, microseconds=0)) - eq(td(1), td(days=1)) - eq(td(0, 1), td(seconds=1)) - eq(td(0, 0, 1), td(microseconds=1)) - eq(td(weeks=1), td(days=7)) - eq(td(days=1), td(hours=24)) - eq(td(hours=1), td(minutes=60)) - eq(td(minutes=1), td(seconds=60)) - eq(td(seconds=1), td(milliseconds=1000)) - eq(td(milliseconds=1), td(microseconds=1000)) - - # Check float args to constructor - eq(td(weeks=1.0/7), td(days=1)) - eq(td(days=1.0/24), td(hours=1)) - eq(td(hours=1.0/60), td(minutes=1)) - eq(td(minutes=1.0/60), td(seconds=1)) - eq(td(seconds=0.001), td(milliseconds=1)) - eq(td(milliseconds=0.001), td(microseconds=1)) - - def test_computations(self): - eq = self.assertEqual - td = timedelta - - a = td(7) # One week - b = td(0, 60) # One minute - c = td(0, 0, 1000) # One millisecond - eq(a+b+c, td(7, 60, 1000)) - eq(a-b, td(6, 24*3600 - 60)) - eq(-a, td(-7)) - eq(+a, td(7)) - eq(-b, td(-1, 24*3600 - 60)) - eq(-c, td(-1, 24*3600 - 1, 999000)) - eq(abs(a), a) - eq(abs(-a), a) - eq(td(6, 24*3600), a) - eq(td(0, 0, 60*1000000), b) - eq(a*10, td(70)) - eq(a*10, 10*a) - eq(a*10L, 10*a) - eq(b*10, td(0, 600)) - eq(10*b, td(0, 600)) - eq(b*10L, td(0, 600)) - eq(c*10, td(0, 0, 10000)) - eq(10*c, td(0, 0, 10000)) - eq(c*10L, td(0, 0, 10000)) - eq(a*-1, -a) - eq(b*-2, -b-b) - eq(c*-2, -c+-c) - eq(b*(60*24), (b*60)*24) - eq(b*(60*24), (60*b)*24) - eq(c*1000, td(0, 1)) - eq(1000*c, td(0, 1)) - eq(a//7, td(1)) - eq(b//10, td(0, 6)) - eq(c//1000, td(0, 0, 1)) - eq(a//10, td(0, 7*24*360)) - eq(a//3600000, td(0, 0, 7*24*1000)) - - def test_disallowed_computations(self): - a = timedelta(42) - - # Add/sub ints, longs, floats should be illegal - for i in 1, 1L, 1.0: - self.assertRaises(TypeError, lambda: a+i) - self.assertRaises(TypeError, lambda: a-i) - self.assertRaises(TypeError, lambda: i+a) - self.assertRaises(TypeError, lambda: i-a) - - # Mul/div by float isn't supported. - x = 2.3 - self.assertRaises(TypeError, lambda: a*x) - self.assertRaises(TypeError, lambda: x*a) - self.assertRaises(TypeError, lambda: a/x) - self.assertRaises(TypeError, lambda: x/a) - self.assertRaises(TypeError, lambda: a // x) - self.assertRaises(TypeError, lambda: x // a) - - # Divison of int by timedelta doesn't make sense. - # Division by zero doesn't make sense. - for zero in 0, 0L: - self.assertRaises(TypeError, lambda: zero // a) - self.assertRaises(ZeroDivisionError, lambda: a // zero) - - def test_basic_attributes(self): - days, seconds, us = 1, 7, 31 - td = timedelta(days, seconds, us) - self.assertEqual(td.days, days) - self.assertEqual(td.seconds, seconds) - self.assertEqual(td.microseconds, us) - - def test_carries(self): - t1 = timedelta(days=100, - weeks=-7, - hours=-24*(100-49), - minutes=-3, - seconds=12, - microseconds=(3*60 - 12) * 1e6 + 1) - t2 = timedelta(microseconds=1) - self.assertEqual(t1, t2) - - def test_hash_equality(self): - t1 = timedelta(days=100, - weeks=-7, - hours=-24*(100-49), - minutes=-3, - seconds=12, - microseconds=(3*60 - 12) * 1000000) - t2 = timedelta() - self.assertEqual(hash(t1), hash(t2)) - - t1 += timedelta(weeks=7) - t2 += timedelta(days=7*7) - self.assertEqual(t1, t2) - self.assertEqual(hash(t1), hash(t2)) - - d = {t1: 1} - d[t2] = 2 - self.assertEqual(len(d), 1) - self.assertEqual(d[t1], 2) - - def test_pickling(self): - args = 12, 34, 56 - orig = timedelta(*args) - for pickler, unpickler, proto in pickle_choices: - green = pickler.dumps(orig, proto) - derived = unpickler.loads(green) - self.assertEqual(orig, derived) - - def test_compare(self): - t1 = timedelta(2, 3, 4) - t2 = timedelta(2, 3, 4) - self.failUnless(t1 == t2) - self.failUnless(t1 <= t2) - self.failUnless(t1 >= t2) - self.failUnless(not t1 != t2) - self.failUnless(not t1 < t2) - self.failUnless(not t1 > t2) - self.assertEqual(cmp(t1, t2), 0) - self.assertEqual(cmp(t2, t1), 0) - - for args in (3, 3, 3), (2, 4, 4), (2, 3, 5): - t2 = timedelta(*args) # this is larger than t1 - self.failUnless(t1 < t2) - self.failUnless(t2 > t1) - self.failUnless(t1 <= t2) - self.failUnless(t2 >= t1) - self.failUnless(t1 != t2) - self.failUnless(t2 != t1) - self.failUnless(not t1 == t2) - self.failUnless(not t2 == t1) - self.failUnless(not t1 > t2) - self.failUnless(not t2 < t1) - self.failUnless(not t1 >= t2) - self.failUnless(not t2 <= t1) - self.assertEqual(cmp(t1, t2), -1) - self.assertEqual(cmp(t2, t1), 1) - - for badarg in OTHERSTUFF: - self.assertEqual(t1 == badarg, False) - self.assertEqual(t1 != badarg, True) - self.assertEqual(badarg == t1, False) - self.assertEqual(badarg != t1, True) - - self.assertRaises(TypeError, lambda: t1 <= badarg) - self.assertRaises(TypeError, lambda: t1 < badarg) - self.assertRaises(TypeError, lambda: t1 > badarg) - self.assertRaises(TypeError, lambda: t1 >= badarg) - self.assertRaises(TypeError, lambda: badarg <= t1) - self.assertRaises(TypeError, lambda: badarg < t1) - self.assertRaises(TypeError, lambda: badarg > t1) - self.assertRaises(TypeError, lambda: badarg >= t1) - - def test_str(self): - td = timedelta - eq = self.assertEqual - - eq(str(td(1)), "1 day, 0:00:00") - eq(str(td(-1)), "-1 day, 0:00:00") - eq(str(td(2)), "2 days, 0:00:00") - eq(str(td(-2)), "-2 days, 0:00:00") - - eq(str(td(hours=12, minutes=58, seconds=59)), "12:58:59") - eq(str(td(hours=2, minutes=3, seconds=4)), "2:03:04") - eq(str(td(weeks=-30, hours=23, minutes=12, seconds=34)), - "-210 days, 23:12:34") - - eq(str(td(milliseconds=1)), "0:00:00.001000") - eq(str(td(microseconds=3)), "0:00:00.000003") - - eq(str(td(days=999999999, hours=23, minutes=59, seconds=59, - microseconds=999999)), - "999999999 days, 23:59:59.999999") - - def test_roundtrip(self): - for td in (timedelta(days=999999999, hours=23, minutes=59, - seconds=59, microseconds=999999), - timedelta(days=-999999999), - timedelta(days=1, seconds=2, microseconds=3)): - - # Verify td -> string -> td identity. - s = repr(td) - self.failUnless(s.startswith('datetime.')) - s = s[9:] - td2 = eval(s) - self.assertEqual(td, td2) - - # Verify identity via reconstructing from pieces. - td2 = timedelta(td.days, td.seconds, td.microseconds) - self.assertEqual(td, td2) - - def test_resolution_info(self): - self.assert_(isinstance(timedelta.min, timedelta)) - self.assert_(isinstance(timedelta.max, timedelta)) - self.assert_(isinstance(timedelta.resolution, timedelta)) - self.assert_(timedelta.max > timedelta.min) - self.assertEqual(timedelta.min, timedelta(-999999999)) - self.assertEqual(timedelta.max, timedelta(999999999, 24*3600-1, 1e6-1)) - self.assertEqual(timedelta.resolution, timedelta(0, 0, 1)) - - def test_overflow(self): - tiny = timedelta.resolution - - td = timedelta.min + tiny - td -= tiny # no problem - self.assertRaises(OverflowError, td.__sub__, tiny) - self.assertRaises(OverflowError, td.__add__, -tiny) - - td = timedelta.max - tiny - td += tiny # no problem - self.assertRaises(OverflowError, td.__add__, tiny) - self.assertRaises(OverflowError, td.__sub__, -tiny) - - self.assertRaises(OverflowError, lambda: -timedelta.max) - - def test_microsecond_rounding(self): - td = timedelta - eq = self.assertEqual - - # Single-field rounding. - eq(td(milliseconds=0.4/1000), td(0)) # rounds to 0 - eq(td(milliseconds=-0.4/1000), td(0)) # rounds to 0 - eq(td(milliseconds=0.6/1000), td(microseconds=1)) - eq(td(milliseconds=-0.6/1000), td(microseconds=-1)) - - # Rounding due to contributions from more than one field. - us_per_hour = 3600e6 - us_per_day = us_per_hour * 24 - eq(td(days=.4/us_per_day), td(0)) - eq(td(hours=.2/us_per_hour), td(0)) - eq(td(days=.4/us_per_day, hours=.2/us_per_hour), td(microseconds=1)) - - eq(td(days=-.4/us_per_day), td(0)) - eq(td(hours=-.2/us_per_hour), td(0)) - eq(td(days=-.4/us_per_day, hours=-.2/us_per_hour), td(microseconds=-1)) - - def test_massive_normalization(self): - td = timedelta(microseconds=-1) - self.assertEqual((td.days, td.seconds, td.microseconds), - (-1, 24*3600-1, 999999)) - - def test_bool(self): - self.failUnless(timedelta(1)) - self.failUnless(timedelta(0, 1)) - self.failUnless(timedelta(0, 0, 1)) - self.failUnless(timedelta(microseconds=1)) - self.failUnless(not timedelta(0)) - -############################################################################# -# date tests - -class TestDateOnly(unittest.TestCase): - # Tests here won't pass if also run on datetime objects, so don't - # subclass this to test datetimes too. - - def test_delta_non_days_ignored(self): - dt = date(2000, 1, 2) - delta = timedelta(days=1, hours=2, minutes=3, seconds=4, - microseconds=5) - days = timedelta(delta.days) - self.assertEqual(days, timedelta(1)) - - dt2 = dt + delta - self.assertEqual(dt2, dt + days) - - dt2 = delta + dt - self.assertEqual(dt2, dt + days) - - dt2 = dt - delta - self.assertEqual(dt2, dt - days) - - delta = -delta - days = timedelta(delta.days) - self.assertEqual(days, timedelta(-2)) - - dt2 = dt + delta - self.assertEqual(dt2, dt + days) - - dt2 = delta + dt - self.assertEqual(dt2, dt + days) - - dt2 = dt - delta - self.assertEqual(dt2, dt - days) - -class TestDate(HarmlessMixedComparison): - # Tests here should pass for both dates and datetimes, except for a - # few tests that TestDateTime overrides. - - theclass = date - - def test_basic_attributes(self): - dt = self.theclass(2002, 3, 1) - self.assertEqual(dt.year, 2002) - self.assertEqual(dt.month, 3) - self.assertEqual(dt.day, 1) - - def test_roundtrip(self): - for dt in (self.theclass(1, 2, 3), - self.theclass.today()): - # Verify dt -> string -> date identity. - s = repr(dt) - self.failUnless(s.startswith('datetime.')) - s = s[9:] - dt2 = eval(s) - self.assertEqual(dt, dt2) - - # Verify identity via reconstructing from pieces. - dt2 = self.theclass(dt.year, dt.month, dt.day) - self.assertEqual(dt, dt2) - - def test_ordinal_conversions(self): - # Check some fixed values. - for y, m, d, n in [(1, 1, 1, 1), # calendar origin - (1, 12, 31, 365), - (2, 1, 1, 366), - # first example from "Calendrical Calculations" - (1945, 11, 12, 710347)]: - d = self.theclass(y, m, d) - self.assertEqual(n, d.toordinal()) - fromord = self.theclass.fromordinal(n) - self.assertEqual(d, fromord) - if hasattr(fromord, "hour"): - # if we're checking something fancier than a date, verify - # the extra fields have been zeroed out - self.assertEqual(fromord.hour, 0) - self.assertEqual(fromord.minute, 0) - self.assertEqual(fromord.second, 0) - self.assertEqual(fromord.microsecond, 0) - - # Check first and last days of year spottily across the whole - # range of years supported. - for year in xrange(MINYEAR, MAXYEAR+1, 7): - # Verify (year, 1, 1) -> ordinal -> y, m, d is identity. - d = self.theclass(year, 1, 1) - n = d.toordinal() - d2 = self.theclass.fromordinal(n) - self.assertEqual(d, d2) - # Verify that moving back a day gets to the end of year-1. - if year > 1: - d = self.theclass.fromordinal(n-1) - d2 = self.theclass(year-1, 12, 31) - self.assertEqual(d, d2) - self.assertEqual(d2.toordinal(), n-1) - - # Test every day in a leap-year and a non-leap year. - dim = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] - for year, isleap in (2000, True), (2002, False): - n = self.theclass(year, 1, 1).toordinal() - for month, maxday in zip(range(1, 13), dim): - if month == 2 and isleap: - maxday += 1 - for day in range(1, maxday+1): - d = self.theclass(year, month, day) - self.assertEqual(d.toordinal(), n) - self.assertEqual(d, self.theclass.fromordinal(n)) - n += 1 - - def test_extreme_ordinals(self): - a = self.theclass.min - a = self.theclass(a.year, a.month, a.day) # get rid of time parts - aord = a.toordinal() - b = a.fromordinal(aord) - self.assertEqual(a, b) - - self.assertRaises(ValueError, lambda: a.fromordinal(aord - 1)) - - b = a + timedelta(days=1) - self.assertEqual(b.toordinal(), aord + 1) - self.assertEqual(b, self.theclass.fromordinal(aord + 1)) - - a = self.theclass.max - a = self.theclass(a.year, a.month, a.day) # get rid of time parts - aord = a.toordinal() - b = a.fromordinal(aord) - self.assertEqual(a, b) - - self.assertRaises(ValueError, lambda: a.fromordinal(aord + 1)) - - b = a - timedelta(days=1) - self.assertEqual(b.toordinal(), aord - 1) - self.assertEqual(b, self.theclass.fromordinal(aord - 1)) - - def test_bad_constructor_arguments(self): - # bad years - self.theclass(MINYEAR, 1, 1) # no exception - self.theclass(MAXYEAR, 1, 1) # no exception - self.assertRaises(ValueError, self.theclass, MINYEAR-1, 1, 1) - self.assertRaises(ValueError, self.theclass, MAXYEAR+1, 1, 1) - # bad months - self.theclass(2000, 1, 1) # no exception - self.theclass(2000, 12, 1) # no exception - self.assertRaises(ValueError, self.theclass, 2000, 0, 1) - self.assertRaises(ValueError, self.theclass, 2000, 13, 1) - # bad days - self.theclass(2000, 2, 29) # no exception - self.theclass(2004, 2, 29) # no exception - self.theclass(2400, 2, 29) # no exception - self.assertRaises(ValueError, self.theclass, 2000, 2, 30) - self.assertRaises(ValueError, self.theclass, 2001, 2, 29) - self.assertRaises(ValueError, self.theclass, 2100, 2, 29) - self.assertRaises(ValueError, self.theclass, 1900, 2, 29) - self.assertRaises(ValueError, self.theclass, 2000, 1, 0) - self.assertRaises(ValueError, self.theclass, 2000, 1, 32) - - def test_hash_equality(self): - d = self.theclass(2000, 12, 31) - # same thing - e = self.theclass(2000, 12, 31) - self.assertEqual(d, e) - self.assertEqual(hash(d), hash(e)) - - dic = {d: 1} - dic[e] = 2 - self.assertEqual(len(dic), 1) - self.assertEqual(dic[d], 2) - self.assertEqual(dic[e], 2) - - d = self.theclass(2001, 1, 1) - # same thing - e = self.theclass(2001, 1, 1) - self.assertEqual(d, e) - self.assertEqual(hash(d), hash(e)) - - dic = {d: 1} - dic[e] = 2 - self.assertEqual(len(dic), 1) - self.assertEqual(dic[d], 2) - self.assertEqual(dic[e], 2) - - def test_computations(self): - a = self.theclass(2002, 1, 31) - b = self.theclass(1956, 1, 31) - - diff = a-b - self.assertEqual(diff.days, 46*365 + len(range(1956, 2002, 4))) - self.assertEqual(diff.seconds, 0) - self.assertEqual(diff.microseconds, 0) - - day = timedelta(1) - week = timedelta(7) - a = self.theclass(2002, 3, 2) - self.assertEqual(a + day, self.theclass(2002, 3, 3)) - self.assertEqual(day + a, self.theclass(2002, 3, 3)) - self.assertEqual(a - day, self.theclass(2002, 3, 1)) - self.assertEqual(-day + a, self.theclass(2002, 3, 1)) - self.assertEqual(a + week, self.theclass(2002, 3, 9)) - self.assertEqual(a - week, self.theclass(2002, 2, 23)) - self.assertEqual(a + 52*week, self.theclass(2003, 3, 1)) - self.assertEqual(a - 52*week, self.theclass(2001, 3, 3)) - self.assertEqual((a + week) - a, week) - self.assertEqual((a + day) - a, day) - self.assertEqual((a - week) - a, -week) - self.assertEqual((a - day) - a, -day) - self.assertEqual(a - (a + week), -week) - self.assertEqual(a - (a + day), -day) - self.assertEqual(a - (a - week), week) - self.assertEqual(a - (a - day), day) - - # Add/sub ints, longs, floats should be illegal - for i in 1, 1L, 1.0: - self.assertRaises(TypeError, lambda: a+i) - self.assertRaises(TypeError, lambda: a-i) - self.assertRaises(TypeError, lambda: i+a) - self.assertRaises(TypeError, lambda: i-a) - - # delta - date is senseless. - self.assertRaises(TypeError, lambda: day - a) - # mixing date and (delta or date) via * or // is senseless - self.assertRaises(TypeError, lambda: day * a) - self.assertRaises(TypeError, lambda: a * day) - self.assertRaises(TypeError, lambda: day // a) - self.assertRaises(TypeError, lambda: a // day) - self.assertRaises(TypeError, lambda: a * a) - self.assertRaises(TypeError, lambda: a // a) - # date + date is senseless - self.assertRaises(TypeError, lambda: a + a) - - def test_overflow(self): - tiny = self.theclass.resolution - - dt = self.theclass.min + tiny - dt -= tiny # no problem - self.assertRaises(OverflowError, dt.__sub__, tiny) - self.assertRaises(OverflowError, dt.__add__, -tiny) - - dt = self.theclass.max - tiny - dt += tiny # no problem - self.assertRaises(OverflowError, dt.__add__, tiny) - self.assertRaises(OverflowError, dt.__sub__, -tiny) - - def test_fromtimestamp(self): - import time - - # Try an arbitrary fixed value. - year, month, day = 1999, 9, 19 - ts = time.mktime((year, month, day, 0, 0, 0, 0, 0, -1)) - d = self.theclass.fromtimestamp(ts) - self.assertEqual(d.year, year) - self.assertEqual(d.month, month) - self.assertEqual(d.day, day) - - def test_today(self): - import time - - # We claim that today() is like fromtimestamp(time.time()), so - # prove it. - for dummy in range(3): - today = self.theclass.today() - ts = time.time() - todayagain = self.theclass.fromtimestamp(ts) - if today == todayagain: - break - # There are several legit reasons that could fail: - # 1. It recently became midnight, between the today() and the - # time() calls. - # 2. The platform time() has such fine resolution that we'll - # never get the same value twice. - # 3. The platform time() has poor resolution, and we just - # happened to call today() right before a resolution quantum - # boundary. - # 4. The system clock got fiddled between calls. - # In any case, wait a little while and try again. - time.sleep(0.1) - - # It worked or it didn't. If it didn't, assume it's reason #2, and - # let the test pass if they're within half a second of each other. - self.failUnless(today == todayagain or - abs(todayagain - today) < timedelta(seconds=0.5)) - - def test_weekday(self): - for i in range(7): - # March 4, 2002 is a Monday - self.assertEqual(self.theclass(2002, 3, 4+i).weekday(), i) - self.assertEqual(self.theclass(2002, 3, 4+i).isoweekday(), i+1) - # January 2, 1956 is a Monday - self.assertEqual(self.theclass(1956, 1, 2+i).weekday(), i) - self.assertEqual(self.theclass(1956, 1, 2+i).isoweekday(), i+1) - - def test_isocalendar(self): - # Check examples from - # http://www.phys.uu.nl/~vgent/calendar/isocalendar.htm - for i in range(7): - d = self.theclass(2003, 12, 22+i) - self.assertEqual(d.isocalendar(), (2003, 52, i+1)) - d = self.theclass(2003, 12, 29) + timedelta(i) - self.assertEqual(d.isocalendar(), (2004, 1, i+1)) - d = self.theclass(2004, 1, 5+i) - self.assertEqual(d.isocalendar(), (2004, 2, i+1)) - d = self.theclass(2009, 12, 21+i) - self.assertEqual(d.isocalendar(), (2009, 52, i+1)) - d = self.theclass(2009, 12, 28) + timedelta(i) - self.assertEqual(d.isocalendar(), (2009, 53, i+1)) - d = self.theclass(2010, 1, 4+i) - self.assertEqual(d.isocalendar(), (2010, 1, i+1)) - - def test_iso_long_years(self): - # Calculate long ISO years and compare to table from - # http://www.phys.uu.nl/~vgent/calendar/isocalendar.htm - ISO_LONG_YEARS_TABLE = """ - 4 32 60 88 - 9 37 65 93 - 15 43 71 99 - 20 48 76 - 26 54 82 - - 105 133 161 189 - 111 139 167 195 - 116 144 172 - 122 150 178 - 128 156 184 - - 201 229 257 285 - 207 235 263 291 - 212 240 268 296 - 218 246 274 - 224 252 280 - - 303 331 359 387 - 308 336 364 392 - 314 342 370 398 - 320 348 376 - 325 353 381 - """ - iso_long_years = map(int, ISO_LONG_YEARS_TABLE.split()) - iso_long_years.sort() - L = [] - for i in range(400): - d = self.theclass(2000+i, 12, 31) - d1 = self.theclass(1600+i, 12, 31) - self.assertEqual(d.isocalendar()[1:], d1.isocalendar()[1:]) - if d.isocalendar()[1] == 53: - L.append(i) - self.assertEqual(L, iso_long_years) - - def test_isoformat(self): - t = self.theclass(2, 3, 2) - self.assertEqual(t.isoformat(), "0002-03-02") - - def test_ctime(self): - t = self.theclass(2002, 3, 2) - self.assertEqual(t.ctime(), "Sat Mar 2 00:00:00 2002") - - def test_strftime(self): - t = self.theclass(2005, 3, 2) - self.assertEqual(t.strftime("m:%m d:%d y:%y"), "m:03 d:02 y:05") - - self.assertRaises(TypeError, t.strftime) # needs an arg - self.assertRaises(TypeError, t.strftime, "one", "two") # too many args - self.assertRaises(TypeError, t.strftime, 42) # arg wrong type - - # A naive object replaces %z and %Z w/ empty strings. - self.assertEqual(t.strftime("'%z' '%Z'"), "'' ''") - - def test_resolution_info(self): - self.assert_(isinstance(self.theclass.min, self.theclass)) - self.assert_(isinstance(self.theclass.max, self.theclass)) - self.assert_(isinstance(self.theclass.resolution, timedelta)) - self.assert_(self.theclass.max > self.theclass.min) - - def test_extreme_timedelta(self): - big = self.theclass.max - self.theclass.min - # 3652058 days, 23 hours, 59 minutes, 59 seconds, 999999 microseconds - n = (big.days*24*3600 + big.seconds)*1000000 + big.microseconds - # n == 315537897599999999 ~= 2**58.13 - justasbig = timedelta(0, 0, n) - self.assertEqual(big, justasbig) - self.assertEqual(self.theclass.min + big, self.theclass.max) - self.assertEqual(self.theclass.max - big, self.theclass.min) - - def test_timetuple(self): - for i in range(7): - # January 2, 1956 is a Monday (0) - d = self.theclass(1956, 1, 2+i) - t = d.timetuple() - self.assertEqual(t, (1956, 1, 2+i, 0, 0, 0, i, 2+i, -1)) - # February 1, 1956 is a Wednesday (2) - d = self.theclass(1956, 2, 1+i) - t = d.timetuple() - self.assertEqual(t, (1956, 2, 1+i, 0, 0, 0, (2+i)%7, 32+i, -1)) - # March 1, 1956 is a Thursday (3), and is the 31+29+1 = 61st day - # of the year. - d = self.theclass(1956, 3, 1+i) - t = d.timetuple() - self.assertEqual(t, (1956, 3, 1+i, 0, 0, 0, (3+i)%7, 61+i, -1)) - self.assertEqual(t.tm_year, 1956) - self.assertEqual(t.tm_mon, 3) - self.assertEqual(t.tm_mday, 1+i) - self.assertEqual(t.tm_hour, 0) - self.assertEqual(t.tm_min, 0) - self.assertEqual(t.tm_sec, 0) - self.assertEqual(t.tm_wday, (3+i)%7) - self.assertEqual(t.tm_yday, 61+i) - self.assertEqual(t.tm_isdst, -1) - - def test_pickling(self): - args = 6, 7, 23 - orig = self.theclass(*args) - for pickler, unpickler, proto in pickle_choices: - green = pickler.dumps(orig, proto) - derived = unpickler.loads(green) - self.assertEqual(orig, derived) - - def test_compare(self): - t1 = self.theclass(2, 3, 4) - t2 = self.theclass(2, 3, 4) - self.failUnless(t1 == t2) - self.failUnless(t1 <= t2) - self.failUnless(t1 >= t2) - self.failUnless(not t1 != t2) - self.failUnless(not t1 < t2) - self.failUnless(not t1 > t2) - self.assertEqual(cmp(t1, t2), 0) - self.assertEqual(cmp(t2, t1), 0) - - for args in (3, 3, 3), (2, 4, 4), (2, 3, 5): - t2 = self.theclass(*args) # this is larger than t1 - self.failUnless(t1 < t2) - self.failUnless(t2 > t1) - self.failUnless(t1 <= t2) - self.failUnless(t2 >= t1) - self.failUnless(t1 != t2) - self.failUnless(t2 != t1) - self.failUnless(not t1 == t2) - self.failUnless(not t2 == t1) - self.failUnless(not t1 > t2) - self.failUnless(not t2 < t1) - self.failUnless(not t1 >= t2) - self.failUnless(not t2 <= t1) - self.assertEqual(cmp(t1, t2), -1) - self.assertEqual(cmp(t2, t1), 1) - - for badarg in OTHERSTUFF: - self.assertEqual(t1 == badarg, False) - self.assertEqual(t1 != badarg, True) - self.assertEqual(badarg == t1, False) - self.assertEqual(badarg != t1, True) - - self.assertRaises(TypeError, lambda: t1 < badarg) - self.assertRaises(TypeError, lambda: t1 > badarg) - self.assertRaises(TypeError, lambda: t1 >= badarg) - self.assertRaises(TypeError, lambda: badarg <= t1) - self.assertRaises(TypeError, lambda: badarg < t1) - self.assertRaises(TypeError, lambda: badarg > t1) - self.assertRaises(TypeError, lambda: badarg >= t1) - - def test_mixed_compare(self): - our = self.theclass(2000, 4, 5) - self.assertRaises(TypeError, cmp, our, 1) - self.assertRaises(TypeError, cmp, 1, our) - - class AnotherDateTimeClass(object): - def __cmp__(self, other): - # Return "equal" so calling this can't be confused with - # compare-by-address (which never says "equal" for distinct - # objects). - return 0 - - # This still errors, because date and datetime comparison raise - # TypeError instead of NotImplemented when they don't know what to - # do, in order to stop comparison from falling back to the default - # compare-by-address. - their = AnotherDateTimeClass() - self.assertRaises(TypeError, cmp, our, their) - # Oops: The next stab raises TypeError in the C implementation, - # but not in the Python implementation of datetime. The difference - # is due to that the Python implementation defines __cmp__ but - # the C implementation defines tp_richcompare. This is more pain - # to fix than it's worth, so commenting out the test. - # self.assertEqual(cmp(their, our), 0) - - # But date and datetime comparison return NotImplemented instead if the - # other object has a timetuple attr. This gives the other object a - # chance to do the comparison. - class Comparable(AnotherDateTimeClass): - def timetuple(... [truncated message content] |
From: <fwi...@us...> - 2008-07-04 21:25:25
|
Revision: 4850 http://jython.svn.sourceforge.net/jython/?rev=4850&view=rev Author: fwierzbicki Date: 2008-07-04 14:25:24 -0700 (Fri, 04 Jul 2008) Log Message: ----------- Moved the actual emit of the generated newline (for input w/o a newline) to *after* dedents are emitted. Modified Paths: -------------- branches/asm/src/org/python/antlr/PythonTokenSource.java Modified: branches/asm/src/org/python/antlr/PythonTokenSource.java =================================================================== --- branches/asm/src/org/python/antlr/PythonTokenSource.java 2008-07-04 12:33:14 UTC (rev 4849) +++ branches/asm/src/org/python/antlr/PythonTokenSource.java 2008-07-04 21:25:24 UTC (rev 4850) @@ -174,7 +174,6 @@ newline = new CommonToken(PythonLexer.NEWLINE, "\n"); newline.setLine(t.getLine()); newline.setCharPositionInLine(t.getCharPositionInLine()); - tokens.addElement(newline); } // compute cpos as the char pos of next non-WS token in line @@ -217,6 +216,10 @@ } sp = prevIndex; // pop those off indent level } + if (t.getType() == PythonLexer.EOF) { + tokens.addElement(newline); + } + if (t.getType() != PythonLexer.LEADING_WS) { // discard WS tokens.addElement(t); } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <fwi...@us...> - 2008-07-04 12:33:15
|
Revision: 4849 http://jython.svn.sourceforge.net/jython/?rev=4849&view=rev Author: fwierzbicki Date: 2008-07-04 05:33:14 -0700 (Fri, 04 Jul 2008) Log Message: ----------- Formatting and remove unused variable. Modified Paths: -------------- branches/asm/src/org/python/antlr/PythonTokenSource.java Modified: branches/asm/src/org/python/antlr/PythonTokenSource.java =================================================================== --- branches/asm/src/org/python/antlr/PythonTokenSource.java 2008-07-04 12:21:30 UTC (rev 4848) +++ branches/asm/src/org/python/antlr/PythonTokenSource.java 2008-07-04 12:33:14 UTC (rev 4849) @@ -88,8 +88,6 @@ int lastTokenAddedIndex = -1; - boolean atEnd = false; - public PythonTokenSource(PythonLexer lexer) { } @@ -123,7 +121,7 @@ */ public Token nextToken() { // if something in queue, just remove and return it - if ( tokens.size()>0 ) { + if (tokens.size() > 0) { Token t = (Token)tokens.firstElement(); tokens.removeElementAt(0); //System.out.println(t); @@ -135,15 +133,14 @@ return nextToken(); } - protected void insertImaginaryIndentDedentTokens() - { + protected void insertImaginaryIndentDedentTokens() { Token t = stream.LT(1); stream.consume(); // if the current token is not a NEWLINE or EOF, it doesn't signal indent/dedent work; just enqueue if (t.getType() != PythonLexer.NEWLINE && t.getType() != PythonLexer.EOF) { - List hiddenTokens = stream.getTokens(lastTokenAddedIndex+1,t.getTokenIndex()-1); - if ( hiddenTokens!=null ) { + List hiddenTokens = stream.getTokens(lastTokenAddedIndex + 1,t.getTokenIndex() - 1); + if (hiddenTokens != null) { tokens.addAll(hiddenTokens); } lastTokenAddedIndex = t.getTokenIndex(); @@ -156,7 +153,7 @@ // save NEWLINE in the queue //System.out.println("found newline: "+t+" stack is "+stackString()); newline = (CommonToken)t; - List hiddenTokens = stream.getTokens(lastTokenAddedIndex+1,t.getTokenIndex()-1); + List hiddenTokens = stream.getTokens(lastTokenAddedIndex + 1,t.getTokenIndex() - 1); if (hiddenTokens!=null) { tokens.addAll(hiddenTokens); } @@ -167,7 +164,7 @@ t = stream.LT(1); stream.consume(); - hiddenTokens = stream.getTokens(lastTokenAddedIndex+1,t.getTokenIndex()-1); + hiddenTokens = stream.getTokens(lastTokenAddedIndex + 1,t.getTokenIndex() - 1); if (hiddenTokens!=null) { tokens.addAll(hiddenTokens); } @@ -182,10 +179,10 @@ // compute cpos as the char pos of next non-WS token in line int cpos = t.getCharPositionInLine(); // column dictates indent/dedent - if ( t.getType()==Token.EOF ) { + if (t.getType() == Token.EOF) { cpos = -1; // pretend EOF always happens at left edge } - else if ( t.getType()==PythonLexer.LEADING_WS ) { + else if (t.getType() == PythonLexer.LEADING_WS) { cpos = t.getText().length(); } @@ -194,7 +191,7 @@ // compare to last indent level int lastIndent = peek(); //System.out.println("cpos, lastIndent = "+cpos+", "+lastIndent); - if ( cpos > lastIndent ) { // they indented; track and gen INDENT + if (cpos > lastIndent) { // they indented; track and gen INDENT push(cpos); //System.out.println("push("+cpos+"): "+stackString()); Token indent = new ImaginaryToken(PythonParser.INDENT,""); @@ -202,12 +199,12 @@ indent.setLine(t.getLine()); tokens.addElement(indent); } - else if ( cpos < lastIndent ) { // they dedented + else if (cpos < lastIndent) { // they dedented // how far back did we dedent? int prevIndex = findPreviousIndent(cpos); //System.out.println("dedented; prevIndex of cpos="+cpos+" is "+prevIndex); // generate DEDENTs for each indent level we backed up over - for (int d=sp-1; d>=prevIndex; d--) { + for (int d = sp - 1; d >= prevIndex; d--) { ImaginaryToken dedent = new ImaginaryToken(PythonParser.DEDENT,""); dedent.setCharPositionInLine(t.getCharPositionInLine()); dedent.setLine(t.getLine()); @@ -220,7 +217,7 @@ } sp = prevIndex; // pop those off indent level } - if ( t.getType()!=PythonLexer.LEADING_WS ) { // discard WS + if (t.getType() != PythonLexer.LEADING_WS) { // discard WS tokens.addElement(t); } } @@ -228,7 +225,7 @@ // T O K E N S T A C K M E T H O D S protected void push(int i) { - if (sp>=MAX_INDENTS) { + if (sp >= MAX_INDENTS) { throw new IllegalStateException("stack overflow"); } sp++; @@ -250,8 +247,8 @@ /** Return the index on stack of previous indent level == i else -1 */ protected int findPreviousIndent(int i) { - for (int j=sp-1; j>=0; j--) { - if ( indentStack[j]==i ) { + for (int j = sp - 1; j >= 0; j--) { + if (indentStack[j] == i) { return j; } } @@ -260,7 +257,7 @@ public String stackString() { StringBuffer buf = new StringBuffer(); - for (int j=sp; j>=0; j--) { + for (int j = sp; j >= 0; j--) { buf.append(" "); buf.append(indentStack[j]); } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |