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: <pj...@us...> - 2008-10-29 02:39:05
|
Revision: 5525 http://jython.svn.sourceforge.net/jython/?rev=5525&view=rev Author: pjenvey Date: 2008-10-29 02:38:55 +0000 (Wed, 29 Oct 2008) Log Message: ----------- o fix assert not nan == nan and nan != nan, and cmp on nans o fix math.frexp(nan) causing an endless loop Modified Paths: -------------- trunk/jython/Lib/test/test_float_jy.py trunk/jython/src/org/python/core/PyFloat.java trunk/jython/src/org/python/modules/math.java Added Paths: ----------- trunk/jython/Lib/test/test_math_jy.py Modified: trunk/jython/Lib/test/test_float_jy.py =================================================================== --- trunk/jython/Lib/test/test_float_jy.py 2008-10-28 21:47:35 UTC (rev 5524) +++ trunk/jython/Lib/test/test_float_jy.py 2008-10-29 02:38:55 UTC (rev 5525) @@ -66,10 +66,23 @@ self.assertNotEqual(0.1, shuge_int) def test_nan(self): - self.assert_(type(float('NaN')), float) - self.assert_(type(float('nan')), float) - self.assertEqual(long(float('NaN')), 0) + nan = float('nan') + self.assert_(type(nan), float) + if jython: + # support Java syntax + self.assert_(type(float('NaN')), float) + # CPython 2.4/2.5 allow this + self.assertEqual(long(nan), 0) + + self.assertNotEqual(nan, float('nan')) + self.assertNotEqual(nan, nan) + self.assertEqual(cmp(nan, float('nan')), 1) + self.assertEqual(cmp(nan, nan), 0) + for i in (-1, 1, -1.0, 1.0): + self.assertEqual(cmp(nan, i), -1) + self.assertEqual(cmp(i, nan), 1) + def test_infinity(self): self.assert_(type(float('Infinity')), float) self.assert_(type(float('inf')), float) Added: trunk/jython/Lib/test/test_math_jy.py =================================================================== --- trunk/jython/Lib/test/test_math_jy.py (rev 0) +++ trunk/jython/Lib/test/test_math_jy.py 2008-10-29 02:38:55 UTC (rev 5525) @@ -0,0 +1,26 @@ +"""Misc math module tests + +Made for Jython. +""" +import math +import unittest +from test import test_support + +inf = float('inf') +nan = float('nan') + +class MathTestCase(unittest.TestCase): + + def test_frexp(self): + self.assertEqual(math.frexp(inf), (inf, 0)) + mantissa, exponent = math.frexp(nan) + self.assertNotEqual(mantissa, mantissa) + self.assertEqual(exponent, 0) + + +def test_main(): + test_support.run_unittest(MathTestCase) + + +if __name__ == '__main__': + test_main() Modified: trunk/jython/src/org/python/core/PyFloat.java =================================================================== --- trunk/jython/src/org/python/core/PyFloat.java 2008-10-28 21:47:35 UTC (rev 5524) +++ trunk/jython/src/org/python/core/PyFloat.java 2008-10-29 02:38:55 UTC (rev 5525) @@ -168,6 +168,22 @@ return super.__tojava__(c); } + public PyObject __eq__(PyObject other) { + // preclude _cmp_unsafe's this == other shortcut because NaN != anything, even + // itself + if (Double.isNaN(value)) { + return Py.False; + } + return null; + } + + public PyObject __ne__(PyObject other) { + if (Double.isNaN(value)) { + return Py.True; + } + return null; + } + public int __cmp__(PyObject other) { return float___cmp__(other); } @@ -197,7 +213,17 @@ } else { return -2; } - return i < j ? -1 : i > j ? 1 : 0; + + if (i < j) { + return -1; + } else if (i > j) { + return 1; + } else if (i == j) { + return 0; + } else { + // at least one side is NaN + return Double.isNaN(i) ? (Double.isNaN(j) ? 1 : -1) : 1; + } } public Object __coerce_ex__(PyObject other) { Modified: trunk/jython/src/org/python/modules/math.java =================================================================== --- trunk/jython/src/org/python/modules/math.java 2008-10-28 21:47:35 UTC (rev 5524) +++ trunk/jython/src/org/python/modules/math.java 2008-10-29 02:38:55 UTC (rev 5525) @@ -157,26 +157,26 @@ return new PyTuple(new PyFloat(w), new PyFloat(v)); } - public static PyTuple frexp(double v) { - int i = 0; - if (v != 0.0) { - int sign = 1; - if (v < 0) { + public static PyTuple frexp(double x) { + int exponent = 0; + + if (Double.isNaN(x) || Double.isInfinite(x) || x == 0.0) { + exponent = 0; + } else { + short sign = 1; + + if (x < 0.0) { + x = -x; sign = -1; - v = -v; } - // slow... - while (v < 0.5) { - v = v*2.0; - i = i-1; - } - while (v >= 1.0) { - v = v*0.5; - i = i+1; - } - v = v*sign; + + for (; x < 0.5; x *= 2.0, exponent--); + + for (; x >= 1.0; x *= 0.5, exponent++); + + x *= sign; } - return new PyTuple(new PyFloat(v), new PyInteger(i)); + return new PyTuple(new PyFloat(x), new PyInteger(exponent)); } public static double ldexp(double v, int w) { This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <pj...@us...> - 2008-10-28 21:51:11
|
Revision: 5524 http://jython.svn.sourceforge.net/jython/?rev=5524&view=rev Author: pjenvey Date: 2008-10-28 21:47:35 +0000 (Tue, 28 Oct 2008) Log Message: ----------- fix float and complex's __pow__ not being exposed as binary ops Modified Paths: -------------- trunk/jython/Lib/test/test_complex_jy.py trunk/jython/Lib/test/test_float_jy.py trunk/jython/src/org/python/core/PyComplex.java trunk/jython/src/org/python/core/PyFloat.java Modified: trunk/jython/Lib/test/test_complex_jy.py =================================================================== --- trunk/jython/Lib/test/test_complex_jy.py 2008-10-28 07:58:42 UTC (rev 5523) +++ trunk/jython/Lib/test/test_complex_jy.py 2008-10-28 21:47:35 UTC (rev 5524) @@ -11,7 +11,14 @@ self.assertEqual(complex.__coerce__(1+1j, None), NotImplemented) self.assertRaises(TypeError, complex.__coerce__, None, 1+2j) + def test_pow(self): + class Foo(object): + def __rpow__(self, other): + return other ** 2 + # regression in 2.5 alphas + self.assertEqual((4+0j) ** Foo(), (16+0j)) + def test_main(): test_support.run_unittest(ComplexTest) Modified: trunk/jython/Lib/test/test_float_jy.py =================================================================== --- trunk/jython/Lib/test/test_float_jy.py 2008-10-28 07:58:42 UTC (rev 5523) +++ trunk/jython/Lib/test/test_float_jy.py 2008-10-28 21:47:35 UTC (rev 5524) @@ -78,7 +78,14 @@ def test_float_none(self): self.assertRaises(TypeError, float, None) + def test_pow(self): + class Foo(object): + def __rpow__(self, other): + return other ** 2 + # regression in 2.5 alphas + self.assertEqual(4.0 ** Foo(), 16.0) + def test_main(): test_support.run_unittest(FloatTestCase) Modified: trunk/jython/src/org/python/core/PyComplex.java =================================================================== --- trunk/jython/src/org/python/core/PyComplex.java 2008-10-28 07:58:42 UTC (rev 5523) +++ trunk/jython/src/org/python/core/PyComplex.java 2008-10-28 21:47:35 UTC (rev 5524) @@ -569,7 +569,7 @@ return complex___pow__(right, modulo); } - @ExposedMethod(defaults = "null") + @ExposedMethod(type = MethodType.BINARY, defaults = "null") final PyObject complex___pow__(PyObject right, PyObject modulo) { if (modulo != null) { throw Py.ValueError("complex modulo"); Modified: trunk/jython/src/org/python/core/PyFloat.java =================================================================== --- trunk/jython/src/org/python/core/PyFloat.java 2008-10-28 07:58:42 UTC (rev 5523) +++ trunk/jython/src/org/python/core/PyFloat.java 2008-10-28 21:47:35 UTC (rev 5524) @@ -468,7 +468,7 @@ return float___pow__(right, modulo); } - @ExposedMethod(defaults = "null") + @ExposedMethod(type = MethodType.BINARY, defaults = "null") final PyObject float___pow__(PyObject right, PyObject modulo) { if (!canCoerce(right)) return null; This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <cg...@us...> - 2008-10-28 07:58:52
|
Revision: 5523 http://jython.svn.sourceforge.net/jython/?rev=5523&view=rev Author: cgroves Date: 2008-10-28 07:58:42 +0000 (Tue, 28 Oct 2008) Log Message: ----------- Make Java static inner classes visible from Java subclasses. From garyh's patch. Resolves issue 1147. Modified Paths: -------------- trunk/jython/Lib/test/test_java_visibility.py trunk/jython/src/org/python/core/Py.java trunk/jython/src/org/python/core/PyJavaClass.java trunk/jython/tests/java/org/python/tests/Visible.java Modified: trunk/jython/Lib/test/test_java_visibility.py =================================================================== --- trunk/jython/Lib/test/test_java_visibility.py 2008-10-27 21:15:22 UTC (rev 5522) +++ trunk/jython/Lib/test/test_java_visibility.py 2008-10-28 07:58:42 UTC (rev 5523) @@ -14,7 +14,7 @@ Visible.__init__(self, publicValue) else: Visible.__init__(self) - # TODO - protectedStaticMethod, protectedStaticField, and protectedField should + # TODO - protectedStaticMethod, protectedStaticField, StaticInner, and protectedField should # be here s = SubVisible() self.assertEquals(Results.PROTECTED_METHOD, s.protectedMethod(0)) @@ -37,6 +37,7 @@ v.visibleStatic('a')) self.assertEquals(Results.EXTRA_ARG_PUBLIC_STATIC_METHOD, v.visibleStatic(0, 'a')) + self.assertEquals(Results.PUBLIC_STATIC_FIELD, Visible.StaticInner.visibleStaticField) # Ensure that the visibleInstance method from SubVisible that takes a double doesn't # leak through to the parent @@ -57,7 +58,9 @@ # Java methods don't allow direct calling of the superclass method, so it should # return the subclass value here. self.assertEquals(Results.SUBCLASS_OVERRIDE, Visible.visibleInstance(s, 3)) + self.assertEquals(Results.PUBLIC_STATIC_FIELD, SubVisible.StaticInner.visibleStaticField) + def test_in_dict(self): for c in Visible, SubVisible, VisibleOverride: self.failUnless('visibleInstance' in c.__dict__, Modified: trunk/jython/src/org/python/core/Py.java =================================================================== --- trunk/jython/src/org/python/core/Py.java 2008-10-27 21:15:22 UTC (rev 5522) +++ trunk/jython/src/org/python/core/Py.java 2008-10-28 07:58:42 UTC (rev 5523) @@ -762,20 +762,6 @@ return true; } - public static Class relFindClass(Class home, String name) { - try { - ClassLoader loader = home.getClassLoader(); - if (loader != null) { - return loader.loadClass(name); - } else { - return Class.forName(name); - } - } catch (ClassNotFoundException exc) { - return null; - } catch (Throwable t) { - throw Py.JavaError(t); - } - } private static boolean secEnv = false; public static Class findClass(String name) { Modified: trunk/jython/src/org/python/core/PyJavaClass.java =================================================================== --- trunk/jython/src/org/python/core/PyJavaClass.java 2008-10-27 21:15:22 UTC (rev 5522) +++ trunk/jython/src/org/python/core/PyJavaClass.java 2008-10-28 07:58:42 UTC (rev 5523) @@ -709,10 +709,16 @@ } private PyObject findInnerClass(String name) { - Class p = getProxyClass(); - Class innerClass = Py.relFindClass(p, p.getName() + "$" + name); - if (innerClass == null) + Class<?> innerClass = null; + for (Class<?> inner : getProxyClass().getClasses()) { + if(inner.getSimpleName().equals(name)) { + innerClass = inner; + break; + } + } + if (innerClass == null) { return null; + } PyObject jinner = Py.java2py(innerClass); // xxx lookup(innerClass); __dict__.__setitem__(name, jinner); return jinner; Modified: trunk/jython/tests/java/org/python/tests/Visible.java =================================================================== --- trunk/jython/tests/java/org/python/tests/Visible.java 2008-10-27 21:15:22 UTC (rev 5522) +++ trunk/jython/tests/java/org/python/tests/Visible.java 2008-10-28 07:58:42 UTC (rev 5523) @@ -12,6 +12,11 @@ public static int visibleStatic = PUBLIC_STATIC_METHOD_FIELD; + public static class StaticInner { + + public static int visibleStaticField = PUBLIC_STATIC_FIELD; + } + public Visible() { this(PUBLIC_FIELD); } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <fwi...@us...> - 2008-10-27 21:15:27
|
Revision: 5522 http://jython.svn.sourceforge.net/jython/?rev=5522&view=rev Author: fwierzbicki Date: 2008-10-27 21:15:22 +0000 (Mon, 27 Oct 2008) Log Message: ----------- Another change to checking for AST as the first arg to __builtins__.compile(). Using the reasonably forward-compatible __tojava__ now instead of the more implementation dependent javaProxy field. Modified Paths: -------------- trunk/jython/src/org/python/core/__builtin__.java Modified: trunk/jython/src/org/python/core/__builtin__.java =================================================================== --- trunk/jython/src/org/python/core/__builtin__.java 2008-10-27 17:35:45 UTC (rev 5521) +++ trunk/jython/src/org/python/core/__builtin__.java 2008-10-27 21:15:22 UTC (rev 5522) @@ -303,10 +303,11 @@ * java integration changes. */ private static modType py2node(PyObject obj) { - if (obj != null && obj.javaProxy instanceof modType) { - return (modType)obj.javaProxy; + Object node = obj.__tojava__(modType.class); + if (node == Py.NoConversion) { + return null; } - return null; + return (modType)node; } } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <am...@us...> - 2008-10-27 17:35:48
|
Revision: 5521 http://jython.svn.sourceforge.net/jython/?rev=5521&view=rev Author: amak Date: 2008-10-27 17:35:45 +0000 (Mon, 27 Oct 2008) Log Message: ----------- Adding support for address manipulation functions inet_pton, inet_ntop, inet_aton and inet_ntoa. Modified Paths: -------------- trunk/jython/Lib/socket.py trunk/jython/Lib/test/test_socket.py Modified: trunk/jython/Lib/socket.py =================================================================== --- trunk/jython/Lib/socket.py 2008-10-27 17:02:39 UTC (rev 5520) +++ trunk/jython/Lib/socket.py 2008-10-27 17:35:45 UTC (rev 5521) @@ -580,6 +580,33 @@ def ntohs(x): return x def ntohl(x): return x +def inet_pton(family, ip_string): + try: + ia = java.net.InetAddress.getByName(ip_string) + bytes = [] + for byte in ia.getAddress(): + if byte < 0: + bytes.append(byte+256) + else: + bytes.append(byte) + return "".join([chr(byte) for byte in bytes]) + except java.lang.Exception, jlx: + raise _map_exception(jlx) + +def inet_ntop(family, packed_ip): + try: + jByteArray = jarray.array(packed_ip, 'b') + ia = java.net.InetAddress.getByAddress(jByteArray) + return ia.getHostAddress() + except java.lang.Exception, jlx: + raise _map_exception(jlx) + +def inet_aton(ip_string): + return inet_pton(AF_INET, ip_string) + +def inet_ntoa(packed_ip): + return inet_ntop(AF_INET, packed_ip) + class _nonblocking_api_mixin: timeout = _defaulttimeout Modified: trunk/jython/Lib/test/test_socket.py =================================================================== --- trunk/jython/Lib/test/test_socket.py 2008-10-27 17:02:39 UTC (rev 5520) +++ trunk/jython/Lib/test/test_socket.py 2008-10-27 17:35:45 UTC (rev 5521) @@ -477,8 +477,11 @@ return f = lambda a: inet_ntop(AF_INET6, a) - self.assertEquals('::', f('\x00' * 16)) - self.assertEquals('::1', f('\x00' * 15 + '\x01')) +# self.assertEquals('::', f('\x00' * 16)) +# self.assertEquals('::1', f('\x00' * 15 + '\x01')) + # java.net.InetAddress always return the full unabbreviated form + self.assertEquals('0:0:0:0:0:0:0:0', f('\x00' * 16)) + self.assertEquals('0:0:0:0:0:0:0:1', f('\x00' * 15 + '\x01')) self.assertEquals( 'aef:b01:506:1001:ffff:9997:55:170', f('\x0a\xef\x0b\x01\x05\x06\x10\x01\xff\xff\x99\x97\x00\x55\x01\x70') This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <am...@us...> - 2008-10-27 17:02:53
|
Revision: 5520 http://jython.svn.sourceforge.net/jython/?rev=5520&view=rev Author: amak Date: 2008-10-27 17:02:39 +0000 (Mon, 27 Oct 2008) Log Message: ----------- Adding support for address manipulation functions inet_pton, inet_ntop, inet_aton and inet_ntoa. Modified Paths: -------------- branches/Release_2_2maint/jython/Lib/socket.py branches/Release_2_2maint/jython/Lib/test/test_socket.py Modified: branches/Release_2_2maint/jython/Lib/socket.py =================================================================== --- branches/Release_2_2maint/jython/Lib/socket.py 2008-10-27 15:11:18 UTC (rev 5519) +++ branches/Release_2_2maint/jython/Lib/socket.py 2008-10-27 17:02:39 UTC (rev 5520) @@ -588,6 +588,33 @@ def ntohs(x): return x def ntohl(x): return x +def inet_pton(family, ip_string): + try: + ia = java.net.InetAddress.getByName(ip_string) + bytes = [] + for byte in ia.getAddress(): + if byte < 0: + bytes.append(byte+256) + else: + bytes.append(byte) + return "".join([chr(byte) for byte in bytes]) + except java.lang.Exception, jlx: + raise _map_exception(jlx) + +def inet_ntop(family, packed_ip): + try: + jByteArray = jarray.array(packed_ip, 'b') + ia = java.net.InetAddress.getByAddress(jByteArray) + return ia.getHostAddress() + except java.lang.Exception, jlx: + raise _map_exception(jlx) + +def inet_aton(ip_string): + return inet_pton(AF_INET, ip_string) + +def inet_ntoa(packed_ip): + return inet_ntop(AF_INET, packed_ip) + class _nonblocking_api_mixin: timeout = _defaulttimeout Modified: branches/Release_2_2maint/jython/Lib/test/test_socket.py =================================================================== --- branches/Release_2_2maint/jython/Lib/test/test_socket.py 2008-10-27 15:11:18 UTC (rev 5519) +++ branches/Release_2_2maint/jython/Lib/test/test_socket.py 2008-10-27 17:02:39 UTC (rev 5520) @@ -471,8 +471,11 @@ return f = lambda a: inet_ntop(AF_INET6, a) - self.assertEquals('::', f('\x00' * 16)) - self.assertEquals('::1', f('\x00' * 15 + '\x01')) +# self.assertEquals('::', f('\x00' * 16)) +# self.assertEquals('::1', f('\x00' * 15 + '\x01')) + # java.net.InetAddress always return the full unabbreviated form + self.assertEquals('0:0:0:0:0:0:0:0', f('\x00' * 16)) + self.assertEquals('0:0:0:0:0:0:0:1', f('\x00' * 15 + '\x01')) self.assertEquals( 'aef:b01:506:1001:ffff:9997:55:170', f('\x0a\xef\x0b\x01\x05\x06\x10\x01\xff\xff\x99\x97\x00\x55\x01\x70') This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <fwi...@us...> - 2008-10-27 15:11:31
|
Revision: 5519 http://jython.svn.sourceforge.net/jython/?rev=5519&view=rev Author: fwierzbicki Date: 2008-10-27 15:11:18 +0000 (Mon, 27 Oct 2008) Log Message: ----------- Test for fixes in r5517 and r5518. Added Paths: ----------- trunk/jython/Lib/test/test_ast_jy.py Added: trunk/jython/Lib/test/test_ast_jy.py =================================================================== --- trunk/jython/Lib/test/test_ast_jy.py (rev 0) +++ trunk/jython/Lib/test/test_ast_jy.py 2008-10-27 15:11:18 UTC (rev 5519) @@ -0,0 +1,21 @@ +"""Extra unittests for ast in Jython. Look to integrate into CPython in the +future""" + +import unittest +from test import test_support +from ast import PyCF_ONLY_AST + +class TestCompile(unittest.TestCase): + + def test_compile_ast(self): + node = compile("1/2", '<unknown>', 'exec', PyCF_ONLY_AST) + compile(node, "<string>", 'exec') + +#============================================================================== + +def test_main(verbose=None): + test_classes = [TestCompile] + test_support.run_unittest(*test_classes) + +if __name__ == "__main__": + test_main(verbose=True) This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <fwi...@us...> - 2008-10-27 14:54:43
|
Revision: 5518 http://jython.svn.sourceforge.net/jython/?rev=5518&view=rev Author: fwierzbicki Date: 2008-10-27 14:54:38 +0000 (Mon, 27 Oct 2008) Log Message: ----------- Simplifying the fix for http://bugs.jython.org/issue1158 based on the java integration changes in r5516. Mainly, javaProxy now lives directly in PyObject, so there is no need to check for a PyInstance first. Modified Paths: -------------- trunk/jython/src/org/python/core/__builtin__.java Modified: trunk/jython/src/org/python/core/__builtin__.java =================================================================== --- trunk/jython/src/org/python/core/__builtin__.java 2008-10-27 13:19:32 UTC (rev 5517) +++ trunk/jython/src/org/python/core/__builtin__.java 2008-10-27 14:54:38 UTC (rev 5518) @@ -296,15 +296,15 @@ } /** - * @returns modType if obj is a wrapper around an AST modType + * @returns modType if obj is a wrapper around an AST modType else returns + * null * - * XXX: Reaches deep into implementation details -- needs to be reviewed if - * PyInstance is significantly changed. + * XXX: Reaches into implementation details -- needs to be reviewed if our + * java integration changes. */ private static modType py2node(PyObject obj) { - if (obj != null && obj instanceof PyInstance && ((PyInstance)obj).javaProxy - instanceof modType) { - return (modType)((PyInstance)obj).javaProxy; + if (obj != null && obj.javaProxy instanceof modType) { + return (modType)obj.javaProxy; } return null; } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <fwi...@us...> - 2008-10-27 13:19:34
|
Revision: 5517 http://jython.svn.sourceforge.net/jython/?rev=5517&view=rev Author: fwierzbicki Date: 2008-10-27 13:19:32 +0000 (Mon, 27 Oct 2008) Log Message: ----------- Fix for bug http://bugs.jython.org/issue1158, where the __builtin__ compile function does not recognize when it is passed an AST as the first argument. Modified Paths: -------------- trunk/jython/src/org/python/core/__builtin__.java Modified: trunk/jython/src/org/python/core/__builtin__.java =================================================================== --- trunk/jython/src/org/python/core/__builtin__.java 2008-10-27 03:09:47 UTC (rev 5516) +++ trunk/jython/src/org/python/core/__builtin__.java 2008-10-27 13:19:32 UTC (rev 5517) @@ -274,7 +274,10 @@ if (args.length > 4) { dont_inherit = Py.py2boolean(args[4]); } - + modType ast = py2node(args[0]); + if (ast != null) { + return __builtin__.compile(ast, args[1].toString(), args[2].toString(), flags, dont_inherit); + } if (args[0] instanceof PyUnicode) { flags += PyTableCode.PyCF_SOURCE_IS_UTF8; } @@ -291,6 +294,21 @@ public PyObject getModule() { return module; } + + /** + * @returns modType if obj is a wrapper around an AST modType + * + * XXX: Reaches deep into implementation details -- needs to be reviewed if + * PyInstance is significantly changed. + */ + private static modType py2node(PyObject obj) { + if (obj != null && obj instanceof PyInstance && ((PyInstance)obj).javaProxy + instanceof modType) { + return (modType)((PyInstance)obj).javaProxy; + } + return null; + } + } /** This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <cg...@us...> - 2008-10-27 03:09:58
|
Revision: 5516 http://jython.svn.sourceforge.net/jython/?rev=5516&view=rev Author: cgroves Date: 2008-10-27 03:09:47 +0000 (Mon, 27 Oct 2008) Log Message: ----------- Make non-PyObject subclasses wrapped in PyJavaType instantiable Modified Paths: -------------- trunk/jython/src/org/python/core/PyInstance.java trunk/jython/src/org/python/core/PyJavaClass.java trunk/jython/src/org/python/core/PyJavaInstance.java trunk/jython/src/org/python/core/PyJavaType.java trunk/jython/src/org/python/core/PyObject.java trunk/jython/src/org/python/core/PyReflectedConstructor.java trunk/jython/src/org/python/core/PyType.java Modified: trunk/jython/src/org/python/core/PyInstance.java =================================================================== --- trunk/jython/src/org/python/core/PyInstance.java 2008-10-27 03:08:48 UTC (rev 5515) +++ trunk/jython/src/org/python/core/PyInstance.java 2008-10-27 03:09:47 UTC (rev 5516) @@ -18,9 +18,6 @@ return instclass; } - //This field is only used by Python subclasses of Java classes - Object javaProxy; - /** The namespace of this instance. Contains all instance attributes. **/ Modified: trunk/jython/src/org/python/core/PyJavaClass.java =================================================================== --- trunk/jython/src/org/python/core/PyJavaClass.java 2008-10-27 03:08:48 UTC (rev 5515) +++ trunk/jython/src/org/python/core/PyJavaClass.java 2008-10-27 03:09:47 UTC (rev 5516) @@ -740,16 +740,6 @@ public PyObject __call__(PyObject[] args, String[] keywords) { if (!constructorsInitialized) initConstructors(); - // xxx instantiation of PyObject subclass, still needed? - if (PyObject.class.isAssignableFrom(proxyClass)) { - if (Modifier.isAbstract(proxyClass.getModifiers())) { - throw Py.TypeError("can't instantiate abstract class (" + fullName() + ")"); - } - if (__init__ == null) { - throw Py.TypeError("no public constructors for " + fullName()); - } - return __init__.make(args, keywords); - } PyInstance inst = new PyJavaInstance(this); inst.__init__(args, keywords); return inst; Modified: trunk/jython/src/org/python/core/PyJavaInstance.java =================================================================== --- trunk/jython/src/org/python/core/PyJavaInstance.java 2008-10-27 03:08:48 UTC (rev 5515) +++ trunk/jython/src/org/python/core/PyJavaInstance.java 2008-10-27 03:09:47 UTC (rev 5516) @@ -66,8 +66,7 @@ PyReflectedConstructor init = ((PyJavaClass)instclass).__init__; if (init == null) { - throw Py.TypeError("no public constructors for "+ - instclass.__name__); + throw Py.TypeError("no public constructors for " + instclass.__name__); } init.__call__(this, args, keywords); } Modified: trunk/jython/src/org/python/core/PyJavaType.java =================================================================== --- trunk/jython/src/org/python/core/PyJavaType.java 2008-10-27 03:08:48 UTC (rev 5515) +++ trunk/jython/src/org/python/core/PyJavaType.java 2008-10-27 03:09:47 UTC (rev 5516) @@ -19,13 +19,15 @@ } @Override - protected void fillDict(Class<?> base) { + protected void fillDict() { dict = new PyStringMap(); Map<String, Object> propnames = new HashMap<String, Object>(); + Class<?> base = underlying_class.getSuperclass(); Method[] methods = underlying_class.getMethods(); for (Method meth : methods) { Class<?> declaring = meth.getDeclaringClass(); - if (declaring != base && base.isAssignableFrom(declaring) && !ignore(meth)) { + if (base == null || + (declaring != base && base.isAssignableFrom(declaring) && !ignore(meth))) { String methname = meth.getName(); String nmethname = normalize_name(methname); PyReflectedFunction reflfunc = (PyReflectedFunction)dict.__finditem__(nmethname); @@ -118,16 +120,20 @@ for (Constructor<?> ctr : ctrs) { reflctr.addConstructor(ctr); } - PyObject new_ = new PyNewWrapper(underlying_class, "__new__", -1, -1) { + if (PyObject.class.isAssignableFrom(underlying_class)) { + PyObject new_ = new PyNewWrapper(underlying_class, "__new__", -1, -1) { - public PyObject new_impl(boolean init, - PyType subtype, - PyObject[] args, - String[] keywords) { - return reflctr.make(args, keywords); - } - }; - dict.__setitem__("__new__", new_); + public PyObject new_impl(boolean init, + PyType subtype, + PyObject[] args, + String[] keywords) { + return reflctr.make(args, keywords); + } + }; + dict.__setitem__("__new__", new_); + } else { + dict.__setitem__("__init__", reflctr); + } } if (ClassDictInit.class.isAssignableFrom(underlying_class) && underlying_class != ClassDictInit.class) { Modified: trunk/jython/src/org/python/core/PyObject.java =================================================================== --- trunk/jython/src/org/python/core/PyObject.java 2008-10-27 03:08:48 UTC (rev 5515) +++ trunk/jython/src/org/python/core/PyObject.java 2008-10-27 03:09:47 UTC (rev 5516) @@ -35,6 +35,10 @@ } + // This field is only filled on Python wrappers for Java objects and for Python subclasses of + // Java classes. + Object javaProxy; + private PyType objtype; @ExposedGet(name = "__class__") Modified: trunk/jython/src/org/python/core/PyReflectedConstructor.java =================================================================== --- trunk/jython/src/org/python/core/PyReflectedConstructor.java 2008-10-27 03:08:48 UTC (rev 5515) +++ trunk/jython/src/org/python/core/PyReflectedConstructor.java 2008-10-27 03:09:47 UTC (rev 5516) @@ -6,10 +6,8 @@ import java.lang.reflect.InvocationTargetException; import java.lang.InstantiationException; +public class PyReflectedConstructor extends PyReflectedFunction { -public class PyReflectedConstructor extends PyReflectedFunction -{ - public PyReflectedConstructor(String name) { super(name); __name__ = name; @@ -23,8 +21,7 @@ } private ReflectedArgs makeArgs(Constructor m) { - return new ReflectedArgs(m, m.getParameterTypes(), - m.getDeclaringClass(), true); + return new ReflectedArgs(m, m.getParameterTypes(), m.getDeclaringClass(), true); } public void addConstructor(Constructor m) { @@ -36,15 +33,13 @@ } // xxx temporary solution, type ctr will go through __new__ ... - PyObject make(PyObject[] args,String[] keywords) { + PyObject make(PyObject[] args, String[] keywords) { ReflectedArgs[] argsl = argslist; - ReflectedCallData callData = new ReflectedCallData(); - Object method=null; + Object method = null; boolean consumes_keywords = false; int nkeywords = keywords.length; PyObject[] allArgs = null; - // Check for a matching constructor to call if (nargs > 0) { // PyArgsKeywordsCall signature, if present, is the first if (argsl[0].matches(null, args, keywords, callData)) { @@ -67,140 +62,84 @@ } } } - // Throw an error if no valid set of arguments if (method == null) { - throwError(callData.errArg, args.length, true /*xxx?*/,false); + throwError(callData.errArg, args.length, true /* xxx? */, false); } - // Do the actual constructor call PyObject obj = null; - Constructor ctor = (Constructor)method; try { - obj = (PyObject)ctor.newInstance(callData.getArgsArray()); - } - catch (Throwable t) { + obj = (PyObject)((Constructor<?>)method).newInstance(callData.getArgsArray()); + } catch (Throwable t) { throw Py.JavaError(t); } - if (!consumes_keywords) { int offset = args.length; for (int i = 0; i < nkeywords; i++) { obj.__setattr__(keywords[i], allArgs[i + offset]); } } - return obj; } - public PyObject __call__(PyObject self, PyObject[] args, - String[] keywords) - { - ReflectedArgs[] argsl = argslist; - - if (self == null || !(self instanceof PyInstance)) { + public PyObject __call__(PyObject self, PyObject[] args, String[] keywords) { + if (self == null) { throw Py.TypeError("invalid self argument to constructor"); } - - PyInstance iself = (PyInstance)self; - Class javaClass = iself.instclass.proxyClass; - Class declaringClass = argsl[0].declaringClass; - - // If this is the constructor for a proxy class or not... - if (PyProxy.class.isAssignableFrom(declaringClass)) { -// if (self instanceof PyJavaInstance) { -// throw Py.TypeError( -// "invalid self argument to proxy constructor"); -// } + Class<?> javaClass; + if (self instanceof PyInstance) { + javaClass = ((PyInstance)self).instclass.proxyClass; + } else { + javaClass = self.getType().underlying_class; } - else { - if (!(iself instanceof PyJavaInstance)) { - // Get proxy constructor and call it - if (declaringClass.isAssignableFrom(javaClass)) { - } else { - throw Py.TypeError("invalid self argument"); - } - PyJavaClass jc = PyJavaClass.lookup(javaClass); // xxx - jc.initConstructors(); - return jc.__init__.__call__(iself, args, keywords); - } + Class<?> declaringClass = argslist[0].declaringClass; + if (!declaringClass.isAssignableFrom(javaClass)) { + throw Py.TypeError("self invalid - must implement: " + declaringClass.getName()); } - - if (declaringClass.isAssignableFrom(javaClass)) { - } else { - throw Py.TypeError("self invalid - must implement: "+ - declaringClass.getName()); + if (!PyProxy.class.isAssignableFrom(declaringClass) && !(self instanceof PyJavaInstance)) { + PyJavaClass jc = PyJavaClass.lookup(javaClass); + jc.initConstructors(); + return jc.__init__.__call__(self, args, keywords); } - if (iself.javaProxy != null) { - Class sup = iself.instclass.proxyClass; - if (PyProxy.class.isAssignableFrom(sup)) + if (self.javaProxy != null) { + Class<?> sup = javaClass; + if (PyProxy.class.isAssignableFrom(sup)) { sup = sup.getSuperclass(); - throw Py.TypeError("instance already instantiated for "+ - sup.getName()); + } + throw Py.TypeError("instance already instantiated for " + sup.getName()); } - ReflectedCallData callData = new ReflectedCallData(); - Object method=null; - + Object method = null; // Remove keyword args int nkeywords = keywords.length; PyObject[] allArgs = args; if (nkeywords > 0) { - args = new PyObject[allArgs.length-nkeywords]; + args = new PyObject[allArgs.length - nkeywords]; System.arraycopy(allArgs, 0, args, 0, args.length); } - // Check for a matching constructor to call int n = nargs; - for (int i=0; i<n; i++) { - ReflectedArgs rargs = argsl[i]; + for (int i = 0; i < n; i++) { + ReflectedArgs rargs = argslist[i]; if (rargs.matches(null, args, Py.NoKeywords, callData)) { method = rargs.data; break; } } - // Throw an error if no valid set of arguments if (method == null) { throwError(callData.errArg, args.length, false, false); } - // Do the actual constructor call - Object jself = null; - ThreadState ts = Py.getThreadState(); - try { - ts.pushInitializingProxy(iself); - Constructor ctor = (Constructor)method; - try { - jself = ctor.newInstance(callData.getArgsArray()); - } - catch (InvocationTargetException e) { - if (e.getTargetException() instanceof InstantiationException){ - Class sup = iself.instclass.proxyClass.getSuperclass(); - String msg = "Constructor failed for Java superclass"; - if (sup != null) - msg += " " + sup.getName(); - throw Py.TypeError(msg); - } - else throw Py.JavaError(e); - } - catch (Throwable t) { - throw Py.JavaError(t); - } - } - finally { - ts.popInitializingProxy(); - } + constructProxy(self, (Constructor<?>)method, callData.getArgsArray(), javaClass); - iself.javaProxy = jself; - // Do setattr's for keyword args int offset = args.length; - for (int i=0; i<nkeywords; i++) { - iself.__setattr__(keywords[i], allArgs[i+offset]); + for (int i = 0; i < nkeywords; i++) { + self.__setattr__(keywords[i], allArgs[i + offset]); } return Py.None; } @@ -209,14 +148,44 @@ if (args.length < 1) { throw Py.TypeError("constructor requires self argument"); } - PyObject[] newArgs = new PyObject[args.length-1]; + PyObject[] newArgs = new PyObject[args.length - 1]; System.arraycopy(args, 1, newArgs, 0, newArgs.length); - return __call__(args[0], newArgs, keywords); } + protected void constructProxy(PyObject obj, Constructor<?> ctor, Object[] args, Class<?> proxy) { + // Do the actual constructor call + Object jself = null; + ThreadState ts = Py.getThreadState(); + try { + if (obj instanceof PyInstance) { + ts.pushInitializingProxy((PyInstance)obj); + } + try { + jself = ctor.newInstance(args); + } catch (InvocationTargetException e) { + if (e.getTargetException() instanceof InstantiationException) { + Class<?> sup = proxy.getSuperclass(); + String msg = "Constructor failed for Java superclass"; + if (sup != null) { + msg += " " + sup.getName(); + } + throw Py.TypeError(msg); + } else + throw Py.JavaError(e); + } catch (Throwable t) { + throw Py.JavaError(t); + } + } finally { + if (obj instanceof PyInstance) { + ts.popInitializingProxy(); + } + } + obj.javaProxy = jself; + } + public String toString() { - //printArgs(); - return "<java constructor "+__name__+" "+Py.idstr(this)+">"; + // printArgs(); + return "<java constructor " + __name__ + " " + Py.idstr(this) + ">"; } } Modified: trunk/jython/src/org/python/core/PyType.java =================================================================== --- trunk/jython/src/org/python/core/PyType.java 2008-10-27 03:08:48 UTC (rev 5515) +++ trunk/jython/src/org/python/core/PyType.java 2008-10-27 03:09:47 UTC (rev 5516) @@ -279,7 +279,7 @@ return newobj; } - protected void fillDict(Class<?> base) { + protected void fillDict() { if (Py.BOOTSTRAP_TYPES.contains(underlying_class)) { return; } @@ -295,8 +295,13 @@ private static void fillInMRO(PyType type, Class<?> base) { PyType[] mro; - if (base == Object.class) { - mro = new PyType[] {type}; + + if (base == Object.class || base == null) { + if (type.underlying_class == Object.class) { + mro = new PyType[] {type, PyObject.TYPE}; + } else { + mro = new PyType[] {type}; + } } else { PyType baseType = fromClass(base); mro = new PyType[baseType.mro.length + 1]; @@ -923,7 +928,7 @@ newtype.underlying_class = c; newtype.builtin = true; fillInMRO(newtype, base); // basic mro, base, bases - newtype.fillDict(base); + newtype.fillDict(); return newtype; } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <cg...@us...> - 2008-10-27 03:08:53
|
Revision: 5515 http://jython.svn.sourceforge.net/jython/?rev=5515&view=rev Author: cgroves Date: 2008-10-27 03:08:48 +0000 (Mon, 27 Oct 2008) Log Message: ----------- Missed this when adding type information to Py.tojava Modified Paths: -------------- trunk/jython/src/org/python/util/PythonInterpreter.java Modified: trunk/jython/src/org/python/util/PythonInterpreter.java =================================================================== --- trunk/jython/src/org/python/util/PythonInterpreter.java 2008-10-26 22:13:05 UTC (rev 5514) +++ trunk/jython/src/org/python/util/PythonInterpreter.java 2008-10-27 03:08:48 UTC (rev 5515) @@ -22,7 +22,7 @@ * Initializes the jython runtime. This should only be called once, and * should be called before any other python objects are created (including a * PythonInterpreter). - * + * * @param preProperties * A set of properties. Typically System.getProperties() is used. * @param postProperties @@ -188,7 +188,7 @@ /** * Get the value of a variable in the local namespace - * + * * @param name * the name of the variable * @return the value of the variable, or null if that name isn't assigned @@ -202,7 +202,7 @@ * as an instance of the given Java class. * <code>interp.get("foo", Object.class)</code> will return the most * appropriate generic Java object. - * + * * @param name * the name of the variable * @param javaclass @@ -210,7 +210,7 @@ * @return the value of the variable as the given class, or null if that * name isn't assigned */ - public Object get(String name, Class javaclass) { + public <T> T get(String name, Class<T> javaclass) { PyObject val = locals.__finditem__(name.intern()); if(val == null) { return null; This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <cg...@us...> - 2008-10-26 22:13:10
|
Revision: 5514 http://jython.svn.sourceforge.net/jython/?rev=5514&view=rev Author: cgroves Date: 2008-10-26 22:13:05 +0000 (Sun, 26 Oct 2008) Log Message: ----------- Move Java Stream wrapping off into FileUtil so PyFile doesn't have to be exposed as the type file and as the PyJavaClass PyFile Modified Paths: -------------- trunk/jython/Lib/os.py trunk/jython/Lib/popen2.py trunk/jython/Lib/test/test_java_integration.py trunk/jython/Lib/test/test_javashell.py trunk/jython/src/org/python/core/Options.java trunk/jython/src/org/python/core/Py.java trunk/jython/src/org/python/core/PyFile.java trunk/jython/src/org/python/core/StdoutWrapper.java trunk/jython/src/org/python/core/io/FileDescriptors.java trunk/jython/src/org/python/core/util/FileUtil.java Modified: trunk/jython/Lib/os.py =================================================================== --- trunk/jython/Lib/os.py 2008-10-26 21:13:51 UTC (rev 5513) +++ trunk/jython/Lib/os.py 2008-10-26 22:13:05 UTC (rev 5514) @@ -46,7 +46,6 @@ import stat as _stat import sys from java.io import File -from org.python.core import PyFile from org.python.core.io import FileDescriptors, FileIO, IOBase from org.python.core.Py import newString as asPyString @@ -554,7 +553,7 @@ raise OSError(errno.EBADF, errno.strerror(errno.EBADF)) try: - fp = PyFile(rawio, '<fdopen>', mode, bufsize) + fp = FileDescriptors.wrap(rawio, mode, bufsize) except IOError: raise OSError(errno.EINVAL, errno.strerror(errno.EINVAL)) return fp Modified: trunk/jython/Lib/popen2.py =================================================================== --- trunk/jython/Lib/popen2.py 2008-10-26 21:13:51 UTC (rev 5513) +++ trunk/jython/Lib/popen2.py 2008-10-26 22:13:05 UTC (rev 5514) @@ -27,9 +27,10 @@ from java.io import BufferedInputStream from java.io import PipedOutputStream from java.io import PipedInputStream -from org.python.core import PyFile from javashell import shellexecute +from org.python.core.util import FileUtil + __all__ = ["popen", "popen2", "popen3", "popen4", "Popen3", "Popen4"] _active = [] @@ -43,7 +44,7 @@ the close method. """ def __init__(self, stream, process, name): - self._file = PyFile(stream, "'%s'" % name) + self._file = FileUtil.wrap(stream) self._process = process def __getattr__(self, name): @@ -92,10 +93,10 @@ bufsize ) - self.tochild = PyFile( self._tochild ) - self.fromchild = PyFile( self._fromchild ) + self.tochild = FileUtil.wrap(self._tochild) + self.fromchild = FileUtil.wrap(self._fromchild) if self._childerr: - self.childerr = PyFile( self._childerr ) + self.childerr = FileUtil.wrap(self._childerr) def _startChildWaiter(self): """Start a subthread that waits for the child process to exit.""" @@ -197,7 +198,7 @@ "%s-stderr" % self.process, self._close ) - return PyFile( joinedStream ) + return FileUtil.wrap(joinedStream) def _close( self ): """Must be closed twice (once for each of the two joined pipes)""" Modified: trunk/jython/Lib/test/test_java_integration.py =================================================================== --- trunk/jython/Lib/test/test_java_integration.py 2008-10-26 21:13:51 UTC (rev 5513) +++ trunk/jython/Lib/test/test_java_integration.py 2008-10-26 22:13:05 UTC (rev 5514) @@ -155,7 +155,8 @@ self.assertRaises(FileNotFoundException, FileInputStream, "garbage") def test_unsupported(self): - fp = open(System.out) + from org.python.core.util import FileUtil + fp = FileUtil.wrap(System.out) self.assertRaises(IOError, fp.tell) class VectorTest(unittest.TestCase): Modified: trunk/jython/Lib/test/test_javashell.py =================================================================== --- trunk/jython/Lib/test/test_javashell.py 2008-10-26 21:13:51 UTC (rev 5513) +++ trunk/jython/Lib/test/test_javashell.py 2008-10-26 22:13:05 UTC (rev 5514) @@ -1,11 +1,11 @@ import unittest from test import test_support -from org.python.core import PyFile import re import os import javashell +from org.python.core.util import FileUtil # testCmds is a list of (command, expectedOutput) # each command is executed twice, once in unitialized environment and @@ -73,7 +73,7 @@ for cmd, pattern in testCmds: dprint( "\nExecuting '%s' with %s environment" % (cmd, whichEnv)) p = javashell.shellexecute(cmd) - line = PyFile( p.getInputStream() ).readlines()[0] + line = FileUtil.wrap(p.getInputStream()).readlines()[0] assert re.match( pattern, line ), \ "expected match for %s, got %s" % ( pattern, line ) dprint( "waiting for", cmd, "to complete") Modified: trunk/jython/src/org/python/core/Options.java =================================================================== --- trunk/jython/src/org/python/core/Options.java 2008-10-26 21:13:51 UTC (rev 5513) +++ trunk/jython/src/org/python/core/Options.java 2008-10-26 22:13:05 UTC (rev 5514) @@ -22,7 +22,7 @@ * considerably. */ public static boolean includeJavaStackInExceptions = false; - + /** * When true, python exception raised in overriden methods will be shown on * stderr. This option is remarkably useful when python is used for @@ -123,7 +123,7 @@ // Set the more unusual options Options.showJavaExceptions = getBooleanOption( "options.showJavaExceptions", Options.showJavaExceptions); - + Options.includeJavaStackInExceptions = getBooleanOption( "options.includeJavaStackInExceptions", Options.includeJavaStackInExceptions); Modified: trunk/jython/src/org/python/core/Py.java =================================================================== --- trunk/jython/src/org/python/core/Py.java 2008-10-26 21:13:51 UTC (rev 5513) +++ trunk/jython/src/org/python/core/Py.java 2008-10-26 22:13:05 UTC (rev 5514) @@ -455,13 +455,13 @@ @param o the <code>PyObject</code> to convert. @param c the class to convert it to. **/ - public static Object tojava(PyObject o, Class c) { + public static <T> T tojava(PyObject o, Class<T> c) { Object obj = o.__tojava__(c); if (obj == Py.NoConversion) { throw Py.TypeError("can't convert " + o.__repr__() + " to " + c.getName()); } - return obj; + return (T)obj; } // ??pending: was @deprecated but is actually used by proxie code. @@ -1963,7 +1963,7 @@ if (file instanceof PyJavaInstance) { Object tojava = file.__tojava__(OutputStream.class); if (tojava != null && tojava != Py.NoConversion) { - this.file = new PyFile((OutputStream) tojava, "<java OutputStream>"); + this.file = new PyFile((OutputStream) tojava); } } } Modified: trunk/jython/src/org/python/core/PyFile.java =================================================================== --- trunk/jython/src/org/python/core/PyFile.java 2008-10-26 21:13:51 UTC (rev 5513) +++ trunk/jython/src/org/python/core/PyFile.java 2008-10-26 22:13:05 UTC (rev 5514) @@ -3,7 +3,6 @@ import java.io.InputStream; import java.io.OutputStream; -import java.io.RandomAccessFile; import java.util.LinkedList; import org.python.core.io.BinaryIOWrapper; @@ -20,13 +19,13 @@ import org.python.core.io.TextIOBase; import org.python.core.io.TextIOWrapper; import org.python.core.io.UniversalIOWrapper; +import org.python.core.util.FileUtil; import org.python.expose.ExposedDelete; import org.python.expose.ExposedGet; import org.python.expose.ExposedMethod; import org.python.expose.ExposedNew; import org.python.expose.ExposedSet; import org.python.expose.ExposedType; -import org.python.expose.MethodType; /** * A python file wrapper around a java stream, reader/writer or file. @@ -35,7 +34,7 @@ public class PyFile extends PyObject { public static final PyType TYPE = PyType.fromClass(PyFile.class); - + /** The filename */ @ExposedGet public PyObject name; @@ -75,14 +74,13 @@ private Closer closer; /** All PyFiles' closers */ - private static LinkedList closers = new LinkedList(); + private static LinkedList<Closer> closers = new LinkedList<Closer>(); static { initCloser(); } - public PyFile() { - } + public PyFile() {} public PyFile(PyType subType) { super(subType); @@ -93,100 +91,41 @@ file___init__(raw, name, mode, bufsize); } - public PyFile(InputStream istream, String name, String mode, int bufsize, - boolean closefd) { + PyFile(InputStream istream, String name, String mode, int bufsize, boolean closefd) { parseMode(mode); file___init__(new StreamIO(istream, closefd), name, mode, bufsize); } - public PyFile(InputStream istream, String name, String mode, int bufsize) { - this(istream, name, mode, -1, true); - } - - public PyFile(InputStream istream, String name, String mode) { - this(istream, name, mode, -1); - } - - public PyFile(InputStream istream, String name) { - this(istream, name, "r"); - } - + /** + * Creates a file object wrapping the given <code>InputStream</code>. The builtin methods + * <code>file</code> and <code>open</code> don't expose this functionality as it isn't available + * to regular Python code. To wrap an InputStream in a file from Python, use + * {@link FileUtil#wrap(InputStream)} + */ public PyFile(InputStream istream) { - this(istream, "<???>", "r"); + this(istream, "<Java InputStream '" + istream + "' as file>", "r", -1, true); } - public PyFile(OutputStream ostream, String name, String mode, int bufsize, boolean closefd) { + PyFile(OutputStream ostream, String name, String mode, int bufsize, boolean closefd) { parseMode(mode); file___init__(new StreamIO(ostream, closefd), name, mode, bufsize); } - public PyFile(OutputStream ostream, String name, String mode, int bufsize) { - this(ostream, name, mode, -1, true); - } - - public PyFile(OutputStream ostream, String name, String mode) { - this(ostream, name, mode, -1); - } - - public PyFile(OutputStream ostream, String name) { - this(ostream, name, "w"); - } - + /** + * Creates a file object wrapping the given <code>OutputStream</code>. The builtin methods + * <code>file</code> and <code>open</code> don't expose this functionality as it isn't available + * to regular Python code. To wrap an OutputStream in a file from Python, use + * {@link FileUtil#wrap(OutputStream)} + */ public PyFile(OutputStream ostream) { - this(ostream, "<???>", "w"); + this(ostream, "<Java OutputStream '" + ostream + "' as file>", "w", -1, true); } - public PyFile(RandomAccessFile file, String name, String mode, int bufsize) { - file___init__(new FileIO(file.getChannel(), parseMode(mode)), name, mode, bufsize); - } - - public PyFile(RandomAccessFile file, String name, String mode) { - this(file, name, mode, -1); - } - - public PyFile(RandomAccessFile file, String name) { - this(file, name, "r+"); - } - - public PyFile(RandomAccessFile file) { - this(file, "<???>", "r+"); - } - public PyFile(String name, String mode, int bufsize) { file___init__(new FileIO(name, parseMode(mode)), name, mode, bufsize); } @ExposedNew - static final PyObject file_new(PyNewWrapper new_, boolean init, PyType subtype, - PyObject[] args, String[] keywords) { - PyFile newFile; - if (new_.for_type == subtype) { - if (init) { - if (args.length - keywords.length == 0) { - newFile = new PyFile(); - newFile.file___init__(args, keywords); - } else if (args[0] instanceof PyString || - (args[0] instanceof PyJavaInstance && - ((PyJavaInstance)args[0]).javaProxy == String.class)) { - // If first arg is a PyString or String, assume - // its being called as a builtin. - newFile = new PyFile(); - newFile.file___init__(args, keywords); - newFile.closer = new Closer(newFile.file); - } else { - // assume it's being called as a java class - PyJavaClass pjc = new PyJavaClass(PyFile.class); - newFile = (PyFile)pjc.__call__(args, keywords); - } - } else { - newFile = new PyFile(); - } - } else { - newFile = new PyFileDerived(subtype); - } - return newFile; - } - @ExposedMethod final void file___init__(PyObject[] args, String[] kwds) { ArgParser ap = new ArgParser("file", args, kwds, new String[] {"name", "mode", "bufsize"}, @@ -199,6 +138,7 @@ String mode = ap.getString(1, "r"); int bufsize = ap.getInt(2, -1); file___init__(new FileIO(name.toString(), parseMode(mode)), name, mode, bufsize); + closer = new Closer(file); } private void file___init__(RawIOBase raw, String name, String mode, int bufsize) { @@ -613,18 +553,15 @@ } /** - * A mechanism to make sure PyFiles are closed on exit. On - * creation Closer adds itself to a list of Closers that will be - * run by PyFileCloser on JVM shutdown. When a PyFile's close or - * finalize methods are called, PyFile calls its Closer.close - * which clears Closer out of the shutdown queue. + * A mechanism to make sure PyFiles are closed on exit. On creation Closer adds itself to a list + * of Closers that will be run by PyFileCloser on JVM shutdown. When a PyFile's close or + * finalize methods are called, PyFile calls its Closer.close which clears Closer out of the + * shutdown queue. * - * We use a regular object here rather than WeakReferences and - * their ilk as they may be collected before the shutdown hook - * runs. There's no guarantee that finalize will be called during - * shutdown, so we can't use it. It's vital that this Closer has - * no reference to the PyFile it's closing so the PyFile remains - * garbage collectable. + * We use a regular object here rather than WeakReferences and their ilk as they may be + * collected before the shutdown hook runs. There's no guarantee that finalize will be called + * during shutdown, so we can't use it. It's vital that this Closer has no reference to the + * PyFile it's closing so the PyFile remains garbage collectable. */ private static class Closer { @@ -667,7 +604,7 @@ synchronized (closers) { while (closers.size() > 0) { try { - ((Closer)closers.removeFirst()).doClose(); + closers.removeFirst().doClose(); } catch (PyException e) { // continue } Modified: trunk/jython/src/org/python/core/StdoutWrapper.java =================================================================== --- trunk/jython/src/org/python/core/StdoutWrapper.java 2008-10-26 21:13:51 UTC (rev 5513) +++ trunk/jython/src/org/python/core/StdoutWrapper.java 2008-10-26 22:13:05 UTC (rev 5514) @@ -31,7 +31,7 @@ Object tojava = obj.__tojava__(OutputStream.class); if (tojava != null && tojava != Py.NoConversion) { - f = new PyFile((OutputStream)tojava, "<java OutputStream>"); + f = new PyFile((OutputStream)tojava); } if (f != null) { setObject(ss, f); Modified: trunk/jython/src/org/python/core/io/FileDescriptors.java =================================================================== --- trunk/jython/src/org/python/core/io/FileDescriptors.java 2008-10-26 21:13:51 UTC (rev 5513) +++ trunk/jython/src/org/python/core/io/FileDescriptors.java 2008-10-26 22:13:05 UTC (rev 5514) @@ -2,7 +2,7 @@ package org.python.core.io; import org.python.core.Py; -import org.python.core.PyJavaInstance; +import org.python.core.PyFile; import org.python.core.PyObject; /** @@ -14,22 +14,20 @@ */ public class FileDescriptors { + public static PyFile wrap(RawIOBase raw, String mode, int bufsize) { + return new PyFile(raw, "<fdopen>", mode, bufsize); + } + /** - * Return the RawIOBase associated with the specified file - * descriptor. + * Return the RawIOBase associated with the specified file descriptor. * * Raises a Python exception is the file descriptor is invalid * - * @param fd a Jython file descriptor object + * @param fd + * a Jython file descriptor object * @return the RawIOBase associated with the file descriptor */ public static RawIOBase get(PyObject fd) { - if (fd instanceof PyJavaInstance) { - Object tojava = ((PyJavaInstance)fd).__tojava__(RawIOBase.class); - if (tojava instanceof RawIOBase) { - return (RawIOBase)tojava; - } - } - throw Py.TypeError("a fileno is required"); + return Py.tojava(fd, RawIOBase.class); } } Modified: trunk/jython/src/org/python/core/util/FileUtil.java =================================================================== --- trunk/jython/src/org/python/core/util/FileUtil.java 2008-10-26 21:13:51 UTC (rev 5513) +++ trunk/jython/src/org/python/core/util/FileUtil.java 2008-10-26 22:13:05 UTC (rev 5514) @@ -2,14 +2,32 @@ package org.python.core.util; import java.io.ByteArrayOutputStream; +import java.io.IOException; import java.io.InputStream; -import java.io.IOException; +import java.io.OutputStream; +import org.python.core.PyFile; + /** * Utility methods for Java file handling. */ public class FileUtil { + /** + * Creates a PyFile that reads from the given <code>InputStream</code>. + */ + public static PyFile wrap(InputStream is) { + return new PyFile(is); + } + + /** + * Creates a PyFile that writes to the given <code>OutputStream</code>. + */ + public static PyFile wrap(OutputStream os) { + return new PyFile(os); + } + + /** * Read all bytes from the input stream. <p/> Note that using this method to * read very large streams could cause out-of-memory exceptions and/or block * for large periods of time. This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <pj...@us...> - 2008-10-26 21:13:54
|
Revision: 5513 http://jython.svn.sourceforge.net/jython/?rev=5513&view=rev Author: pjenvey Date: 2008-10-26 21:13:51 +0000 (Sun, 26 Oct 2008) Log Message: ----------- workaround Jython ASTisms Modified Paths: -------------- trunk/jython/Lib/ast.py trunk/jython/Lib/test/test_ast.py Modified: trunk/jython/Lib/ast.py =================================================================== --- trunk/jython/Lib/ast.py 2008-10-26 19:55:08 UTC (rev 5512) +++ trunk/jython/Lib/ast.py 2008-10-26 21:13:51 UTC (rev 5513) @@ -25,10 +25,35 @@ :copyright: Copyright 2008 by Armin Ronacher. :license: Python License. """ +import sys from _ast import * from _ast import __version__ +if sys.platform.startswith('java'): + import array + ast_list = array.ArrayType + + def get_class_name(t): + result = t.__class__.__name__ + if result in ("expr_contextType", + "boolopType", + "unaryopType", + "cmpopType", + "operatorType"): + result = str(t) + if result == "AugLoad": + result = "Load" + elif result == "AugStore": + result = "Store" + elif result.endswith("Type"): + result = result[:-4] + return result +else: + ast_list = list + get_class_name = lambda node: node.__class__.__name__ + + def parse(expr, filename='<unknown>', mode='exec'): """ Parse an expression into an AST node. @@ -80,7 +105,7 @@ def _format(node): if isinstance(node, AST): fields = [(a, _format(b)) for a, b in iter_fields(node)] - rv = '%s(%s' % (node.__class__.__name__, ', '.join( + rv = '%s(%s' % (get_class_name(node), ', '.join( ('%s=%s' % field for field in fields) if annotate_fields else (b for a, b in fields) @@ -90,11 +115,11 @@ rv += ', '.join('%s=%s' % (a, _format(getattr(node, a))) for a in node._attributes) return rv + ')' - elif isinstance(node, list): + elif isinstance(node, ast_list): return '[%s]' % ', '.join(_format(x) for x in node) return repr(node) if not isinstance(node, AST): - raise TypeError('expected AST, got %r' % node.__class__.__name__) + raise TypeError('expected AST, got %r' % get_class_name(node)) return _format(node) @@ -168,7 +193,7 @@ for name, field in iter_fields(node): if isinstance(field, AST): yield field - elif isinstance(field, list): + elif isinstance(field, ast_list): for item in field: if isinstance(item, AST): yield item @@ -181,7 +206,7 @@ will be raised. """ if not isinstance(node, (FunctionDef, ClassDef, Module)): - raise TypeError("%r can't have docstrings" % node.__class__.__name__) + raise TypeError("%r can't have docstrings" % get_class_name(node)) if node.body and isinstance(node.body[0], Expr) and \ isinstance(node.body[0].value, Str): if clean: @@ -226,14 +251,14 @@ def visit(self, node): """Visit a node.""" - method = 'visit_' + node.__class__.__name__ + method = 'visit_' + get_class_name(node) visitor = getattr(self, method, self.generic_visit) return visitor(node) def generic_visit(self, node): """Called if no explicit visitor function exists for a node.""" for field, value in iter_fields(node): - if isinstance(value, list): + if isinstance(value, ast_list): for item in value: if isinstance(item, AST): self.visit(item) @@ -280,7 +305,7 @@ def generic_visit(self, node): for field, old_value in iter_fields(node): old_value = getattr(node, field, None) - if isinstance(old_value, list): + if isinstance(old_value, ast_list): new_values = [] for value in old_value: if isinstance(value, AST): Modified: trunk/jython/Lib/test/test_ast.py =================================================================== --- trunk/jython/Lib/test/test_ast.py 2008-10-26 19:55:08 UTC (rev 5512) +++ trunk/jython/Lib/test/test_ast.py 2008-10-26 21:13:51 UTC (rev 5513) @@ -1,6 +1,6 @@ #Taken and modified from CPython's release25-maint branch, revision 62446. import sys,os, itertools -import _ast +import ast def get_class_name(t): result = t.__class__.__name__ @@ -146,11 +146,11 @@ def test_order(ast_node, parent_pos): - if (not isinstance(ast_node, _ast.AST) + if (not isinstance(ast_node, ast.AST) or not hasattr(ast_node, '_fields') or ast_node._fields == None): return - if isinstance(ast_node, (_ast.expr, _ast.stmt, _ast.excepthandler)): + if isinstance(ast_node, (ast.expr, ast.stmt, ast.excepthandler)): node_pos = (ast_node.lineno, ast_node.col_offset) assert node_pos >= parent_pos, (node_pos, parent_pos) parent_pos = (ast_node.lineno, ast_node.col_offset) This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <pj...@us...> - 2008-10-26 19:55:16
|
Revision: 5512 http://jython.svn.sourceforge.net/jython/?rev=5512&view=rev Author: pjenvey Date: 2008-10-26 19:55:08 +0000 (Sun, 26 Oct 2008) Log Message: ----------- from: http://svn.python.org/projects/python/branches/release26-maint/Lib/ast.py@66986 Added Paths: ----------- trunk/jython/Lib/ast.py Added: trunk/jython/Lib/ast.py =================================================================== --- trunk/jython/Lib/ast.py (rev 0) +++ trunk/jython/Lib/ast.py 2008-10-26 19:55:08 UTC (rev 5512) @@ -0,0 +1,301 @@ +# -*- coding: utf-8 -*- +""" + ast + ~~~ + + The `ast` module helps Python applications to process trees of the Python + abstract syntax grammar. The abstract syntax itself might change with + each Python release; this module helps to find out programmatically what + the current grammar looks like and allows modifications of it. + + An abstract syntax tree can be generated by passing `ast.PyCF_ONLY_AST` as + a flag to the `compile()` builtin function or by using the `parse()` + function from this module. The result will be a tree of objects whose + classes all inherit from `ast.AST`. + + A modified abstract syntax tree can be compiled into a Python code object + using the built-in `compile()` function. + + Additionally various helper functions are provided that make working with + the trees simpler. The main intention of the helper functions and this + module in general is to provide an easy to use interface for libraries + that work tightly with the python syntax (template engines for example). + + + :copyright: Copyright 2008 by Armin Ronacher. + :license: Python License. +""" +from _ast import * +from _ast import __version__ + + +def parse(expr, filename='<unknown>', mode='exec'): + """ + Parse an expression into an AST node. + Equivalent to compile(expr, filename, mode, PyCF_ONLY_AST). + """ + return compile(expr, filename, mode, PyCF_ONLY_AST) + + +def literal_eval(node_or_string): + """ + Safely evaluate an expression node or a string containing a Python + expression. The string or node provided may only consist of the following + Python literal structures: strings, numbers, tuples, lists, dicts, booleans, + and None. + """ + _safe_names = {'None': None, 'True': True, 'False': False} + if isinstance(node_or_string, basestring): + node_or_string = parse(node_or_string, mode='eval') + if isinstance(node_or_string, Expression): + node_or_string = node_or_string.body + def _convert(node): + if isinstance(node, Str): + return node.s + elif isinstance(node, Num): + return node.n + elif isinstance(node, Tuple): + return tuple(map(_convert, node.elts)) + elif isinstance(node, List): + return list(map(_convert, node.elts)) + elif isinstance(node, Dict): + return dict((_convert(k), _convert(v)) for k, v + in zip(node.keys, node.values)) + elif isinstance(node, Name): + if node.id in _safe_names: + return _safe_names[node.id] + raise ValueError('malformed string') + return _convert(node_or_string) + + +def dump(node, annotate_fields=True, include_attributes=False): + """ + Return a formatted dump of the tree in *node*. This is mainly useful for + debugging purposes. The returned string will show the names and the values + for fields. This makes the code impossible to evaluate, so if evaluation is + wanted *annotate_fields* must be set to False. Attributes such as line + numbers and column offsets are not dumped by default. If this is wanted, + *include_attributes* can be set to True. + """ + def _format(node): + if isinstance(node, AST): + fields = [(a, _format(b)) for a, b in iter_fields(node)] + rv = '%s(%s' % (node.__class__.__name__, ', '.join( + ('%s=%s' % field for field in fields) + if annotate_fields else + (b for a, b in fields) + )) + if include_attributes and node._attributes: + rv += fields and ', ' or ' ' + rv += ', '.join('%s=%s' % (a, _format(getattr(node, a))) + for a in node._attributes) + return rv + ')' + elif isinstance(node, list): + return '[%s]' % ', '.join(_format(x) for x in node) + return repr(node) + if not isinstance(node, AST): + raise TypeError('expected AST, got %r' % node.__class__.__name__) + return _format(node) + + +def copy_location(new_node, old_node): + """ + Copy source location (`lineno` and `col_offset` attributes) from + *old_node* to *new_node* if possible, and return *new_node*. + """ + for attr in 'lineno', 'col_offset': + if attr in old_node._attributes and attr in new_node._attributes \ + and hasattr(old_node, attr): + setattr(new_node, attr, getattr(old_node, attr)) + return new_node + + +def fix_missing_locations(node): + """ + When you compile a node tree with compile(), the compiler expects lineno and + col_offset attributes for every node that supports them. This is rather + tedious to fill in for generated nodes, so this helper adds these attributes + recursively where not already set, by setting them to the values of the + parent node. It works recursively starting at *node*. + """ + def _fix(node, lineno, col_offset): + if 'lineno' in node._attributes: + if not hasattr(node, 'lineno'): + node.lineno = lineno + else: + lineno = node.lineno + if 'col_offset' in node._attributes: + if not hasattr(node, 'col_offset'): + node.col_offset = col_offset + else: + col_offset = node.col_offset + for child in iter_child_nodes(node): + _fix(child, lineno, col_offset) + _fix(node, 1, 0) + return node + + +def increment_lineno(node, n=1): + """ + Increment the line number of each node in the tree starting at *node* by *n*. + This is useful to "move code" to a different location in a file. + """ + if 'lineno' in node._attributes: + node.lineno = getattr(node, 'lineno', 0) + n + for child in walk(node): + if 'lineno' in child._attributes: + child.lineno = getattr(child, 'lineno', 0) + n + return node + + +def iter_fields(node): + """ + Yield a tuple of ``(fieldname, value)`` for each field in ``node._fields`` + that is present on *node*. + """ + for field in node._fields: + try: + yield field, getattr(node, field) + except AttributeError: + pass + + +def iter_child_nodes(node): + """ + Yield all direct child nodes of *node*, that is, all fields that are nodes + and all items of fields that are lists of nodes. + """ + for name, field in iter_fields(node): + if isinstance(field, AST): + yield field + elif isinstance(field, list): + for item in field: + if isinstance(item, AST): + yield item + + +def get_docstring(node, clean=True): + """ + Return the docstring for the given node or None if no docstring can + be found. If the node provided does not have docstrings a TypeError + will be raised. + """ + if not isinstance(node, (FunctionDef, ClassDef, Module)): + raise TypeError("%r can't have docstrings" % node.__class__.__name__) + if node.body and isinstance(node.body[0], Expr) and \ + isinstance(node.body[0].value, Str): + if clean: + import inspect + return inspect.cleandoc(node.body[0].value.s) + return node.body[0].value.s + + +def walk(node): + """ + Recursively yield all child nodes of *node*, in no specified order. This is + useful if you only want to modify nodes in place and don't care about the + context. + """ + from collections import deque + todo = deque([node]) + while todo: + node = todo.popleft() + todo.extend(iter_child_nodes(node)) + yield node + + +class NodeVisitor(object): + """ + A node visitor base class that walks the abstract syntax tree and calls a + visitor function for every node found. This function may return a value + which is forwarded by the `visit` method. + + This class is meant to be subclassed, with the subclass adding visitor + methods. + + Per default the visitor functions for the nodes are ``'visit_'`` + + class name of the node. So a `TryFinally` node visit function would + be `visit_TryFinally`. This behavior can be changed by overriding + the `visit` method. If no visitor function exists for a node + (return value `None`) the `generic_visit` visitor is used instead. + + Don't use the `NodeVisitor` if you want to apply changes to nodes during + traversing. For this a special visitor exists (`NodeTransformer`) that + allows modifications. + """ + + def visit(self, node): + """Visit a node.""" + method = 'visit_' + node.__class__.__name__ + visitor = getattr(self, method, self.generic_visit) + return visitor(node) + + def generic_visit(self, node): + """Called if no explicit visitor function exists for a node.""" + for field, value in iter_fields(node): + if isinstance(value, list): + for item in value: + if isinstance(item, AST): + self.visit(item) + elif isinstance(value, AST): + self.visit(value) + + +class NodeTransformer(NodeVisitor): + """ + A :class:`NodeVisitor` subclass that walks the abstract syntax tree and + allows modification of nodes. + + The `NodeTransformer` will walk the AST and use the return value of the + visitor methods to replace or remove the old node. If the return value of + the visitor method is ``None``, the node will be removed from its location, + otherwise it is replaced with the return value. The return value may be the + original node in which case no replacement takes place. + + Here is an example transformer that rewrites all occurrences of name lookups + (``foo``) to ``data['foo']``:: + + class RewriteName(NodeTransformer): + + def visit_Name(self, node): + return copy_location(Subscript( + value=Name(id='data', ctx=Load()), + slice=Index(value=Str(s=node.id)), + ctx=node.ctx + ), node) + + Keep in mind that if the node you're operating on has child nodes you must + either transform the child nodes yourself or call the :meth:`generic_visit` + method for the node first. + + For nodes that were part of a collection of statements (that applies to all + statement nodes), the visitor may also return a list of nodes rather than + just a single node. + + Usually you use the transformer like this:: + + node = YourTransformer().visit(node) + """ + + def generic_visit(self, node): + for field, old_value in iter_fields(node): + old_value = getattr(node, field, None) + if isinstance(old_value, list): + new_values = [] + for value in old_value: + if isinstance(value, AST): + value = self.visit(value) + if value is None: + continue + elif not isinstance(value, AST): + new_values.extend(value) + continue + new_values.append(value) + old_value[:] = new_values + elif isinstance(old_value, AST): + new_node = self.visit(old_value) + if new_node is None: + delattr(node, field) + else: + setattr(node, field, new_node) + return node This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <cg...@us...> - 2008-10-26 17:35:15
|
Revision: 5511 http://jython.svn.sourceforge.net/jython/?rev=5511&view=rev Author: cgroves Date: 2008-10-26 17:35:12 +0000 (Sun, 26 Oct 2008) Log Message: ----------- Document magic values n ReflectedCallData Modified Paths: -------------- trunk/jython/src/org/python/core/PyReflectedConstructor.java trunk/jython/src/org/python/core/PyReflectedFunction.java trunk/jython/src/org/python/core/ReflectedArgs.java trunk/jython/src/org/python/core/ReflectedCallData.java Modified: trunk/jython/src/org/python/core/PyReflectedConstructor.java =================================================================== --- trunk/jython/src/org/python/core/PyReflectedConstructor.java 2008-10-26 14:05:35 UTC (rev 5510) +++ trunk/jython/src/org/python/core/PyReflectedConstructor.java 2008-10-26 17:35:12 UTC (rev 5511) @@ -9,7 +9,7 @@ public class PyReflectedConstructor extends PyReflectedFunction { - + public PyReflectedConstructor(String name) { super(name); __name__ = name; @@ -38,16 +38,15 @@ // xxx temporary solution, type ctr will go through __new__ ... PyObject make(PyObject[] args,String[] keywords) { ReflectedArgs[] argsl = argslist; - + ReflectedCallData callData = new ReflectedCallData(); Object method=null; boolean consumes_keywords = false; - int n = nargs; int nkeywords = keywords.length; PyObject[] allArgs = null; - + // Check for a matching constructor to call - if (n > 0) { // PyArgsKeywordsCall signature, if present, is the first + if (nargs > 0) { // PyArgsKeywordsCall signature, if present, is the first if (argsl[0].matches(null, args, keywords, callData)) { method = argsl[0].data; consumes_keywords = argsl[0].flags == ReflectedArgs.PyArgsKeywordsCall; @@ -55,15 +54,16 @@ allArgs = args; int i = 1; if (nkeywords > 0) { - args = new PyObject[allArgs.length-nkeywords]; + args = new PyObject[allArgs.length - nkeywords]; System.arraycopy(allArgs, 0, args, 0, args.length); i = 0; } - for (; i < n; i++) { + for (; i < nargs; i++) { ReflectedArgs rargs = argsl[i]; - if (rargs - .matches(null, args, Py.NoKeywords, callData)) { - method = rargs.data; break; } + if (rargs.matches(null, args, Py.NoKeywords, callData)) { + method = rargs.data; + break; + } } } } @@ -82,14 +82,14 @@ catch (Throwable t) { throw Py.JavaError(t); } - + if (!consumes_keywords) { int offset = args.length; - for (int i=0; i<nkeywords; i++) { - obj.__setattr__(keywords[i], allArgs[i+offset]); - } + for (int i = 0; i < nkeywords; i++) { + obj.__setattr__(keywords[i], allArgs[i + offset]); + } } - + return obj; } Modified: trunk/jython/src/org/python/core/PyReflectedFunction.java =================================================================== --- trunk/jython/src/org/python/core/PyReflectedFunction.java 2008-10-26 14:05:35 UTC (rev 5510) +++ trunk/jython/src/org/python/core/PyReflectedFunction.java 2008-10-26 17:35:12 UTC (rev 5511) @@ -3,10 +3,11 @@ import java.lang.reflect.Method; import java.lang.reflect.Modifier; -import java.util.Enumeration; -import java.util.Hashtable; +import java.util.Set; +import org.python.util.Generic; + public class PyReflectedFunction extends PyObject { public String __name__; @@ -136,11 +137,11 @@ } Object cself = callData.self; - Method m = (Method)method; + Method m = (Method)method; // Check to see if we should be using a super__ method instead // This is probably a bit inefficient... if (self == null && cself != null && cself instanceof PyProxy && - !__name__.startsWith("super__")) { + !__name__.startsWith("super__")) { PyInstance iself = ((PyProxy)cself)._getPyInstance(); if (argslist[0].declaringClass != iself.instclass.proxyClass) { String mname = ("super__"+__name__); @@ -148,9 +149,9 @@ Method[] super__methods = (Method[])iself.instclass.super__methods.get(mname); if (super__methods != null) { Class[] msig = m.getParameterTypes(); - for (int i=0; i<super__methods.length;i++) { - if (java.util.Arrays.equals(msig,super__methods[i].getParameterTypes())) { - m = super__methods[i]; + for (Method super__method : super__methods) { + if (java.util.Arrays.equals(msig,super__method.getParameterTypes())) { + m = super__method; break; } } @@ -264,64 +265,40 @@ } protected void throwBadArgError(int errArg, int nArgs, boolean self) { - Hashtable table = new Hashtable(); - ReflectedArgs[] argsl = argslist; - int n = nargs; - for(int i=0; i<n; i++) { - ReflectedArgs rargs = argsl[i]; - Class[] args = rargs.args; - int len = args.length; - /*if (!args.isStatic && !self) { - len = len-1; - }*/ + Set<Class<?>> argTypes = Generic.set(); + for (int i = 0; i < nargs; i++) { + // if (!args.isStatic && !self) { len = len-1; } // This check works almost all the time. // I'm still a little worried about non-static methods // called with an explict self... - if (len == nArgs) { - if (errArg == -1) { - table.put(rargs.declaringClass, rargs.declaringClass); + if (argslist[i].args.length == nArgs) { + if (errArg == ReflectedCallData.UNABLE_TO_CONVERT_SELF) { + argTypes.add(argslist[i].declaringClass); } else { - table.put(args[errArg], args[errArg]); + argTypes.add(argslist[i].args[errArg]); } } } - - StringBuffer buf = new StringBuffer(); - Enumeration keys = table.keys(); - while (keys.hasMoreElements()) { - Class arg = (Class)keys.nextElement(); - String name = niceName(arg); - if (keys.hasMoreElements()) { - buf.append(name); - buf.append(", "); - } else { - if (buf.length() > 2) { - buf.setLength(buf.length()-2); - buf.append(" or "); - } - buf.append(name); - } + StringBuilder buf = new StringBuilder(); + for (Class<?> arg : argTypes) { + buf.append(niceName(arg)); + buf.append(", "); } + if(buf.length() > 2) { + buf.setLength(buf.length() - 2); + } - throwError(ordinal(errArg)+" arg can't be coerced to "+buf); + throwError(ordinal(errArg) + " arg can't be coerced to " + buf); } - protected void throwError(int errArg, int nArgs, boolean self, - boolean keywords) - { - if (keywords) throwError("takes no keyword arguments"); - - if (errArg == -2) { + protected void throwError(int errArg, int nArgs, boolean self, boolean keywords) { + if (keywords) { + throwError("takes no keyword arguments"); + } else if (errArg == ReflectedCallData.BAD_ARG_COUNT) { throwArgCountError(nArgs, self); + } else { + throwBadArgError(errArg, nArgs, self); } - - /*if (errArg == -1) { - throwBadArgError(-1); - throwError("bad self argument"); - // Bad declared class - }*/ - - throwBadArgError(errArg, nArgs, self); } // Included only for debugging purposes... Modified: trunk/jython/src/org/python/core/ReflectedArgs.java =================================================================== --- trunk/jython/src/org/python/core/ReflectedArgs.java 2008-10-26 14:05:35 UTC (rev 5510) +++ trunk/jython/src/org/python/core/ReflectedArgs.java 2008-10-26 17:35:12 UTC (rev 5511) @@ -101,7 +101,7 @@ } // Make error messages clearer - callData.errArg = -1; + callData.errArg = ReflectedCallData.UNABLE_TO_CONVERT_SELF; if (self != null) { Object tmp = self.__tojava__(this.declaringClass); @@ -199,7 +199,7 @@ return cmp > 0 ? +1 : -1; } } - } + } return p1 > p2 ? +2 : (p1 == p2 ? 0 : -2); } @@ -261,8 +261,8 @@ String s = "" + this.declaringClass + ", " + this.isStatic + ", " + this.flags + ", " + this.data + "\n"; s = s + "\t("; - for (int j = 0; j < this.args.length; j++) { - s += this.args[j].getName() + ", "; + for (Class arg : this.args) { + s += arg.getName() + ", "; } s += ")"; return s; Modified: trunk/jython/src/org/python/core/ReflectedCallData.java =================================================================== --- trunk/jython/src/org/python/core/ReflectedCallData.java 2008-10-26 14:05:35 UTC (rev 5510) +++ trunk/jython/src/org/python/core/ReflectedCallData.java 2008-10-26 17:35:12 UTC (rev 5511) @@ -2,21 +2,25 @@ package org.python.core; class ReflectedCallData { - public Object[] args; + /** errArg value if the self passed to a call wasn't compatible with the type of the method. */ + public static final int UNABLE_TO_CONVERT_SELF = -1; + + /** errArg value if the method has no forms that take the number of arguments given. */ + public static final int BAD_ARG_COUNT = -2; + + public Object[] args = Py.EmptyObjects; + public int length; public Object self; - public int errArg; + /** + * Either {@link #BAD_ARG_COUNT}, {@link #UNABLE_TO_CONVERT_SELF}, or the index of the + * unconvertible argument in args. + */ + public int errArg = BAD_ARG_COUNT; - public ReflectedCallData() { - this.args = Py.EmptyObjects; - this.length = 0; - this.self = null; - this.errArg = -2; - } - public void setLength(int newLength) { this.length = newLength; if (newLength <= this.args.length) { This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <fwi...@us...> - 2008-10-26 14:05:42
|
Revision: 5510 http://jython.svn.sourceforge.net/jython/?rev=5510&view=rev Author: fwierzbicki Date: 2008-10-26 14:05:35 +0000 (Sun, 26 Oct 2008) Log Message: ----------- Although not as nice, replace jdk6 LinkedList methods names with jdk5 names. Modified Paths: -------------- trunk/jython/src/org/python/core/ThreadState.java Modified: trunk/jython/src/org/python/core/ThreadState.java =================================================================== --- trunk/jython/src/org/python/core/ThreadState.java 2008-10-26 06:23:15 UTC (rev 5509) +++ trunk/jython/src/org/python/core/ThreadState.java 2008-10-26 14:05:35 UTC (rev 5510) @@ -40,14 +40,14 @@ if (initializingProxies == null) { initializingProxies = new LinkedList<PyInstance>(); } - initializingProxies.push(proxy); + initializingProxies.addFirst(proxy); } public void popInitializingProxy() { if (initializingProxies == null || initializingProxies.isEmpty()) { throw Py.RuntimeError("invalid initializing proxies state"); } - initializingProxies.pop(); + initializingProxies.removeFirst(); } public ThreadState(Thread t, PySystemState systemState) { This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <cg...@us...> - 2008-10-26 06:23:25
|
Revision: 5509 http://jython.svn.sourceforge.net/jython/?rev=5509&view=rev Author: cgroves Date: 2008-10-26 06:23:15 +0000 (Sun, 26 Oct 2008) Log Message: ----------- Stuff commented out "for now" 10 years ago referring to code that no longer exists is probably with us for good. Modified Paths: -------------- trunk/jython/src/org/python/core/ThreadState.java Modified: trunk/jython/src/org/python/core/ThreadState.java =================================================================== --- trunk/jython/src/org/python/core/ThreadState.java 2008-10-25 23:03:38 UTC (rev 5508) +++ trunk/jython/src/org/python/core/ThreadState.java 2008-10-26 06:23:15 UTC (rev 5509) @@ -1,70 +1,58 @@ // Copyright (c) Corporation for National Research Initiatives package org.python.core; -import java.util.Stack; +import java.util.LinkedList; public class ThreadState { - // public InterpreterState interp; + public PySystemState systemState; public PyFrame frame; - // public PyObject curexc_type, curexc_value, curexc_traceback; - // public PyObject exc_type, exc_value, exc_traceback; public PyException exception; public Thread thread; public boolean tracing; - public PyList reprStack = null; + public PyList reprStack; - // public PyInstance initializingProxy = null; - private Stack initializingProxies = null; + public int compareStateNesting; - public int compareStateNesting = 0; + public int recursion_depth; - private PyDictionary compareStateDict; - - public int recursion_depth = 0; - public TraceFunction tracefunc; + public TraceFunction profilefunc; - + + private LinkedList<PyInstance> initializingProxies; + + private PyDictionary compareStateDict; + public PyInstance getInitializingProxy() { - if (this.initializingProxies == null - || this.initializingProxies.empty()) { + if (initializingProxies == null) { return null; } - return (PyInstance) this.initializingProxies.peek(); + return initializingProxies.peek(); } public void pushInitializingProxy(PyInstance proxy) { - if (this.initializingProxies == null) { - this.initializingProxies = new Stack(); + if (initializingProxies == null) { + initializingProxies = new LinkedList<PyInstance>(); } - this.initializingProxies.push(proxy); + initializingProxies.push(proxy); } public void popInitializingProxy() { - if (this.initializingProxies == null - || this.initializingProxies.empty()) { + if (initializingProxies == null || initializingProxies.isEmpty()) { throw Py.RuntimeError("invalid initializing proxies state"); } - this.initializingProxies.pop(); + initializingProxies.pop(); } public ThreadState(Thread t, PySystemState systemState) { - this.thread = t; - // Fake multiple interpreter states for now - /* - * if (Py.interp == null) { Py.interp = - * InterpreterState.getInterpreterState(); } - */ this.systemState = systemState; - // interp = Py.interp; - this.tracing = false; - // System.out.println("new thread state"); + thread = t; } public boolean enterRepr(PyObject obj) { @@ -85,7 +73,6 @@ if (reprStack == null) { return; } - for (int i = reprStack.size() - 1; i >= 0; i--) { if (reprStack.pyget(i) == obj) { reprStack.delRange(i, reprStack.size(), 1); @@ -94,9 +81,9 @@ } public PyDictionary getCompareStateDict() { - if (this.compareStateDict == null) { - this.compareStateDict = new PyDictionary(); + if (compareStateDict == null) { + compareStateDict = new PyDictionary(); } - return this.compareStateDict; + return compareStateDict; } } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <pj...@us...> - 2008-10-25 23:03:44
|
Revision: 5508 http://jython.svn.sourceforge.net/jython/?rev=5508&view=rev Author: pjenvey Date: 2008-10-25 23:03:38 +0000 (Sat, 25 Oct 2008) Log Message: ----------- on SystemRestart: o shutdown all active sockets o hide InterruptedExceptions in threads for better SystemRestart support in PasteScript Modified Paths: -------------- trunk/jython/Lib/socket.py trunk/jython/Lib/threading.py trunk/jython/src/org/python/util/jython.java Modified: trunk/jython/Lib/socket.py =================================================================== --- trunk/jython/Lib/socket.py 2008-10-25 21:53:49 UTC (rev 5507) +++ trunk/jython/Lib/socket.py 2008-10-25 23:03:38 UTC (rev 5508) @@ -988,6 +988,16 @@ send = recv = recv_into = sendto = recvfrom = recvfrom_into = _dummy __getattr__ = _dummy +_active_sockets = set() + +def _closeActiveSockets(): + for socket in _active_sockets.copy(): + try: + socket.close() + except error: + msg = 'Problem closing socket: %s: %r' % (socket, sys.exc_info()) + print >> sys.stderr, msg + class _socketobject(object): __doc__ = _realsocket.__doc__ @@ -1005,8 +1015,13 @@ meth = getattr(_sock, method, None) if meth: setattr(self, method, meth) + _active_sockets.add(self) def close(self): + try: + _active_sockets.remove(self) + except KeyError: + pass _sock = self._sock if isinstance(_sock, _nonblocking_api_mixin): _sock.close_lock.acquire() Modified: trunk/jython/Lib/threading.py =================================================================== --- trunk/jython/Lib/threading.py 2008-10-25 21:53:49 UTC (rev 5507) +++ trunk/jython/Lib/threading.py 2008-10-25 23:03:38 UTC (rev 5508) @@ -1,6 +1,8 @@ +from java.lang import InterruptedException from java.util import Collections, WeakHashMap from java.util.concurrent import Semaphore, CyclicBarrier from java.util.concurrent.locks import ReentrantLock +from org.python.util import jython from thread import _newFunctionThread from thread import _local as local import java.lang.Thread @@ -245,6 +247,11 @@ self.run() except SystemExit: pass + except InterruptedException: + # Quiet InterruptedExceptions if they're caused by + # _systemrestart + if not jython.shouldRestart: + raise except: # If sys.stderr is no more (most likely from interpreter # shutdown) use self.__stderr. Otherwise still use sys (as in Modified: trunk/jython/src/org/python/util/jython.java =================================================================== --- trunk/jython/src/org/python/util/jython.java 2008-10-25 21:53:49 UTC (rev 5507) +++ trunk/jython/src/org/python/util/jython.java 2008-10-25 23:03:38 UTC (rev 5508) @@ -63,7 +63,7 @@ "JYTHONPATH: '" + java.io.File.pathSeparator + "'-separated list of directories prefixed to the default module\n" + " search path. The result is sys.path."; - private static boolean shouldRestart; + public static boolean shouldRestart; public static void runJar(String filename) { // TBD: this is kind of gross because a local called `zipfile' just @@ -228,12 +228,12 @@ } catch(Throwable t) { if (t instanceof PyException && Py.matchException((PyException)t, _systemrestart.SystemRestart)) { - // Stop current threads... - thread.interruptAllThreads(); + // Shutdown this instance... + shouldRestart = true; + shutdownInterpreter(); // ..reset the state... Py.setSystemState(new PySystemState()); // ...and start again - shouldRestart = true; } else { Py.printException(t); if (!opts.interactive) { @@ -323,6 +323,21 @@ //System.err.println("imp"); return interp; } + + /** + * Run any finalizations on the current interpreter in preparation for a SytemRestart. + */ + public static void shutdownInterpreter() { + // Stop all the active threads + thread.interruptAllThreads(); + // Close all sockets -- not all of their operations are stopped by + // Thread.interrupt (in particular pre-nio sockets) + try { + imp.load("socket").__findattr__("_closeActiveSockets").__call__(); + } catch (PyException pye) { + // continue + } + } } class CommandLineOptions This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <pj...@us...> - 2008-10-25 21:53:54
|
Revision: 5507 http://jython.svn.sourceforge.net/jython/?rev=5507&view=rev Author: pjenvey Date: 2008-10-25 21:53:49 +0000 (Sat, 25 Oct 2008) Log Message: ----------- rename to _update to match the other _update method, we'll keep the underscore for incase we want to add update to go along with set_update Modified Paths: -------------- trunk/jython/src/org/python/core/BaseSet.java trunk/jython/src/org/python/core/PyFrozenSet.java trunk/jython/src/org/python/core/PySet.java Modified: trunk/jython/src/org/python/core/BaseSet.java =================================================================== --- trunk/jython/src/org/python/core/BaseSet.java 2008-10-25 21:47:49 UTC (rev 5506) +++ trunk/jython/src/org/python/core/BaseSet.java 2008-10-25 21:53:49 UTC (rev 5507) @@ -26,7 +26,7 @@ } protected void _update(PyObject data) throws PyIgnoreMethodTag { - update(_set, data); + _update(_set, data); } /** @@ -35,7 +35,7 @@ * @param data An iterable instance. * @throws PyIgnoreMethodTag Ignore. */ - protected static Set update(Set set, PyObject data) throws PyIgnoreMethodTag { + protected static Set _update(Set set, PyObject data) throws PyIgnoreMethodTag { if (data == null) { return set; } Modified: trunk/jython/src/org/python/core/PyFrozenSet.java =================================================================== --- trunk/jython/src/org/python/core/PyFrozenSet.java 2008-10-25 21:47:49 UTC (rev 5506) +++ trunk/jython/src/org/python/core/PyFrozenSet.java 2008-10-25 21:53:49 UTC (rev 5507) @@ -19,11 +19,11 @@ } public PyFrozenSet(PyObject data) { - super(update(new HashSet<PyObject>(), data)); + super(_update(new HashSet<PyObject>(), data)); } public PyFrozenSet(PyType type, PyObject data) { - super(type, update(new HashSet<PyObject>(), data)); + super(type, _update(new HashSet<PyObject>(), data)); } @ExposedNew Modified: trunk/jython/src/org/python/core/PySet.java =================================================================== --- trunk/jython/src/org/python/core/PySet.java 2008-10-25 21:47:49 UTC (rev 5506) +++ trunk/jython/src/org/python/core/PySet.java 2008-10-25 21:53:49 UTC (rev 5507) @@ -23,7 +23,7 @@ } public PySet(PyObject data) { - super(update(new ConcurrentHashSet<PyObject>(), data)); + super(_update(new ConcurrentHashSet<PyObject>(), data)); } @ExposedNew This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <pj...@us...> - 2008-10-25 21:51:54
|
Revision: 5506 http://jython.svn.sourceforge.net/jython/?rev=5506&view=rev Author: pjenvey Date: 2008-10-25 21:47:49 +0000 (Sat, 25 Oct 2008) Log Message: ----------- o back set with ConcurrentHashSet (just wraps ConcurrentHashMap) to make it thread safe o make frozenset immutable from the Java side's Set interface methods -- avoid unmodifiableSet because that complicates BaseSet Modified Paths: -------------- trunk/jython/src/org/python/core/BaseSet.java trunk/jython/src/org/python/core/PyFrozenSet.java trunk/jython/src/org/python/core/PyFrozenSetDerived.java trunk/jython/src/org/python/core/PySet.java trunk/jython/src/org/python/core/PySetIterator.java trunk/jython/src/templates/frozenset.derived Added Paths: ----------- trunk/jython/src/org/python/core/util/ConcurrentHashSet.java Modified: trunk/jython/src/org/python/core/BaseSet.java =================================================================== --- trunk/jython/src/org/python/core/BaseSet.java 2008-10-24 00:48:16 UTC (rev 5505) +++ trunk/jython/src/org/python/core/BaseSet.java 2008-10-25 21:47:49 UTC (rev 5506) @@ -8,51 +8,46 @@ public abstract class BaseSet extends PyObject implements Set { - /** - * The underlying container. HashSet is used rather than Set because - * clone is protected on Object and I didn't want to cast. - */ - protected HashSet _set; + /** The underlying Set. */ + protected Set _set; /** - * Create a new, empty set instance. - */ - public BaseSet() { - super(); - _set = new HashSet(); - } - - /** - * Create a new set instance from the values of the iterable object. + * Create a new Python set instance from the specified Set object. * - * @param data An iterable instance. + * @param set An Set object. */ - public BaseSet(PyObject data) { - super(); - _set = new HashSet(); - _update(data); + protected BaseSet(Set set) { + _set = set; } - public BaseSet(PyType type) { + protected BaseSet(PyType type, Set set) { super(type); - _set = new HashSet(); + _set = set; } + protected void _update(PyObject data) throws PyIgnoreMethodTag { + update(_set, data); + } + /** * Update the underlying set with the contents of the iterable. * * @param data An iterable instance. * @throws PyIgnoreMethodTag Ignore. */ - protected void _update(PyObject data) throws PyIgnoreMethodTag { + protected static Set update(Set set, PyObject data) throws PyIgnoreMethodTag { + if (data == null) { + return set; + } if (data instanceof BaseSet) { // Skip the iteration if both are sets - _set.addAll(((BaseSet)data)._set); - return; + set.addAll(((BaseSet)data)._set); + return set; } for (PyObject item : data.asIterable()) { - _set.add(item); + set.add(item); } + return set; } /** @@ -458,17 +453,15 @@ protected static BaseSet makeNewSet(PyType type, PyObject iterable) { BaseSet so; if (type == PySet.TYPE) { - so = new PySet(); + so = new PySet(iterable); } else if (type == PyFrozenSet.TYPE) { - so = new PyFrozenSet(); + so = new PyFrozenSet(iterable); } else if (Py.isSubClass(type, PySet.TYPE)) { so = new PySetDerived(type); + so._update(iterable); } else { - so = new PyFrozenSetDerived(type); + so = new PyFrozenSetDerived(type, iterable); } - if (iterable != null) { - so._update(iterable); - } return so; } Modified: trunk/jython/src/org/python/core/PyFrozenSet.java =================================================================== --- trunk/jython/src/org/python/core/PyFrozenSet.java 2008-10-24 00:48:16 UTC (rev 5505) +++ trunk/jython/src/org/python/core/PyFrozenSet.java 2008-10-25 21:47:49 UTC (rev 5506) @@ -1,5 +1,9 @@ package org.python.core; +import java.util.Collection; +import java.util.HashSet; +import java.util.Iterator; + import org.python.expose.ExposedMethod; import org.python.expose.ExposedNew; import org.python.expose.ExposedType; @@ -11,15 +15,15 @@ public static final PyType TYPE = PyType.fromClass(PyFrozenSet.class); public PyFrozenSet() { - super(); + super(new HashSet<PyObject>()); } - public PyFrozenSet(PyType type) { - super(type); + public PyFrozenSet(PyObject data) { + super(update(new HashSet<PyObject>(), data)); } - public PyFrozenSet(PyObject data) { - super(data); + public PyFrozenSet(PyType type, PyObject data) { + super(type, update(new HashSet<PyObject>(), data)); } @ExposedNew @@ -32,7 +36,7 @@ if (new_.for_type == subtype) { if (iterable == null) { fset = Py.EmptyFrozenSet; - } else if (iterable.getClass() == PyFrozenSet.class) { + } else if (iterable.getType() == TYPE) { fset = (PyFrozenSet)iterable; } else { fset = new PyFrozenSet(iterable); @@ -41,10 +45,7 @@ } } } else { - fset = new PyFrozenSetDerived(subtype); - if (iterable != null) { - fset._update(iterable); - } + fset = new PyFrozenSetDerived(subtype, iterable); } return fset; @@ -177,4 +178,44 @@ public int hashCode() { return frozenset___hash__(); } + + public void clear() { + throw new UnsupportedOperationException(); + } + + public boolean add(Object o) { + throw new UnsupportedOperationException(); + } + + public boolean remove(Object o) { + throw new UnsupportedOperationException(); + } + + public boolean addAll(Collection c) { + throw new UnsupportedOperationException(); + } + + public boolean removeAll(Collection c) { + throw new UnsupportedOperationException(); + } + + public boolean retainAll(Collection c) { + throw new UnsupportedOperationException(); + } + + public Iterator iterator() { + return new Iterator() { + Iterator i = _set.iterator(); + + public boolean hasNext() { + return i.hasNext(); + } + public Object next() { + return i.next(); + } + public void remove() { + throw new UnsupportedOperationException(); + } + }; + } } Modified: trunk/jython/src/org/python/core/PyFrozenSetDerived.java =================================================================== --- trunk/jython/src/org/python/core/PyFrozenSetDerived.java 2008-10-24 00:48:16 UTC (rev 5505) +++ trunk/jython/src/org/python/core/PyFrozenSetDerived.java 2008-10-25 21:47:49 UTC (rev 5506) @@ -36,8 +36,8 @@ dict=new PyStringMap(); } - public PyFrozenSetDerived(PyType subtype) { - super(subtype); + public PyFrozenSetDerived(PyType subtype,PyObject data) { + super(subtype,data); slots=new PyObject[subtype.getNumSlots()]; dict=subtype.instDict(); } Modified: trunk/jython/src/org/python/core/PySet.java =================================================================== --- trunk/jython/src/org/python/core/PySet.java 2008-10-24 00:48:16 UTC (rev 5505) +++ trunk/jython/src/org/python/core/PySet.java 2008-10-25 21:47:49 UTC (rev 5506) @@ -3,6 +3,7 @@ import java.util.Iterator; import java.util.NoSuchElementException; +import org.python.core.util.ConcurrentHashSet; import org.python.expose.ExposedMethod; import org.python.expose.ExposedNew; import org.python.expose.ExposedType; @@ -14,15 +15,15 @@ public static final PyType TYPE = PyType.fromClass(PySet.class); public PySet() { - super(); + super(new ConcurrentHashSet<PyObject>()); } public PySet(PyType type) { - super(type); + super(type, new ConcurrentHashSet<PyObject>()); } public PySet(PyObject data) { - super(data); + super(update(new ConcurrentHashSet<PyObject>(), data)); } @ExposedNew @@ -37,8 +38,7 @@ } _set.clear(); - PyObject o = args[0]; - _update(o); + _update(args[0]); } @ExposedMethod(type = MethodType.BINARY) @@ -245,11 +245,11 @@ final PyObject set_pop() { Iterator iterator = _set.iterator(); try { - Object first = iterator.next(); + Object first = iterator.next(); _set.remove(first); - return (PyObject) first; + return (PyObject)first; } catch (NoSuchElementException e) { - throw new PyException(Py.KeyError, "pop from an empty set"); + throw new PyException(Py.KeyError, "pop from an empty set"); } } Modified: trunk/jython/src/org/python/core/PySetIterator.java =================================================================== --- trunk/jython/src/org/python/core/PySetIterator.java 2008-10-24 00:48:16 UTC (rev 5505) +++ trunk/jython/src/org/python/core/PySetIterator.java 2008-10-25 21:47:49 UTC (rev 5506) @@ -2,18 +2,20 @@ import java.util.Iterator; import java.util.Set; -import java.util.ConcurrentModificationException; public class PySetIterator extends PyObject { - private Set _set; - private int _count; - private Iterator _iterator; + private Set set; + + private int size; + + private Iterator<PyObject> iterator; + public PySetIterator(Set set) { super(); - this._set = set; - this._count = 0; - this._iterator = set.iterator(); + this.set = set; + size = set.size(); + iterator = set.iterator(); } public PyObject __iter__() { @@ -22,24 +24,12 @@ /** * Returns the next item in the iteration or raises a StopIteration. - * <p/> - * <p/> - * This differs from the core Jython Set iterator in that it checks if - * the underlying Set changes in size during the course and upon completion - * of the iteration. A RuntimeError is raised if the Set ever changes size - * or is concurrently modified. - * </p> * * @return the next item in the iteration */ public PyObject next() { PyObject o = this.__iternext__(); if (o == null) { - if (this._count != this._set.size()) { - // CPython throws an exception even if you have iterated through the - // entire set, this is not true for Java, so check by hand - throw Py.RuntimeError("dictionary changed size during iteration"); - } throw Py.StopIteration(""); } return o; @@ -48,18 +38,15 @@ /** * Returns the next item in the iteration. * - * @return the next item in the iteration - * or null to signal the end of the iteration + * @return the next item in the iteration or null to signal the end of the iteration */ public PyObject __iternext__() { - if (this._iterator.hasNext()) { - this._count++; - try { - return Py.java2py(this._iterator.next()); - } catch (ConcurrentModificationException e) { - throw Py.RuntimeError("dictionary changed size during iteration"); - } + if (set.size() != size) { + throw Py.RuntimeError("set changed size during iteration"); } + if (iterator.hasNext()) { + return iterator.next(); + } return null; } } Added: trunk/jython/src/org/python/core/util/ConcurrentHashSet.java =================================================================== --- trunk/jython/src/org/python/core/util/ConcurrentHashSet.java (rev 0) +++ trunk/jython/src/org/python/core/util/ConcurrentHashSet.java 2008-10-25 21:47:49 UTC (rev 5506) @@ -0,0 +1,90 @@ +/* Copyright (c) Jython Developers */ +package org.python.core.util; + +import java.util.AbstractSet; +import java.util.Collection; +import java.util.Iterator; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; + +/** + * A Set backed by ConcurrentHashMap. + */ +public class ConcurrentHashSet<E> extends AbstractSet<E> { + + /** The backing Map. */ + private ConcurrentHashMap<E, Object> map; + + /** Backing's KeySet. */ + private transient Set<E> keySet; + + /** Dummy value to associate with the key in the backing map. */ + private static final Object PRESENT = new Object(); + + public ConcurrentHashSet() { + map = new ConcurrentHashMap<E, Object>(); + keySet = map.keySet(); + } + + public ConcurrentHashSet(int initialCapacity) { + map = new ConcurrentHashMap<E, Object>(initialCapacity); + keySet = map.keySet(); + } + + public ConcurrentHashSet(int initialCapacity, float loadFactor, int concurrencyLevel) { + map = new ConcurrentHashMap<E, Object>(initialCapacity, loadFactor, concurrencyLevel); + keySet = map.keySet(); + } + + public int size() { + return map.size(); + } + + public boolean isEmpty() { + return map.isEmpty(); + } + + public boolean contains(Object o) { + return map.containsKey(o); + } + + public Iterator<E> iterator() { + return keySet.iterator(); + } + + public Object[] toArray() { + return keySet.toArray(); + } + + public <T> T[] toArray(T[] a) { + return keySet.toArray(a); + } + + public boolean add(E e) { + return map.put(e, PRESENT) == null; + } + + public boolean remove(Object o) { + return map.remove(o) != null; + } + + public boolean removeAll(Collection<?> c) { + return keySet.removeAll(c); + } + + public boolean retainAll(Collection<?> c) { + return keySet.retainAll(c); + } + + public void clear() { + map.clear(); + } + + public boolean equals(Object o) { + return keySet.equals(o); + } + + public int hashCode() { + return keySet.hashCode(); + } +} Modified: trunk/jython/src/templates/frozenset.derived =================================================================== --- trunk/jython/src/templates/frozenset.derived 2008-10-24 00:48:16 UTC (rev 5505) +++ trunk/jython/src/templates/frozenset.derived 2008-10-25 21:47:49 UTC (rev 5506) @@ -1,4 +1,4 @@ base_class: PyFrozenSet want_dict: true -ctr: +ctr: PyObject data incl: object This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <pj...@us...> - 2008-10-24 00:48:22
|
Revision: 5505 http://jython.svn.sourceforge.net/jython/?rev=5505&view=rev Author: pjenvey Date: 2008-10-24 00:48:16 +0000 (Fri, 24 Oct 2008) Log Message: ----------- have throw take a PyObject traceback to fix the bad bytecode generated for its exposer Modified Paths: -------------- trunk/jython/src/org/python/core/PyGenerator.java Modified: trunk/jython/src/org/python/core/PyGenerator.java =================================================================== --- trunk/jython/src/org/python/core/PyGenerator.java 2008-10-22 08:27:42 UTC (rev 5504) +++ trunk/jython/src/org/python/core/PyGenerator.java 2008-10-24 00:48:16 UTC (rev 5505) @@ -40,7 +40,12 @@ } @ExposedMethod(names="throw", defaults={"null", "null"}) - public PyObject throw$(PyObject type, PyObject value, PyTraceback tb) { + public PyObject throw$(PyObject type, PyObject value, PyObject tb) { + if (tb == Py.None) { + tb = null; + } else if (tb != null && !(tb instanceof PyTraceback)) { + throw Py.TypeError("throw() third argument must be a traceback object"); + } return raiseException(Py.makeException(type, value, tb)); } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <cg...@us...> - 2008-10-22 08:32:04
|
Revision: 5504 http://jython.svn.sourceforge.net/jython/?rev=5504&view=rev Author: cgroves Date: 2008-10-22 08:27:42 +0000 (Wed, 22 Oct 2008) Log Message: ----------- Expose PyGenerator so we can control the visibility of gi_running. test_generators checks on __doc__ from next on generators, so this commit adds docstrings to exposed methods to satisfy that requirement. Modified Paths: -------------- trunk/jython/CoreExposed.includes trunk/jython/src/org/python/core/PyBuiltinCallable.java trunk/jython/src/org/python/core/PyBuiltinFunction.java trunk/jython/src/org/python/core/PyGenerator.java trunk/jython/src/org/python/core/PyIterator.java trunk/jython/src/org/python/core/PyObject.java trunk/jython/src/org/python/expose/ExposedMethod.java trunk/jython/src/org/python/expose/generate/ClassMethodExposer.java trunk/jython/src/org/python/expose/generate/ExposedMethodFinder.java trunk/jython/src/org/python/expose/generate/InstanceMethodExposer.java trunk/jython/src/org/python/expose/generate/MethodExposer.java trunk/jython/tests/java/org/python/expose/generate/MethodExposerTest.java Modified: trunk/jython/CoreExposed.includes =================================================================== --- trunk/jython/CoreExposed.includes 2008-10-22 04:53:59 UTC (rev 5503) +++ trunk/jython/CoreExposed.includes 2008-10-22 08:27:42 UTC (rev 5504) @@ -16,6 +16,7 @@ org/python/core/PyFloat.class org/python/core/PyFrozenSet.class org/python/core/PyFunction.class +org/python/core/PyGenerator.class org/python/core/PyInteger.class org/python/core/PyList.class org/python/core/PyLong.class Modified: trunk/jython/src/org/python/core/PyBuiltinCallable.java =================================================================== --- trunk/jython/src/org/python/core/PyBuiltinCallable.java 2008-10-22 04:53:59 UTC (rev 5503) +++ trunk/jython/src/org/python/core/PyBuiltinCallable.java 2008-10-22 08:27:42 UTC (rev 5504) @@ -9,6 +9,8 @@ protected Info info; + protected String doc; + protected PyBuiltinCallable(PyType type, Info info) { super(type); this.info = info; @@ -29,8 +31,8 @@ } @ExposedGet(name = "__doc__") - public PyObject fastGetDoc() { - return Py.None; + public String fastGetDoc() { + return doc; } @ExposedGet(name = "__module__") Modified: trunk/jython/src/org/python/core/PyBuiltinFunction.java =================================================================== --- trunk/jython/src/org/python/core/PyBuiltinFunction.java 2008-10-22 04:53:59 UTC (rev 5503) +++ trunk/jython/src/org/python/core/PyBuiltinFunction.java 2008-10-22 08:27:42 UTC (rev 5504) @@ -4,21 +4,15 @@ public class PyBuiltinFunction extends PyBuiltinCallable implements ExposeAsSuperclass { - private PyString doc; - protected PyBuiltinFunction(String name, String doc) { this(name, -1, -1, doc); } protected PyBuiltinFunction(String name, int minargs, int maxargs, String doc) { super(new DefaultInfo(name, minargs, maxargs)); - this.doc = doc == null ? null : Py.newString(doc); + this.doc = doc == null ? null : doc; } - public PyObject fastGetDoc() { - return doc; - } - public boolean isMappingType() { return false; } Modified: trunk/jython/src/org/python/core/PyGenerator.java =================================================================== --- trunk/jython/src/org/python/core/PyGenerator.java 2008-10-22 04:53:59 UTC (rev 5503) +++ trunk/jython/src/org/python/core/PyGenerator.java 2008-10-22 08:27:42 UTC (rev 5504) @@ -1,39 +1,33 @@ -// Copyright 2002 Finn Bock - package org.python.core; +import org.python.expose.ExposedGet; +import org.python.expose.ExposedMethod; +import org.python.expose.ExposedType; + +@ExposedType(name="generator", base=PyObject.class) public class PyGenerator extends PyIterator { - public PyFrame gi_frame; - PyObject closure; - public boolean gi_running; + + @ExposedGet + protected PyFrame gi_frame; + + @ExposedGet + protected boolean gi_running; + private PyException generatorExit; + private PyObject closure; + public PyGenerator(PyFrame frame, PyObject closure) { - this.gi_frame = frame; + gi_frame = frame; this.closure = closure; - this.gi_running = false; - // Create an exception instance while we have a frame to create it from. - // When the GC runs it doesn't have any associated thread state. - // this is necessary for finalize calling close on the generator - this.generatorExit = Py.makeException(Py.GeneratorExit); - } - private static final String[] __members__ = { - "close", "gi_frame", "gi_running", "next", "send", "throw" - }; - - public PyObject __dir__() { - PyString members[] = new PyString[__members__.length]; - for (int i = 0; i < __members__.length; i++) - members[i] = new PyString(__members__[i]); - PyList ret = new PyList(members); - PyDictionary accum = new PyDictionary(); - addKeys(accum, "__dict__"); - ret.extend(accum.keys()); - ret.sort(); - return ret; + // Create an exception instance while we have a frame to create it from. When the GC runs it + // doesn't have any associated thread state. this is necessary for finalize calling close on + // the generator + generatorExit = Py.makeException(Py.GeneratorExit); } + @ExposedMethod public PyObject send(PyObject value) { if (gi_frame == null) { throw Py.StopIteration(""); @@ -45,26 +39,12 @@ return next(); } - private PyObject raiseException(PyException ex) { - if (gi_frame == null || gi_frame.f_lasti == 0) { - throw ex; - } - gi_frame.setGeneratorInput(ex); - return next(); - } - - public PyObject throw$(PyObject type) { - return raiseException(Py.makeException(type)); - } - - public PyObject throw$(PyObject type, PyObject value) { - return raiseException(Py.makeException(type, value)); - } - + @ExposedMethod(names="throw", defaults={"null", "null"}) public PyObject throw$(PyObject type, PyObject value, PyTraceback tb) { return raiseException(Py.makeException(type, value, tb)); } + @ExposedMethod public PyObject close() { try { raiseException(generatorExit); @@ -77,25 +57,43 @@ return Py.None; } + @Override + @ExposedMethod(doc="x.next() -> the next value, or raise StopIteration") + public PyObject next() { + return super.next(); + } + + @Override + @ExposedMethod + public PyObject __iter__() { + return this; + } + + private PyObject raiseException(PyException ex) { + if (gi_frame == null || gi_frame.f_lasti == 0) { + throw ex; + } + gi_frame.setGeneratorInput(ex); + return next(); + } + + @Override protected void finalize() throws Throwable { - if (gi_frame == null || gi_frame.f_lasti == -1) + if (gi_frame == null || gi_frame.f_lasti == -1) return; try { close(); } catch (PyException e) { // PEP 342 specifies that if an exception is raised by close, - // we output to stderr and then forget about it; + // we output to stderr and then forget about it; String className = PyException.exceptionClassName(e.type); int lastDot = className.lastIndexOf('.'); if (lastDot != -1) { className = className.substring(lastDot + 1); } - PyString m = Py.newString( - String.format("Exception %s: %s in %s", - className, - e.value.__repr__().toString(), - this.__repr__().toString())); - Py.println(Py.getSystemState().stderr, m); + String msg = String.format("Exception %s: %s in %s", className, e.value.__repr__() + .toString(), __repr__().toString()); + Py.println(Py.getSystemState().stderr, Py.newString(msg)); } catch (Throwable e) { // but we currently ignore any Java exception completely. perhaps we // can also output something meaningful too? @@ -110,7 +108,7 @@ if (gi_frame == null) { return null; } - + if (gi_frame.f_lasti == -1) { gi_frame = null; return null; Modified: trunk/jython/src/org/python/core/PyIterator.java =================================================================== --- trunk/jython/src/org/python/core/PyIterator.java 2008-10-22 04:53:59 UTC (rev 5503) +++ trunk/jython/src/org/python/core/PyIterator.java 2008-10-22 08:27:42 UTC (rev 5504) @@ -28,9 +28,8 @@ return this; } - public static PyString __doc__next = new PyString( - "x.next() -> the next value, or raise StopIteration" - ); + public static PyString __doc__next = + new PyString("x.next() -> the next value, or raise StopIteration"); /** * The exposed next method. Modified: trunk/jython/src/org/python/core/PyObject.java =================================================================== --- trunk/jython/src/org/python/core/PyObject.java 2008-10-22 04:53:59 UTC (rev 5503) +++ trunk/jython/src/org/python/core/PyObject.java 2008-10-22 08:27:42 UTC (rev 5504) @@ -3539,7 +3539,9 @@ } public void __set__(PyObject obj, PyObject value) { - throw Py.AttributeError("object internal __set__ impl is abstract"); + if (!_doset(obj, value)) { + throw Py.AttributeError("object internal __set__ impl is abstract"); + } } public void __delete__(PyObject obj) { Modified: trunk/jython/src/org/python/expose/ExposedMethod.java =================================================================== --- trunk/jython/src/org/python/expose/ExposedMethod.java 2008-10-22 04:53:59 UTC (rev 5503) +++ trunk/jython/src/org/python/expose/ExposedMethod.java 2008-10-22 08:27:42 UTC (rev 5504) @@ -7,24 +7,29 @@ /** * Indicates a method should be exposed to Python code. - * + * */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface ExposedMethod { /** - * @return the names to expose this method as. Defaults to just actual name of the method. + * Returns the names to expose this method as. Defaults to the name of the method. */ String[] names() default {}; /** - * @return default arguments. Starts at the number of arguments - defaults.length. + * Returns default arguments. Starts at the number of arguments - defaults.length. */ String[] defaults() default {}; /** - * @return - how to expose this method. See {@link MethodType} for the options. + * Returns how to expose this method. See {@link MethodType} for the options. */ MethodType type() default MethodType.DEFAULT; -} + + /** + * Returns the __doc__ String for this method. + */ + String doc() default ""; +} \ No newline at end of file Modified: trunk/jython/src/org/python/expose/generate/ClassMethodExposer.java =================================================================== --- trunk/jython/src/org/python/expose/generate/ClassMethodExposer.java 2008-10-22 04:53:59 UTC (rev 5503) +++ trunk/jython/src/org/python/expose/generate/ClassMethodExposer.java 2008-10-22 08:27:42 UTC (rev 5504) @@ -2,7 +2,6 @@ import org.python.objectweb.asm.Type; import org.python.core.PyBuiltinClassMethodNarrow; -import org.python.core.PyBuiltinMethodNarrow; public class ClassMethodExposer extends MethodExposer { @@ -14,7 +13,8 @@ String desc, String typeName, String[] asNames, - String[] defaults) { + String[] defaults, + String doc) { super(onType, methodName, getArgs(onType, methodName, desc), @@ -22,7 +22,8 @@ typeName, asNames, defaults, - PyBuiltinClassMethodNarrow.class); + PyBuiltinClassMethodNarrow.class, + doc); actualArgs = Type.getArgumentTypes(desc); } Modified: trunk/jython/src/org/python/expose/generate/ExposedMethodFinder.java =================================================================== --- trunk/jython/src/org/python/expose/generate/ExposedMethodFinder.java 2008-10-22 04:53:59 UTC (rev 5503) +++ trunk/jython/src/org/python/expose/generate/ExposedMethodFinder.java 2008-10-22 08:27:42 UTC (rev 5504) @@ -137,6 +137,15 @@ class ExposedMethodVisitor extends RestrictiveAnnotationVisitor { @Override + public void visit(String name, Object value) { + if (name.equals("doc")) { + doc = (String)value; + } else { + super.visit(name, value); + } + } + + @Override public AnnotationVisitor visitArray(String name) { if(name.equals("names")) { return new StringArrayBuilder() { @@ -173,6 +182,8 @@ private String[] defaults = new String[0]; private MethodType type = MethodType.DEFAULT; + + private String doc = ""; } @Override @@ -185,7 +196,8 @@ typeName, methVisitor.names, methVisitor.defaults, - methVisitor.type)); + methVisitor.type, + methVisitor.doc)); } if(newExp != null) { handleNewExposer(newExp); @@ -197,7 +209,8 @@ methodDesc, typeName, classMethVisitor.names, - classMethVisitor.defaults)); + classMethVisitor.defaults, + classMethVisitor.doc)); } super.visitEnd(); } Modified: trunk/jython/src/org/python/expose/generate/InstanceMethodExposer.java =================================================================== --- trunk/jython/src/org/python/expose/generate/InstanceMethodExposer.java 2008-10-22 04:53:59 UTC (rev 5503) +++ trunk/jython/src/org/python/expose/generate/InstanceMethodExposer.java 2008-10-22 08:27:42 UTC (rev 5504) @@ -27,7 +27,8 @@ typeName, new String[0], new String[0], - MethodType.DEFAULT); + MethodType.DEFAULT, + null); } public InstanceMethodExposer(Type onType, @@ -37,7 +38,8 @@ String typeName, String[] asNames, String[] defaults, - MethodType type) { + MethodType type, + String doc) { super(onType, methodName, Type.getArgumentTypes(desc), @@ -45,7 +47,8 @@ typeName, asNames, defaults, - isWide(desc) ? PyBuiltinMethod.class : PyBuiltinMethodNarrow.class); + isWide(desc) ? PyBuiltinMethod.class : PyBuiltinMethodNarrow.class, + doc); if ((access & ACC_STATIC) != 0) { throwInvalid("@ExposedMethod can't be applied to static methods"); } Modified: trunk/jython/src/org/python/expose/generate/MethodExposer.java =================================================================== --- trunk/jython/src/org/python/expose/generate/MethodExposer.java 2008-10-22 04:53:59 UTC (rev 5503) +++ trunk/jython/src/org/python/expose/generate/MethodExposer.java 2008-10-22 08:27:42 UTC (rev 5504) @@ -1,12 +1,11 @@ package org.python.expose.generate; import org.python.objectweb.asm.Type; -import org.python.expose.MethodType; public abstract class MethodExposer extends Exposer { protected String[] defaults; - + protected final String[] asNames; protected final String prefix, typeName; @@ -17,6 +16,8 @@ protected final Type onType, returnType; + protected final String doc; + public MethodExposer(Type onType, String methodName, Type[] args, @@ -24,12 +25,14 @@ String typeName, String[] asNames, String[] defaults, - Class superClass) { + Class superClass, + String doc) { super(superClass, onType.getClassName() + "$" + methodName + "_exposer"); this.onType = onType; this.methodName = methodName; this.args = args; this.typeName = typeName; + this.doc = doc; String prefix = typeName; int lastDot = prefix.lastIndexOf('.'); if (lastDot != -1) { @@ -64,7 +67,7 @@ } return asNames; } - + protected void generate() { generateNamedConstructor(); generateFullConstructor(); @@ -85,6 +88,12 @@ mv.visitVarInsn(ALOAD, 2); mv.visitVarInsn(ALOAD, 3); superConstructor(PYTYPE, PYOBJ, BUILTIN_INFO); + mv.visitVarInsn(ALOAD, 0); + mv.visitLdcInsn(doc); + mv.visitFieldInsn(PUTFIELD, + BUILTIN_FUNCTION.getInternalName(), + "doc", + STRING.getDescriptor()); endConstructor(); } @@ -99,6 +108,12 @@ mv.visitLdcInsn(args.length + 1); superConstructor(STRING, INT, INT); } + mv.visitVarInsn(ALOAD, 0); + mv.visitLdcInsn(doc); + mv.visitFieldInsn(PUTFIELD, + BUILTIN_FUNCTION.getInternalName(), + "doc", + STRING.getDescriptor()); endConstructor(); } @@ -126,7 +141,7 @@ toPy(returnType); endMethod(ARETURN); } - + private boolean hasDefault(int argIndex) { return defaults.length - args.length + argIndex >= 0; } Modified: trunk/jython/tests/java/org/python/expose/generate/MethodExposerTest.java =================================================================== --- trunk/jython/tests/java/org/python/expose/generate/MethodExposerTest.java 2008-10-22 04:53:59 UTC (rev 5503) +++ trunk/jython/tests/java/org/python/expose/generate/MethodExposerTest.java 2008-10-22 08:27:42 UTC (rev 5504) @@ -6,7 +6,6 @@ import org.python.core.Py; import org.python.core.PyBuiltinCallable; import org.python.core.PyException; -import org.python.core.PyObject; import org.python.expose.MethodType; public class MethodExposerTest extends InterpTestCase implements Opcodes, PyTypes { @@ -167,7 +166,8 @@ "simpleexposed", new String[0], new String[] {"X"}, - MethodType.DEFAULT); + MethodType.DEFAULT, + ""); fail("Shouldn't be able to create the exposer with a default value"); } catch (InvalidExposingException ite) {} } @@ -197,7 +197,8 @@ new Type[] {PYTYPE}), "simpleexposed", new String[0], - new String[0]); + new String[0], + ""); PyBuiltinCallable bound = createBound(exp); assertEquals("a", bound.__call__().toString()); } @@ -212,7 +213,8 @@ PYOBJ}), "simpleexposed", new String[0], - new String[] {"null", "Py.None"}); + new String[] {"null", "Py.None"}, + ""); PyBuiltinCallable bound = createBound(exp); assertEquals(0, bound.__call__().asInt()); assertEquals(1, bound.__call__(Py.newString("hello")).asInt()); This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <cg...@us...> - 2008-10-22 04:54:08
|
Revision: 5503 http://jython.svn.sourceforge.net/jython/?rev=5503&view=rev Author: cgroves Date: 2008-10-22 04:53:59 +0000 (Wed, 22 Oct 2008) Log Message: ----------- Split Java-wrapping PyType creation out into its own subclass, PyJavaType. Modified Paths: -------------- trunk/jython/src/org/python/core/PyType.java Added Paths: ----------- trunk/jython/src/org/python/core/PyJavaType.java Added: trunk/jython/src/org/python/core/PyJavaType.java =================================================================== --- trunk/jython/src/org/python/core/PyJavaType.java (rev 0) +++ trunk/jython/src/org/python/core/PyJavaType.java 2008-10-22 04:53:59 UTC (rev 5503) @@ -0,0 +1,189 @@ +package org.python.core; + +import java.lang.reflect.Constructor; +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; +import java.util.HashMap; +import java.util.Map; + +import org.python.core.util.StringUtil; +import org.python.expose.ExposeAsSuperclass; + +public class PyJavaType extends PyType implements ExposeAsSuperclass { + + private final static Class<?>[] OO = {PyObject.class, PyObject.class}; + + public PyJavaType() { + super(TYPE == null ? fromClass(PyType.class) : TYPE); + } + + @Override + protected void fillDict(Class<?> base) { + dict = new PyStringMap(); + Map<String, Object> propnames = new HashMap<String, Object>(); + Method[] methods = underlying_class.getMethods(); + for (Method meth : methods) { + Class<?> declaring = meth.getDeclaringClass(); + if (declaring != base && base.isAssignableFrom(declaring) && !ignore(meth)) { + String methname = meth.getName(); + String nmethname = normalize_name(methname); + PyReflectedFunction reflfunc = (PyReflectedFunction)dict.__finditem__(nmethname); + boolean added = false; + if (reflfunc == null) { + dict.__setitem__(nmethname, new PyReflectedFunction(meth)); + added = true; + } else { + reflfunc.addMethod(meth); + added = true; + } + if (added && !Modifier.isStatic(meth.getModifiers())) { + // check for xxxX.* + int n = meth.getParameterTypes().length; + if (methname.startsWith("get") && n == 0) { + propnames.put(methname.substring(3), "getter"); + } else if (methname.startsWith("is") && n == 0 + && meth.getReturnType() == Boolean.TYPE) { + propnames.put(methname.substring(2), "getter"); + } else if (methname.startsWith("set") && n == 1) { + propnames.put(methname.substring(3), meth); + } + } + } + } + for (Method meth : methods) { + String nmethname = normalize_name(meth.getName()); + PyReflectedFunction reflfunc = (PyReflectedFunction)dict.__finditem__(nmethname); + if (reflfunc != null) { + reflfunc.addMethod(meth); + } + } + Field[] fields = underlying_class.getFields(); + for (Field field : fields) { + Class<?> declaring = field.getDeclaringClass(); + if (declaring != base && base.isAssignableFrom(declaring)) { + String fldname = field.getName(); + int fldmods = field.getModifiers(); + Class<?> fldtype = field.getType(); + if (Modifier.isStatic(fldmods)) { + if (fldname.startsWith("__doc__") && fldname.length() > 7 + && fldtype == PyString.class) { + String fname = fldname.substring(7).intern(); + PyObject memb = dict.__finditem__(fname); + if (memb != null && memb instanceof PyReflectedFunction) { + PyString doc = null; + try { + doc = (PyString)field.get(null); + } catch (IllegalAccessException e) { + throw error(e); + } + ((PyReflectedFunction)memb).__doc__ = doc; + } + } + } + dict.__setitem__(normalize_name(fldname), new PyReflectedField(field)); + } + } + for (String propname : propnames.keySet()) { + String npropname = normalize_name(StringUtil.decapitalize(propname)); + PyObject prev = dict.__finditem__(npropname); + if (prev != null && prev instanceof PyReflectedFunction) { + continue; + } + Method getter = null; + Method setter = null; + Class<?> proptype = null; + getter = get_non_static_method(underlying_class, "get" + propname); + if (getter == null) + getter = get_non_static_method(underlying_class, "is" + propname); + if (getter != null) { + proptype = getter.getReturnType(); + setter = get_non_static_method(underlying_class, "set" + propname, proptype); + } else { + Object o = propnames.get(propname); + if (o instanceof Method) { + setter = (Method)o; + proptype = setter.getParameterTypes()[0]; + } + } + if (setter != null || getter != null) { + dict.__setitem__(npropname, new PyBeanProperty(npropname, proptype, getter, setter)); + } else { + // XXX error + } + } + Constructor<?>[] ctrs = underlying_class.getConstructors(); + if (ctrs.length != 0) { + final PyReflectedConstructor reflctr = new PyReflectedConstructor("_new_impl"); + for (Constructor<?> ctr : ctrs) { + reflctr.addConstructor(ctr); + } + PyObject new_ = new PyNewWrapper(underlying_class, "__new__", -1, -1) { + + public PyObject new_impl(boolean init, + PyType subtype, + PyObject[] args, + String[] keywords) { + return reflctr.make(args, keywords); + } + }; + dict.__setitem__("__new__", new_); + } + if (ClassDictInit.class.isAssignableFrom(underlying_class) + && underlying_class != ClassDictInit.class) { + try { + Method m = underlying_class.getMethod("classDictInit", PyObject.class); + m.invoke(null, dict); + } catch (Exception exc) { + throw error(exc); + } + } + if (base != Object.class) { + has_set = get_descr_method(underlying_class, "__set__", OO) != null + || get_descr_method(underlying_class, "_doset", OO) != null; + has_delete = get_descr_method(underlying_class, "__delete__", PyObject.class) != null + || get_descr_method(underlying_class, "_dodel", PyObject.class) != null; + } + } + + private static String normalize_name(String name) { + if (name.endsWith("$")) { + name = name.substring(0, name.length() - 1); + } + return name.intern(); + } + + private static Method get_non_static_method(Class<?> c, String name, Class<?>... parmtypes) { + try { + Method meth = c.getMethod(name, parmtypes); + if (!Modifier.isStatic(meth.getModifiers())) { + return meth; + } + } catch (NoSuchMethodException e) { + // ok + } + return null; + } + + private static Method get_descr_method(Class<?> c, String name, Class<?>... parmtypes) { + Method meth = get_non_static_method(c, name, parmtypes); + if (meth != null && meth.getDeclaringClass() != PyObject.class) { + return meth; + } + return null; + } + + private static boolean ignore(Method meth) { + Class<?>[] exceptions = meth.getExceptionTypes(); + for (Class<?> exception : exceptions) { + if (exception == PyIgnoreMethodTag.class) { + return true; + } + } + return false; + } + + private static PyException error(Exception e) { + return Py.JavaError(e); + } +} Modified: trunk/jython/src/org/python/core/PyType.java =================================================================== --- trunk/jython/src/org/python/core/PyType.java 2008-10-21 22:36:57 UTC (rev 5502) +++ trunk/jython/src/org/python/core/PyType.java 2008-10-22 04:53:59 UTC (rev 5503) @@ -4,18 +4,11 @@ import java.lang.ref.Reference; import java.lang.ref.ReferenceQueue; import java.lang.ref.WeakReference; -import java.lang.reflect.Constructor; -import java.lang.reflect.Field; -import java.lang.reflect.Method; -import java.lang.reflect.Modifier; -import java.util.HashMap; -import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; -import org.python.core.util.StringUtil; import org.python.expose.ExposeAsSuperclass; import org.python.expose.ExposedDelete; import org.python.expose.ExposedGet; @@ -34,44 +27,42 @@ public static PyType TYPE = fromClass(PyType.class); - /** The type's name. builtin types include their fully qualified - * name, e.g.: time.struct_time. */ - private String name; + /** The type's name. builtin types include their fully qualified name, e.g.: time.struct_time. */ + protected String name; /** __base__, the direct base type or null. */ - private PyType base; + protected PyType base; /** __bases__, the base classes. */ - private PyObject[] bases = new PyObject[0]; + protected PyObject[] bases = new PyObject[0]; /** The real, internal __dict__. */ - private PyObject dict; + protected PyObject dict; /** __mro__, the method resolution. order */ - private PyObject[] mro = null; + protected PyObject[] mro; /** __flags__, the type's options. */ private long tp_flags; /** The underlying java class or null. */ - private Class<?> underlying_class; + protected Class<?> underlying_class; /** Whether it's a builtin type. */ - boolean builtin = false; + protected boolean builtin; /** Whether new instances of this type can be instantiated */ - private boolean non_instantiable = false; + protected boolean instantiable = true; /** Whether this type has set/delete descriptors */ boolean has_set; boolean has_delete; - /** Whether finalization is required for this type's instances - * (implements __del__). */ + /** Whether finalization is required for this type's instances (implements __del__). */ private boolean needs_finalizer; /** Whether this type's instances require a __dict__. */ - private boolean needs_userdict = false; + protected boolean needs_userdict; /** The number of __slots__ defined. */ private int numSlots; @@ -79,15 +70,17 @@ private ReferenceQueue<PyType> subclasses_refq = new ReferenceQueue<PyType>(); private Set<WeakReference<PyType>> subclasses = Generic.set(); - private final static Class<?>[] O = {PyObject.class}; - private final static Class<?>[] OO = {PyObject.class, PyObject.class}; - /** Mapping of Java classes to their PyTypes. */ private static Map<Class<?>, PyType> class_to_type; /** Mapping of Java classes to their TypeBuilders. */ private static Map<Class<?>, TypeBuilder> classToBuilder; + protected PyType(PyType subtype) { + super(subtype); + } + + private PyType() {} /** @@ -98,10 +91,6 @@ super(ignored); } - PyType(PyType subtype) { - super(subtype); - } - @ExposedNew public static PyObject type___new__(PyNewWrapper new_, boolean init, PyType subtype, PyObject[] args, String[] keywords) { @@ -260,8 +249,7 @@ }); } - newtype.has_set = newtype.lookup("__set__") != null; - newtype.has_delete = newtype.lookup("__delete__") != null; + newtype.fillHasSetAndDelete(); newtype.needs_finalizer = newtype.lookup("__del__") != null; for (PyObject cur : bases_list) { @@ -291,170 +279,18 @@ return newobj; } - private static void fillFromClass(PyType newtype, String name, Class<?> c, Class<?> base, - TypeBuilder tb) { - if (base == null) { - base = c.getSuperclass(); + protected void fillDict(Class<?> base) { + if (Py.BOOTSTRAP_TYPES.contains(underlying_class)) { + return; } - if (name == null) { - name = c.getName(); - // Strip the java fully qualified class name (specifically - // remove org.python.core.Py or fallback to stripping to - // the last dot) - if (name.startsWith("org.python.core.Py")) { - name = name.substring("org.python.core.Py".length()).toLowerCase(); - } else { - int lastDot = name.lastIndexOf('.'); - if (lastDot != -1) { - name = name.substring(lastDot + 1); - } - } - } - newtype.name = name; - newtype.underlying_class = c; - newtype.builtin = true; - // basic mro, base, bases - fillInMRO(newtype, base); - PyObject dict; - if (tb != null) { - dict = tb.getDict(newtype); - newtype.non_instantiable = dict.__finditem__("__new__") == null; - } else { - dict = new PyStringMap(); - fillInClassic(c, base, dict); - } - if (base != Object.class) { - if (get_descr_method(c, "__set__", OO) != null || /* backw comp */ - get_descr_method(c, "_doset", OO) != null) { - newtype.has_set = true; - } - if (get_descr_method(c, "__delete__", O) != null || /* backw comp */ - get_descr_method(c, "_dodel", O) != null) { - newtype.has_delete = true; - } - } - newtype.dict = dict; + dict = classToBuilder.get(underlying_class).getDict(this); + instantiable = dict.__finditem__("__new__") != null; + fillHasSetAndDelete(); } - private static void fillInClassic(Class<?> c, Class<?> base, PyObject dict) { - if (Py.BOOTSTRAP_TYPES.contains(c)) { - // BOOTSTRAP_TYPES will be filled in by addBuilder later - return; - } - Map<String, Object> propnames = new HashMap<String, Object>(); - Method[] methods = c.getMethods(); - for (Method meth : methods) { - Class<?> declaring = meth.getDeclaringClass(); - if (declaring != base && base.isAssignableFrom(declaring) && !ignore(meth)) { - String methname = meth.getName(); - String nmethname = normalize_name(methname); - PyReflectedFunction reflfunc = (PyReflectedFunction)dict.__finditem__(nmethname); - boolean added = false; - if (reflfunc == null) { - dict.__setitem__(nmethname, new PyReflectedFunction(meth)); - added = true; - } else { - reflfunc.addMethod(meth); - added = true; - } - if (added && !Modifier.isStatic(meth.getModifiers())) { - // check for xxxX.* - int n = meth.getParameterTypes().length; - if (methname.startsWith("get") && n == 0) { - propnames.put(methname.substring(3), "getter"); - } else if (methname.startsWith("is") && n == 0 - && meth.getReturnType() == Boolean.TYPE) { - propnames.put(methname.substring(2), "getter"); - } else if (methname.startsWith("set") && n == 1) { - propnames.put(methname.substring(3), meth); - } - } - } - } - for (Method meth : methods) { - String nmethname = normalize_name(meth.getName()); - PyReflectedFunction reflfunc = (PyReflectedFunction)dict.__finditem__(nmethname); - if (reflfunc != null) { - reflfunc.addMethod(meth); - } - } - Field[] fields = c.getFields(); - for (Field field : fields) { - Class<?> declaring = field.getDeclaringClass(); - if (declaring != base && base.isAssignableFrom(declaring)) { - String fldname = field.getName(); - int fldmods = field.getModifiers(); - Class<?> fldtype = field.getType(); - if (Modifier.isStatic(fldmods)) { - if (fldname.startsWith("__doc__") && fldname.length() > 7 - && fldtype == PyString.class) { - String fname = fldname.substring(7).intern(); - PyObject memb = dict.__finditem__(fname); - if (memb != null && memb instanceof PyReflectedFunction) { - PyString doc = null; - try { - doc = (PyString)field.get(null); - } catch (IllegalAccessException e) { - throw error(e); - } - ((PyReflectedFunction)memb).__doc__ = doc; - } - } - } - dict.__setitem__(normalize_name(fldname), new PyReflectedField(field)); - } - } - for (String propname : propnames.keySet()) { - String npropname = normalize_name(StringUtil.decapitalize(propname)); - PyObject prev = dict.__finditem__(npropname); - if (prev != null && prev instanceof PyReflectedFunction) { - continue; - } - Method getter = null; - Method setter = null; - Class<?> proptype = null; - getter = get_non_static_method(c, "get" + propname, new Class[] {}); - if (getter == null) - getter = get_non_static_method(c, "is" + propname, new Class[] {}); - if (getter != null) { - proptype = getter.getReturnType(); - setter = get_non_static_method(c, "set" + propname, new Class[] {proptype}); - } else { - Object o = propnames.get(propname); - if (o instanceof Method) { - setter = (Method)o; - proptype = setter.getParameterTypes()[0]; - } - } - if (setter != null || getter != null) { - dict.__setitem__(npropname, new PyBeanProperty(npropname, proptype, getter, - setter)); - } else { - // XXX error - } - } - Constructor<?>[] ctrs = c.getConstructors(); - if (ctrs.length != 0) { - final PyReflectedConstructor reflctr = new PyReflectedConstructor("_new_impl"); - for (Constructor<?> ctr : ctrs) { - reflctr.addConstructor(ctr); - } - PyObject new_ = new PyNewWrapper(c, "__new__", -1, -1) { - public PyObject new_impl(boolean init, PyType subtype, PyObject[] args, - String[] keywords) { - return reflctr.make(args, keywords); - } - }; - dict.__setitem__("__new__", new_); - } - if (ClassDictInit.class.isAssignableFrom(c) && c != ClassDictInit.class) { - try { - Method m = c.getMethod("classDictInit", PyObject.class); - m.invoke(null, dict); - } catch (Exception exc) { - throw error(exc); - } - } + private void fillHasSetAndDelete() { + has_set = lookup("__set__") != null; + has_delete = lookup("__delete__") != null; } private static void fillInMRO(PyType type, Class<?> base) { @@ -481,8 +317,8 @@ } /** - * Ensures that the physical layout between this type and - * <code>other</code> are compatible. Raises a TypeError if not. + * Ensures that the physical layout between this type and <code>other</code> are compatible. + * Raises a TypeError if not. */ public void compatibleForAssignment(PyType other, String attribute) { if (!getLayout().equals(other.getLayout()) || needs_userdict != other.needs_userdict @@ -493,8 +329,8 @@ } /** - * Gets the most parent PyType that determines the layout of this type ie - * has slots or an underlying_class. Can by this PyType. + * Gets the most parent PyType that determines the layout of this type, ie it has slots or an + * underlying_class. Can be this PyType. */ private PyType getLayout() { if (underlying_class != null) { @@ -609,10 +445,9 @@ } /** - * Collects the subclasses and current mro of this type in mroCollector. If - * this type has subclasses C and D, and D has a subclass E current - * mroCollector will equal [C, C.__mro__, D, D.__mro__, E, E.__mro__] after - * this call. + * Collects the subclasses and current mro of this type in mroCollector. If this type has + * subclasses C and D, and D has a subclass E current mroCollector will equal [C, C.__mro__, D, + * D.__mro__, E, E.__mro__] after this call. */ private void mro_subclasses(List<Object> mroCollector) { for (WeakReference<PyType> ref : subclasses) { @@ -924,7 +759,6 @@ } public boolean isSubType(PyType supertype) { - PyObject[] mro = this.mro; if (mro != null) { for (PyObject base : mro) { if (base == supertype) { @@ -1008,47 +842,6 @@ return null; } - private static String normalize_name(String name) { - if (name.endsWith("$")) { - name = name.substring(0, name.length() - 1); - } - return name.intern(); - } - - private static PyException error(Exception e) { - return Py.JavaError(e); - } - - private static Method get_non_static_method(Class<?> c, String name, Class<?>[] parmtypes) { - try { - Method meth = c.getMethod(name, parmtypes); - if (!Modifier.isStatic(meth.getModifiers())) { - return meth; - } - } catch (NoSuchMethodException e) { - // ok - } - return null; - } - - private static Method get_descr_method(Class<?> c, String name, Class<?>[] parmtypes) { - Method meth = get_non_static_method(c, name, parmtypes); - if (meth != null && meth.getDeclaringClass() != PyObject.class) { - return meth; - } - return null; - } - - private static boolean ignore(Method meth) { - Class<?>[] exceptions = meth.getExceptionTypes(); - for (Class<?> exception : exceptions) { - if (exception == PyIgnoreMethodTag.class) { - return true; - } - } - return false; - } - public static void addBuilder(Class<?> forClass, TypeBuilder builder) { if (classToBuilder == null) { classToBuilder = Generic.map(); @@ -1070,7 +863,7 @@ base = forClass.getSuperclass(); } fillInMRO(objType, base); - objType.non_instantiable = objType.dict.__finditem__("__new__") == null; + objType.instantiable = objType.dict.__finditem__("__new__") != null; } } @@ -1082,19 +875,55 @@ } Class<?> base = null; String name = null; - TypeBuilder tb = classToBuilder == null ? null : classToBuilder.get(c); + TypeBuilder tb = getBuilder(c); if (tb != null) { name = tb.getName(); if (!tb.getBase().equals(Object.class)) { base = tb.getBase(); } } - PyType newtype = class_to_type.get(c); - if (newtype == null) { - newtype = c == PyType.class ? new PyType(false) : new PyType(); - class_to_type.put(c, newtype); - fillFromClass(newtype, name, c, base, tb); + PyType type = class_to_type.get(c); + if (type == null) { + type = createType(c, base, name); } + return type; + } + + private static TypeBuilder getBuilder(Class<?> c) { + return classToBuilder == null ? null : classToBuilder.get(c); + } + + private static PyType createType(Class<?> c, Class<?> base, String name) { + PyType newtype; + if (c == PyType.class) { + newtype = new PyType(false); + } else if (Py.BOOTSTRAP_TYPES.contains(c) || getBuilder(c) != null) { + newtype = new PyType(); + } else { + newtype = new PyJavaType(); + } + class_to_type.put(c, newtype); + if (base == null) { + base = c.getSuperclass(); + } + if (name == null) { + name = c.getName(); + // Strip the java fully qualified class name (specifically remove org.python.core.Py or + // fallback to stripping to the last dot) + if (name.startsWith("org.python.core.Py")) { + name = name.substring("org.python.core.Py".length()).toLowerCase(); + } else { + int lastDot = name.lastIndexOf('.'); + if (lastDot != -1) { + name = name.substring(lastDot + 1); + } + } + } + newtype.name = name; + newtype.underlying_class = c; + newtype.builtin = true; + fillInMRO(newtype, base); // basic mro, base, bases + newtype.fillDict(base); return newtype; } @@ -1244,7 +1073,7 @@ @ExposedMethod final PyObject type___call__(PyObject[] args, String[] keywords) { PyObject new_ = lookup("__new__"); - if (non_instantiable || new_ == null) { + if (!instantiable || new_ == null) { throw Py.TypeError("cannot create '" + name + "' instances"); } return invoke_new_(new_, this, true, args, keywords); @@ -1426,8 +1255,8 @@ return methodname; } - private Object writeReplace() { - // XXX: needed? + /** Used when serializing this type. */ + protected Object writeReplace() { return new TypeResolver(underlying_class, getModule().toString(), name); } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <otm...@us...> - 2008-10-21 22:37:04
|
Revision: 5502 http://jython.svn.sourceforge.net/jython/?rev=5502&view=rev Author: otmarhumbel Date: 2008-10-21 22:36:57 +0000 (Tue, 21 Oct 2008) Log Message: ----------- auto switch to console mode if running on GNU java this partly fixes issue #1135 Modified Paths: -------------- trunk/installer/src/java/org/python/util/install/Installation.java trunk/installer/src/java/org/python/util/install/InstallerCommandLine.java trunk/installer/test/java/org/python/util/install/InstallationTest.java trunk/installer/test/java/org/python/util/install/InstallerCommandLineTest.java Modified: trunk/installer/src/java/org/python/util/install/Installation.java =================================================================== --- trunk/installer/src/java/org/python/util/install/Installation.java 2008-10-21 21:59:40 UTC (rev 5501) +++ trunk/installer/src/java/org/python/util/install/Installation.java 2008-10-21 22:36:57 UTC (rev 5502) @@ -23,6 +23,7 @@ protected static final String OS_NAME = "os.name"; protected static final String OS_VERSION = "os.version"; + protected static final String JAVA_VM_NAME = "java.vm.name"; protected static final String EMPTY = ""; protected static final String HEADLESS_PROPERTY_NAME = "java.awt.headless"; @@ -126,6 +127,16 @@ return isMacintosh; } + protected static boolean isGNUJava() { + boolean isGNUJava = false; + String javaVmName = System.getProperty(JAVA_VM_NAME, ""); + String lowerVmName = javaVmName.toLowerCase(); + if (lowerVmName.indexOf("gnu") >= 0 && lowerVmName.indexOf("libgcj") >= 0) { + isGNUJava = true; + } + return isGNUJava; + } + protected static boolean isJDK141() { boolean isJDK141 = false; String javaVersion = System.getProperty(JavaVersionTester.JAVA_VERSION, ""); Modified: trunk/installer/src/java/org/python/util/install/InstallerCommandLine.java =================================================================== --- trunk/installer/src/java/org/python/util/install/InstallerCommandLine.java 2008-10-21 21:59:40 UTC (rev 5501) +++ trunk/installer/src/java/org/python/util/install/InstallerCommandLine.java 2008-10-21 22:36:57 UTC (rev 5502) @@ -171,16 +171,17 @@ */ public boolean setArgs(String args[]) { _args = args; - if (!hasConsoleOptionInArgs(args) && !hasSilentOptionInArgs(args) - && !Installation.isGuiAllowed()) { - // auto switch to console mode - if (hasVerboseOptionInArgs(args)) { - ConsoleInstaller.message("auto-switching to console mode"); + if (!hasConsoleOptionInArgs(args) && !hasSilentOptionInArgs(args)) { + if (!Installation.isGuiAllowed() || Installation.isGNUJava()) { + // auto switch to console mode + if (hasVerboseOptionInArgs(args)) { + ConsoleInstaller.message("auto-switching to console mode"); + } + String[] newArgs = new String[args.length + 1]; + System.arraycopy(args, 0, newArgs, 0, args.length); + newArgs[args.length] = "-" + CONSOLE_SHORT; + _args = newArgs; } - String[] newArgs = new String[args.length + 1]; - System.arraycopy(args, 0, newArgs, 0, args.length); - newArgs[args.length] = "-" + CONSOLE_SHORT; - _args = newArgs; } try { // throws for missing or unknown options / arguments Modified: trunk/installer/test/java/org/python/util/install/InstallationTest.java =================================================================== --- trunk/installer/test/java/org/python/util/install/InstallationTest.java 2008-10-21 21:59:40 UTC (rev 5501) +++ trunk/installer/test/java/org/python/util/install/InstallationTest.java 2008-10-21 22:36:57 UTC (rev 5502) @@ -71,4 +71,17 @@ assertTrue(Installation.isValidJava(javaVersionInfo)); } + public void testIsGNUJava() { + assertFalse(Installation.isGNUJava()); + String originalVmName = System.getProperty(Installation.JAVA_VM_NAME); + try { + // fake GNU java + System.setProperty(Installation.JAVA_VM_NAME, "GNU libgcj"); + assertTrue(Installation.isGNUJava()); + } finally { + System.setProperty(Installation.JAVA_VM_NAME, originalVmName); + assertFalse(Installation.isGNUJava()); + } + } + } Modified: trunk/installer/test/java/org/python/util/install/InstallerCommandLineTest.java =================================================================== --- trunk/installer/test/java/org/python/util/install/InstallerCommandLineTest.java 2008-10-21 21:59:40 UTC (rev 5501) +++ trunk/installer/test/java/org/python/util/install/InstallerCommandLineTest.java 2008-10-21 22:36:57 UTC (rev 5502) @@ -277,6 +277,38 @@ } } + public void testGNUSwitchToConsole() { + String originalVmName = System.getProperty(Installation.JAVA_VM_NAME); + try { + // fake GNU java + System.setProperty(Installation.JAVA_VM_NAME, "GNU libgcj"); + assertTrue(Installation.isGNUJava()); + String[] args; + InstallerCommandLine commandLine; + // expect auto switch + args = new String[] {"-v"}; + commandLine = new InstallerCommandLine(); + assertTrue(commandLine.setArgs(args)); + assertTrue(commandLine.hasVerboseOption()); + assertTrue(commandLine.hasConsoleOption()); // auto switch + // expect no auto switch + args = new String[] {"-s", "-d", "some_dir"}; + commandLine = new InstallerCommandLine(); + assertTrue(commandLine.setArgs(args)); + assertTrue(commandLine.hasSilentOption()); + assertFalse(commandLine.hasVerboseOption()); + assertFalse(commandLine.hasConsoleOption()); // no auto switch + assertTrue(commandLine.hasDirectoryOption()); + File dir = commandLine.getTargetDirectory(); + assertNotNull(dir); + assertEquals("some_dir", dir.getName()); + } finally { + System.setProperty(Installation.JAVA_VM_NAME, originalVmName); + assertFalse(Installation.isGNUJava()); + } + } + + public void testDirectory() { String[] args; InstallerCommandLine commandLine; This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <pj...@us...> - 2008-10-21 21:59:47
|
Revision: 5501 http://jython.svn.sourceforge.net/jython/?rev=5501&view=rev Author: pjenvey Date: 2008-10-21 21:59:40 +0000 (Tue, 21 Oct 2008) Log Message: ----------- fake support for an EEXIST OSError from mkdir. not 100% correct but this allows pylint to install Modified Paths: -------------- trunk/jython/Lib/os.py Modified: trunk/jython/Lib/os.py =================================================================== --- trunk/jython/Lib/os.py 2008-10-21 21:25:21 UTC (rev 5500) +++ trunk/jython/Lib/os.py 2008-10-21 21:59:40 UTC (rev 5501) @@ -286,8 +286,15 @@ The optional parameter is currently ignored. """ - if not File(sys.getPath(path)).mkdir(): - raise OSError(0, "couldn't make directory", path) + # XXX: use _posix.mkdir when we can get the real errno upon failure + fp = File(sys.getPath(path)) + if not fp.mkdir(): + if fp.isDirectory() or fp.isFile(): + err = errno.EEXIST + else: + err = 0 + msg = errno.strerror(err) if err else "couldn't make directory" + raise OSError(err, msg, path) def makedirs(path, mode='ignored'): """makedirs(path [, mode=0777]) This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |