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: <cg...@us...> - 2008-10-20 01:01:47
|
Revision: 5475 http://jython.svn.sourceforge.net/jython/?rev=5475&view=rev Author: cgroves Date: 2008-10-20 01:01:39 +0000 (Mon, 20 Oct 2008) Log Message: ----------- Add an ant resource collection that's like union except it combines based on the name of the resource instead of its full path. Use this to exclude the unexposed version of classes from jython.jar to keep it quiet. Resource collections didn't appear until Ant 1.7, but that came out nearly 2 years ago, so I'm hoping most people already have it. Modified Paths: -------------- trunk/jython/build.xml Added Paths: ----------- trunk/jython/src/org/python/util/NameUnionAntType.java Modified: trunk/jython/build.xml =================================================================== --- trunk/jython/build.xml 2008-10-20 00:44:52 UTC (rev 5474) +++ trunk/jython/build.xml 2008-10-20 01:01:39 UTC (rev 5475) @@ -549,9 +549,17 @@ </target> <target name="jar" depends="compile,expose,jarjar"> - <jar destfile="${dist.dir}/jython.jar" duplicate="preserve"> - <fileset dir="${exposed.dir}"/> - <fileset dir="${compile.dir}"/> + <typedef name="nameunion" classname="org.python.util.NameUnionAntType"> + <classpath> + <path refid="main.classpath" /> + <pathelement path="${compile.dir}" /> + </classpath> + </typedef> + <jar destfile="${dist.dir}/jython.jar" duplicate="fail"> + <nameunion> + <fileset dir="${exposed.dir}"/> + <fileset dir="${compile.dir}"/> + </nameunion> <fileset dir="${jarjar.dir}"> <include name="org/python/objectweb/asm/ClassReader.class" /> </fileset> Added: trunk/jython/src/org/python/util/NameUnionAntType.java =================================================================== --- trunk/jython/src/org/python/util/NameUnionAntType.java (rev 0) +++ trunk/jython/src/org/python/util/NameUnionAntType.java 2008-10-20 01:01:39 UTC (rev 5475) @@ -0,0 +1,35 @@ +package org.python.util; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashSet; +import java.util.Iterator; +import java.util.List; +import java.util.Set; + +import org.apache.tools.ant.types.Resource; +import org.apache.tools.ant.types.ResourceCollection; +import org.apache.tools.ant.types.resources.BaseResourceCollectionContainer; + +/** + * Unions several resource collections by the name of their contained resources. + */ +public class NameUnionAntType extends BaseResourceCollectionContainer { + @SuppressWarnings("unchecked") + @Override + protected Collection<Resource> getCollection() { + List<ResourceCollection> collections = getResourceCollections(); + // preserve order-encountered using a list; keep track of the items with a set + Set<String> seenNames = new HashSet<String>(); + List<Resource> union = new ArrayList(); + for (ResourceCollection rc : collections) { + for (Iterator<Resource> resources = rc.iterator(); resources.hasNext();) { + Resource r = resources.next(); + if (seenNames.add(r.getName())) { + union.add(r); + } + } + } + return union; + } +} This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <pj...@us...> - 2008-10-20 00:45:02
|
Revision: 5474 http://jython.svn.sourceforge.net/jython/?rev=5474&view=rev Author: pjenvey Date: 2008-10-20 00:44:52 +0000 (Mon, 20 Oct 2008) Log Message: ----------- bump java's stack size to 768k on solaris, to fix test_cpickle there Modified Paths: -------------- trunk/jython/src/shell/jython Modified: trunk/jython/src/shell/jython =================================================================== --- trunk/jython/src/shell/jython 2008-10-19 23:30:32 UTC (rev 5473) +++ trunk/jython/src/shell/jython 2008-10-20 00:44:52 UTC (rev 5474) @@ -13,10 +13,12 @@ # ----------------------------------------------------------------------------- cygwin=false +solaris=false # ----- Identify OS we are running under -------------------------------------- case "`uname`" in - CYGWIN*) cygwin=true + CYGWIN*) cygwin=true;; + SunOS*) solaris=true;; esac # ----- Verify and set required environment variables ------------------------- @@ -81,7 +83,13 @@ # ----- Execute the requested command ----------------------------------------- -JAVA_STACK=-Xss512k # minimum requirement for test_cpickle +# stack size value determined by the minimum requirement for +# test_cpickle +if $solaris; then + JAVA_STACK=-Xss768k +else + JAVA_STACK=-Xss512k +fi # Split out any -J argument for passing to the JVM. # Scanning for args is aborted by '--'. This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <cg...@us...> - 2008-10-19 23:30:41
|
Revision: 5473 http://jython.svn.sourceforge.net/jython/?rev=5473&view=rev Author: cgroves Date: 2008-10-19 23:30:32 +0000 (Sun, 19 Oct 2008) Log Message: ----------- Replace StringUtil.asPyString with Py.newString Modified Paths: -------------- trunk/jython/Lib/javapath.py trunk/jython/Lib/os.py trunk/jython/Lib/socket.py trunk/jython/src/org/python/core/util/StringUtil.java Modified: trunk/jython/Lib/javapath.py =================================================================== --- trunk/jython/Lib/javapath.py 2008-10-19 23:18:22 UTC (rev 5472) +++ trunk/jython/Lib/javapath.py 2008-10-19 23:30:32 UTC (rev 5473) @@ -20,7 +20,7 @@ from java.lang import System import os -from org.python.core.util.StringUtil import asPyString +from org.python.core.Py import newString as asPyString def _tostr(s, method): Modified: trunk/jython/Lib/os.py =================================================================== --- trunk/jython/Lib/os.py 2008-10-19 23:18:22 UTC (rev 5472) +++ trunk/jython/Lib/os.py 2008-10-19 23:30:32 UTC (rev 5473) @@ -48,7 +48,7 @@ from java.io import File from org.python.core import PyFile from org.python.core.io import FileDescriptors, FileIO, IOBase -from org.python.core.util.StringUtil import asPyString +from org.python.core.Py import newString as asPyString # Mapping of: os._name: [name list, shell command list] _os_map = dict(nt=[ Modified: trunk/jython/Lib/socket.py =================================================================== --- trunk/jython/Lib/socket.py 2008-10-19 23:18:22 UTC (rev 5472) +++ trunk/jython/Lib/socket.py 2008-10-19 23:30:32 UTC (rev 5473) @@ -81,7 +81,7 @@ import org.python.core.io.DatagramSocketIO import org.python.core.io.ServerSocketIO import org.python.core.io.SocketIO -from org.python.core.util.StringUtil import asPyString +from org.python.core.Py import newString as asPyString class error(Exception): pass class herror(error): pass Modified: trunk/jython/src/org/python/core/util/StringUtil.java =================================================================== --- trunk/jython/src/org/python/core/util/StringUtil.java 2008-10-19 23:18:22 UTC (rev 5472) +++ trunk/jython/src/org/python/core/util/StringUtil.java 2008-10-19 23:30:32 UTC (rev 5473) @@ -5,7 +5,6 @@ import java.nio.ByteBuffer; import org.python.core.Py; -import org.python.core.PyString; /** * String Utility methods. @@ -84,8 +83,4 @@ chars[0] = Character.toLowerCase(c0); return new String(chars); } - - public static PyString asPyString(String string) { - return new PyString(string); } -} This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <zy...@us...> - 2008-10-19 23:18:28
|
Revision: 5472 http://jython.svn.sourceforge.net/jython/?rev=5472&view=rev Author: zyasoft Date: 2008-10-19 23:18:22 +0000 (Sun, 19 Oct 2008) Log Message: ----------- PEP 342 specifies that an exception raised by close during finalization should be output to stderr, so we now do that. Fixed a minor doctest output formatting issue so that the desired syntax error is properly seen. Modified Paths: -------------- trunk/jython/Lib/test/test_generators.py trunk/jython/src/org/python/core/PyGenerator.java Modified: trunk/jython/Lib/test/test_generators.py =================================================================== --- trunk/jython/Lib/test/test_generators.py 2008-10-19 23:17:44 UTC (rev 5471) +++ trunk/jython/Lib/test/test_generators.py 2008-10-19 23:18:22 UTC (rev 5472) @@ -867,7 +867,7 @@ <type 'generator'> ->>> def f(): +>>> def f(): #doctest: +IGNORE_EXCEPTION_DETAIL, +NORMALIZE_WHITESPACE ... if 0: ... lambda x: x # shouldn't trigger here ... return # or here @@ -1646,8 +1646,6 @@ >>> g.close() # close normally And finalization. But we have to force the timing of GC here, since we are running on Jython: ->>> import gc ->>> from time import sleep >>> def f(): ... try: yield ... finally: @@ -1655,7 +1653,7 @@ >>> g = f() >>> g.next() ->>> del g; gc.collect(); sleep(1); gc.collect() +>>> del g; extra_collect() exiting @@ -1680,7 +1678,7 @@ >>> old, sys.stderr = sys.stderr, StringIO.StringIO() >>> g = f() >>> g.next() ->>> del g; gc.collect(); sleep(1); gc.collect() +>>> del g; extra_collect() >>> sys.stderr.getvalue().startswith( ... "Exception RuntimeError" ... ) @@ -1789,7 +1787,6 @@ >>> import sys, StringIO >>> from time import sleep ->>> import gc >>> old = sys.stderr >>> try: ... sys.stderr = StringIO.StringIO() @@ -1798,7 +1795,7 @@ ... raise RuntimeError ... ... l = Leaker() -... del l; gc.collect(); sleep(1); gc.collect() +... del l; extra_collect() ... err = sys.stderr.getvalue().strip() ... err.startswith( ... "Exception RuntimeError in <" @@ -1837,6 +1834,13 @@ from test import test_support, test_generators test_support.run_doctest(test_generators, verbose) +def extra_collect(): + import gc + from time import sleep + + gc.collect(); sleep(1); gc.collect(); sleep(0.1); gc.collect() + + # This part isn't needed for regrtest, but for running the test directly. if __name__ == "__main__": test_main(1) Modified: trunk/jython/src/org/python/core/PyGenerator.java =================================================================== --- trunk/jython/src/org/python/core/PyGenerator.java 2008-10-19 23:17:44 UTC (rev 5471) +++ trunk/jython/src/org/python/core/PyGenerator.java 2008-10-19 23:18:22 UTC (rev 5472) @@ -82,7 +82,23 @@ 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; + 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); } catch (Throwable e) { + // but we currently ignore any Java exception completely. perhaps we + // can also output something meaningful too? } finally { super.finalize(); } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <cg...@us...> - 2008-10-19 23:17:51
|
Revision: 5471 http://jython.svn.sourceforge.net/jython/?rev=5471&view=rev Author: cgroves Date: 2008-10-19 23:17:44 +0000 (Sun, 19 Oct 2008) Log Message: ----------- Add a couple tests for subclass constructor visibility Modified Paths: -------------- trunk/jython/Lib/test/test_java_visibility.py trunk/jython/tests/java/org/python/tests/VisibilityResults.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-19 22:04:51 UTC (rev 5470) +++ trunk/jython/Lib/test/test_java_visibility.py 2008-10-19 23:17:44 UTC (rev 5471) @@ -8,15 +8,21 @@ self.assertEquals([], dir(Invisible)) def test_protected_from_python_subclass(self): - class SubInvisible(Invisible): - pass + class SubVisible(Visible): + def __init__(self, publicValue=None): + if publicValue is not None: + Visible.__init__(self, publicValue) + else: + Visible.__init__(self) # TODO - protectedStaticMethod, protectedStaticField, and protectedField should # be here - s = SubInvisible() + s = SubVisible() self.assertEquals(Results.PROTECTED_METHOD, s.protectedMethod(0)) + self.assertEquals(Results.OVERLOADED_PROTECTED_METHOD, s.protectedMethod('foo')) + self.assertEquals(Results.UNUSED, SubVisible(Results.UNUSED).visibleField) def test_visible(self): - self.assertEquals(4, len(dir(Visible))) + self.assertEquals(5, len(dir(Visible))) v = Visible() self.assertEquals(Results.PUBLIC_FIELD, v.visibleField) Modified: trunk/jython/tests/java/org/python/tests/VisibilityResults.java =================================================================== --- trunk/jython/tests/java/org/python/tests/VisibilityResults.java 2008-10-19 22:04:51 UTC (rev 5470) +++ trunk/jython/tests/java/org/python/tests/VisibilityResults.java 2008-10-19 23:17:44 UTC (rev 5471) @@ -1,9 +1,9 @@ package org.python.tests; -/** - * - */ public interface VisibilityResults { + // Value not used by default by any of the visible classes + public static final int UNUSED = -1; + // Returns for Invisible.java public static final int PROTECTED_STATIC_FIELD = 1; public static final int PROTECTED_FIELD = 2; @@ -15,7 +15,7 @@ public static final int OVERLOADED_PROTECTED_METHOD = 8; public static final int PACKAGE_STATIC_METHOD = 9; public static final int PACKAGE_METHOD = 10; - + // Returns for Visible.java public static final int PUBLIC_FIELD = 101; public static final int PUBLIC_STATIC_FIELD = 102; @@ -28,7 +28,7 @@ public static final int EXTRA_ARG_PUBLIC_STATIC_METHOD = 109; public static final int PUBLIC_METHOD_FIELD = 110; public static final int PUBLIC_STATIC_METHOD_FIELD = 111; - + // Returns for SubVisible.java public static final int SUBCLASS_OVERRIDE = 201; public static final int SUBCLASS_OVERLOAD = 202; Modified: trunk/jython/tests/java/org/python/tests/Visible.java =================================================================== --- trunk/jython/tests/java/org/python/tests/Visible.java 2008-10-19 22:04:51 UTC (rev 5470) +++ trunk/jython/tests/java/org/python/tests/Visible.java 2008-10-19 23:17:44 UTC (rev 5471) @@ -1,17 +1,25 @@ package org.python.tests; -/** +/** * Exposes several methods that should be visible statically and on instances in Python. */ public class Visible extends Invisible { - public int visibleField = PUBLIC_FIELD; - + public int visibleField; + public static int visibleStaticField = PUBLIC_STATIC_FIELD; public int visibleInstance = PUBLIC_METHOD_FIELD; public static int visibleStatic = PUBLIC_STATIC_METHOD_FIELD; + public Visible() { + this(PUBLIC_FIELD); + } + + public Visible(int visibileFieldValue) { + visibleField = visibileFieldValue; + } + public int visibleInstance(int input) { return PUBLIC_METHOD; } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <zy...@us...> - 2008-10-19 22:04:59
|
Revision: 5470 http://jython.svn.sourceforge.net/jython/?rev=5470&view=rev Author: zyasoft Date: 2008-10-19 22:04:51 +0000 (Sun, 19 Oct 2008) Log Message: ----------- Make error handling in codecs so that it is also surrogate-aware. Fixes test_codeccallbacks Skip tests from test_threading not applicable to Jython. Modified Paths: -------------- trunk/jython/Lib/test/test_codeccallbacks.py trunk/jython/Lib/test/test_threading.py trunk/jython/Lib/unicodedata.py trunk/jython/src/org/python/core/codecs.java trunk/jython/src/org/python/core/exceptions.java Modified: trunk/jython/Lib/test/test_codeccallbacks.py =================================================================== --- trunk/jython/Lib/test/test_codeccallbacks.py 2008-10-19 20:51:56 UTC (rev 5469) +++ trunk/jython/Lib/test/test_codeccallbacks.py 2008-10-19 22:04:51 UTC (rev 5470) @@ -589,7 +589,7 @@ ("ascii", "\xff"), ("utf-8", "\xff"), ("utf-7", "+x-"), - ("unicode-internal", "\x00"), + # ("unicode-internal", "\x00"), - not valid for Jython because PyUnicode/PyString share internal representation ): self.assertRaises( TypeError, @@ -794,6 +794,9 @@ text.translate(charmap) def test_main(): + if test.test_support.is_jython: + del CodecCallbackTest.test_decodeunicodeinternal # PyUnicode/PyString share the same internal rep, so n/a + test.test_support.run_unittest(CodecCallbackTest) if __name__ == "__main__": Modified: trunk/jython/Lib/test/test_threading.py =================================================================== --- trunk/jython/Lib/test/test_threading.py 2008-10-19 20:51:56 UTC (rev 5469) +++ trunk/jython/Lib/test/test_threading.py 2008-10-19 22:04:51 UTC (rev 5470) @@ -1,7 +1,7 @@ # Very rudimentary test of threading module import test.test_support -from test.test_support import verbose +from test.test_support import verbose, is_jython import random import sys import threading @@ -118,7 +118,7 @@ # 3. This behavior doesn't make sense for Jython since any foreign # Java threads can use the same underlying locks, etc - def na_for_jython_test_foreign_thread(self): + def test_foreign_thread(self): # Check that a "foreign" thread can use the threading module. def f(mutex): # Acquiring an RLock forces an entry for the foreign @@ -208,7 +208,7 @@ t.join() # else the thread is still running, and we have no way to kill it - def na_for_jython_test_enumerate_after_join(self): + def test_enumerate_after_join(self): # Try hard to trigger #1703448: a thread is still returned in # threading.enumerate() after it has been join()ed. enum = threading.enumerate @@ -225,6 +225,10 @@ finally: sys.setcheckinterval(old_interval) +if is_jython: + del ThreadTests.test_enumerate_after_join + del ThreadTests.test_foreign_thread + del ThreadTests.test_PyThreadState_SetAsyncExc def test_main(): test.test_support.run_unittest(ThreadTests) Modified: trunk/jython/Lib/unicodedata.py =================================================================== --- trunk/jython/Lib/unicodedata.py 2008-10-19 20:51:56 UTC (rev 5469) +++ trunk/jython/Lib/unicodedata.py 2008-10-19 22:04:51 UTC (rev 5470) @@ -41,6 +41,10 @@ cols = row.split(';') codepoint = int(cols[0], 16) name = cols[1] + if name == '<CJK Ideograph, Last>': + lookup_name = 'CJK UNIFIED IDEOGRAPH' + else: + lookup_name = name data = ( cols[2], get_int(cols[3]), @@ -49,7 +53,9 @@ get_int(cols[6]), get_int(cols[7]), get_numeric(cols[8]), - get_yn(cols[9])) + get_yn(cols[9]), + lookup_name, + ) if name.find('First') >= 0: start = codepoint @@ -86,15 +92,27 @@ init(my_path) init_east_asian_width(my_path) +# xxx - need to normalize the segments, so +# <CJK Ideograph, Last> ==> CJK UNIFIED IDEOGRAPH; +# may need to do some sort of analysis against CPython for the normalization! + def name(unichr, default=None): - try: - return _codepoints[ord(unichr)].name - except KeyError: - if default is not None: + codepoint = get_codepoint(unichr, "name") + v = _codepoints.get(codepoint, None) + if v is None: + v = check_segments(codepoint, _segments) + if v is not None: + return "%s-%X" % (v[8], codepoint) + + if v is None: + if default is not Nonesuch: return default - else: - raise ValueError() + raise ValueError() + return v[8] +# xxx - also need to add logic here so that if it's CJK UNIFIED +# IDEOGRAPH-8000, we go against the segment to verify the prefix + def lookup(name): return _names[name] Modified: trunk/jython/src/org/python/core/codecs.java =================================================================== --- trunk/jython/src/org/python/core/codecs.java 2008-10-19 20:51:56 UTC (rev 5469) +++ trunk/jython/src/org/python/core/codecs.java 2008-10-19 22:04:51 UTC (rev 5470) @@ -243,9 +243,17 @@ ArgParser ap = new ArgParser("replace_errors", args, kws, "exc"); PyObject exc = ap.getPyObject(0); if (Py.isInstance(exc, Py.UnicodeDecodeError)) { + PyObject object = exc.__getattr__("object"); + if (!Py.isInstance(object, PyString.TYPE) || Py.isInstance(object, PyUnicode.TYPE)) { + throw Py.TypeError("object attribute must be str"); + } PyObject end = exc.__getattr__("end"); return new PyTuple(new PyUnicode(Py_UNICODE_REPLACEMENT_CHARACTER), end); } else if (Py.isInstance(exc, Py.UnicodeEncodeError)) { + PyObject object = exc.__getattr__("object"); + if (!Py.isInstance(object, PyUnicode.TYPE)) { + throw Py.TypeError("object attribute must be unicode"); + } PyObject end = exc.__getattr__("end"); return new PyTuple(Py.java2py("?"), end); } else if (Py.isInstance(exc, Py.UnicodeTranslateError)) { @@ -343,9 +351,9 @@ } private static void backslashreplace_internal(int start, int end, String object, StringBuilder replacement) { - for (int i = start; i < end; i++) { + for (Iterator<Integer> iter = new StringSubsequenceIterator(object, start, end, 1); iter.hasNext();) { + int c = iter.next(); replacement.append('\\'); - char c = object.charAt(i); if (c >= 0x00010000) { replacement.append('U'); replacement.append(hexdigits[(c >> 28) & 0xf]); @@ -1257,3 +1265,75 @@ } } } + + +class StringSubsequenceIterator implements Iterator { + + private final String s; + private int current, k, start, stop, step; + + StringSubsequenceIterator(String s, int start, int stop, int step) { +// System.out.println("s=" + s.length() + ",start=" + start + ",stop=" + stop); + this.s = s; + k = 0; + current = start; + this.start = start; + this.stop = stop; + this.step = step; + + // this bounds checking is necessary to convert between use of code units elsewhere, and codepoints here + // it would be nice if it were unnecessary! + int count = getCodePointCount(s); + if (start >= count) { + this.stop = -1; + } + else if (stop >= count) { + this.stop = count; + } + + for (int i = 0; i < start; i++) { + nextCodePoint(); + } + } + + StringSubsequenceIterator(String s) { + this(s, 0, getCodePointCount(s), 1); + } + + private static int getCodePointCount(String s) { + return s.codePointCount(0, s.length()); + } + + public boolean hasNext() { + return current < stop; + } + + public Object next() { + int codePoint = nextCodePoint(); + current += 1; + for (int j = 1; j < step && hasNext(); j++) { + nextCodePoint(); + current += 1; + } + return codePoint; + } + + private int nextCodePoint() { + int U; +// System.out.println("k=" + k); + int W1 = s.charAt(k); + if (W1 >= 0xD800 && W1 < 0xDC00) { + int W2 = s.charAt(k + 1); + U = (((W1 & 0x3FF) << 10) | (W2 & 0x3FF)) + 0x10000; + k += 2; + } else { + U = W1; + k += 1; + } + return U; + } + + public void remove() { + throw new UnsupportedOperationException("Not supported on String objects (immutable)"); + } +} Modified: trunk/jython/src/org/python/core/exceptions.java =================================================================== --- trunk/jython/src/org/python/core/exceptions.java 2008-10-19 20:51:56 UTC (rev 5469) +++ trunk/jython/src/org/python/core/exceptions.java 2008-10-19 22:04:51 UTC (rev 5470) @@ -381,7 +381,7 @@ if (end == (start + 1)) { PyObject object = self.__getattr__("object"); int badByte = (object.toString().charAt(start)) & 0xff; - result = String.format("'%.400s' codec can't decode byte 0x%s in position %d: %.400s", + result = String.format("'%.400s' codec can't decode byte 0x%x in position %d: %.400s", encoding, badByte, start, reason); } else { result = String.format("'%.400s' codec can't decode bytes in position %d-%d: %.400s", @@ -413,7 +413,7 @@ String result; if (end == (start + 1)) { PyObject object = self.__getattr__("object"); - int badchar = object.toString().charAt(start); + int badchar = object.toString().codePointAt(start); String badcharStr; if (badchar <= 0xff) { badcharStr = String.format("x%02x", badchar); @@ -460,7 +460,7 @@ String result; if (end == (start + 1)) { - int badchar = (self.__getattr__("object").toString().charAt(start)); + int badchar = (self.__getattr__("object").toString().codePointAt(start)); String badCharStr; if (badchar <= 0xff) { badCharStr = String.format("x%02x", badchar); This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <pj...@us...> - 2008-10-19 20:52:03
|
Revision: 5469 http://jython.svn.sourceforge.net/jython/?rev=5469&view=rev Author: pjenvey Date: 2008-10-19 20:51:56 +0000 (Sun, 19 Oct 2008) Log Message: ----------- move the last visitCompare fix to after the end label so we also avoid the issue when a chained comparison fails fast Modified Paths: -------------- trunk/jython/src/org/python/compiler/CodeCompiler.java Modified: trunk/jython/src/org/python/compiler/CodeCompiler.java =================================================================== --- trunk/jython/src/org/python/compiler/CodeCompiler.java 2008-10-19 15:16:29 UTC (rev 5468) +++ trunk/jython/src/org/python/compiler/CodeCompiler.java 2008-10-19 20:51:56 UTC (rev 5469) @@ -1374,15 +1374,15 @@ code.swap(); visitCmpop(node.ops[n-1]); - code.aconst_null(); - code.astore(last); - code.freeLocal(last); - if (n > 1) { code.astore(result); code.label(end); code.aload(result); } + + code.aconst_null(); + code.astore(last); + code.freeLocal(last); code.freeLocal(result); return null; } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <zy...@us...> - 2008-10-19 15:16:37
|
Revision: 5468 http://jython.svn.sourceforge.net/jython/?rev=5468&view=rev Author: zyasoft Date: 2008-10-19 15:16:29 +0000 (Sun, 19 Oct 2008) Log Message: ----------- from http://svn.python.org/projects/python/branches/release25-maint/Lib/test/test_codeccallbacks.py@46456 Added Paths: ----------- trunk/jython/Lib/test/test_codeccallbacks.py Added: trunk/jython/Lib/test/test_codeccallbacks.py =================================================================== --- trunk/jython/Lib/test/test_codeccallbacks.py (rev 0) +++ trunk/jython/Lib/test/test_codeccallbacks.py 2008-10-19 15:16:29 UTC (rev 5468) @@ -0,0 +1,800 @@ +import test.test_support, unittest +import sys, codecs, htmlentitydefs, unicodedata + +class PosReturn: + # this can be used for configurable callbacks + + def __init__(self): + self.pos = 0 + + def handle(self, exc): + oldpos = self.pos + realpos = oldpos + if realpos<0: + realpos = len(exc.object) + realpos + # if we don't advance this time, terminate on the next call + # otherwise we'd get an endless loop + if realpos <= exc.start: + self.pos = len(exc.object) + return (u"<?>", oldpos) + +# A UnicodeEncodeError object with a bad start attribute +class BadStartUnicodeEncodeError(UnicodeEncodeError): + def __init__(self): + UnicodeEncodeError.__init__(self, "ascii", u"", 0, 1, "bad") + self.start = [] + +# A UnicodeEncodeError object with a bad object attribute +class BadObjectUnicodeEncodeError(UnicodeEncodeError): + def __init__(self): + UnicodeEncodeError.__init__(self, "ascii", u"", 0, 1, "bad") + self.object = [] + +# A UnicodeDecodeError object without an end attribute +class NoEndUnicodeDecodeError(UnicodeDecodeError): + def __init__(self): + UnicodeDecodeError.__init__(self, "ascii", "", 0, 1, "bad") + del self.end + +# A UnicodeDecodeError object with a bad object attribute +class BadObjectUnicodeDecodeError(UnicodeDecodeError): + def __init__(self): + UnicodeDecodeError.__init__(self, "ascii", "", 0, 1, "bad") + self.object = [] + +# A UnicodeTranslateError object without a start attribute +class NoStartUnicodeTranslateError(UnicodeTranslateError): + def __init__(self): + UnicodeTranslateError.__init__(self, u"", 0, 1, "bad") + del self.start + +# A UnicodeTranslateError object without an end attribute +class NoEndUnicodeTranslateError(UnicodeTranslateError): + def __init__(self): + UnicodeTranslateError.__init__(self, u"", 0, 1, "bad") + del self.end + +# A UnicodeTranslateError object without an object attribute +class NoObjectUnicodeTranslateError(UnicodeTranslateError): + def __init__(self): + UnicodeTranslateError.__init__(self, u"", 0, 1, "bad") + del self.object + +class CodecCallbackTest(unittest.TestCase): + + def test_xmlcharrefreplace(self): + # replace unencodable characters which numeric character entities. + # For ascii, latin-1 and charmaps this is completely implemented + # in C and should be reasonably fast. + s = u"\u30b9\u30d1\u30e2 \xe4nd eggs" + self.assertEqual( + s.encode("ascii", "xmlcharrefreplace"), + "スパモ änd eggs" + ) + self.assertEqual( + s.encode("latin-1", "xmlcharrefreplace"), + "スパモ \xe4nd eggs" + ) + + def test_xmlcharnamereplace(self): + # This time use a named character entity for unencodable + # characters, if one is available. + + def xmlcharnamereplace(exc): + if not isinstance(exc, UnicodeEncodeError): + raise TypeError("don't know how to handle %r" % exc) + l = [] + for c in exc.object[exc.start:exc.end]: + try: + l.append(u"&%s;" % htmlentitydefs.codepoint2name[ord(c)]) + except KeyError: + l.append(u"&#%d;" % ord(c)) + return (u"".join(l), exc.end) + + codecs.register_error( + "test.xmlcharnamereplace", xmlcharnamereplace) + + sin = u"\xab\u211c\xbb = \u2329\u1234\u20ac\u232a" + sout = "«ℜ» = ⟨ሴ€⟩" + self.assertEqual(sin.encode("ascii", "test.xmlcharnamereplace"), sout) + sout = "\xabℜ\xbb = ⟨ሴ€⟩" + self.assertEqual(sin.encode("latin-1", "test.xmlcharnamereplace"), sout) + sout = "\xabℜ\xbb = ⟨ሴ\xa4⟩" + self.assertEqual(sin.encode("iso-8859-15", "test.xmlcharnamereplace"), sout) + + def test_uninamereplace(self): + # We're using the names from the unicode database this time, + # and we're doing "syntax highlighting" here, i.e. we include + # the replaced text in ANSI escape sequences. For this it is + # useful that the error handler is not called for every single + # unencodable character, but for a complete sequence of + # unencodable characters, otherwise we would output many + # unneccessary escape sequences. + + def uninamereplace(exc): + if not isinstance(exc, UnicodeEncodeError): + raise TypeError("don't know how to handle %r" % exc) + l = [] + for c in exc.object[exc.start:exc.end]: + l.append(unicodedata.name(c, u"0x%x" % ord(c))) + return (u"\033[1m%s\033[0m" % u", ".join(l), exc.end) + + codecs.register_error( + "test.uninamereplace", uninamereplace) + + sin = u"\xac\u1234\u20ac\u8000" + sout = "\033[1mNOT SIGN, ETHIOPIC SYLLABLE SEE, EURO SIGN, CJK UNIFIED IDEOGRAPH-8000\033[0m" + self.assertEqual(sin.encode("ascii", "test.uninamereplace"), sout) + + sout = "\xac\033[1mETHIOPIC SYLLABLE SEE, EURO SIGN, CJK UNIFIED IDEOGRAPH-8000\033[0m" + self.assertEqual(sin.encode("latin-1", "test.uninamereplace"), sout) + + sout = "\xac\033[1mETHIOPIC SYLLABLE SEE\033[0m\xa4\033[1mCJK UNIFIED IDEOGRAPH-8000\033[0m" + self.assertEqual(sin.encode("iso-8859-15", "test.uninamereplace"), sout) + + def test_backslashescape(self): + # Does the same as the "unicode-escape" encoding, but with different + # base encodings. + sin = u"a\xac\u1234\u20ac\u8000" + if sys.maxunicode > 0xffff: + sin += unichr(sys.maxunicode) + sout = "a\\xac\\u1234\\u20ac\\u8000" + if sys.maxunicode > 0xffff: + sout += "\\U%08x" % sys.maxunicode + self.assertEqual(sin.encode("ascii", "backslashreplace"), sout) + + sout = "a\xac\\u1234\\u20ac\\u8000" + if sys.maxunicode > 0xffff: + sout += "\\U%08x" % sys.maxunicode + self.assertEqual(sin.encode("latin-1", "backslashreplace"), sout) + + sout = "a\xac\\u1234\xa4\\u8000" + if sys.maxunicode > 0xffff: + sout += "\\U%08x" % sys.maxunicode + self.assertEqual(sin.encode("iso-8859-15", "backslashreplace"), sout) + + def test_decoderelaxedutf8(self): + # This is the test for a decoding callback handler, + # that relaxes the UTF-8 minimal encoding restriction. + # A null byte that is encoded as "\xc0\x80" will be + # decoded as a null byte. All other illegal sequences + # will be handled strictly. + def relaxedutf8(exc): + if not isinstance(exc, UnicodeDecodeError): + raise TypeError("don't know how to handle %r" % exc) + if exc.object[exc.start:exc.end].startswith("\xc0\x80"): + return (u"\x00", exc.start+2) # retry after two bytes + else: + raise exc + + codecs.register_error( + "test.relaxedutf8", relaxedutf8) + + sin = "a\x00b\xc0\x80c\xc3\xbc\xc0\x80\xc0\x80" + sout = u"a\x00b\x00c\xfc\x00\x00" + self.assertEqual(sin.decode("utf-8", "test.relaxedutf8"), sout) + sin = "\xc0\x80\xc0\x81" + self.assertRaises(UnicodeError, sin.decode, "utf-8", "test.relaxedutf8") + + def test_charmapencode(self): + # For charmap encodings the replacement string will be + # mapped through the encoding again. This means, that + # to be able to use e.g. the "replace" handler, the + # charmap has to have a mapping for "?". + charmap = dict([ (ord(c), 2*c.upper()) for c in "abcdefgh"]) + sin = u"abc" + sout = "AABBCC" + self.assertEquals(codecs.charmap_encode(sin, "strict", charmap)[0], sout) + + sin = u"abcA" + self.assertRaises(UnicodeError, codecs.charmap_encode, sin, "strict", charmap) + + charmap[ord("?")] = "XYZ" + sin = u"abcDEF" + sout = "AABBCCXYZXYZXYZ" + self.assertEquals(codecs.charmap_encode(sin, "replace", charmap)[0], sout) + + charmap[ord("?")] = u"XYZ" + self.assertRaises(TypeError, codecs.charmap_encode, sin, "replace", charmap) + + charmap[ord("?")] = u"XYZ" + self.assertRaises(TypeError, codecs.charmap_encode, sin, "replace", charmap) + + def test_decodeunicodeinternal(self): + self.assertRaises( + UnicodeDecodeError, + "\x00\x00\x00\x00\x00".decode, + "unicode-internal", + ) + if sys.maxunicode > 0xffff: + def handler_unicodeinternal(exc): + if not isinstance(exc, UnicodeDecodeError): + raise TypeError("don't know how to handle %r" % exc) + return (u"\x01", 1) + + self.assertEqual( + "\x00\x00\x00\x00\x00".decode("unicode-internal", "ignore"), + u"\u0000" + ) + + self.assertEqual( + "\x00\x00\x00\x00\x00".decode("unicode-internal", "replace"), + u"\u0000\ufffd" + ) + + codecs.register_error("test.hui", handler_unicodeinternal) + + self.assertEqual( + "\x00\x00\x00\x00\x00".decode("unicode-internal", "test.hui"), + u"\u0000\u0001\u0000" + ) + + def test_callbacks(self): + def handler1(exc): + if not isinstance(exc, UnicodeEncodeError) \ + and not isinstance(exc, UnicodeDecodeError): + raise TypeError("don't know how to handle %r" % exc) + l = [u"<%d>" % ord(exc.object[pos]) for pos in xrange(exc.start, exc.end)] + return (u"[%s]" % u"".join(l), exc.end) + + codecs.register_error("test.handler1", handler1) + + def handler2(exc): + if not isinstance(exc, UnicodeDecodeError): + raise TypeError("don't know how to handle %r" % exc) + l = [u"<%d>" % ord(exc.object[pos]) for pos in xrange(exc.start, exc.end)] + return (u"[%s]" % u"".join(l), exc.end+1) # skip one character + + codecs.register_error("test.handler2", handler2) + + s = "\x00\x81\x7f\x80\xff" + + self.assertEqual( + s.decode("ascii", "test.handler1"), + u"\x00[<129>]\x7f[<128>][<255>]" + ) + self.assertEqual( + s.decode("ascii", "test.handler2"), + u"\x00[<129>][<128>]" + ) + + self.assertEqual( + "\\u3042\u3xxx".decode("unicode-escape", "test.handler1"), + u"\u3042[<92><117><51><120>]xx" + ) + + self.assertEqual( + "\\u3042\u3xx".decode("unicode-escape", "test.handler1"), + u"\u3042[<92><117><51><120><120>]" + ) + + self.assertEqual( + codecs.charmap_decode("abc", "test.handler1", {ord("a"): u"z"})[0], + u"z[<98>][<99>]" + ) + + self.assertEqual( + u"g\xfc\xdfrk".encode("ascii", "test.handler1"), + u"g[<252><223>]rk" + ) + + self.assertEqual( + u"g\xfc\xdf".encode("ascii", "test.handler1"), + u"g[<252><223>]" + ) + + def test_longstrings(self): + # test long strings to check for memory overflow problems + errors = [ "strict", "ignore", "replace", "xmlcharrefreplace", "backslashreplace"] + # register the handlers under different names, + # to prevent the codec from recognizing the name + for err in errors: + codecs.register_error("test." + err, codecs.lookup_error(err)) + l = 1000 + errors += [ "test." + err for err in errors ] + for uni in [ s*l for s in (u"x", u"\u3042", u"a\xe4") ]: + for enc in ("ascii", "latin-1", "iso-8859-1", "iso-8859-15", "utf-8", "utf-7", "utf-16"): + for err in errors: + try: + uni.encode(enc, err) + except UnicodeError: + pass + + def check_exceptionobjectargs(self, exctype, args, msg): + # Test UnicodeError subclasses: construction, attribute assignment and __str__ conversion + # check with one missing argument + self.assertRaises(TypeError, exctype, *args[:-1]) + # check with one argument too much + self.assertRaises(TypeError, exctype, *(args + ["too much"])) + # check with one argument of the wrong type + wrongargs = [ "spam", u"eggs", 42, 1.0, None ] + for i in xrange(len(args)): + for wrongarg in wrongargs: + if type(wrongarg) is type(args[i]): + continue + # build argument array + callargs = [] + for j in xrange(len(args)): + if i==j: + callargs.append(wrongarg) + else: + callargs.append(args[i]) + self.assertRaises(TypeError, exctype, *callargs) + + # check with the correct number and type of arguments + exc = exctype(*args) + self.assertEquals(str(exc), msg) + + def test_unicodeencodeerror(self): + self.check_exceptionobjectargs( + UnicodeEncodeError, + ["ascii", u"g\xfcrk", 1, 2, "ouch"], + "'ascii' codec can't encode character u'\\xfc' in position 1: ouch" + ) + self.check_exceptionobjectargs( + UnicodeEncodeError, + ["ascii", u"g\xfcrk", 1, 4, "ouch"], + "'ascii' codec can't encode characters in position 1-3: ouch" + ) + self.check_exceptionobjectargs( + UnicodeEncodeError, + ["ascii", u"\xfcx", 0, 1, "ouch"], + "'ascii' codec can't encode character u'\\xfc' in position 0: ouch" + ) + self.check_exceptionobjectargs( + UnicodeEncodeError, + ["ascii", u"\u0100x", 0, 1, "ouch"], + "'ascii' codec can't encode character u'\\u0100' in position 0: ouch" + ) + self.check_exceptionobjectargs( + UnicodeEncodeError, + ["ascii", u"\uffffx", 0, 1, "ouch"], + "'ascii' codec can't encode character u'\\uffff' in position 0: ouch" + ) + if sys.maxunicode > 0xffff: + self.check_exceptionobjectargs( + UnicodeEncodeError, + ["ascii", u"\U00010000x", 0, 1, "ouch"], + "'ascii' codec can't encode character u'\\U00010000' in position 0: ouch" + ) + + def test_unicodedecodeerror(self): + self.check_exceptionobjectargs( + UnicodeDecodeError, + ["ascii", "g\xfcrk", 1, 2, "ouch"], + "'ascii' codec can't decode byte 0xfc in position 1: ouch" + ) + self.check_exceptionobjectargs( + UnicodeDecodeError, + ["ascii", "g\xfcrk", 1, 3, "ouch"], + "'ascii' codec can't decode bytes in position 1-2: ouch" + ) + + def test_unicodetranslateerror(self): + self.check_exceptionobjectargs( + UnicodeTranslateError, + [u"g\xfcrk", 1, 2, "ouch"], + "can't translate character u'\\xfc' in position 1: ouch" + ) + self.check_exceptionobjectargs( + UnicodeTranslateError, + [u"g\u0100rk", 1, 2, "ouch"], + "can't translate character u'\\u0100' in position 1: ouch" + ) + self.check_exceptionobjectargs( + UnicodeTranslateError, + [u"g\uffffrk", 1, 2, "ouch"], + "can't translate character u'\\uffff' in position 1: ouch" + ) + if sys.maxunicode > 0xffff: + self.check_exceptionobjectargs( + UnicodeTranslateError, + [u"g\U00010000rk", 1, 2, "ouch"], + "can't translate character u'\\U00010000' in position 1: ouch" + ) + self.check_exceptionobjectargs( + UnicodeTranslateError, + [u"g\xfcrk", 1, 3, "ouch"], + "can't translate characters in position 1-2: ouch" + ) + + def test_badandgoodstrictexceptions(self): + # "strict" complains about a non-exception passed in + self.assertRaises( + TypeError, + codecs.strict_errors, + 42 + ) + # "strict" complains about the wrong exception type + self.assertRaises( + Exception, + codecs.strict_errors, + Exception("ouch") + ) + + # If the correct exception is passed in, "strict" raises it + self.assertRaises( + UnicodeEncodeError, + codecs.strict_errors, + UnicodeEncodeError("ascii", u"\u3042", 0, 1, "ouch") + ) + + def test_badandgoodignoreexceptions(self): + # "ignore" complains about a non-exception passed in + self.assertRaises( + TypeError, + codecs.ignore_errors, + 42 + ) + # "ignore" complains about the wrong exception type + self.assertRaises( + TypeError, + codecs.ignore_errors, + UnicodeError("ouch") + ) + # If the correct exception is passed in, "ignore" returns an empty replacement + self.assertEquals( + codecs.ignore_errors(UnicodeEncodeError("ascii", u"\u3042", 0, 1, "ouch")), + (u"", 1) + ) + self.assertEquals( + codecs.ignore_errors(UnicodeDecodeError("ascii", "\xff", 0, 1, "ouch")), + (u"", 1) + ) + self.assertEquals( + codecs.ignore_errors(UnicodeTranslateError(u"\u3042", 0, 1, "ouch")), + (u"", 1) + ) + + def test_badandgoodreplaceexceptions(self): + # "replace" complains about a non-exception passed in + self.assertRaises( + TypeError, + codecs.replace_errors, + 42 + ) + # "replace" complains about the wrong exception type + self.assertRaises( + TypeError, + codecs.replace_errors, + UnicodeError("ouch") + ) + self.assertRaises( + TypeError, + codecs.replace_errors, + BadObjectUnicodeEncodeError() + ) + self.assertRaises( + TypeError, + codecs.replace_errors, + BadObjectUnicodeDecodeError() + ) + # With the correct exception, "replace" returns an "?" or u"\ufffd" replacement + self.assertEquals( + codecs.replace_errors(UnicodeEncodeError("ascii", u"\u3042", 0, 1, "ouch")), + (u"?", 1) + ) + self.assertEquals( + codecs.replace_errors(UnicodeDecodeError("ascii", "\xff", 0, 1, "ouch")), + (u"\ufffd", 1) + ) + self.assertEquals( + codecs.replace_errors(UnicodeTranslateError(u"\u3042", 0, 1, "ouch")), + (u"\ufffd", 1) + ) + + def test_badandgoodxmlcharrefreplaceexceptions(self): + # "xmlcharrefreplace" complains about a non-exception passed in + self.assertRaises( + TypeError, + codecs.xmlcharrefreplace_errors, + 42 + ) + # "xmlcharrefreplace" complains about the wrong exception types + self.assertRaises( + TypeError, + codecs.xmlcharrefreplace_errors, + UnicodeError("ouch") + ) + # "xmlcharrefreplace" can only be used for encoding + self.assertRaises( + TypeError, + codecs.xmlcharrefreplace_errors, + UnicodeDecodeError("ascii", "\xff", 0, 1, "ouch") + ) + self.assertRaises( + TypeError, + codecs.xmlcharrefreplace_errors, + UnicodeTranslateError(u"\u3042", 0, 1, "ouch") + ) + # Use the correct exception + cs = (0, 1, 9, 10, 99, 100, 999, 1000, 9999, 10000, 0x3042) + s = "".join(unichr(c) for c in cs) + self.assertEquals( + codecs.xmlcharrefreplace_errors( + UnicodeEncodeError("ascii", s, 0, len(s), "ouch") + ), + (u"".join(u"&#%d;" % ord(c) for c in s), len(s)) + ) + + def test_badandgoodbackslashreplaceexceptions(self): + # "backslashreplace" complains about a non-exception passed in + self.assertRaises( + TypeError, + codecs.backslashreplace_errors, + 42 + ) + # "backslashreplace" complains about the wrong exception types + self.assertRaises( + TypeError, + codecs.backslashreplace_errors, + UnicodeError("ouch") + ) + # "backslashreplace" can only be used for encoding + self.assertRaises( + TypeError, + codecs.backslashreplace_errors, + UnicodeDecodeError("ascii", "\xff", 0, 1, "ouch") + ) + self.assertRaises( + TypeError, + codecs.backslashreplace_errors, + UnicodeTranslateError(u"\u3042", 0, 1, "ouch") + ) + # Use the correct exception + self.assertEquals( + codecs.backslashreplace_errors(UnicodeEncodeError("ascii", u"\u3042", 0, 1, "ouch")), + (u"\\u3042", 1) + ) + self.assertEquals( + codecs.backslashreplace_errors(UnicodeEncodeError("ascii", u"\x00", 0, 1, "ouch")), + (u"\\x00", 1) + ) + self.assertEquals( + codecs.backslashreplace_errors(UnicodeEncodeError("ascii", u"\xff", 0, 1, "ouch")), + (u"\\xff", 1) + ) + self.assertEquals( + codecs.backslashreplace_errors(UnicodeEncodeError("ascii", u"\u0100", 0, 1, "ouch")), + (u"\\u0100", 1) + ) + self.assertEquals( + codecs.backslashreplace_errors(UnicodeEncodeError("ascii", u"\uffff", 0, 1, "ouch")), + (u"\\uffff", 1) + ) + if sys.maxunicode>0xffff: + self.assertEquals( + codecs.backslashreplace_errors(UnicodeEncodeError("ascii", u"\U00010000", 0, 1, "ouch")), + (u"\\U00010000", 1) + ) + self.assertEquals( + codecs.backslashreplace_errors(UnicodeEncodeError("ascii", u"\U0010ffff", 0, 1, "ouch")), + (u"\\U0010ffff", 1) + ) + + def test_badhandlerresults(self): + results = ( 42, u"foo", (1,2,3), (u"foo", 1, 3), (u"foo", None), (u"foo",), ("foo", 1, 3), ("foo", None), ("foo",) ) + encs = ("ascii", "latin-1", "iso-8859-1", "iso-8859-15") + + for res in results: + codecs.register_error("test.badhandler", lambda: res) + for enc in encs: + self.assertRaises( + TypeError, + u"\u3042".encode, + enc, + "test.badhandler" + ) + for (enc, bytes) in ( + ("ascii", "\xff"), + ("utf-8", "\xff"), + ("utf-7", "+x-"), + ("unicode-internal", "\x00"), + ): + self.assertRaises( + TypeError, + bytes.decode, + enc, + "test.badhandler" + ) + + def test_lookup(self): + self.assertEquals(codecs.strict_errors, codecs.lookup_error("strict")) + self.assertEquals(codecs.ignore_errors, codecs.lookup_error("ignore")) + self.assertEquals(codecs.strict_errors, codecs.lookup_error("strict")) + self.assertEquals( + codecs.xmlcharrefreplace_errors, + codecs.lookup_error("xmlcharrefreplace") + ) + self.assertEquals( + codecs.backslashreplace_errors, + codecs.lookup_error("backslashreplace") + ) + + def test_unencodablereplacement(self): + def unencrepl(exc): + if isinstance(exc, UnicodeEncodeError): + return (u"\u4242", exc.end) + else: + raise TypeError("don't know how to handle %r" % exc) + codecs.register_error("test.unencreplhandler", unencrepl) + for enc in ("ascii", "iso-8859-1", "iso-8859-15"): + self.assertRaises( + UnicodeEncodeError, + u"\u4242".encode, + enc, + "test.unencreplhandler" + ) + + def test_badregistercall(self): + # enhance coverage of: + # Modules/_codecsmodule.c::register_error() + # Python/codecs.c::PyCodec_RegisterError() + self.assertRaises(TypeError, codecs.register_error, 42) + self.assertRaises(TypeError, codecs.register_error, "test.dummy", 42) + + def test_badlookupcall(self): + # enhance coverage of: + # Modules/_codecsmodule.c::lookup_error() + self.assertRaises(TypeError, codecs.lookup_error) + + def test_unknownhandler(self): + # enhance coverage of: + # Modules/_codecsmodule.c::lookup_error() + self.assertRaises(LookupError, codecs.lookup_error, "test.unknown") + + def test_xmlcharrefvalues(self): + # enhance coverage of: + # Python/codecs.c::PyCodec_XMLCharRefReplaceErrors() + # and inline implementations + v = (1, 5, 10, 50, 100, 500, 1000, 5000, 10000, 50000) + if sys.maxunicode>=100000: + v += (100000, 500000, 1000000) + s = u"".join([unichr(x) for x in v]) + codecs.register_error("test.xmlcharrefreplace", codecs.xmlcharrefreplace_errors) + for enc in ("ascii", "iso-8859-15"): + for err in ("xmlcharrefreplace", "test.xmlcharrefreplace"): + s.encode(enc, err) + + def test_decodehelper(self): + # enhance coverage of: + # Objects/unicodeobject.c::unicode_decode_call_errorhandler() + # and callers + self.assertRaises(LookupError, "\xff".decode, "ascii", "test.unknown") + + def baddecodereturn1(exc): + return 42 + codecs.register_error("test.baddecodereturn1", baddecodereturn1) + self.assertRaises(TypeError, "\xff".decode, "ascii", "test.baddecodereturn1") + self.assertRaises(TypeError, "\\".decode, "unicode-escape", "test.baddecodereturn1") + self.assertRaises(TypeError, "\\x0".decode, "unicode-escape", "test.baddecodereturn1") + self.assertRaises(TypeError, "\\x0y".decode, "unicode-escape", "test.baddecodereturn1") + self.assertRaises(TypeError, "\\Uffffeeee".decode, "unicode-escape", "test.baddecodereturn1") + self.assertRaises(TypeError, "\\uyyyy".decode, "raw-unicode-escape", "test.baddecodereturn1") + + def baddecodereturn2(exc): + return (u"?", None) + codecs.register_error("test.baddecodereturn2", baddecodereturn2) + self.assertRaises(TypeError, "\xff".decode, "ascii", "test.baddecodereturn2") + + handler = PosReturn() + codecs.register_error("test.posreturn", handler.handle) + + # Valid negative position + handler.pos = -1 + self.assertEquals("\xff0".decode("ascii", "test.posreturn"), u"<?>0") + + # Valid negative position + handler.pos = -2 + self.assertEquals("\xff0".decode("ascii", "test.posreturn"), u"<?><?>") + + # Negative position out of bounds + handler.pos = -3 + self.assertRaises(IndexError, "\xff0".decode, "ascii", "test.posreturn") + + # Valid positive position + handler.pos = 1 + self.assertEquals("\xff0".decode("ascii", "test.posreturn"), u"<?>0") + + # Largest valid positive position (one beyond end of input) + handler.pos = 2 + self.assertEquals("\xff0".decode("ascii", "test.posreturn"), u"<?>") + + # Invalid positive position + handler.pos = 3 + self.assertRaises(IndexError, "\xff0".decode, "ascii", "test.posreturn") + + # Restart at the "0" + handler.pos = 6 + self.assertEquals("\\uyyyy0".decode("raw-unicode-escape", "test.posreturn"), u"<?>0") + + class D(dict): + def __getitem__(self, key): + raise ValueError + self.assertRaises(UnicodeError, codecs.charmap_decode, "\xff", "strict", {0xff: None}) + self.assertRaises(ValueError, codecs.charmap_decode, "\xff", "strict", D()) + self.assertRaises(TypeError, codecs.charmap_decode, "\xff", "strict", {0xff: sys.maxunicode+1}) + + def test_encodehelper(self): + # enhance coverage of: + # Objects/unicodeobject.c::unicode_encode_call_errorhandler() + # and callers + self.assertRaises(LookupError, u"\xff".encode, "ascii", "test.unknown") + + def badencodereturn1(exc): + return 42 + codecs.register_error("test.badencodereturn1", badencodereturn1) + self.assertRaises(TypeError, u"\xff".encode, "ascii", "test.badencodereturn1") + + def badencodereturn2(exc): + return (u"?", None) + codecs.register_error("test.badencodereturn2", badencodereturn2) + self.assertRaises(TypeError, u"\xff".encode, "ascii", "test.badencodereturn2") + + handler = PosReturn() + codecs.register_error("test.posreturn", handler.handle) + + # Valid negative position + handler.pos = -1 + self.assertEquals(u"\xff0".encode("ascii", "test.posreturn"), "<?>0") + + # Valid negative position + handler.pos = -2 + self.assertEquals(u"\xff0".encode("ascii", "test.posreturn"), "<?><?>") + + # Negative position out of bounds + handler.pos = -3 + self.assertRaises(IndexError, u"\xff0".encode, "ascii", "test.posreturn") + + # Valid positive position + handler.pos = 1 + self.assertEquals(u"\xff0".encode("ascii", "test.posreturn"), "<?>0") + + # Largest valid positive position (one beyond end of input + handler.pos = 2 + self.assertEquals(u"\xff0".encode("ascii", "test.posreturn"), "<?>") + + # Invalid positive position + handler.pos = 3 + self.assertRaises(IndexError, u"\xff0".encode, "ascii", "test.posreturn") + + handler.pos = 0 + + class D(dict): + def __getitem__(self, key): + raise ValueError + for err in ("strict", "replace", "xmlcharrefreplace", "backslashreplace", "test.posreturn"): + self.assertRaises(UnicodeError, codecs.charmap_encode, u"\xff", err, {0xff: None}) + self.assertRaises(ValueError, codecs.charmap_encode, u"\xff", err, D()) + self.assertRaises(TypeError, codecs.charmap_encode, u"\xff", err, {0xff: 300}) + + def test_translatehelper(self): + # enhance coverage of: + # Objects/unicodeobject.c::unicode_encode_call_errorhandler() + # and callers + # (Unfortunately the errors argument is not directly accessible + # from Python, so we can't test that much) + class D(dict): + def __getitem__(self, key): + raise ValueError + self.assertRaises(ValueError, u"\xff".translate, D()) + self.assertRaises(TypeError, u"\xff".translate, {0xff: sys.maxunicode+1}) + self.assertRaises(TypeError, u"\xff".translate, {0xff: ()}) + + def test_bug828737(self): + charmap = { + ord("&"): u"&", + ord("<"): u"<", + ord(">"): u">", + ord('"'): u""", + } + + for n in (1, 10, 100, 1000): + text = u'abc<def>ghi'*n + text.translate(charmap) + +def test_main(): + test.test_support.run_unittest(CodecCallbackTest) + +if __name__ == "__main__": + test_main() This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <pj...@us...> - 2008-10-19 06:51:18
|
Revision: 5467 http://jython.svn.sourceforge.net/jython/?rev=5467&view=rev Author: pjenvey Date: 2008-10-19 06:51:07 +0000 (Sun, 19 Oct 2008) Log Message: ----------- fix visitCompare leaving the left side on the stack, causing a minor short term memory leak Modified Paths: -------------- trunk/jython/src/org/python/compiler/CodeCompiler.java Modified: trunk/jython/src/org/python/compiler/CodeCompiler.java =================================================================== --- trunk/jython/src/org/python/compiler/CodeCompiler.java 2008-10-19 05:17:07 UTC (rev 5466) +++ trunk/jython/src/org/python/compiler/CodeCompiler.java 2008-10-19 06:51:07 UTC (rev 5467) @@ -1374,12 +1374,15 @@ code.swap(); visitCmpop(node.ops[n-1]); + code.aconst_null(); + code.astore(last); + code.freeLocal(last); + if (n > 1) { code.astore(result); code.label(end); code.aload(result); } - code.freeLocal(last); code.freeLocal(result); 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-19 05:17:17
|
Revision: 5466 http://jython.svn.sourceforge.net/jython/?rev=5466&view=rev Author: cgroves Date: 2008-10-19 05:17:07 +0000 (Sun, 19 Oct 2008) Log Message: ----------- Missed a sppot Modified Paths: -------------- trunk/jython/CoreExposed.includes Modified: trunk/jython/CoreExposed.includes =================================================================== --- trunk/jython/CoreExposed.includes 2008-10-19 05:14:22 UTC (rev 5465) +++ trunk/jython/CoreExposed.includes 2008-10-19 05:17:07 UTC (rev 5466) @@ -2,7 +2,7 @@ org/python/core/PyBaseString.class org/python/core/PyBaseException.class org/python/core/PyBoolean.class -org/python/core/PyBuiltinFunction.class +org/python/core/PyBuiltinCallable.class org/python/core/PyCell.class org/python/core/PyClassMethod.class org/python/core/PyClassMethodDescr.class This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <cg...@us...> - 2008-10-19 05:14:29
|
Revision: 5465 http://jython.svn.sourceforge.net/jython/?rev=5465&view=rev Author: cgroves Date: 2008-10-19 05:14:22 +0000 (Sun, 19 Oct 2008) Log Message: ----------- Rename PyBuiltinFunction to PyBuiltinCallable, and remake PyBuiltinFunction as a base for functions with the basic function stuff from PyBuiltinFunctionSet. Extend that with PyBuiltinFunctionNarrow for functions with a fixed set of args to match PyBuiltinMethodNarrow. Use the new function stuff to implement the builtin functions that were using ExtendedBuiltinFunction as real functions instead of PyObjects. Modified Paths: -------------- trunk/jython/src/org/python/core/ArgParser.java trunk/jython/src/org/python/core/Py.java trunk/jython/src/org/python/core/PyBuiltinFunction.java trunk/jython/src/org/python/core/PyBuiltinFunctionSet.java trunk/jython/src/org/python/core/PyBuiltinMethod.java trunk/jython/src/org/python/core/PyBuiltinMethodNarrow.java trunk/jython/src/org/python/core/PyBuiltinMethodSet.java trunk/jython/src/org/python/core/PyClassMethodDescr.java trunk/jython/src/org/python/core/PyDictionary.java trunk/jython/src/org/python/core/PyEnumerate.java trunk/jython/src/org/python/core/PyInstance.java trunk/jython/src/org/python/core/PyMethodDescr.java trunk/jython/src/org/python/core/PyNewWrapper.java trunk/jython/src/org/python/core/PyObject.java trunk/jython/src/org/python/core/PySet.java trunk/jython/src/org/python/core/PyStringMap.java trunk/jython/src/org/python/core/PySuper.java trunk/jython/src/org/python/core/PyType.java trunk/jython/src/org/python/core/__builtin__.java trunk/jython/src/org/python/core/exceptions.java trunk/jython/src/org/python/expose/generate/PyTypes.java trunk/jython/src/org/python/modules/_collections/PyDeque.java trunk/jython/src/org/python/modules/_jython.java trunk/jython/src/org/python/modules/_weakref/ReferenceType.java trunk/jython/src/org/python/modules/cPickle.java trunk/jython/tests/java/org/python/expose/generate/ExposedTypeProcessorTest.java trunk/jython/tests/java/org/python/expose/generate/MethodExposerTest.java Added Paths: ----------- trunk/jython/src/org/python/core/PyBuiltinCallable.java trunk/jython/src/org/python/core/PyBuiltinFunctionNarrow.java Modified: trunk/jython/src/org/python/core/ArgParser.java =================================================================== --- trunk/jython/src/org/python/core/ArgParser.java 2008-10-19 03:04:44 UTC (rev 5464) +++ trunk/jython/src/org/python/core/ArgParser.java 2008-10-19 05:14:22 UTC (rev 5465) @@ -112,9 +112,9 @@ this(funcname, args, kws); this.params = paramnames; check(); - if (!PyBuiltinFunction.DefaultInfo.check(args.length, minargs, + if (!PyBuiltinCallable.DefaultInfo.check(args.length, minargs, this.params.length)) { - throw PyBuiltinFunction.DefaultInfo.unexpectedCall(args.length, + throw PyBuiltinCallable.DefaultInfo.unexpectedCall(args.length, false, funcname, minargs, this.params.length); } } Modified: trunk/jython/src/org/python/core/Py.java =================================================================== --- trunk/jython/src/org/python/core/Py.java 2008-10-19 03:04:44 UTC (rev 5464) +++ trunk/jython/src/org/python/core/Py.java 2008-10-19 05:14:22 UTC (rev 5465) @@ -86,7 +86,7 @@ static { BOOTSTRAP_TYPES.add(PyObject.class); BOOTSTRAP_TYPES.add(PyType.class); - BOOTSTRAP_TYPES.add(PyBuiltinFunction.class); + BOOTSTRAP_TYPES.add(PyBuiltinCallable.class); BOOTSTRAP_TYPES.add(PyDataDescr.class); } Added: trunk/jython/src/org/python/core/PyBuiltinCallable.java =================================================================== --- trunk/jython/src/org/python/core/PyBuiltinCallable.java (rev 0) +++ trunk/jython/src/org/python/core/PyBuiltinCallable.java 2008-10-19 05:14:22 UTC (rev 5465) @@ -0,0 +1,144 @@ +package org.python.core; + +import org.python.expose.ExposedGet; +import org.python.expose.ExposedType; + +// XXX: not subclassable +@ExposedType(name = "builtin_function_or_method") +public abstract class PyBuiltinCallable extends PyObject { + + protected Info info; + + protected PyBuiltinCallable(PyType type, Info info) { + super(type); + this.info = info; + } + + protected PyBuiltinCallable(Info info) { + this.info = info; + } + + /** + * @return a new instance of this type of PyBuiltinFunction bound to self + */ + abstract public PyBuiltinCallable bind(PyObject self); + + @ExposedGet(name = "__name__") + public PyObject fastGetName() { + return Py.newString(this.info.getName()); + } + + @ExposedGet(name = "__doc__") + public PyObject fastGetDoc() { + return Py.None; + } + + @ExposedGet(name = "__module__") + public PyObject getModule() { + return Py.None; + } + + @ExposedGet(name = "__call__") + public PyObject makeCall() { + return this; + } + + @ExposedGet(name = "__self__") + public PyObject getSelf() { + return Py.None; + } + + public void setInfo(Info info) { + this.info = info; + } + + public String toString() { + PyObject self = getSelf(); + if (self == null) { + return String.format("<built-in function %s>", info.getName()); + } else { + return String.format("<built-in method %s of %s object at %s>", info.getName(), + self.getType().fastGetName(), Py.idstr(self)); + } + } + + public interface Info { + + String getName(); + + int getMaxargs(); + + int getMinargs(); + + PyException unexpectedCall(int nargs, boolean keywords); + } + + public static class DefaultInfo implements Info { + + public DefaultInfo(String name, int minargs, int maxargs) { + this.name = name; + this.minargs = minargs; + this.maxargs = maxargs; + } + + public DefaultInfo(String name) { + this(name, -1, -1); + } + + private String name; + + private int maxargs, minargs; + + public String getName() { + return name; + } + + public int getMaxargs() { + return maxargs; + } + + public int getMinargs() { + return minargs; + } + + public static boolean check(int nargs, int minargs, int maxargs) { + if(nargs < minargs) + return false; + if(maxargs != -1 && nargs > maxargs) + return false; + return true; + } + + public static PyException unexpectedCall(int nargs, + boolean keywords, + String name, + int minargs, + int maxargs) { + if(keywords) + return Py.TypeError(name + "() takes no keyword arguments"); + String argsblurb; + if(minargs == maxargs) { + if(minargs == 0) + argsblurb = "no arguments"; + else if(minargs == 1) + argsblurb = "exactly one argument"; + else + argsblurb = minargs + " arguments"; + } else if(maxargs == -1) { + return Py.TypeError(name + "() requires at least " + minargs + + " (" + nargs + " given)"); + } else { + if(minargs <= 0) + argsblurb = "at most " + maxargs + " arguments"; + else + argsblurb = minargs + "-" + maxargs + " arguments"; + } + return Py.TypeError(name + "() takes " + argsblurb + " (" + nargs + + " given)"); + } + + public PyException unexpectedCall(int nargs, boolean keywords) { + return unexpectedCall(nargs, keywords, name, minargs, maxargs); + } + } +} Modified: trunk/jython/src/org/python/core/PyBuiltinFunction.java =================================================================== --- trunk/jython/src/org/python/core/PyBuiltinFunction.java 2008-10-19 03:04:44 UTC (rev 5464) +++ trunk/jython/src/org/python/core/PyBuiltinFunction.java 2008-10-19 05:14:22 UTC (rev 5465) @@ -1,144 +1,41 @@ package org.python.core; -import org.python.expose.ExposedGet; -import org.python.expose.ExposedType; +import org.python.expose.ExposeAsSuperclass; -// XXX: not subclassable -@ExposedType(name = "builtin_function_or_method") -public abstract class PyBuiltinFunction extends PyObject { +public class PyBuiltinFunction extends PyBuiltinCallable implements ExposeAsSuperclass { - protected Info info; + private PyString doc; - protected PyBuiltinFunction(PyType type, Info info) { - super(type); - this.info = info; + protected PyBuiltinFunction(String name, String doc) { + this(name, -1, -1, doc); } - protected PyBuiltinFunction(Info info) { - this.info = info; + protected PyBuiltinFunction(String name, int minargs, int maxargs, String doc) { + super(new DefaultInfo(name, minargs, maxargs)); + this.doc = doc == null ? null : Py.newString(doc); } - /** - * @return a new instance of this type of PyBuiltinFunction bound to self - */ - abstract public PyBuiltinFunction bind(PyObject self); - - @ExposedGet(name = "__name__") - public PyObject fastGetName() { - return Py.newString(this.info.getName()); - } - - @ExposedGet(name = "__doc__") public PyObject fastGetDoc() { - return Py.None; + return doc; } - @ExposedGet(name = "__module__") - public PyObject getModule() { - return Py.None; + public boolean isMappingType() { + return false; } - @ExposedGet(name = "__call__") - public PyObject makeCall() { - return this; + public boolean isNumberType() { + return false; } - @ExposedGet(name = "__self__") - public PyObject getSelf() { - return Py.None; + public boolean isSequenceType() { + return false; } - public void setInfo(Info info) { - this.info = info; + public PyBuiltinCallable bind(PyObject self) { + throw Py.TypeError("Can't bind a builtin function"); } public String toString() { - PyObject self = getSelf(); - if (self == null) { - return String.format("<built-in function %s>", info.getName()); - } else { - return String.format("<built-in method %s of %s object at %s>", info.getName(), - self.getType().fastGetName(), Py.idstr(self)); - } + return "<built-in function " + info.getName() + ">"; } - - public interface Info { - - String getName(); - - int getMaxargs(); - - int getMinargs(); - - PyException unexpectedCall(int nargs, boolean keywords); - } - - public static class DefaultInfo implements Info { - - public DefaultInfo(String name, int minargs, int maxargs) { - this.name = name; - this.minargs = minargs; - this.maxargs = maxargs; - } - - public DefaultInfo(String name) { - this(name, -1, -1); - } - - private String name; - - private int maxargs, minargs; - - public String getName() { - return name; - } - - public int getMaxargs() { - return maxargs; - } - - public int getMinargs() { - return minargs; - } - - public static boolean check(int nargs, int minargs, int maxargs) { - if(nargs < minargs) - return false; - if(maxargs != -1 && nargs > maxargs) - return false; - return true; - } - - public static PyException unexpectedCall(int nargs, - boolean keywords, - String name, - int minargs, - int maxargs) { - if(keywords) - return Py.TypeError(name + "() takes no keyword arguments"); - String argsblurb; - if(minargs == maxargs) { - if(minargs == 0) - argsblurb = "no arguments"; - else if(minargs == 1) - argsblurb = "exactly one argument"; - else - argsblurb = minargs + " arguments"; - } else if(maxargs == -1) { - return Py.TypeError(name + "() requires at least " + minargs - + " (" + nargs + " given)"); - } else { - if(minargs <= 0) - argsblurb = "at most " + maxargs + " arguments"; - else - argsblurb = minargs + "-" + maxargs + " arguments"; - } - return Py.TypeError(name + "() takes " + argsblurb + " (" + nargs - + " given)"); - } - - public PyException unexpectedCall(int nargs, boolean keywords) { - return unexpectedCall(nargs, keywords, name, minargs, maxargs); - } - } } Added: trunk/jython/src/org/python/core/PyBuiltinFunctionNarrow.java =================================================================== --- trunk/jython/src/org/python/core/PyBuiltinFunctionNarrow.java (rev 0) +++ trunk/jython/src/org/python/core/PyBuiltinFunctionNarrow.java 2008-10-19 05:14:22 UTC (rev 5465) @@ -0,0 +1,58 @@ +package org.python.core; + +public class PyBuiltinFunctionNarrow extends PyBuiltinFunction { + + protected PyBuiltinFunctionNarrow(String name, int minargs, int maxargs, String doc) { + super(name, minargs, maxargs, doc); + } + + public PyObject fancyCall(PyObject[] args) { + throw info.unexpectedCall(args.length, false); + } + + public PyObject __call__(PyObject[] args) { + int nargs = args.length; + switch(nargs){ + case 0: + return __call__(); + case 1: + return __call__(args[0]); + case 2: + return __call__(args[0], args[1]); + case 3: + return __call__(args[0], args[1], args[2]); + case 4: + return __call__(args[0], args[1], args[2], args[3]); + default: + return fancyCall(args); + } + } + + public PyObject __call__(PyObject[] args, String[] kws) { + if (kws.length != 0) { + throw Py.TypeError(fastGetName() + "() takes no keyword arguments"); + } + return __call__(args); + } + + + public PyObject __call__() { + throw info.unexpectedCall(0, false); + } + + public PyObject __call__(PyObject arg1) { + throw info.unexpectedCall(1, false); + } + + public PyObject __call__(PyObject arg1, PyObject arg2) { + throw info.unexpectedCall(2, false); + } + + public PyObject __call__(PyObject arg1, PyObject arg2, PyObject arg3) { + throw info.unexpectedCall(3, false); + } + + public PyObject __call__(PyObject arg1, PyObject arg2, PyObject arg3, PyObject arg4) { + throw info.unexpectedCall(4, false); + } +} Modified: trunk/jython/src/org/python/core/PyBuiltinFunctionSet.java =================================================================== --- trunk/jython/src/org/python/core/PyBuiltinFunctionSet.java 2008-10-19 03:04:44 UTC (rev 5464) +++ trunk/jython/src/org/python/core/PyBuiltinFunctionSet.java 2008-10-19 05:14:22 UTC (rev 5465) @@ -1,34 +1,30 @@ // Copyright (c) Corporation for National Research Initiatives package org.python.core; -import org.python.expose.ExposeAsSuperclass; - /** * A helper class for faster implementations of commonly called methods. * <p> * Subclasses of PyBuiltinFunctionSet will implement some or all of the __call__ * method with a switch on the index number. - * + * */ -public class PyBuiltinFunctionSet extends PyBuiltinFunction implements ExposeAsSuperclass { +public class PyBuiltinFunctionSet extends PyBuiltinFunctionNarrow { // used as an index into a big switch statement in the various derived // class's __call__() methods. - protected int index; + protected final int index; - private PyObject doc = Py.None; - /** * Creates a PyBuiltinFunctionSet that expects 1 argument. */ public PyBuiltinFunctionSet(String name, int index){ this(name, index, 1); } - + public PyBuiltinFunctionSet(String name, int index, int numargs){ this(name, index, numargs, numargs); } - + public PyBuiltinFunctionSet(String name, int index, int minargs, int maxargs){ this(name, index, minargs, maxargs, null); } @@ -39,87 +35,8 @@ int minargs, int maxargs, String doc) { - super(new DefaultInfo(name, minargs, maxargs)); + super(name, minargs, maxargs, doc); this.index = index; - if(doc != null) { - this.doc = Py.newString(doc); - } } - public PyObject fastGetDoc() { - return doc; - } - - public boolean isMappingType() { - return false; - } - - public boolean isNumberType() { - return false; - } - - public boolean isSequenceType() { - return false; - } - - public PyObject fancyCall(PyObject[] args) { - throw info.unexpectedCall(args.length, false); - } - - public PyObject __call__(PyObject[] args) { - int nargs = args.length; - switch(nargs){ - case 0: - return __call__(); - case 1: - return __call__(args[0]); - case 2: - return __call__(args[0], args[1]); - case 3: - return __call__(args[0], args[1], args[2]); - case 4: - return __call__(args[0], args[1], args[2], args[3]); - default: - return fancyCall(args); - } - } - - public PyObject __call__(PyObject[] args, String[] kws) { - if (kws.length != 0) { - throw Py.TypeError(fastGetName() + "() takes no keyword arguments"); - } - return __call__(args); - } - - public PyObject __call__() { - throw info.unexpectedCall(0, false); - } - - public PyObject __call__(PyObject arg1) { - throw info.unexpectedCall(1, false); - } - - public PyObject __call__(PyObject arg1, PyObject arg2) { - throw info.unexpectedCall(2, false); - } - - public PyObject __call__(PyObject arg1, PyObject arg2, PyObject arg3) { - throw info.unexpectedCall(3, false); - } - - public PyObject __call__(PyObject arg1, - PyObject arg2, - PyObject arg3, - PyObject arg4) { - throw info.unexpectedCall(4, false); - } - - public PyBuiltinFunction bind(PyObject self) { - throw Py.TypeError("Can't bind a builtin function"); - } - - public String toString(){ - return "<built-in function "+info.getName()+">"; - } - } Modified: trunk/jython/src/org/python/core/PyBuiltinMethod.java =================================================================== --- trunk/jython/src/org/python/core/PyBuiltinMethod.java 2008-10-19 03:04:44 UTC (rev 5464) +++ trunk/jython/src/org/python/core/PyBuiltinMethod.java 2008-10-19 05:14:22 UTC (rev 5465) @@ -2,7 +2,7 @@ import org.python.expose.ExposeAsSuperclass; -public abstract class PyBuiltinMethod extends PyBuiltinFunction implements ExposeAsSuperclass { +public abstract class PyBuiltinMethod extends PyBuiltinCallable implements ExposeAsSuperclass { protected PyObject self; Modified: trunk/jython/src/org/python/core/PyBuiltinMethodNarrow.java =================================================================== --- trunk/jython/src/org/python/core/PyBuiltinMethodNarrow.java 2008-10-19 03:04:44 UTC (rev 5464) +++ trunk/jython/src/org/python/core/PyBuiltinMethodNarrow.java 2008-10-19 05:14:22 UTC (rev 5465) @@ -1,7 +1,5 @@ package org.python.core; -import org.python.core.PyBuiltinFunction.DefaultInfo; - public abstract class PyBuiltinMethodNarrow extends PyBuiltinMethod { protected PyBuiltinMethodNarrow(String name, int minArgs, int maxArgs) { Modified: trunk/jython/src/org/python/core/PyBuiltinMethodSet.java =================================================================== --- trunk/jython/src/org/python/core/PyBuiltinMethodSet.java 2008-10-19 03:04:44 UTC (rev 5464) +++ trunk/jython/src/org/python/core/PyBuiltinMethodSet.java 2008-10-19 05:14:22 UTC (rev 5465) @@ -25,7 +25,7 @@ return this; } - public PyBuiltinFunction bind(PyObject bindTo) { + public PyBuiltinCallable bind(PyObject bindTo) { if(__self__ == Py.None) { PyBuiltinMethodSet bindable; try { Modified: trunk/jython/src/org/python/core/PyClassMethodDescr.java =================================================================== --- trunk/jython/src/org/python/core/PyClassMethodDescr.java 2008-10-19 03:04:44 UTC (rev 5464) +++ trunk/jython/src/org/python/core/PyClassMethodDescr.java 2008-10-19 05:14:22 UTC (rev 5465) @@ -8,7 +8,7 @@ public static final PyType TYPE = PyType.fromClass(PyClassMethodDescr.class); - PyClassMethodDescr(PyType t, PyBuiltinFunction meth) { + PyClassMethodDescr(PyType t, PyBuiltinCallable meth) { super(t, meth); } Modified: trunk/jython/src/org/python/core/PyDictionary.java =================================================================== --- trunk/jython/src/org/python/core/PyDictionary.java 2008-10-19 03:04:44 UTC (rev 5464) +++ trunk/jython/src/org/python/core/PyDictionary.java 2008-10-19 05:14:22 UTC (rev 5465) @@ -422,7 +422,7 @@ private void updateCommon(PyObject[] args, String[] keywords, String methName) { int nargs = args.length - keywords.length; if (nargs > 1) { - throw PyBuiltinFunction.DefaultInfo.unexpectedCall(nargs, false, methName, 0, 1); + throw PyBuiltinCallable.DefaultInfo.unexpectedCall(nargs, false, methName, 0, 1); } if (nargs == 1) { PyObject arg = args[0]; Modified: trunk/jython/src/org/python/core/PyEnumerate.java =================================================================== --- trunk/jython/src/org/python/core/PyEnumerate.java 2008-10-19 03:04:44 UTC (rev 5464) +++ trunk/jython/src/org/python/core/PyEnumerate.java 2008-10-19 05:14:22 UTC (rev 5465) @@ -51,7 +51,7 @@ public final static PyObject enumerate_new(PyNewWrapper new_, boolean init, PyType subtype, PyObject[] args, String[] keywords) { if (args.length != 1) { - throw PyBuiltinFunction.DefaultInfo.unexpectedCall(args.length, false, "enumerate", 0, + throw PyBuiltinCallable.DefaultInfo.unexpectedCall(args.length, false, "enumerate", 0, 1); } if (new_.for_type == subtype) { Modified: trunk/jython/src/org/python/core/PyInstance.java =================================================================== --- trunk/jython/src/org/python/core/PyInstance.java 2008-10-19 03:04:44 UTC (rev 5464) +++ trunk/jython/src/org/python/core/PyInstance.java 2008-10-19 05:14:22 UTC (rev 5465) @@ -12,12 +12,12 @@ { // xxx doc, final name public transient PyClass instclass; - + // xxx public PyObject fastGetClass() { return instclass; } - + //This field is only used by Python subclasses of Java classes Object javaProxy; @@ -31,7 +31,7 @@ throws java.io.IOException, ClassNotFoundException { in.defaultReadObject(); - + String module = in.readUTF(); String name = in.readUTF(); @@ -153,9 +153,8 @@ return javaProxy; if (instclass.__tojava__ != null) { - //try { - PyObject ret = - instclass.__tojava__.__call__(this, PyJavaClass.lookup(c)); + // try { + PyObject ret = instclass.__tojava__.__call__(this, PyJavaClass.lookup(c)); if (ret == Py.None) return Py.NoConversion; @@ -221,8 +220,8 @@ PyObject[] result2 = instclass.lookupGivingClass(name, stopAtJava); if (result2[0] != null) // xxx do we need to use result2[1] (wherefound) for java cases for backw comp? - return result2[0].__get__(this, instclass); - // xxx do we need to use + return result2[0].__get__(this, instclass); + // xxx do we need to use return ifindfunction(name); } @@ -429,7 +428,7 @@ smod = ((PyString)mod).toString() + '.'; } } - return new PyString("<" + smod + instclass.__name__ + " instance at " + + return new PyString("<" + smod + instclass.__name__ + " instance at " + Py.idstr(this) + ">"); } @@ -483,8 +482,8 @@ if (coerced != null) { v = coerced[0]; w = coerced[1]; - if (!(v instanceof PyInstance) && - !(w instanceof PyInstance)) + if (!(v instanceof PyInstance) && + !(w instanceof PyInstance)) return v._cmp(w); } else { v = this; @@ -497,8 +496,8 @@ int result = ((PyInteger)ret).getValue(); return result < 0 ? -1 : result > 0 ? 1 : 0; } - throw Py.TypeError("__cmp__() must return int"); - } + throw Py.TypeError("__cmp__() must return int"); + } } if (w instanceof PyInstance) { ret = ((PyInstance)w).invoke_ex("__cmp__",v); @@ -507,9 +506,9 @@ int result = ((PyInteger)ret).getValue(); return -(result < 0 ? -1 : result > 0 ? 1 : 0); } - throw Py.TypeError("__cmp__() must return int"); - } - + throw Py.TypeError("__cmp__() must return int"); + } + } return -2; } Modified: trunk/jython/src/org/python/core/PyMethodDescr.java =================================================================== --- trunk/jython/src/org/python/core/PyMethodDescr.java 2008-10-19 03:04:44 UTC (rev 5464) +++ trunk/jython/src/org/python/core/PyMethodDescr.java 2008-10-19 05:14:22 UTC (rev 5465) @@ -5,13 +5,13 @@ import org.python.expose.ExposedType; @ExposedType(name = "method_descriptor", base = PyObject.class) -public class PyMethodDescr extends PyDescriptor implements PyBuiltinFunction.Info { +public class PyMethodDescr extends PyDescriptor implements PyBuiltinCallable.Info { protected int minargs, maxargs; - protected PyBuiltinFunction meth; + protected PyBuiltinCallable meth; - public PyMethodDescr(PyType t, PyBuiltinFunction func) { + public PyMethodDescr(PyType t, PyBuiltinCallable func) { name = func.info.getName(); dtype = t; minargs = func.info.getMinargs(); @@ -50,7 +50,7 @@ } public PyException unexpectedCall(int nargs, boolean keywords) { - return PyBuiltinFunction.DefaultInfo.unexpectedCall(nargs, keywords, name, minargs, + return PyBuiltinCallable.DefaultInfo.unexpectedCall(nargs, keywords, name, minargs, maxargs); } Modified: trunk/jython/src/org/python/core/PyNewWrapper.java =================================================================== --- trunk/jython/src/org/python/core/PyNewWrapper.java 2008-10-19 03:04:44 UTC (rev 5464) +++ trunk/jython/src/org/python/core/PyNewWrapper.java 2008-10-19 05:14:22 UTC (rev 5465) @@ -29,7 +29,7 @@ PyObject[] args, String[] keywords); - public PyBuiltinFunction bind(PyObject self) { + public PyBuiltinCallable bind(PyObject self) { throw Py.SystemError("__new__ wrappers are already bound"); } Modified: trunk/jython/src/org/python/core/PyObject.java =================================================================== --- trunk/jython/src/org/python/core/PyObject.java 2008-10-19 03:04:44 UTC (rev 5464) +++ trunk/jython/src/org/python/core/PyObject.java 2008-10-19 05:14:22 UTC (rev 5465) @@ -332,8 +332,8 @@ String name; if (this instanceof PyFunction) { name = ((PyFunction) this).__name__ + "() "; - } else if (this instanceof PyBuiltinFunction) { - name = ((PyBuiltinFunction)this).fastGetName().toString() + "() "; + } else if (this instanceof PyBuiltinCallable) { + name = ((PyBuiltinCallable)this).fastGetName().toString() + "() "; } else { name = getType().fastGetName() + " "; } Modified: trunk/jython/src/org/python/core/PySet.java =================================================================== --- trunk/jython/src/org/python/core/PySet.java 2008-10-19 03:04:44 UTC (rev 5464) +++ trunk/jython/src/org/python/core/PySet.java 2008-10-19 05:14:22 UTC (rev 5465) @@ -30,7 +30,7 @@ final void set___init__(PyObject[] args, String[] kwds) { int nargs = args.length - kwds.length; if (nargs > 1) { - throw PyBuiltinFunction.DefaultInfo.unexpectedCall(nargs, false, "Set", 0, 1); + throw PyBuiltinCallable.DefaultInfo.unexpectedCall(nargs, false, "Set", 0, 1); } if (nargs == 0) { return; Modified: trunk/jython/src/org/python/core/PyStringMap.java =================================================================== --- trunk/jython/src/org/python/core/PyStringMap.java 2008-10-19 03:04:44 UTC (rev 5464) +++ trunk/jython/src/org/python/core/PyStringMap.java 2008-10-19 05:14:22 UTC (rev 5465) @@ -242,7 +242,7 @@ public void update(PyObject[] args, String[] keywords) { int nargs = args.length - keywords.length; if (nargs > 1) { - throw PyBuiltinFunction.DefaultInfo.unexpectedCall(nargs, false, "update", 0, 1); + throw PyBuiltinCallable.DefaultInfo.unexpectedCall(nargs, false, "update", 0, 1); } if (nargs == 1) { PyObject arg = args[0]; Modified: trunk/jython/src/org/python/core/PySuper.java =================================================================== --- trunk/jython/src/org/python/core/PySuper.java 2008-10-19 03:04:44 UTC (rev 5464) +++ trunk/jython/src/org/python/core/PySuper.java 2008-10-19 05:14:22 UTC (rev 5465) @@ -34,8 +34,8 @@ @ExposedMethod @ExposedNew public void super___init__(PyObject[] args, String[] keywords) { - if (keywords.length != 0 || !PyBuiltinFunction.DefaultInfo.check(args.length, 1, 2)) { - throw PyBuiltinFunction.DefaultInfo.unexpectedCall(args.length, keywords.length != 0, + if (keywords.length != 0 || !PyBuiltinCallable.DefaultInfo.check(args.length, 1, 2)) { + throw PyBuiltinCallable.DefaultInfo.unexpectedCall(args.length, keywords.length != 0, "super", 1, 2); } if (!(args[0] instanceof PyType)) { Modified: trunk/jython/src/org/python/core/PyType.java =================================================================== --- trunk/jython/src/org/python/core/PyType.java 2008-10-19 03:04:44 UTC (rev 5464) +++ trunk/jython/src/org/python/core/PyType.java 2008-10-19 05:14:22 UTC (rev 5465) @@ -13,6 +13,7 @@ import java.util.HashSet; import java.util.Iterator; import java.util.List; +import java.util.Map; import org.python.core.util.StringUtil; import org.python.expose.ExposeAsSuperclass; @@ -260,8 +261,7 @@ newtype.has_delete = newtype.lookup("__delete__") != null; newtype.needs_finalizer = newtype.lookup("__del__") != null; - for (int i = 0; i < bases_list.length; i++) { - PyObject cur = bases_list[i]; + for (PyObject cur : bases_list) { if (cur instanceof PyType) ((PyType)cur).attachSubclass(newtype); } @@ -338,10 +338,9 @@ // BOOTSTRAP_TYPES will be filled in by addBuilder later return; } - HashMap<String, Object> propnames = new HashMap<String, Object>(); + Map<String, Object> propnames = new HashMap<String, Object>(); Method[] methods = c.getMethods(); - for (int i = 0; i < methods.length; i++) { - Method meth = methods[i]; + for (Method meth : methods) { Class declaring = meth.getDeclaringClass(); if (declaring != base && base.isAssignableFrom(declaring) && !ignore(meth)) { String methname = meth.getName(); @@ -369,8 +368,7 @@ } } } - for (int i = 0; i < methods.length; i++) { - Method meth = methods[i]; + for (Method meth : methods) { String nmethname = normalize_name(meth.getName()); PyReflectedFunction reflfunc = (PyReflectedFunction)dict.__finditem__(nmethname); if (reflfunc != null) { @@ -378,8 +376,7 @@ } } Field[] fields = c.getFields(); - for (int i = 0; i < fields.length; i++) { - Field field = fields[i]; + for (Field field : fields) { Class declaring = field.getDeclaringClass(); if (declaring != base && base.isAssignableFrom(declaring)) { String fldname = field.getName(); @@ -404,8 +401,7 @@ dict.__setitem__(normalize_name(fldname), new PyReflectedField(field)); } } - for (Iterator iter = propnames.keySet().iterator(); iter.hasNext();) { - String propname = (String)iter.next(); + for (String propname : propnames.keySet()) { String npropname = normalize_name(StringUtil.decapitalize(propname)); PyObject prev = dict.__finditem__(npropname); if (prev != null && prev instanceof PyReflectedFunction) { @@ -437,8 +433,8 @@ Constructor[] ctrs = c.getConstructors(); if (ctrs.length != 0) { final PyReflectedConstructor reflctr = new PyReflectedConstructor("_new_impl"); - for (int i = 0; i < ctrs.length; i++) { - reflctr.addConstructor(ctrs[i]); + 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, @@ -557,14 +553,14 @@ base = newBase; mro_internal(); mro_subclasses(savedSubMros); - for (int i = 0; i < savedBases.length; i++) { - if (savedBases[i] instanceof PyType) { - ((PyType)savedBases[i]).detachSubclass(this); + for (PyObject saved : savedBases) { + if (saved instanceof PyType) { + ((PyType)saved).detachSubclass(this); } } - for (int i = 0; i < newBases.length; i++) { - if (newBases[i] instanceof PyType) { - ((PyType)newBases[i]).attachSubclass(this); + for (PyObject newb : newBases) { + if (newb instanceof PyType) { + ((PyType)newb).attachSubclass(this); } } } catch (PyException t) { @@ -703,8 +699,8 @@ acc.add(classic_cl); } PyObject[] bases = classic_cl.__bases__.getArray(); - for (int i = 0; i < bases.length; i++) { - fill_classic_mro(acc,(PyClass)bases[i]); + for (PyObject base : bases) { + fill_classic_mro(acc,(PyClass)base); } } @@ -850,24 +846,22 @@ PyType winner = null; PyType candidate = null; PyType best = null; - for (int i = 0; i < bases.length; i++) { - PyObject base_proto = bases[i]; - if (base_proto instanceof PyClass) { + for (PyObject base : bases) { + if (base instanceof PyClass) { continue; } - if (!(base_proto instanceof PyType)) { + if (!(base instanceof PyType)) { throw Py.TypeError("bases must be types"); } - PyType base = (PyType)base_proto; - candidate = solid_base(base); + candidate = solid_base((PyType)base); if (winner == null) { winner = candidate; - best = base; + best = (PyType)base; } else if (winner.isSubType(candidate)) { ; } else if (candidate.isSubType(winner)) { winner = candidate; - best = base; + best = (PyType)base; } else { throw Py.TypeError("multiple bases have instance lay-out conflict"); } @@ -889,18 +883,17 @@ */ private static PyType findMostDerivedMetatype(PyObject[] bases_list, PyType initialMetatype) { PyType winner = initialMetatype; - for (int i = 0; i < bases_list.length; i++) { - PyObject bases_i = bases_list[i]; - if (bases_i instanceof PyJavaClass) { + for (PyObject base : bases_list) { + if (base instanceof PyJavaClass) { throw Py.TypeError("can't mix new-style and java classes"); } - if (bases_i instanceof PyClass) { - if (((PyClass)bases_i).proxyClass != null) { + if (base instanceof PyClass) { + if (((PyClass)base).proxyClass != null) { throw Py.TypeError("can't mix new-style and java classes"); } continue; } - PyType curtype = bases_i.getType(); + PyType curtype = base.getType(); if (winner.isSubType(curtype)) { continue; } @@ -962,8 +955,8 @@ if (mro == null) { return null; } - for (int i = 0; i < mro.length; i++) { - PyObject dict = mro[i].fastGetDict(); + for (PyObject element : mro) { + PyObject dict = element.fastGetDict(); if (dict != null) { PyObject obj = dict.__finditem__(name); if (obj != null) @@ -978,8 +971,7 @@ if (mro == null) { return null; } - for (int i = 0; i < mro.length; i++) { - PyObject t = mro[i]; + for (PyObject t : mro) { PyObject dict = t.fastGetDict(); if (dict != null) { PyObject obj = dict.__finditem__(name); @@ -1047,8 +1039,8 @@ private static boolean ignore(Method meth) { Class[] exceptions = meth.getExceptionTypes(); - for (int j = 0; j < exceptions.length; j++) { - if (exceptions[j] == PyIgnoreMethodTag.class) { + for (Class exception : exceptions) { + if (exception == PyIgnoreMethodTag.class) { return true; } } @@ -1261,8 +1253,8 @@ if (mro == null) { return; } - for (int i = 0; i < mro.length; i++) { - mro[i].addKeys(accum, "__dict__"); + for (PyObject element : mro) { + element.addKeys(accum, "__dict__"); } } Modified: trunk/jython/src/org/python/core/__builtin__.java =================================================================== --- trunk/jython/src/org/python/core/__builtin__.java 2008-10-19 03:04:44 UTC (rev 5464) +++ trunk/jython/src/org/python/core/__builtin__.java 2008-10-19 05:14:22 UTC (rev 5465) @@ -1,15 +1,11 @@ // Copyright (c) Corporation for National Research Initiatives package org.python.core; -import java.util.Arrays; import java.util.Iterator; import java.util.Map; import org.python.antlr.ast.modType; import org.python.core.util.RelativeFile; -import org.python.expose.ExposedGet; -import org.python.expose.ExposedNew; -import org.python.expose.ExposedType; class BuiltinFunctions extends PyBuiltinFunctionSet { @@ -236,7 +232,7 @@ /** * @param intern - should the resulting string be interned - * @return arg as a String, or throws TypeError with message if asString throws a ConversionException. + * @return arg as a String, or throws TypeError with message if asString throws a ConversionException. */ private String asString(PyObject arg, String message, boolean intern) { @@ -280,7 +276,7 @@ } if (args[0] instanceof PyUnicode) { - flags += PyTableCode.PyCF_SOURCE_IS_UTF8; + flags += PyTableCode.PyCF_SOURCE_IS_UTF8; } return __builtin__.compile(args[0].toString(), args[1].toString(), args[2].toString(), flags, dont_inherit); case 29: @@ -373,23 +369,23 @@ dict.__setitem__("iter", new BuiltinFunctions("iter", 27, 1, 2)); dict.__setitem__("locals", new BuiltinFunctions("locals", 28, 0)); dict.__setitem__("map", new BuiltinFunctions("map", 29, 2, -1)); - dict.__setitem__("max", MaxFunction.INSTANCE); - dict.__setitem__("min", MinFunction.INSTANCE); + dict.__setitem__("max", new MaxFunction()); + dict.__setitem__("min", new MinFunction()); dict.__setitem__("oct", new BuiltinFunctions("oct", 32, 1)); dict.__setitem__("pow", new BuiltinFunctions("pow", 33, 2, 3)); dict.__setitem__("raw_input", new BuiltinFunctions("raw_input", 34, 0, 1)); dict.__setitem__("reduce", new BuiltinFunctions("reduce", 35, 2, 3)); dict.__setitem__("reload", new BuiltinFunctions("reload", 36, 1)); dict.__setitem__("repr", new BuiltinFunctions("repr", 37, 1)); - dict.__setitem__("round", RoundFunction.INSTANCE); + dict.__setitem__("round", new RoundFunction()); dict.__setitem__("setattr", new BuiltinFunctions("setattr", 39, 3)); dict.__setitem__("vars", new BuiltinFunctions("vars", 41, 0, 1)); dict.__setitem__("zip", new BuiltinFunctions("zip", 43, 0, -1)); dict.__setitem__("reversed", new BuiltinFunctions("reversed", 45, 1)); - dict.__setitem__("__import__", ImportFunction.INSTANCE); - dict.__setitem__("sorted", SortedFunction.INSTANCE); - dict.__setitem__("all", AllFunction.INSTANCE); - dict.__setitem__("any", AnyFunction.INSTANCE); + dict.__setitem__("__import__", new ImportFunction()); + dict.__setitem__("sorted", new SortedFunction()); + dict.__setitem__("all", new AllFunction()); + dict.__setitem__("any", new AnyFunction()); } public static PyObject abs(PyObject o) { @@ -399,7 +395,7 @@ public static PyObject apply(PyObject o) { return o.__call__(); } - + public static PyObject apply(PyObject o, PyObject args) { return o.__call__(Py.make_array(args)); } @@ -465,7 +461,7 @@ public static PyObject compile(modType node, String filename, String kind) { return Py.compile_flags(node, filename, kind, Py.getCompilerFlags()); } - + public static PyObject compile(String data, String filename, String kind, int flags, boolean dont_inherit) { if ((flags & ~PyTableCode.CO_ALL_FEATURES) != 0) { throw Py.ValueError("compile(): unrecognised flags"); @@ -518,16 +514,16 @@ (o.__findattr__("__getitem__") != null && (!rw || o.__findattr__("__setitem__") != null)); } - + private static void verify_mappings(PyObject globals, PyObject locals, boolean rw) { if (!PyMapping_check(globals, rw)) { throw Py.TypeError("globals must be a mapping"); - } + } if (!PyMapping_check(locals, rw)) { throw Py.TypeError("locals must be a mapping"); } } - + public static PyObject eval(PyObject o, PyObject globals, PyObject locals) { verify_mappings(globals, locals, false); PyCode code; @@ -900,7 +896,7 @@ throw Py.TypeError("ord() expected a character, but string of length " + length + " found"); } - + public static PyObject pow(PyObject x, PyObject y) { return x._pow(y); } @@ -1037,7 +1033,7 @@ return (PyString) ret; } } - + public static String raw_input(PyObject prompt, PyObject file) { PyObject stdout = Py.getSystemState().stdout; if (stdout instanceof PyAttributeDeleted) { @@ -1157,7 +1153,7 @@ public static PyObject zip() { return new PyList(); } - + public static PyObject zip(PyObject[] argstar) { int itemsize = argstar.length; @@ -1233,81 +1229,40 @@ } } -// simulates a PyBuiltinFunction for functions not using the PyBuiltinFunctionSet approach of above -abstract class ExtendedBuiltinFunction extends PyObject { - public static final PyType TYPE = PyType.fromClass(PyBuiltinFunction.class); - @ExposedGet(name = "__class__") - @Override - public PyType getType() { - return TYPE; +class ImportFunction extends PyBuiltinFunction { + ImportFunction() { + super("__import__", + "__import__(name, globals={}, locals={}, fromlist=[], level=-1) -> module\n\n" + + "Import a module. The globals are only used to determine the context;\n" + + "they are not modified. The locals are currently unused. The fromlist\n" + + "should be a list of names to emulate ``from name import ...'', or an\n" + + "empty list to emulate ``import name''.\n" + + "When importing a module from a package, note that __import__('A.B', ...)\n" + + "returns package A when fromlist is empty, but its submodule B when\n" + + "fromlist is not empty. Level is used to determine whether to perform \n" + + "absolute or relative imports. -1 is the original strategy of attempting\n" + + "both absolute and relative imports, 0 is absolute, a positive number\n" + + "is the number of parent directories to search relative to the current module."); } -} -class ImportFunction extends ExtendedBuiltinFunction { - static final ImportFunction INSTANCE = new ImportFunction(); - - private ImportFunction() {} - - @ExposedNew - public static PyObject __new__(PyObject[] args, String[] keyword) { - return INSTANCE; - } - - @ExposedGet(name = "__doc__") - public PyObject getDoc() { - return new PyString("__import__(name, globals={}, locals={}, fromlist=[], level=-1) -> module\n\n" + - "Import a module. The globals are only used to determine the context;\n" + - "they are not modified. The locals are currently unused. The fromlist\n" + - "should be a list of names to emulate ``from name import ...'', or an\n" + - "empty list to emulate ``import name''.\n" + - "When importing a module from a package, note that __import__('A.B', ...)\n" + - "returns package A when fromlist is empty, but its submodule B when\n" + - "fromlist is not empty. Level is used to determine whether to perform \n" + - "absolute or relative imports. -1 is the original strategy of attempting\n" + - "both absolute and relative imports, 0 is absolute, a positive number\n" + - "is the number of parent directories to search relative to the current module."); - } - public PyObject __call__(PyObject args[], String keywords[]) { - ArgParser ap = new ArgParser("__import__", args, keywords, new String[]{"name", "globals", "locals", "fromlist", "level"}, 1); - + ArgParser ap = new ArgParser("__import__", args, keywords, + new String[]{"name", "globals", "locals", "fromlist", "level"}, + 1); String module = ap.getString(0); PyObject globals = ap.getPyObject(1, null); PyObject fromlist = ap.getPyObject(3, Py.EmptyTuple); int level = ap.getInt(4, imp.DEFAULT_LEVEL); - - return load(module, globals, fromlist, level); + return imp.importName(module.intern(), fromlist.__len__() == 0, globals, fromlist, level); } +} - private PyObject load(String module, PyObject globals, PyObject fromlist, int level) { - PyObject mod = imp.importName(module.intern(), fromlist.__len__() == 0, globals, fromlist, level); - return mod; +class SortedFunction extends PyBuiltinFunction { + SortedFunction() { + super("sorted", "sorted(iterable, cmp=None, key=None, reverse=False) --> new sorted list"); } - public String toString() { - return "<built-in function __import__>"; - } - - -} - -class SortedFunction extends ExtendedBuiltinFunction { - static final SortedFunction INSTANCE = new SortedFunction(); - - private SortedFunction() {} - - @ExposedNew - public static PyObject __new__(PyObject[] args, String[] keyword) { - return INSTANCE; - } - - @ExposedGet(name = "__doc__") @Override - public PyObject getDoc() { - return new PyString("sorted(iterable, cmp=None, key=None, reverse=False) --> new sorted list"); - } - - @Override public PyObject __call__(PyObject args[], String kwds[]) { if (args.length == 0) { throw Py.TypeError(" sorted() takes at least 1 argument (0 given)"); @@ -1333,37 +1288,20 @@ seq.sort(cmp, key, reverse); return seq; } - - @Override - public String toString() { - return "<built-in function sorted>"; - } } -class AllFunction extends ExtendedBuiltinFunction { - static final AllFunction INSTANCE = new AllFunction(); - - private AllFunction() {} - - @ExposedNew - public static PyObject __new__(PyObject[] args, String[] keyword) { - return INSTANCE; - } - - @ExposedGet(name = "__doc__") - @Override - public PyObject getDoc() { - return new PyString("all(iterable) -> bool\n\nReturn True if bool(x) is True for all values x in the iterable."); +class AllFunction extends PyBuiltinFunctionNarrow { + AllFunction() { + super("all", 1, 1, + "all(iterable) -> bool\n\n" + + "Return True if bool(x) is True for all values x in the iterable."); } @Override - public PyObject __call__(PyObject args[], String kwds[]) { - if (args.length !=1) { - throw Py.TypeError(" all() takes exactly one argument (" + args.length + " given)"); - } - PyObject iter = args[0].__iter__(); + public PyObject __call__(PyObject arg) { + PyObject iter = arg.__iter__(); if (iter == null) { - throw Py.TypeError("'" + args[0].getType().fastGetName() + "' object is not iterable"); + throw Py.TypeError("'" + arg.getType().fastGetName() + "' object is not iterable"); } for (PyObject item : iter.asIterable()) { if (!item.__nonzero__()) { @@ -1372,78 +1310,44 @@ } return Py.True; } - - @Override - public String toString() { - return "<built-in function all>"; - } } -class AnyFunction extends ExtendedBuiltinFunction { - static final AnyFunction INSTANCE = new AnyFunction(); - - private AnyFunction() {} - - @ExposedNew - public static PyObject __new__(PyObject[] args, String[] keyword) { - return INSTANCE; - } - - @ExposedGet(name = "__doc__") - @Override - public PyObject getDoc() { - return new PyString("any(iterable) -> bool\n\nReturn True if bool(x) is True for any x in the iterable."); +class AnyFunction extends PyBuiltinFunctionNarrow { + AnyFunction() { + super("any", 1, 1, + "any(iterable) -> bool\n\nReturn True if bool(x) is True for any x in the iterable."); } @Override - public PyObject __call__(PyObject args[], String kwds[]) { - if (args.length !=1) { - throw Py.TypeError(" any() takes exactly one argument (" + args.length + " given)"); - } - PyObject iter = args[0].__iter__(); + public PyObject __call__(PyObject arg) { + PyObject iter = arg.__iter__(); if (iter == null) { - throw Py.TypeError("'" + args[0].getType().fastGetName() + "' object is not iterable"); + throw Py.TypeError("'" + arg.getType().fastGetName() + "' object is not iterable"); } for (PyObject item : iter.asIterable()) { if (item.__nonzero__()) { return Py.True; } } - return Py.False; + return Py.False; } - - @Override - public String toString() { - return "<built-in function any>"; - } } -class MaxFunction extends ExtendedBuiltinFunction { - static final MaxFunction INSTANCE = new MaxFunction(); - - private MaxFunction() {} - - @ExposedNew - public static PyObject __new__(PyObject[] args, String[] keyword) { - return INSTANCE; - } - - @ExposedGet(name = "__doc__") - @Override - public PyObject getDoc() { - return new PyString( - "max(iterable[, key=func]) -> value\nmax(a, b, c, ...[, key=func]) -> value\n\n" + - "With a single iterable argument, return its largest item.\n" + - "With two or more arguments, return the largest argument."); +class MaxFunction extends PyBuiltinFunction { + MaxFunction() { + super("max", + "max(iterable[, key=func]) -> value\nmax(a, b, c, ...[, key=func]) -> value\n\n" + + "With a single iterable argument, return its largest item.\n" + + "With two or more arguments, return the largest argument."); } @Override public PyObject __call__(PyObject args[], String kwds[]) { int argslen = args.length; PyObject key = null; - + if (args.length - kwds.length == 0) { - throw Py.TypeError(" max() expected 1 arguments, got 0"); + throw Py.TypeError("max() expected 1 arguments, got 0"); } if (kwds.length > 0) { if (kwds[0].equals("key")) { @@ -1453,23 +1357,18 @@ args = newargs; } else { - throw Py.TypeError(" max() got an unexpected keyword argument"); + throw Py.TypeError("max() got an unexpected keyword argument"); } } - + if (args.length > 1) { return max(new PyTuple(args), key); } else { return max(args[0], key); } - } - - @Override - public String toString() { - return "<built-in function max>"; } - + private static PyObject max(PyObject o, PyObject key) { PyObject max = null; PyObject maxKey = null; @@ -1494,31 +1393,19 @@ } -class MinFunction extends ExtendedBuiltinFunction { - static final MinFunction INSTANCE = new MinFunction(); - - private MinFunction() {} - - @ExposedNew - public static PyObject __new__(PyObject[] args, String[] keyword) { - return INSTANCE; - } - - - @ExposedGet(name = "__doc__") - @Override - public PyObject getDoc() { - return new PyString( - "min(iterable[, key=func]) -> value\nmin(a, b, c, ...[, key=func]) -> value\n\n" + - "With a single iterable argument, return its smallest item.\n" + - "With two or more arguments, return the smallest argument.'"); +class MinFunction extends PyBuiltinFunction { + MinFunction() { + super("min", + "min(iterable[, key=func]) -> value\nmin(a, b, c, ...[, key=func]) -> value\n\n" + + "With a single iterable argument, return its smallest item.\n" + + "With two or more arguments, return the smallest argument.'"); } @Override public PyObject __call__(PyObject args[], String kwds[]) { int argslen = args.length; PyObject key = null; - + if (args.length - kwds.length == 0) { throw Py.TypeError(" min() expected 1 arguments, got 0"); } @@ -1530,10 +1417,10 @@ args = newargs; } else { - throw Py.TypeError(" min() got an unexpected keyword argument"); + throw Py.TypeError("min() got an unexpected keyword argument"); } } - + if (args.length > 1) { return min(new PyTuple(args), key); } @@ -1541,12 +1428,7 @@ return min(args[0], key); } } - - @Override - public String toString() { - return "<built-in function min>"; - } - + private static PyObject min(PyObject o, PyObject key) { PyObject min = null; PyObject minKey = null; @@ -1570,37 +1452,20 @@ } } -class RoundFunction extends ExtendedBuiltinFunction { - static final RoundFunction INSTANCE = new RoundFunction(); - private RoundFunction() {} - - @ExposedNew - public static PyObject __new__(PyObject[] args, String[] keyword) { - return INSTANCE; - } - - @ExposedGet(name = "__doc__") - @Override - public PyObject getDoc() { - return new PyString( - "round(number[, ndigits]) -> floating point number\n\n" + - "Round a number to a given precision in decimal digits (default 0 digits).\n" + - "This always returns a floating point number. Precision may be negative."); +class RoundFunction extends PyBuiltinFunction { + RoundFunction() { + super("round", "round(number[, ndigits]) -> floating point number\n\n" + + "Round a number to a given precision in decimal digits (default 0 digits).\n" + + "This always returns a floating point number. Precision may be negative."); } - - @Override - public String toString() { - return "<built-in function round>"; - } - - @Override + public PyObject __call__(PyObject args[], String kwds[]) { - ArgParser ap = new ArgParser("round", args, kwds, new String[]{"number", "ndigits"}, 0); + ArgParser ap = new ArgParser("round", args, kwds, new String[] {"number", "ndigits"}, 0); PyObject number = ap.getPyObject(0); int ndigits = ap.getInt(1, 0); return round(Py.py2double(number), ndigits); } - + private static PyFloat round(double f, int digits) { boolean neg = f < 0; double multiple = Math.pow(10., digits); Modified: trunk/jython/src/org/python/core/exceptions.java =================================================================== --- trunk/jython/src/org/python/core/exceptions.java 2008-10-19 03:04:44 UTC (rev 5464) +++ trunk/jython/src/org/python/core/exceptions.java 2008-10-19 05:14:22 UTC (rev 5465) @@ -661,7 +661,7 @@ this.javaMethod = javaMethod; } - public PyBuiltinFunction bind(PyObject self) { + public PyBuiltinCallable bind(PyObject self) { return new BoundStaticJavaMethod(getType(), self, info, javaMethod); } Modified: trunk/jython/src/org/python/expose/generate/Py... [truncated message content] |
From: <cg...@us...> - 2008-10-19 03:04:50
|
Revision: 5464 http://jython.svn.sourceforge.net/jython/?rev=5464&view=rev Author: cgroves Date: 2008-10-19 03:04:44 +0000 (Sun, 19 Oct 2008) Log Message: ----------- Some formatting and cleanup Modified Paths: -------------- trunk/jython/src/org/python/core/PyBeanEvent.java trunk/jython/src/org/python/core/PyBeanEventProperty.java trunk/jython/src/org/python/core/PyClass.java trunk/jython/src/org/python/core/PyJavaClass.java Modified: trunk/jython/src/org/python/core/PyBeanEvent.java =================================================================== --- trunk/jython/src/org/python/core/PyBeanEvent.java 2008-10-19 00:01:20 UTC (rev 5463) +++ trunk/jython/src/org/python/core/PyBeanEvent.java 2008-10-19 03:04:44 UTC (rev 5464) @@ -1,6 +1,6 @@ // Copyright (c) Corporation for National Research Initiatives package org.python.core; -import java.lang.reflect.*; +import java.lang.reflect.Method; public class PyBeanEvent extends PyObject { public Method addMethod; @@ -34,7 +34,7 @@ } public String toString() { - return "<beanEvent "+__name__+" for event "+ - eventClass.toString()+" "+Py.idstr(this)+">"; + return "<beanEvent " + __name__ + " for event " + eventClass.toString() + " " + + Py.idstr(this) + ">"; } } Modified: trunk/jython/src/org/python/core/PyBeanEventProperty.java =================================================================== --- trunk/jython/src/org/python/core/PyBeanEventProperty.java 2008-10-19 00:01:20 UTC (rev 5463) +++ trunk/jython/src/org/python/core/PyBeanEventProperty.java 2008-10-19 03:04:44 UTC (rev 5464) @@ -50,17 +50,13 @@ return func; } - private synchronized static Class getAdapterClass(Class c) { - // System.err.println("getting adapter for: "+c+", "+c.getName()); - InternalTables tbl=PyJavaClass.getInternalTables(); - Object o = tbl.getAdapterClass(c); + private synchronized static Class<?> getAdapterClass(Class<?> c) { + InternalTables tbl = PyJavaClass.getInternalTables(); + Class<?> o = tbl.getAdapterClass(c); if (o != null) - return (Class)o; - Class pc = Py.findClass("org.python.proxies."+c.getName()+"$Adapter"); + return o; + Class<?> pc = Py.findClass("org.python.proxies." + c.getName() + "$Adapter"); if (pc == null) { - //System.err.println("adapter not found for: "+ - // "org.python.proxies."+ - // c.getName()+"$Adapter"); pc = MakeProxies.makeAdapter(c); } tbl.putAdapterClass(c, pc); @@ -68,13 +64,11 @@ } private synchronized Object getAdapter(Object self) { - InternalTables tbl=PyJavaClass.getInternalTables(); + InternalTables tbl = PyJavaClass.getInternalTables(); String eventClassName = eventClass.getName(); - Object adapter = tbl.getAdapter(self, eventClassName); if (adapter != null) return adapter; - try { adapter = adapterClass.newInstance(); addMethod.invoke(self, new Object[] {adapter}); @@ -96,8 +90,7 @@ try { adapterField = adapterClass.getField(__name__); } catch (NoSuchFieldException exc) { - throw Py.AttributeError("Internal bean event error: "+ - __name__); + throw Py.AttributeError("Internal bean event error: " + __name__); } } } Modified: trunk/jython/src/org/python/core/PyClass.java =================================================================== --- trunk/jython/src/org/python/core/PyClass.java 2008-10-19 00:01:20 UTC (rev 5463) +++ trunk/jython/src/org/python/core/PyClass.java 2008-10-19 03:04:44 UTC (rev 5464) @@ -2,6 +2,7 @@ package org.python.core; import java.io.Serializable; +import java.lang.reflect.Method; import java.util.ArrayList; import java.util.List; @@ -32,7 +33,7 @@ // Holds the classes for which this is a proxy // Only used when subclassing from a Java class - protected Class proxyClass; + protected Class<?> proxyClass; // xxx map 'super__*' names -> array of methods protected java.util.HashMap super__methods; @@ -43,12 +44,12 @@ /** * Create a python class. - * + * * @param name name of the class. * @param bases A list of base classes. * @param dict The class dict. Normally this dict is returned by the class * code object. - * + * * @see org.python.core.Py#makeClass(String, PyObject[], PyCode, PyObject) */ public PyClass(String name, PyTuple bases, PyObject dict) { @@ -60,12 +61,12 @@ * already have generated a proxyclass. If we do not have a pre-generated * proxyclass, the class initialization method will create such a proxyclass * if bases contain a java class. - * + * * @param name name of the class. * @param bases A list of base classes. * @param dict The class dict. Normally this dict is returned by the class * code object. - * + * * @see org.python.core.Py#makeClass(String, PyObject[], PyCode, PyObject, * Class) */ @@ -144,8 +145,7 @@ super__methods = new java.util.HashMap(); - for (int i = 0; i < proxy_methods.length; i++) { - java.lang.reflect.Method meth = proxy_methods[i]; + for (Method meth : proxy_methods) { String meth_name = meth.getName(); if (meth_name.startsWith("super__")) { java.util.ArrayList samename = (java.util.ArrayList) super__methods @@ -193,7 +193,7 @@ } } - public Object __tojava__(Class c) { + public Object __tojava__(Class<?> c) { if ((c == Object.class || c == Class.class || c == Serializable.class) && proxyClass != null) { return proxyClass; @@ -208,9 +208,8 @@ if (result == null && __bases__ != null) { int n = __bases__.__len__(); for (int i = 0; i < n; i++) { - resolvedClass = (PyClass) (__bases__.__getitem__(i)); - PyObject[] res = resolvedClass.lookupGivingClass(name, - stop_at_java); + resolvedClass = (PyClass)(__bases__.__getitem__(i)); + PyObject[] res = resolvedClass.lookupGivingClass(name, stop_at_java); if (res[0] != null) { return res; } @@ -284,8 +283,8 @@ public void __rawdir__(PyDictionary accum) { addKeys(accum, "__dict__"); PyObject[] bases = __bases__.getArray(); - for (int i = 0; i < bases.length; i++) { - bases[i].__rawdir__(accum); + for (PyObject base : bases) { + base.__rawdir__(accum); } } Modified: trunk/jython/src/org/python/core/PyJavaClass.java =================================================================== --- trunk/jython/src/org/python/core/PyJavaClass.java 2008-10-19 00:01:20 UTC (rev 5463) +++ trunk/jython/src/org/python/core/PyJavaClass.java 2008-10-19 03:04:44 UTC (rev 5464) @@ -1,28 +1,37 @@ // Copyright (c) Corporation for National Research Initiatives package org.python.core; -import org.python.core.packagecache.PackageManager; - +import java.beans.Introspector; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.lang.reflect.Modifier; +import java.util.EventListener; +import org.python.core.packagecache.PackageManager; + /** * A wrapper around a java class. */ +public class PyJavaClass extends PyClass { -public class PyJavaClass extends PyClass -{ + private static InternalTables tbl; + public PyReflectedConstructor __init__; public PackageManager __mgr__; - private static InternalTables tbl; + public String __module__; + private boolean initialized = false; + + // Prevent recursive calls to initialize() + private boolean initializing = false; + public synchronized final static InternalTables getInternalTables() { - if(tbl == null) - tbl = InternalTables.createInternalTables(); + if (tbl == null) { + tbl = InternalTables.createInternalTables(); + } return tbl; } @@ -30,9 +39,9 @@ return proxyClass == null; } - public static final PyJavaClass lookup(String name,PackageManager mgr) { + public static final PyJavaClass lookup(String name, PackageManager mgr) { if (tbl.queryCanonical(name)) { - Class c = mgr.findClass(null,name,"forced java class"); + Class<?> c = mgr.findClass(null, name, "forced java class"); check_lazy_allowed(c); // xxx return lookup(c); } @@ -41,12 +50,12 @@ return ret; } - public synchronized static final PyJavaClass lookup(Class c) { + public synchronized static final PyJavaClass lookup(Class<?> c) { if (tbl == null) { - tbl = InternalTables.createInternalTables(); + tbl = new InternalTables(); PyJavaClass jc = new PyJavaClass(); jc.init(PyJavaClass.class); - tbl.putCanonical(PyJavaClass.class,jc); + tbl.putCanonical(PyJavaClass.class, jc); } PyJavaClass ret = tbl.getCanonical(c); if (ret != null) @@ -54,28 +63,22 @@ PyJavaClass lazy = tbl.getLazyCanonical(c.getName()); if (lazy != null) { initLazy(lazy); - if (lazy.proxyClass == c) return lazy; + if (lazy.proxyClass == c) { + return lazy; + } } - - Class parent = c.getDeclaringClass(); - if (parent == null) - ret = new PyJavaClass(c); - else - ret = new PyJavaInnerClass(c, lookup(parent)); - tbl.putCanonical(c,ret); - + Class<?> parent = c.getDeclaringClass(); + ret = parent == null ? new PyJavaClass(c) : new PyJavaInnerClass(c, lookup(parent)); + tbl.putCanonical(c, ret); return ret; } - private PyJavaClass() { - super(); - } + private PyJavaClass() {} - protected PyJavaClass(Class c) { + protected PyJavaClass(Class<?> c) { init(c); } - public String __module__; /** * Set the full name of this class. */ @@ -85,7 +88,7 @@ __name__ = name; __module__ = ""; } else { - __name__ = name.substring(name.lastIndexOf(".")+1, name.length()); + __name__ = name.substring(name.lastIndexOf(".") + 1, name.length()); __module__ = name.substring(0, name.lastIndexOf(".")); } } @@ -104,7 +107,7 @@ protected void findModule(PyObject dict) {} - protected Class getProxyClass() { + protected Class<?> getProxyClass() { initialize(); return proxyClass; } @@ -112,138 +115,118 @@ // for the moment trying to lazily load a PyObject subclass // is not allowed, (because of the PyJavaClass vs PyType class mismatch) // pending PyJavaClass becoming likely a subclass of PyType - private static final void check_lazy_allowed(Class c) { + private static final void check_lazy_allowed(Class<?> c) { if (PyObject.class.isAssignableFrom(c)) { // xxx throw Py.TypeError("cannot lazy load PyObject subclass"); } } private static final void initLazy(PyJavaClass jc) { - Class c = jc.__mgr__.findClass(null,jc.fullName(),"lazy java class"); + Class<?> c = jc.__mgr__.findClass(null, jc.fullName(), "lazy java class"); check_lazy_allowed(c); // xxx jc.init(c); - tbl.putCanonical(jc.proxyClass,jc); + tbl.putCanonical(jc.proxyClass, jc); jc.__mgr__ = null; } - private boolean initialized=false; - - // Prevent recursive calls to initialize() - private boolean initializing=false; - private synchronized void initialize() { - if (initialized || initializing) + if (initialized || initializing) { return; + } initializing = true; - synchronized(PyJavaClass.class) { + synchronized (PyJavaClass.class) { if (proxyClass == null) { initLazy(this); } } init__bases__(proxyClass); init__dict__(); - - if (ClassDictInit.class.isAssignableFrom(proxyClass) - && proxyClass != ClassDictInit.class) { + if (ClassDictInit.class.isAssignableFrom(proxyClass) && proxyClass != ClassDictInit.class) { try { - Method m = proxyClass.getMethod("classDictInit", - new Class[] { PyObject.class }); - m.invoke(null, new Object[] { __dict__ }); - } - catch (Exception exc) { - // System.err.println("Got exception: " + exc + " " + - // proxyClass); + Method m = proxyClass.getMethod("classDictInit", PyObject.class); + m.invoke(null, __dict__); + } catch (Exception exc) { throw Py.JavaError(exc); } } - if (InitModule.class.isAssignableFrom(proxyClass)) { try { InitModule m = (InitModule)proxyClass.newInstance(); m.initModule(__dict__); - } - catch (Exception exc) { -// System.err.println("Got exception: " + exc); + } catch (Exception exc) { throw Py.JavaError(exc); } } - initialized = true; initializing = false; } private synchronized void init__dict__() { - if (__dict__ != null) + if (__dict__ != null) { return; + } PyStringMap d = new PyStringMap(); -// d.__setitem__("__module__", Py.None); __dict__ = d; try { Method[] methods = getAccessibleMethods(proxyClass); setBeanInfoCustom(proxyClass, methods); setFields(proxyClass); setMethods(proxyClass, methods); - } catch(SecurityException se) {} + } catch (SecurityException se) {} } - private synchronized void init__bases__(Class c) { - if (__bases__ != null) return; - + private synchronized void init__bases__(Class<?> c) { + if (__bases__ != null) + return; Class interfaces[] = getAccessibleInterfaces(c); int nInterfaces = interfaces.length; int nBases = 0; int i; - for (i=0; i<nInterfaces; i++) { + for (i = 0; i < nInterfaces; i++) { Class inter = interfaces[i]; - if (inter == InitModule.class || inter == PyProxy.class || - inter == ClassDictInit.class) + if (inter == InitModule.class || inter == PyProxy.class || inter == ClassDictInit.class) continue; nBases++; } - Class superclass = c.getSuperclass(); - int index=0; + int index = 0; PyObject[] bases; PyJavaClass tmp; if (superclass == null || superclass == PyObject.class) { bases = new PyObject[nBases]; } else { - bases = new PyObject[nBases+1]; + bases = new PyObject[nBases + 1]; tmp = PyJavaClass.lookup(superclass); bases[0] = tmp; tmp.initialize(); index++; } - - for (i=0; i<nInterfaces; i++) { + for (i = 0; i < nInterfaces; i++) { Class inter = interfaces[i]; - if (inter == InitModule.class || inter == PyProxy.class || - inter == ClassDictInit.class) + if (inter == InitModule.class || inter == PyProxy.class || inter == ClassDictInit.class) continue; tmp = PyJavaClass.lookup(inter); tmp.initialize(); bases[index++] = tmp; } - __bases__ = new PyTuple(bases); } - - private void init(Class c) { + private void init(Class c) { proxyClass = c; setName(c.getName()); } /** - * Return the list of all accessible interfaces for a class. This will - * only the public interfaces. Since we can't set accessibility on - * interfaces, the Options.respectJavaAccessibility is not honored. + * Return the list of all accessible interfaces for a class. This will only the public + * interfaces. Since we can't set accessibility on interfaces, the + * Options.respectJavaAccessibility is not honored. */ private static Class[] getAccessibleInterfaces(Class c) { // can't modify accessibility of interfaces in Java2 // thus get only public interfaces Class[] in = c.getInterfaces(); - java.util.Vector v=new java.util.Vector(); + java.util.Vector v = new java.util.Vector(); for (int i = 0; i < in.length; i++) { if (!Modifier.isPublic(in[i].getModifiers())) continue; @@ -256,11 +239,10 @@ return ret; } - /** - * Return the list of all accessible fields for a class. This will - * only be the public fields unless Options.respectJavaAccessibility is - * false, in which case all fields are returned. - */ + /** + * Return the list of all accessible fields for a class. This will only be the public fields + * unless Options.respectJavaAccessibility is false, in which case all fields are returned. + */ private static Field[] getAccessibleFields(Class c) { if (Options.respectJavaAccessibility) // returns just the public fields @@ -270,17 +252,17 @@ // get all declared fields for this class, mutate their // accessibility and pop it into the array for later Field[] declared = c.getDeclaredFields(); - for (int i=0; i < declared.length; i++) { - // TBD: this is a permanent change. Should we provide a + for (Field element : declared) { + // TBD: this is a permanent change. Should we provide a // way to restore the original accessibility flag? - declared[i].setAccessible(true); - fields.add(declared[i]); + element.setAccessible(true); + fields.add(element); } - // walk down superclass chain. no need to deal specially with + // walk down superclass chain. no need to deal specially with // interfaces... c = c.getSuperclass(); } -// return (Field[])fields.toArray(new Field[fields.size()]); +// return (Field[])fields.toArray(new Field[fields.size()]); Field[] ret = new Field[fields.size()]; ret = (Field[])fields.toArray(ret); return ret; @@ -288,14 +270,11 @@ private void setFields(Class c) { Field[] fields = getAccessibleFields(c); - for (int i=0; i<fields.length; i++) { - Field field = fields[i]; + for (Field field : fields) { if (field.getDeclaringClass() != c) continue; - String name = getName(field.getName()); boolean isstatic = Modifier.isStatic(field.getModifiers()); - if (isstatic) { if (name.startsWith("__doc__") && name.length() > 7) continue; @@ -311,58 +290,51 @@ } } - /* Produce a good Python name for a Java method. If the Java method - ends in '$', strip it (this handles reserved Java keywords) Don't - make any changes to keywords since this is now handled by parser - */ - + /* + * Produce a good Python name for a Java method. If the Java method ends in '$', strip it (this + * handles reserved Java keywords) Don't make any changes to keywords since this is now handled + * by parser + */ private String getName(String name) { - if (name.endsWith("$")) name = name.substring(0, name.length()-1); + if (name.endsWith("$")) + name = name.substring(0, name.length() - 1); return name.intern(); } private void addMethod(Method meth) { String name = getName(meth.getName()); - if (name == "_getPyInstance" || name == "_setPyInstance" || - name == "_getPySystemState" || name == "_setPySystemState") - { + if (name == "_getPyInstance" || name == "_setPyInstance" || name == "_getPySystemState" + || name == "_setPySystemState") { return; } - // Special case to handle a few troublesome methods in java.awt.*. // These methods are all deprecated and interfere too badly with - // bean properties to be tolerated. This is totally a hack, but a + // bean properties to be tolerated. This is totally a hack, but a // lot of code that uses java.awt will break without it. String classname = proxyClass.getName(); - if (classname.startsWith("java.awt.") && - classname.indexOf('.', 9) == -1) - { - if (name == "layout" || name == "insets" || - name == "size" || name == "minimumSize" || - name == "preferredSize" || name == "maximumSize" || - name == "bounds" || name == "enable") - { + if (classname.startsWith("java.awt.") && classname.indexOf('.', 9) == -1) { + if (name == "layout" || name == "insets" || name == "size" || name == "minimumSize" + || name == "preferredSize" || name == "maximumSize" || name == "bounds" + || name == "enable") { return; } } - // See if any of my superclasses are using 'name' for something - // else. Or if I'm already using it myself + // else. Or if I'm already using it myself PyObject o = lookup(name, false); // If it's being used as a function, then things get more // interesting... PyReflectedFunction func; if (o != null && o instanceof PyReflectedFunction) { func = (PyReflectedFunction)o; - PyObject o1 = __dict__.__finditem__(name); - - /* If this function already exists, add this method to the - signature. If this alters the signature of the function in - some significant way, then return a duplicate and stick it in - the __dict__ */ - if(o1 != o) { - if(func.handles(meth)) { + /* + * If this function already exists, add this method to the signature. If this alters the + * signature of the function in some significant way, then return a duplicate and stick + * it in the __dict__ + */ + if (o1 != o) { + if (func.handles(meth)) { __dict__.__setitem__(name, func); return; } @@ -374,39 +346,36 @@ try { Field docField = proxyClass.getField("__doc__" + name); int mods = docField.getModifiers(); - if (docField.getType() == PyString.class && - Modifier.isPublic(mods) && - Modifier.isStatic(mods)); - func.__doc__ = (PyString) docField.get(null); - } catch (NoSuchFieldException ex) { - } catch (SecurityException ex) { - } catch (IllegalAccessException ex) {} + if (docField.getType() == PyString.class && Modifier.isPublic(mods) + && Modifier.isStatic(mods)) + ; + func.__doc__ = (PyString)docField.get(null); + } catch (NoSuchFieldException ex) {} catch (SecurityException ex) {} catch (IllegalAccessException ex) {} } __dict__.__setitem__(name, func); } - - /** - * Return the list of all accessible methods for a class. This will - * only the public methods unless Options.respectJavaAccessibility is - * false, in which case all methods are returned. - */ + + /** + * Return the list of all accessible methods for a class. This will only the public methods + * unless Options.respectJavaAccessibility is false, in which case all methods are returned. + */ private static Method[] getAccessibleMethods(Class c) { if (Options.respectJavaAccessibility) // returns just the public methods return c.getMethods(); Method[] declared = c.getDeclaredMethods(); - for (int i=0; i < declared.length; i++) { - // TBD: this is a permanent change. Should we provide a way to + for (Method element : declared) { + // TBD: this is a permanent change. Should we provide a way to // restore the original accessibility flag? - declared[i].setAccessible(true); + element.setAccessible(true); } return declared; } private boolean ignoreMethod(Method method) { Class[] exceptions = method.getExceptionTypes(); - for (int j = 0; j < exceptions.length; j++) { - if (exceptions[j] == PyIgnoreMethodTag.class) { + for (Class exception : exceptions) { + if (exception == PyIgnoreMethodTag.class) { return true; } } @@ -415,28 +384,25 @@ /* Add all methods declared by this class */ private void setMethods(Class c, Method[] methods) { - for (int i=0; i<methods.length; i++) { - Method method = methods[i]; + for (Method method : methods) { Class dc = method.getDeclaringClass(); if (dc != c) continue; - if(isPackagedProtected(dc) && Modifier.isPublic(method.getModifiers())) { + if (isPackagedProtected(dc) && Modifier.isPublic(method.getModifiers())) { /* - * Set public methods on package protected classes accessible so - * that reflected calls to the method in subclasses of the - * package protected class will succeed. Yes, it's convoluted. - * + * Set public methods on package protected classes accessible so that reflected + * calls to the method in subclasses of the package protected class will succeed. + * Yes, it's convoluted. + * * This fails when done through reflection due to Sun JVM bug - * 4071957(http://tinyurl.com/le9vo). 4533479 actually describes - * the problem we're seeing, but there are a bevy of reflection - * bugs that stem from 4071957. Supposedly it'll be fixed in - * Dolphin but it's been promised in every version since Tiger - * so don't hold your breath. - * + * 4071957(http://tinyurl.com/le9vo). 4533479 actually describes the problem we're + * seeing, but there are a bevy of reflection bugs that stem from 4071957. + * Supposedly it'll be fixed in Dolphin but it's been promised in every version + * since Tiger so don't hold your breath. */ try { method.setAccessible(true); - } catch(SecurityException se) {} + } catch (SecurityException se) {} } if (ignoreMethod(method)) continue; @@ -450,37 +416,26 @@ } /* Adds a bean property to this class */ - void addProperty(String name, Class propClass, - Method getMethod, Method setMethod) - { + void addProperty(String name, Class propClass, Method getMethod, Method setMethod) { // This will skip indexed property types if (propClass == null) return; - boolean set = true; name = getName(name); - - PyBeanProperty prop = new PyBeanProperty(name, propClass, getMethod, - setMethod); - + PyBeanProperty prop = new PyBeanProperty(name, propClass, getMethod, setMethod); // Check to see if this name is already being used... PyObject o = lookup(name, false); - if (o != null) { if (!(o instanceof PyReflectedField)) return; - if (o instanceof PyBeanProperty) { PyBeanProperty oldProp = (PyBeanProperty)o; if (prop.myType == oldProp.myType) { // If this adds nothing over old property, do nothing if ((prop.getMethod == null || oldProp.getMethod != null) - && - (prop.setMethod == null || oldProp.setMethod != null)) - { + && (prop.setMethod == null || oldProp.setMethod != null)) { set = false; } - // Add old get/set methods to current prop // Handles issues with private classes if (oldProp.getMethod != null) { @@ -491,112 +446,63 @@ } } } - // This is now handled in setFields which gets called after - // setBeanProperties -// else { -// // Keep static fields around... -// PyReflectedField field = (PyReflectedField)o; -// if (Modifier.isStatic(field.field.getModifiers())) { -// prop.field = field.field; -// } else { -// // If the field is not static (and thus subsumable) -// // don't overwrite -// return; -// } -// } } if (set) __dict__.__setitem__(name, prop); } /* Adds a bean event to this class */ - void addEvent(String name, Class eventClass, Method addMethod, - Method[] meths) - { - for (int i=0; i<meths.length; i++) { - PyBeanEventProperty prop; - prop = new PyBeanEventProperty(name, eventClass, addMethod, - meths[i]); + void addEvent(String name, Class eventClass, Method addMethod) { + for (Method meth : eventClass.getMethods()) { + PyBeanEventProperty prop = new PyBeanEventProperty(name, eventClass, addMethod, meth); __dict__.__setitem__(prop.__name__, prop); } PyBeanEvent event = new PyBeanEvent(name, eventClass, addMethod); __dict__.__setitem__(event.__name__, event); } - - /* A reimplementation of java.beans.Introspector.decapitalize. - This is needed due to bugs in Netscape Navigator - */ - private static String decapitalize(String s) { - //return java.beans.Introspector.decapitalize(s); - if (s.length() == 0) - return s; - char c0 = s.charAt(0); - if (Character.isUpperCase(c0)) { - if (s.length() > 1 && Character.isUpperCase(s.charAt(1))) - return s; - char[] cs = s.toCharArray(); - cs[0] = Character.toLowerCase(c0); - return new String(cs); - } else { - return s; - } - } - // This method is a workaround for Netscape's stupid security bug! private void setBeanInfoCustom(Class c, Method[] meths) { - //try { - int i; - int n = meths.length; - for (i=0; i<n; i++) { - Method method = meths[i]; - - if (ignoreMethod(method)) + for (Method method : meths) { + if (ignoreMethod(method) || method.getDeclaringClass() != c + || Modifier.isStatic(method.getModifiers())) { continue; - if (method.getDeclaringClass() != c || - Modifier.isStatic(method.getModifiers())) - { - continue; } - String name = method.getName(); Method getter = null; Method setter = null; Class[] args = method.getParameterTypes(); Class ret = method.getReturnType(); - Class myType=null; - - String pname=""; - + Class myType = null; + String pname = ""; if (name.startsWith("get")) { if (args.length != 0) continue; getter = method; - pname = decapitalize(name.substring(3)); + pname = Introspector.decapitalize(name.substring(3)); myType = ret; } else { if (name.startsWith("is")) { if (args.length != 0 || ret != Boolean.TYPE) continue; getter = method; - pname = decapitalize(name.substring(2)); + pname = Introspector.decapitalize(name.substring(2)); myType = ret; } else { if (name.startsWith("set")) { if (args.length != 1) continue; setter = method; - pname = decapitalize(name.substring(3)); + pname = Introspector.decapitalize(name.substring(3)); myType = args[0]; } else { continue; } } } - PyObject o = __dict__.__finditem__(new PyString(pname)); PyBeanProperty prop; - if (o == null || !(o instanceof PyBeanProperty) ) { + if (o == null || !(o instanceof PyBeanProperty)) { addProperty(pname, myType, getter, setter); } else { prop = (PyBeanProperty)o; @@ -605,91 +511,60 @@ addProperty(pname, myType, getter, setter); } } else { - if (getter != null) prop.getMethod = getter; - if (setter != null && (ret == Void.TYPE || prop.setMethod==null)) + if (getter != null) + prop.getMethod = getter; + if (setter != null && (ret == Void.TYPE || prop.setMethod == null)) prop.setMethod = setter; - } } } - - for (i=0; i<n; i++) { - Method method = meths[i]; - - if (method.getDeclaringClass() != c || - Modifier.isStatic(method.getModifiers())) - { + for (Method method : meths) { + if (method.getDeclaringClass() != c || Modifier.isStatic(method.getModifiers())) { continue; } - String mname = method.getName(); - - if (!(mname.startsWith("add") || mname.startsWith("set")) || - !mname.endsWith("Listener")) - { + if (!(mname.startsWith("add") || mname.startsWith("set")) + || !mname.endsWith("Listener")) { continue; } - Class[] args = method.getParameterTypes(); Class ret = method.getReturnType(); if (args.length != 1 || ret != Void.TYPE) continue; - Class eClass = args[0]; - - // This test and call of getClassLoader() function as a - // workaround for a bug in MRJ2.2.4. The bug occured when - // this program was compiled with jythonc: - // import java - // print dir(java.awt.Button) - // The 'actionPerformed' attributed would be missing. - if (eClass.getInterfaces().length > 0) - eClass.getInterfaces()[0].getClassLoader(); - // And of Mac workaround - - if (!(java.util.EventListener.class.isAssignableFrom(eClass))) + if (!EventListener.class.isAssignableFrom(eClass)) continue; - String name = eClass.getName(); int idot = name.lastIndexOf('.'); if (idot != -1) - name = decapitalize(name.substring(idot+1)); - - addEvent(name, eClass, method, eClass.getMethods()); + name = Introspector.decapitalize(name.substring(idot + 1)); + addEvent(name, eClass, method); } - /*} catch (Throwable t) { - System.err.println("Custom Bean error: "+t); - t.printStackTrace(); - }*/ } - /** - * Return the list of all accessible constructors for a class. This - * will only the public constructors unless - * Options.respectJavaAccessibility is false, in which case all - * constructors are returned. Note that constructors are not - * inherited like methods or fields. - */ + /** + * Return the list of all accessible constructors for a class. This will only the public + * constructors unless Options.respectJavaAccessibility is false, in which case all constructors + * are returned. Note that constructors are not inherited like methods or fields. + */ private static Constructor[] getAccessibleConstructors(Class c) { if (Options.respectJavaAccessibility) // returns just the public fields return c.getConstructors(); // return all constructors - - Constructor[] declared = c.getDeclaredConstructors(); - for (int i=0; i < declared.length; i++) { - // TBD: this is a permanent change. Should we provide a way to + for (Constructor element : declared) { + // TBD: this is a permanent change. Should we provide a way to // restore the original accessibility flag? - declared[i].setAccessible(true); + element.setAccessible(true); } return declared; } private boolean ignoreConstructor(Constructor method) { Class[] exceptions = method.getExceptionTypes(); - for (int j = 0; j < exceptions.length; j++) { - if (exceptions[j] == PyIgnoreMethodTag.class) { + for (Class exception : exceptions) { + if (exception == PyIgnoreMethodTag.class) { return true; } } @@ -701,14 +576,14 @@ __init__ = null; } else { Constructor[] constructors = getAccessibleConstructors(c); - for (int i = 0; i < constructors.length; i++) { - if (ignoreConstructor(constructors[i])) { + for (Constructor constructor : constructors) { + if (ignoreConstructor(constructor)) { continue; } if (__init__ == null) { - __init__ = new PyReflectedConstructor(constructors[i]); + __init__ = new PyReflectedConstructor(constructor); } else { - __init__.addConstructor(constructors[i]); + __init__.addConstructor(constructor); } } if (__init__ != null) { @@ -716,7 +591,9 @@ } } } - private boolean constructorsInitialized=false; + + private boolean constructorsInitialized = false; + synchronized void initConstructors() { if (constructorsInitialized) return; @@ -726,20 +603,20 @@ } /* - If the new name conflicts with a Python keyword, add an '_' - */ - private static java.util.Hashtable keywords=null; + * If the new name conflicts with a Python keyword, add an '_' + */ + private static java.util.Hashtable keywords = null; + private static String unmangleKeyword(String name) { if (keywords == null) { keywords = new java.util.Hashtable(); - String[] words = new String[] - {"or", "and", "not", "is", "in", "lambda", "if", "else", "elif", - "while", "for", "try", "except", "def", "class", "finally", - "print", - "pass", "break", "continue", "return", "import", "from", "del", - "raise", "global", "exec", "assert"}; - for (int i=0; i<words.length; i++) { - keywords.put(words[i]+"_", words[i].intern()); + String[] words = + new String[] {"or", "and", "not", "is", "in", "lambda", "if", "else", "elif", + "while", "for", "try", "except", "def", "class", "finally", "print", + "pass", "break", "continue", "return", "import", "from", "del", + "raise", "global", "exec", "assert"}; + for (String word : words) { + keywords.put(word + "_", word.intern()); } } return (String)keywords.get(name); @@ -754,15 +631,14 @@ initConstructors(); return new PyObject[] {__init__, null}; } - // For backwards compatibilty, support keyword_ as a substitute for - // keyword. An improved parser makes this no longer necessary. + // keyword. An improved parser makes this no longer necessary. if (Options.deprecatedKeywordMangling && name.endsWith("_")) { String newName = unmangleKeyword(name); if (newName != null) name = newName; } - return super.lookupGivingClass(name, stop_at_java); + return super.lookupGivingClass(name, stop_at_java); } public PyObject __dir__() { @@ -775,6 +651,7 @@ } private PyStringMap missingAttributes = null; + public PyObject __findattr_ex__(String name) { if (name == "__dict__") { if (__dict__ == null) @@ -796,27 +673,20 @@ return super.lookupGivingClass(name, false)[0]; return __init__; } - PyObject result = lookup(name, false); if (result != null) return result.__get__(null, null); // xxx messy - // A cache of missing attributes to short-circuit later tests - if (missingAttributes != null && - missingAttributes.__finditem__(name) != null) - { + if (missingAttributes != null && missingAttributes.__finditem__(name) != null) { return null; } - // These two tests can be expensive, see above for short-circuiting result = findClassAttr(name); if (result != null) return result; - result = findInnerClass(name); if (result != null) return result; - // Add this attribute to missing attributes cache if (missingAttributes == null) { missingAttributes = new PyStringMap(); @@ -826,22 +696,23 @@ } private PyJavaInstance classInstance; + private PyObject findClassAttr(String name) { if (classInstance == null) { classInstance = new PyJavaInstance(proxyClass); } PyObject result = classInstance.__findattr__(name); return result; - //if (result == null) return null; - //__dict__.__setitem__(name, result); - //return result; + // if (result == null) return null; + // __dict__.__setitem__(name, result); + // return result; } private PyObject findInnerClass(String name) { Class p = getProxyClass(); - Class innerClass = Py.relFindClass(p, p.getName()+"$"+name); - if (innerClass == null) return null; - + Class innerClass = Py.relFindClass(p, p.getName() + "$" + name); + if (innerClass == null) + return null; PyObject jinner = Py.java2py(innerClass); // xxx lookup(innerClass); __dict__.__setitem__(name, jinner); return jinner; @@ -859,9 +730,8 @@ public void __delattr__(String name) { PyObject field = lookup(name, false); if (field == null) { - throw Py.NameError("attribute not found: "+name); + throw Py.NameError("attribute not found: " + name); } - if (!field.jdontdel()) { __dict__.__delitem__(name); } @@ -870,27 +740,22 @@ 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()+")"); + throw Py.TypeError("can't instantiate abstract class (" + fullName() + ")"); } if (__init__ == null) { - throw Py.TypeError("no public constructors for "+ - fullName()); + throw Py.TypeError("no public constructors for " + fullName()); } - return __init__.make(args,keywords); + return __init__.make(args, keywords); } - PyInstance inst = new PyJavaInstance(this); inst.__init__(args, keywords); - return inst; } - public Object __tojava__(Class c) { + public Object __tojava__(Class<?> c) { initialize(); return super.__tojava__(c); } @@ -899,7 +764,7 @@ if (!(other instanceof PyJavaClass)) { return -2; } - int c = fullName().compareTo(((PyJavaClass) other).fullName()); + int c = fullName().compareTo(((PyJavaClass)other).fullName()); return c < 0 ? -1 : c > 0 ? 1 : 0; } @@ -907,7 +772,7 @@ return new PyString(fullName()); } - public String toString() { - return "<jclass "+fullName()+" "+Py.idstr(this)+">"; + public String toString() { + return "<jclass " + fullName() + " " + Py.idstr(this) + ">"; } } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <pj...@us...> - 2008-10-19 00:01:26
|
Revision: 5463 http://jython.svn.sourceforge.net/jython/?rev=5463&view=rev Author: pjenvey Date: 2008-10-19 00:01:20 +0000 (Sun, 19 Oct 2008) Log Message: ----------- fix forgetting to free the var/starargs of Calls, which produced bad byte for: def gen(): if True: # or b(**c) a = b(*c) yield d Modified Paths: -------------- trunk/jython/src/org/python/compiler/CodeCompiler.java Modified: trunk/jython/src/org/python/compiler/CodeCompiler.java =================================================================== --- trunk/jython/src/org/python/compiler/CodeCompiler.java 2008-10-18 20:23:01 UTC (rev 5462) +++ trunk/jython/src/org/python/compiler/CodeCompiler.java 2008-10-19 00:01:20 UTC (rev 5463) @@ -1589,6 +1589,8 @@ code.aload(argArray); code.aload(strArray); + code.freeLocal(argArray); + code.freeLocal(strArray); code.dup2_x2(); code.pop2(); This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <pj...@us...> - 2008-10-18 20:23:04
|
Revision: 5462 http://jython.svn.sourceforge.net/jython/?rev=5462&view=rev Author: pjenvey Date: 2008-10-18 20:23:01 +0000 (Sat, 18 Oct 2008) Log Message: ----------- fix os.access to never raise an exception with a valid mode, which I broke in r5420 Modified Paths: -------------- trunk/jython/Lib/os.py Modified: trunk/jython/Lib/os.py =================================================================== --- trunk/jython/Lib/os.py 2008-10-18 19:03:40 UTC (rev 5461) +++ trunk/jython/Lib/os.py 2008-10-18 20:23:01 UTC (rev 5462) @@ -428,9 +428,12 @@ result = False if mode & W_OK and not f.canWrite(): result = False - if mode & X_OK and not (stat(path).st_mode & _stat.S_IEXEC): + if mode & X_OK: # NOTE: always False without jna-posix stat - result = False + try: + result = (stat(path).st_mode & _stat.S_IEXEC) != 0 + except OSError: + result = False return result def stat(path): This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <am...@us...> - 2008-10-18 19:03:47
|
Revision: 5461 http://jython.svn.sourceforge.net/jython/?rev=5461&view=rev Author: amak Date: 2008-10-18 19:03:40 +0000 (Sat, 18 Oct 2008) Log Message: ----------- 1. Fixed a bug whereby timeouts were not being honoured when recv()ing (http://bugs.jython.com/issue1154) 2. Fixed another (previously unreported) bug that resulted in an exception when switching from non-blocking to timeout mode. 3. Back-ported some of pjenvey's changes relating to getaddrinfo, non-blocking connects and file buffer sizes. 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-18 01:58:29 UTC (rev 5460) +++ branches/Release_2_2maint/jython/Lib/socket.py 2008-10-18 19:03:40 UTC (rev 5461) @@ -6,8 +6,6 @@ XXX Restrictions: - Only INET sockets -- No asynchronous behavior -- No socket options - Can't do a very good gethostbyaddr() right... AMAK: 20050527: added socket timeouts AMAK: 20070515: Added non-blocking (asynchronous) support @@ -201,16 +199,6 @@ timeout = None mode = MODE_BLOCKING - def read(self, buf): - bytebuf = java.nio.ByteBuffer.wrap(buf) - count = self.jchannel.read(bytebuf) - return count - - def write(self, buf): - bytebuf = java.nio.ByteBuffer.wrap(buf) - count = self.jchannel.write(bytebuf) - return count - def getpeername(self): return (self.jsocket.getInetAddress().getHostName(), self.jsocket.getPort() ) @@ -221,6 +209,7 @@ if self.mode == MODE_NONBLOCKING: self.jchannel.configureBlocking(0) if self.mode == MODE_TIMEOUT: + self.jchannel.configureBlocking(1) self._timeout_millis = int(timeout*1000) self.jsocket.setSoTimeout(self._timeout_millis) @@ -310,6 +299,36 @@ def finish_connect(self): return self.jchannel.finishConnect() + def _do_read_net(self, buf): + # Need two separate implementations because the java.nio APIs do not support timeouts + return self.jsocket.getInputStream().read(buf) + + def _do_read_nio(self, buf): + bytebuf = java.nio.ByteBuffer.wrap(buf) + count = self.jchannel.read(bytebuf) + return count + + def _do_write_net(self, buf): + self.jsocket.getOutputStream().write(buf) + return len(buf) + + def _do_write_nio(self, buf): + bytebuf = java.nio.ByteBuffer.wrap(buf) + count = self.jchannel.write(bytebuf) + return count + + def read(self, buf): + if self.mode == MODE_TIMEOUT: + return self._do_read_net(buf) + else: + return self._do_read_nio(buf) + + def write(self, buf): + if self.mode == MODE_TIMEOUT: + return self._do_write_net(buf) + else: + return self._do_write_nio(buf) + class _server_socket_impl(_nio_impl): options = { @@ -515,10 +534,10 @@ else: return _udpsocket() -def getaddrinfo(host, port, family=None, socktype=None, proto=0, flags=None): +def getaddrinfo(host, port, family=AF_INET, socktype=None, proto=0, flags=None): try: if not family in [AF_INET, AF_INET6, AF_UNSPEC]: - raise NotSupportedError() + raise gaierror(errno.EIO, 'ai_family not supported') filter_fns = [] filter_fns.append({ AF_INET: lambda x: isinstance(x, java.net.Inet4Address), @@ -736,9 +755,12 @@ def connect_ex(self, addr): "This signifies a client socket" - self._do_connect(addr) + if not self.sock_impl: + self._do_connect(addr) if self.sock_impl.finish_connect(): self._setup() + if self.mode == MODE_NONBLOCKING: + return errno.EISCONN return 0 return errno.EINPROGRESS @@ -775,6 +797,8 @@ if self.sock_impl.jchannel.isConnectionPending(): self.sock_impl.jchannel.finishConnect() numwritten = self.sock_impl.write(s) + if numwritten == 0 and self.mode == MODE_NONBLOCKING: + raise would_block_error() return numwritten except java.lang.Exception, jlx: raise _map_exception(jlx) @@ -861,8 +885,11 @@ self._do_connect(addr) def connect_ex(self, addr): - self._do_connect(addr) + if not self.sock_impl: + self._do_connect(addr) if self.sock_impl.finish_connect(): + if self.mode == MODE_NONBLOCKING: + return errno.EISCONN return 0 return errno.EINPROGRESS @@ -1151,7 +1178,7 @@ self._rbuf = "" while True: left = size - buf_len - recv_size = max(self._rbufsize, left) + recv_size = min(self._rbufsize, left) data = self._sock.recv(recv_size) if not data: break Modified: branches/Release_2_2maint/jython/Lib/test/test_socket.py =================================================================== --- branches/Release_2_2maint/jython/Lib/test/test_socket.py 2008-10-18 01:58:29 UTC (rev 5460) +++ branches/Release_2_2maint/jython/Lib/test/test_socket.py 2008-10-18 19:03:40 UTC (rev 5461) @@ -292,6 +292,22 @@ if not fqhn in all_host_names: self.fail("Error testing host resolution mechanisms.") + def testGetAddrInfo(self): + try: + socket.getaddrinfo(HOST, PORT, 9999) + except socket.gaierror, gaix: + self.failUnlessEqual(gaix[0], errno.EIO) + except Exception, x: + self.fail("getaddrinfo with bad family raised wrong exception: %s" % x) + else: + self.fail("getaddrinfo with bad family should have raised exception") + + addrinfos = socket.getaddrinfo(HOST, PORT) + for addrinfo in addrinfos: + family, socktype, proto, canonname, sockaddr = addrinfo + self.assert_(isinstance(canonname, str)) + self.assert_(isinstance(sockaddr[0], str)) + def testRefCountGetNameInfo(self): # Testing reference count for getnameinfo import sys @@ -670,6 +686,16 @@ def _testRecv(self): self.serv_conn.send(MSG) + def testRecvTimeoutMode(self): + # Do this test in timeout mode, because the code path is different + self.cli_conn.settimeout(10) + msg = self.cli_conn.recv(1024) + self.assertEqual(msg, MSG) + + def _testRecvTimeoutMode(self): + self.serv_conn.settimeout(10) + self.serv_conn.send(MSG) + def testOverFlowRecv(self): # Testing receive in chunks over TCP seg1 = self.cli_conn.recv(len(MSG) - 3) @@ -1226,14 +1252,14 @@ bufsize = 2 # Exercise the buffering code -class TCPTimeoutTest(SocketTCPTest): +class TCPServerTimeoutTest(SocketTCPTest): - def testTCPTimeout(self): + def testAcceptTimeout(self): def raise_timeout(*args, **kwargs): self.serv.settimeout(1.0) self.serv.accept() self.failUnlessRaises(socket.timeout, raise_timeout, - "Error generating a timeout exception (TCP)") + "TCP socket accept failed to generate a timeout exception (TCP)") def testTimeoutZero(self): ok = False @@ -1249,9 +1275,9 @@ if not ok: self.fail("accept() returned success when we did not expect it") -class TCPClientTimeoutTest(unittest.TestCase): +class TCPClientTimeoutTest(SocketTCPTest): - def testClientTimeout(self): + def testConnectTimeout(self): cli = socket.socket(socket.AF_INET, socket.SOCK_STREAM) cli.settimeout(0.1) host = '192.168.192.168' @@ -1266,8 +1292,45 @@ socket.timeout. This tries to connect to %s in the assumption that it isn't used, but if it is on your network this failure is bogus.''' % host) - + def testRecvTimeout(self): + def raise_timeout(*args, **kwargs): + cli_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + cli_sock.connect( (HOST, PORT) ) + cli_sock.settimeout(1) + cli_sock.recv(1024) + self.failUnlessRaises(socket.timeout, raise_timeout, + "TCP socket recv failed to generate a timeout exception (TCP)") + # Disable this test, but leave it present for documentation purposes + # socket timeouts only work for read and accept, not for write + # http://java.sun.com/j2se/1.4.2/docs/api/java/net/SocketTimeoutException.html + def estSendTimeout(self): + def raise_timeout(*args, **kwargs): + cli_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + cli_sock.connect( (HOST, PORT) ) + # First fill the socket + cli_sock.settimeout(1) + sent = 0 + while True: + bytes_sent = cli_sock.send(MSG) + sent += bytes_sent + self.failUnlessRaises(socket.timeout, raise_timeout, + "TCP socket send failed to generate a timeout exception (TCP)") + + def testSwitchModes(self): + cli_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + cli_sock.connect( (HOST, PORT) ) + # set non-blocking mode + cli_sock.setblocking(0) + # then set timeout mode + cli_sock.settimeout(1) + try: + cli_sock.send(MSG) + except Exception, x: + self.fail("Switching mode from non-blocking to timeout raised exception: %s" % x) + else: + pass + # # AMAK: 20070307 # Corrected the superclass of UDPTimeoutTest @@ -1487,7 +1550,7 @@ TestSupportedOptions, TestUnsupportedOptions, BasicTCPTest, - TCPTimeoutTest, + TCPServerTimeoutTest, TCPClientTimeoutTest, TestExceptions, TestInvalidUsage, This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <pj...@us...> - 2008-10-18 01:58:37
|
Revision: 5460 http://jython.svn.sourceforge.net/jython/?rev=5460&view=rev Author: pjenvey Date: 2008-10-18 01:58:29 +0000 (Sat, 18 Oct 2008) Log Message: ----------- store the symbol name info in a LinkedHashMap to maintain the order they're encountered in. fixes test_code technically this should bump the bytecode magic but it's not that important Modified Paths: -------------- trunk/jython/src/org/python/compiler/CodeCompiler.java trunk/jython/src/org/python/compiler/Module.java trunk/jython/src/org/python/compiler/ScopeInfo.java Modified: trunk/jython/src/org/python/compiler/CodeCompiler.java =================================================================== --- trunk/jython/src/org/python/compiler/CodeCompiler.java 2008-10-17 23:56:07 UTC (rev 5459) +++ trunk/jython/src/org/python/compiler/CodeCompiler.java 2008-10-18 01:58:29 UTC (rev 5460) @@ -4,6 +4,7 @@ import java.io.IOException; import java.util.Hashtable; +import java.util.Map; import java.util.Stack; import java.util.Vector; @@ -109,7 +110,7 @@ public boolean fast_locals, print_results; - public Hashtable tbl; + public Map<String, SymInfo> tbl; public ScopeInfo my_scope; boolean optimizeGlobals = true; @@ -369,7 +370,7 @@ code.iconst(n); code.anewarray("org/python/core/PyObject"); code.astore(tmp); - Hashtable upTbl = scope.up.tbl; + Map<String, SymInfo> upTbl = scope.up.tbl; for(int i=0; i<n; i++) { code.aload(tmp); code.iconst(i); @@ -377,7 +378,7 @@ for(int j = 1; j < scope.distance; j++) { loadf_back(); } - SymInfo symInfo = (SymInfo)upTbl.get(scope.freevars.elementAt(i)); + SymInfo symInfo = upTbl.get(scope.freevars.elementAt(i)); code.iconst(symInfo.env_index); code.invokevirtual("org/python/core/PyFrame", "getclosure", "(I)" + $pyObj); code.aastore(); @@ -2044,7 +2045,7 @@ else name = getName(node.id); - SymInfo syminf = (SymInfo)tbl.get(name); + SymInfo syminf = tbl.get(name); expr_contextType ctx = node.ctx; if (ctx == expr_contextType.AugStore) { Modified: trunk/jython/src/org/python/compiler/Module.java =================================================================== --- trunk/jython/src/org/python/compiler/Module.java 2008-10-17 23:56:07 UTC (rev 5459) +++ trunk/jython/src/org/python/compiler/Module.java 2008-10-18 01:58:29 UTC (rev 5460) @@ -6,6 +6,7 @@ import java.io.OutputStream; import java.util.Enumeration; import java.util.Hashtable; +import java.util.Map; import java.util.Vector; import org.python.objectweb.asm.Label; @@ -460,11 +461,11 @@ } int nparamcell = scope.jy_paramcells.size(); if(nparamcell > 0) { - Hashtable tbl = scope.tbl; + Map<String, SymInfo> tbl = scope.tbl; Vector paramcells = scope.jy_paramcells; for(int i = 0; i < nparamcell; i++) { c.aload(1); - SymInfo syminf = (SymInfo)tbl.get(paramcells.elementAt(i)); + SymInfo syminf = tbl.get(paramcells.elementAt(i)); c.iconst(syminf.locals_index); c.iconst(syminf.env_index); c.invokevirtual("org/python/core/PyFrame", "to_cell", "(II)V"); Modified: trunk/jython/src/org/python/compiler/ScopeInfo.java =================================================================== --- trunk/jython/src/org/python/compiler/ScopeInfo.java 2008-10-17 23:56:07 UTC (rev 5459) +++ trunk/jython/src/org/python/compiler/ScopeInfo.java 2008-10-18 01:58:29 UTC (rev 5460) @@ -3,6 +3,8 @@ package org.python.compiler; import java.util.Enumeration; +import java.util.LinkedHashMap; +import java.util.Map; import java.util.Hashtable; import java.util.Vector; @@ -24,9 +26,9 @@ for(int i=0; i<level; i++) System.err.print(' '); System.err.print(((kind != CLASSSCOPE)?scope_name:"class "+ scope_name)+": "); - for (Enumeration e = tbl.keys(); e.hasMoreElements(); ) { - String name = (String)e.nextElement(); - SymInfo info = (SymInfo)tbl.get(name); + for (Map.Entry<String, SymInfo> entry : tbl.entrySet()) { + String name = entry.getKey(); + SymInfo info = entry.getValue(); int flags = info.flags; System.err.print(name); if ((flags&BOUND) != 0) System.err.print('='); @@ -66,13 +68,13 @@ public ArgListCompiler ac; - public Hashtable tbl = new Hashtable(); + public Map<String, SymInfo> tbl = new LinkedHashMap<String, SymInfo>(); public Vector names = new Vector(); public int addGlobal(String name) { // global kind = func vs. class int global = kind==CLASSSCOPE?CLASS_GLOBAL:NGLOBAL; - SymInfo info = (SymInfo)tbl.get(name); + SymInfo info = tbl.get(name); if (info == null) { tbl.put(name,new SymInfo(global|BOUND)); return -1; @@ -91,14 +93,13 @@ } public void markFromParam() { - for (Enumeration e=tbl.elements(); e.hasMoreElements(); ) { - SymInfo info = (SymInfo)e.nextElement(); + for (SymInfo info : tbl.values()) { info.flags |= FROM_PARAM; } } public void addBound(String name) { - SymInfo info = (SymInfo)tbl.get(name); + SymInfo info = tbl.get(name); if (info == null) { tbl.put(name, new SymInfo(BOUND)); return; @@ -140,7 +141,7 @@ for (Enumeration e = inner_free.keys(); e.hasMoreElements(); ) { String name = (String)e.nextElement(); - SymInfo info = (SymInfo)tbl.get(name); + SymInfo info = tbl.get(name); if (info == null) { tbl.put(name,new SymInfo(FREE)); continue; @@ -164,9 +165,9 @@ boolean some_free = false; boolean nested = up.kind != TOPSCOPE; - for (Enumeration e = tbl.keys(); e.hasMoreElements(); ) { - String name = (String)e.nextElement(); - SymInfo info = (SymInfo)tbl.get(name); + for (Map.Entry<String, SymInfo> entry : tbl.entrySet()) { + String name = entry.getKey(); + SymInfo info = entry.getValue(); int flags = info.flags; if (nested && (flags&FREE) != 0) up.inner_free.put(name,PRESENT); if ((flags&(GLOBAL|PARAM|CELL)) == 0) { @@ -236,14 +237,14 @@ */ public void setup_closure(ScopeInfo up){ int free = cell; // env = cell...,free... - Hashtable up_tbl = up.tbl; + Map<String, SymInfo> up_tbl = up.tbl; boolean nested = up.kind != TOPSCOPE; - for (Enumeration e = tbl.keys(); e.hasMoreElements(); ) { - String name = (String)e.nextElement(); - SymInfo info = (SymInfo)tbl.get(name); + for (Map.Entry<String, SymInfo> entry : tbl.entrySet()) { + String name = entry.getKey(); + SymInfo info = entry.getValue(); int flags = info.flags; if ((flags&FREE) != 0) { - SymInfo up_info = (SymInfo)up_tbl.get(name); + SymInfo up_info = up_tbl.get(name); // ?? differs from CPython -- what is the intended behaviour? if (up_info != null) { int up_flags = up_info.flags; This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <pj...@us...> - 2008-10-17 23:56:14
|
Revision: 5459 http://jython.svn.sourceforge.net/jython/?rev=5459&view=rev Author: pjenvey Date: 2008-10-17 23:56:07 +0000 (Fri, 17 Oct 2008) Log Message: ----------- remove stray print statement that was preventing this from passing Modified Paths: -------------- trunk/jython/Lib/test/test_trace.py Modified: trunk/jython/Lib/test/test_trace.py =================================================================== --- trunk/jython/Lib/test/test_trace.py 2008-10-17 23:55:52 UTC (rev 5458) +++ trunk/jython/Lib/test/test_trace.py 2008-10-17 23:56:07 UTC (rev 5459) @@ -750,7 +750,6 @@ del TraceTestCase.test_14_onliner_if del TraceTestCase.test_15_loops - print tests test_support.run_unittest(*tests) if __name__ == "__main__": This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <pj...@us...> - 2008-10-17 23:55:57
|
Revision: 5458 http://jython.svn.sourceforge.net/jython/?rev=5458&view=rev Author: pjenvey Date: 2008-10-17 23:55:52 +0000 (Fri, 17 Oct 2008) Log Message: ----------- allow more heap for the regrtest to avoid the OutOfMemory errors. we don't seem to actually be leaking -- we just have more test modules Modified Paths: -------------- trunk/jython/build.xml Modified: trunk/jython/build.xml =================================================================== --- trunk/jython/build.xml 2008-10-17 21:21:36 UTC (rev 5457) +++ trunk/jython/build.xml 2008-10-17 23:55:52 UTC (rev 5458) @@ -171,6 +171,7 @@ <pathelement path="${exposed.dir}" /> <pathelement path="${compile.dir}" /> </path> + <property name="regrtest.Xmx" value="-Xmx96m" /> </target> <target name="version-init"> @@ -757,6 +758,7 @@ <target name="regrtest-unix" if="os.family.unix"> <exec executable="${dist.dir}/bin/jython"> <arg value="--verify"/> + <arg value="-J${regrtest.Xmx}"/> <arg value="${dist.dir}/Lib/test/regrtest.py"/> <!-- Only run the tests that are expected to work on Jython --> <arg value="--expected"/> @@ -764,6 +766,7 @@ </target> <target name="regrtest-windows" if="os.family.windows"> <exec executable="${dist.dir}/bin/jython.bat"> + <arg value="-J${regrtest.Xmx}"/> <arg value="${dist.dir}/Lib/test/regrtest.py"/> <!-- Only run the tests that are expected to work on Jython --> <arg value="--expected"/> This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <th...@us...> - 2008-10-17 21:21:41
|
Revision: 5457 http://jython.svn.sourceforge.net/jython/?rev=5457&view=rev Author: thobes Date: 2008-10-17 21:21:36 +0000 (Fri, 17 Oct 2008) Log Message: ----------- Added a check for return and yield in the same scope in ScopesCompiler, There are cases that can be missed in CodeCompiler due to dead code elimination, this gets around that. Modified Paths: -------------- trunk/jython/src/org/python/compiler/ScopeInfo.java trunk/jython/src/org/python/compiler/ScopesCompiler.java Modified: trunk/jython/src/org/python/compiler/ScopeInfo.java =================================================================== --- trunk/jython/src/org/python/compiler/ScopeInfo.java 2008-10-17 20:46:47 UTC (rev 5456) +++ trunk/jython/src/org/python/compiler/ScopeInfo.java 2008-10-17 21:21:36 UTC (rev 5457) @@ -5,7 +5,11 @@ import java.util.Enumeration; import java.util.Hashtable; import java.util.Vector; + +import org.python.antlr.ParseException; import org.python.antlr.PythonTree; +import org.python.antlr.ast.Return; +import org.python.antlr.ast.exprType; public class ScopeInfo extends Object implements ScopeConstants { @@ -56,6 +60,7 @@ public boolean from_import_star; public boolean contains_ns_free_vars; public boolean generator; + private boolean hasReturnWithValue; public int yield_count; public int max_with_count; @@ -264,4 +269,20 @@ return "ScopeInfo[" + scope_name + " " + kind + "]@" + System.identityHashCode(this); } + + public void defineAsGenerator(exprType node) { + generator = true; + if (hasReturnWithValue) { + throw new ParseException("'return' with argument " + + "inside generator", node); + } + } + + public void noteReturnValue(Return node) { + if (generator) { + throw new ParseException("'return' with argument " + + "inside generator", node); + } + hasReturnWithValue = true; + } } Modified: trunk/jython/src/org/python/compiler/ScopesCompiler.java =================================================================== --- trunk/jython/src/org/python/compiler/ScopesCompiler.java 2008-10-17 20:46:47 UTC (rev 5456) +++ trunk/jython/src/org/python/compiler/ScopesCompiler.java 2008-10-17 21:21:36 UTC (rev 5457) @@ -4,6 +4,7 @@ import org.python.antlr.*; import org.python.antlr.ast.*; + import java.util.*; public class ScopesCompiler extends Visitor implements ScopeConstants { @@ -262,11 +263,20 @@ @Override public Object visitYield(Yield node) throws Exception { - cur.generator = true; + cur.defineAsGenerator(node); cur.yield_count++; traverse(node); return null; } + + @Override + public Object visitReturn(Return node) throws Exception { + if (node.value != null) { + cur.noteReturnValue(node); + } + traverse(node); + return null; + } @Override public Object visitGeneratorExp(GeneratorExp node) throws Exception { @@ -286,7 +296,7 @@ cur.addParam(bound_exp); cur.markFromParam(); - cur.generator = true; + cur.defineAsGenerator(node); cur.yield_count++; // The reset of the iterators are evaluated in the inner scope if (node.elt != null) { This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <th...@us...> - 2008-10-17 20:46:49
|
Revision: 5456 http://jython.svn.sourceforge.net/jython/?rev=5456&view=rev Author: thobes Date: 2008-10-17 20:46:47 +0000 (Fri, 17 Oct 2008) Log Message: ----------- Improved the scope analysis for generator expressions. Also fixed a bug in my recent commit where the fix for yield as an expression accidentially reordered the value to be yielded on the stack. Modified Paths: -------------- trunk/jython/src/org/python/compiler/CodeCompiler.java trunk/jython/src/org/python/compiler/ScopesCompiler.java Modified: trunk/jython/src/org/python/compiler/CodeCompiler.java =================================================================== --- trunk/jython/src/org/python/compiler/CodeCompiler.java 2008-10-17 19:28:20 UTC (rev 5455) +++ trunk/jython/src/org/python/compiler/CodeCompiler.java 2008-10-17 20:46:47 UTC (rev 5456) @@ -555,13 +555,16 @@ throw new ParseException("'yield' outside function", node); } + int stackState = saveStack(); + if (node.value != null) { visit(node.value); } else { getNone(); } + setLastI(++yield_count); - int stackState = saveStack(); + saveLocals(); code.areturn(); Modified: trunk/jython/src/org/python/compiler/ScopesCompiler.java =================================================================== --- trunk/jython/src/org/python/compiler/ScopesCompiler.java 2008-10-17 19:28:20 UTC (rev 5455) +++ trunk/jython/src/org/python/compiler/ScopesCompiler.java 2008-10-17 20:46:47 UTC (rev 5456) @@ -271,9 +271,9 @@ @Override public Object visitGeneratorExp(GeneratorExp node) throws Exception { // The first iterator is evaluated in the outer scope - /*if (node.generators != null && node.generators.length > 0) { + if (node.generators != null && node.generators.length > 0) { visit(node.generators[0].iter); - }*/ + } String bound_exp = "_(x)"; String tmp = "_(" + node.getLine() + "_" + node.getCharPositionInLine() + ")"; @@ -289,7 +289,7 @@ cur.generator = true; cur.yield_count++; // The reset of the iterators are evaluated in the inner scope - /*if (node.elt != null) { + if (node.elt != null) { visit(node.elt); } if (node.generators != null) { @@ -310,9 +310,6 @@ } } } - /*/ - traverse(node); - //*/ endScope(); return null; This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <th...@us...> - 2008-10-17 19:28:23
|
Revision: 5455 http://jython.svn.sourceforge.net/jython/?rev=5455&view=rev Author: thobes Date: 2008-10-17 19:28:20 +0000 (Fri, 17 Oct 2008) Log Message: ----------- Removed some erronious code in visitYield. Modified Paths: -------------- trunk/jython/src/org/python/compiler/CodeCompiler.java Modified: trunk/jython/src/org/python/compiler/CodeCompiler.java =================================================================== --- trunk/jython/src/org/python/compiler/CodeCompiler.java 2008-10-17 18:15:50 UTC (rev 5454) +++ trunk/jython/src/org/python/compiler/CodeCompiler.java 2008-10-17 19:28:20 UTC (rev 5455) @@ -555,18 +555,6 @@ throw new ParseException("'yield' outside function", node); } - if (yield_count == 0) { - loadFrame(); - code.invokevirtual("org/python/core/PyFrame", "getGeneratorInput", "()" + $obj); - code.dup(); - code.instanceof_("org/python/core/PyException"); - Label done = new Label(); - code.ifeq(done); - code.checkcast("java/lang/Throwable"); - code.athrow(); - code.label(done); - } - if (node.value != null) { visit(node.value); } else { This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <th...@us...> - 2008-10-17 18:15:54
|
Revision: 5454 http://jython.svn.sourceforge.net/jython/?rev=5454&view=rev Author: thobes Date: 2008-10-17 18:15:50 +0000 (Fri, 17 Oct 2008) Log Message: ----------- Modifying the generated bytecode so that yield as an expression does not empty the stack. Modified Paths: -------------- trunk/jython/src/org/python/compiler/CodeCompiler.java trunk/jython/src/org/python/compiler/Module.java trunk/jython/src/org/python/compiler/ProxyMaker.java Modified: trunk/jython/src/org/python/compiler/CodeCompiler.java =================================================================== --- trunk/jython/src/org/python/compiler/CodeCompiler.java 2008-10-17 07:06:39 UTC (rev 5453) +++ trunk/jython/src/org/python/compiler/CodeCompiler.java 2008-10-17 18:15:50 UTC (rev 5454) @@ -7,19 +7,6 @@ import java.util.Stack; import java.util.Vector; -import org.python.objectweb.asm.ClassWriter; -import org.python.objectweb.asm.Label; -import org.python.objectweb.asm.Opcodes; -import org.python.objectweb.asm.Type; -import org.python.objectweb.asm.commons.Method; -import org.python.core.CompilerFlags; -import org.python.core.PyComplex; -import org.python.core.PyFloat; -import org.python.core.PyInteger; -import org.python.core.PyLong; -import org.python.core.PyObject; -import org.python.core.PyString; -import org.python.core.PyUnicode; import org.python.antlr.ParseException; import org.python.antlr.PythonTree; import org.python.antlr.Visitor; @@ -81,6 +68,19 @@ import org.python.antlr.ast.modType; import org.python.antlr.ast.operatorType; import org.python.antlr.ast.stmtType; +import org.python.core.CompilerFlags; +import org.python.core.PyComplex; +import org.python.core.PyFloat; +import org.python.core.PyInteger; +import org.python.core.PyLong; +import org.python.core.PyObject; +import org.python.core.PyString; +import org.python.core.PyUnicode; +import org.python.objectweb.asm.ClassWriter; +import org.python.objectweb.asm.Label; +import org.python.objectweb.asm.Opcodes; +import org.python.objectweb.asm.Type; +import org.python.objectweb.asm.commons.Method; public class CodeCompiler extends Visitor implements Opcodes, ClassConstants //, PythonGrammarTreeConstants { @@ -131,7 +131,8 @@ public int bcfLevel = 0; int yield_count = 0; - int with_count = 0; + + private int stackDepth = 0; public CodeCompiler(Module module, boolean print_results) { this.module = module; @@ -199,18 +200,18 @@ private void saveAugTmps(PythonTree node, int count) throws Exception { if (count >= 4) { - augtmp4 = code.getLocal("org/python/core/PyObject"); + augtmp4 = code.getLocal("Lorg/python/core/PyObject;"); code.astore(augtmp4); } if (count >= 3) { - augtmp3 = code.getLocal("org/python/core/PyObject"); + augtmp3 = code.getLocal("Lorg/python/core/PyObject;"); code.astore(augtmp3); } if (count >= 2) { - augtmp2 = code.getLocal("org/python/core/PyObject"); + augtmp2 = code.getLocal("Lorg/python/core/PyObject;"); code.astore(augtmp2); } - augtmp1 = code.getLocal("org/python/core/PyObject"); + augtmp1 = code.getLocal("Lorg/python/core/PyObject;"); code.astore(augtmp1); code.aload(augtmp1); @@ -320,7 +321,7 @@ return visitReturn(new Return(node, node.body), true); } - public void makeArray(PythonTree[] nodes) throws Exception { + public int makeArray(PythonTree[] nodes) throws Exception { int n; if (nodes == null) @@ -328,25 +329,25 @@ else n = nodes.length; + int array = code.getLocal("[Lorg/python/core/PyObject;"); if (n == 0) { code.getstatic("org/python/core/Py", "EmptyObjects", $pyObjArr); + code.astore(array); } else { - int tmp = code.getLocal("[Lorg/python/core/PyObject;"); code.iconst(n); code.anewarray("org/python/core/PyObject"); - code.astore(tmp); + code.astore(array); for(int i=0; i<n; i++) { visit(nodes[i]); - code.aload(tmp); + code.aload(array); code.swap(); code.iconst(i); code.swap(); code.aastore(); } - code.aload(tmp); - code.freeLocal(tmp); } + return array; } public void getDocString(stmtType[] suite) throws Exception { @@ -364,7 +365,7 @@ int n = scope.freevars.size(); if (n == 0) return false; - int tmp = code.getLocal("[org/python/core/PyObject"); + int tmp = code.getLocal("[Lorg/python/core/PyObject;"); code.iconst(n); code.anewarray("org/python/core/PyObject"); code.astore(tmp); @@ -394,15 +395,17 @@ setline(node); + ScopeInfo scope = module.getScopeInfo(node); + + int defaults = makeArray(scope.ac.getDefaults()); + code.new_("org/python/core/PyFunction"); code.dup(); loadFrame(); code.getfield("org/python/core/PyFrame", "f_globals", $pyObj); + code.aload(defaults); + code.freeLocal(defaults); - ScopeInfo scope = module.getScopeInfo(node); - - makeArray(scope.ac.getDefaults()); - scope.setup_closure(); scope.dump(); module.PyCode(new Suite(node, node.body), name, true, @@ -570,6 +573,7 @@ getNone(); } setLastI(++yield_count); + int stackState = saveStack(); saveLocals(); code.areturn(); @@ -577,6 +581,7 @@ yields.addElement(restart); code.label(restart); restoreLocals(); + restoreStack(stackState); loadFrame(); code.invokevirtual("org/python/core/PyFrame", "getGeneratorInput", "()" + $obj); @@ -591,7 +596,54 @@ return null; } + + private void stackProduce() { + stackDepth++; + } + + private void stackConsume() { + stackDepth--; + } + + private void stackConsume(int numItems) { + stackDepth -= numItems; + } + private int saveStack() throws Exception { + if (stackDepth > 0) { + int array = code.getLocal("[Lorg/python/core/PyObject;"); + code.iconst(stackDepth); + code.anewarray("org/python/core/PyObject"); + code.astore(array); + for (int i = 0; i < stackDepth; i++) { + code.aload(array); + // Stack: |- ... value array + code.swap(); + code.iconst(i); + code.swap(); + // Stack: |- ... array index value + code.aastore(); + // Stack: |- ... + } + return array; + } else { + return -1; + } + } + + private void restoreStack(int array) throws Exception { + if (stackDepth > 0) { + for (int i = stackDepth - 1; i >= 0; i--) { + code.aload(array); + // Stack: |- ... array + code.iconst(i); + code.aaload(); + // Stack: |- ... value + } + code.freeLocal(array); + } + } + private boolean inFinallyBody() { for (int i = 0; i < exceptionHandlers.size(); ++i) { ExceptionHandler handler = @@ -605,13 +657,13 @@ private void restoreLocals() throws Exception { endExceptionHandlers(); - + Vector v = code.getActiveLocals(); loadFrame(); code.getfield("org/python/core/PyFrame", "f_savedlocals", "[Ljava/lang/Object;"); - int locals = code.getLocal("[java/lang/Object"); + int locals = code.getLocal("[Ljava/lang/Object;"); code.astore(locals); for (int i = 0; i < v.size(); i++) { @@ -662,7 +714,7 @@ Vector v = code.getActiveLocals(); code.iconst(v.size()); code.anewarray("java/lang/Object"); - int locals = code.getLocal("[java/lang/Object"); + int locals = code.getLocal("[Ljava/lang/Object;"); code.astore(locals); for (int i = 0; i < v.size(); i++) { @@ -721,14 +773,19 @@ @Override public Object visitRaise(Raise node) throws Exception { setline(node); - traverse(node); + if (node.type != null) { visit(node.type); stackProduce(); } + if (node.inst != null) { visit(node.inst); stackProduce(); } + if (node.tback != null) { visit(node.tback); stackProduce(); } if (node.type == null) { code.invokestatic("org/python/core/Py", "makeException", "()" + $pyExc); } else if (node.inst == null) { + stackConsume(); code.invokestatic("org/python/core/Py", "makeException", "(" + $pyObj + ")" + $pyExc); } else if (node.tback == null) { + stackConsume(2); code.invokestatic("org/python/core/Py", "makeException", "(" + $pyObj + $pyObj + ")" + $pyExc); } else { + stackConsume(3); code.invokestatic("org/python/core/Py", "makeException", "(" + $pyObj + $pyObj + $pyObj + ")" + $pyExc); } code.athrow(); @@ -799,7 +856,9 @@ if (asnames[i] == null) asnames[i] = fromNames[i]; } - makeStrings(code, fromNames, fromNames.length); + int strArray = makeStrings(code, fromNames, fromNames.length); + code.aload(strArray); + code.freeLocal(strArray); loadFrame(); @@ -834,20 +893,24 @@ public Object visitExec(Exec node) throws Exception { setline(node); visit(node.body); + stackProduce(); if (node.globals != null) { visit(node.globals); } else { code.aconst_null(); } + stackProduce(); if (node.locals != null) { visit(node.locals); } else { code.aconst_null(); } + stackProduce(); //do the real work here + stackConsume(3); code.invokestatic("org/python/core/Py", "exec", "(" + $pyObj + $pyObj + $pyObj + ")V"); return null; } @@ -873,9 +936,6 @@ /* If evaluation is false, then branch to end of method */ code.ifne(end_of_assert); - - /* Push exception type onto stack(Py.AssertionError) */ - code.getstatic("org/python/core/Py", "AssertionError", "Lorg/python/core/PyObject;"); /* Visit the message part of the assertion, or pass Py.None */ if( node.msg != null ) { @@ -883,6 +943,12 @@ } else { getNone(); } + + /* Push exception type onto stack(Py.AssertionError) */ + code.getstatic("org/python/core/Py", "AssertionError", "Lorg/python/core/PyObject;"); + + code.swap(); // The type is the first argument, but the message could be a yield + code.invokestatic("org/python/core/Py", "makeException", "(" + $pyObj + $pyObj + ")" + $pyExc); /* Raise assertion error. Only executes this logic if assertion @@ -1290,35 +1356,39 @@ @Override public Object visitCompare(Compare node) throws Exception { - int tmp1 = code.getLocal("org/python/core/PyObject"); - int tmp2 = code.getLocal("org/python/core/PyObject"); + int last = code.getLocal("org/python/core/PyObject"); + int result = code.getLocal("org/python/core/PyObject"); Label end = new Label(); visit(node.left); + code.astore(last); int n = node.ops.length; for(int i = 0; i < n - 1; i++) { visit(node.comparators[i]); + code.aload(last); + code.swap(); code.dup(); - code.astore(tmp1); + code.astore(last); visitCmpop(node.ops[i]); code.dup(); - code.astore(tmp2); + code.astore(result); code.invokevirtual("org/python/core/PyObject", "__nonzero__", "()Z"); code.ifeq(end); - code.aload(tmp1); } visit(node.comparators[n-1]); + code.aload(last); + code.swap(); visitCmpop(node.ops[n-1]); if (n > 1) { - code.astore(tmp2); + code.astore(result); code.label(end); - code.aload(tmp2); + code.aload(result); } - code.freeLocal(tmp1); - code.freeLocal(tmp2); + code.freeLocal(last); + code.freeLocal(result); return null; } @@ -1342,7 +1412,9 @@ @Override public Object visitBinOp(BinOp node) throws Exception { visit(node.left); + stackProduce(); visit(node.right); + stackConsume(); String name = null; switch (node.op) { case Add: name = "_add"; break; @@ -1384,13 +1456,14 @@ public Object visitAugAssign(AugAssign node) throws Exception { setline(node); - visit(node.value); - int tmp = storeTop(); - augmode = expr_contextType.Load; visit(node.target); + int target = storeTop(); - code.aload(tmp); + visit(node.value); + + code.aload(target); + code.swap(); String name = null; switch (node.op) { case Add: name = "_iadd"; break; @@ -1410,7 +1483,7 @@ name = "_itruediv"; } code.invokevirtual("org/python/core/PyObject", name, "(" + $pyObj + ")" + $pyObj); - code.freeLocal(tmp); + code.freeLocal(target); temporary = storeTop(); augmode = expr_contextType.Store; @@ -1421,12 +1494,12 @@ } - public static void makeStrings(Code c, String[] names, int n) + public static int makeStrings(Code c, String[] names, int n) throws IOException { c.iconst(n); c.anewarray("java/lang/String"); - int strings = c.getLocal("[java/lang/String"); + int strings = c.getLocal("[Ljava/lang/String;"); c.astore(strings); for (int i=0; i<n; i++) { c.aload(strings); @@ -1434,46 +1507,53 @@ c.ldc(names[i]); c.aastore(); } - c.aload(strings); - c.freeLocal(strings); + return strings; } public Object invokeNoKeywords(Attribute node, PythonTree[] values) throws Exception { String name = getName(node.attr); - visit(node.value); + visit(node.value); stackProduce(); code.ldc(name); code.invokevirtual("org/python/core/PyObject", "__getattr__", "(" + $str + ")" + $pyObj); switch (values.length) { case 0: + stackConsume(); // target code.invokevirtual("org/python/core/PyObject", "__call__", "()" + $pyObj); break; case 1: visit(values[0]); + stackConsume(); // target code.invokevirtual("org/python/core/PyObject", "__call__", "(" + $pyObj + ")" + $pyObj); break; case 2: - visit(values[0]); + visit(values[0]); stackProduce(); visit(values[1]); + stackConsume(2); // target + arguments code.invokevirtual("org/python/core/PyObject", "__call__", "(" + $pyObj + $pyObj + ")" + $pyObj); break; case 3: - visit(values[0]); - visit(values[1]); + visit(values[0]); stackProduce(); + visit(values[1]); stackProduce(); visit(values[2]); + stackConsume(3); // target + arguments code.invokevirtual("org/python/core/PyObject", "__call__", "(" + $pyObj + $pyObj + $pyObj + ")" + $pyObj); break; case 4: - visit(values[0]); - visit(values[1]); - visit(values[2]); + visit(values[0]); stackProduce(); + visit(values[1]); stackProduce(); + visit(values[2]); stackProduce(); visit(values[3]); + stackConsume(4); // target + arguments code.invokevirtual("org/python/core/PyObject", "__call__", "(" + $pyObj + $pyObj + $pyObj + $pyObj + ")" + $pyObj); break; default: - makeArray(values); + int argArray = makeArray(values); + code.aload(argArray); + code.freeLocal(argArray); + stackConsume(); // target code.invokevirtual("org/python/core/PyObject", "__call__", "(" + $pyObjArr + ")" + $pyObj); break; } @@ -1499,54 +1579,76 @@ return invokeNoKeywords((Attribute) node.func, values); } - visit(node.func); + visit(node.func); stackProduce(); if (node.starargs != null || node.kwargs != null) { - makeArray(values); - makeStrings(code, keys, keys.length); + int argArray = makeArray(values); + int strArray = makeStrings(code, keys, keys.length); if (node.starargs == null) code.aconst_null(); else visit(node.starargs); + stackProduce(); if (node.kwargs == null) code.aconst_null(); else visit(node.kwargs); + stackProduce(); + + code.aload(argArray); + code.aload(strArray); + code.dup2_x2(); + code.pop2(); + + stackConsume(3); // target + starargs + kwargs code.invokevirtual("org/python/core/PyObject", "_callextra", "(" + $pyObjArr + $strArr + $pyObj + $pyObj + ")" + $pyObj); } else if (keys.length > 0) { - makeArray(values); - makeStrings(code, keys, keys.length); + int argArray = makeArray(values); + int strArray = makeStrings(code, keys, keys.length); + code.aload(argArray); + code.aload(strArray); + code.freeLocal(argArray); + code.freeLocal(strArray); + stackConsume(); // target code.invokevirtual("org/python/core/PyObject", "__call__", "(" + $pyObjArr + $strArr + ")" + $pyObj); } else { switch (values.length) { case 0: + stackConsume(); // target code.invokevirtual("org/python/core/PyObject", "__call__", "()" + $pyObj); break; case 1: visit(values[0]); + stackConsume(); // target code.invokevirtual("org/python/core/PyObject", "__call__", "(" + $pyObj + ")" + $pyObj); break; case 2: - visit(values[0]); + visit(values[0]); stackProduce(); visit(values[1]); + stackConsume(2); // target + arguments code.invokevirtual("org/python/core/PyObject", "__call__", "(" + $pyObj + $pyObj + ")" + $pyObj); break; case 3: - visit(values[0]); - visit(values[1]); + visit(values[0]); stackProduce(); + visit(values[1]); stackProduce(); visit(values[2]); + stackConsume(3); // target + arguments code.invokevirtual("org/python/core/PyObject", "__call__", "(" + $pyObj + $pyObj + $pyObj + ")" + $pyObj); break; case 4: - visit(values[0]); - visit(values[1]); - visit(values[2]); + visit(values[0]); stackProduce(); + visit(values[1]); stackProduce(); + visit(values[2]); stackProduce(); visit(values[3]); + stackConsume(4); // target + arguments code.invokevirtual("org/python/core/PyObject", "__call__", "(" + $pyObj + $pyObj + $pyObj + $pyObj + ")" + $pyObj); break; default: - makeArray(values); + int argArray = makeArray(values); + code.aload(argArray); + code.freeLocal(argArray); + stackConsume(); // target code.invokevirtual("org/python/core/PyObject", "__call__", "(" + $pyObjArr + ")" + $pyObj); break; } @@ -1562,18 +1664,22 @@ ctx = expr_contextType.Store; } else { visit(node.value); + stackProduce(); if (slice.lower != null) visit(slice.lower); else code.aconst_null(); + stackProduce(); if (slice.upper != null) visit(slice.upper); else code.aconst_null(); + stackProduce(); if (slice.step != null) visit(slice.step); else code.aconst_null(); + stackProduce(); if (node.ctx == expr_contextType.AugStore && augmode == expr_contextType.Load) { saveAugTmps(node, 4); @@ -1581,6 +1687,7 @@ } } + stackConsume(4); switch (ctx) { case Del: code.invokevirtual("org/python/core/PyObject", "__delslice__", "(" + $pyObj + $pyObj + $pyObj + ")V"); @@ -1610,7 +1717,7 @@ restoreAugTmps(node, 2); ctx = expr_contextType.Store; } else { - visit(node.value); + visit(node.value); stackProduce(); visit(node.slice); if (node.ctx == expr_contextType.AugStore && augmode == expr_contextType.Load) { @@ -1619,6 +1726,7 @@ } } + stackConsume(); switch (ctx) { case Del: code.invokevirtual("org/python/core/PyObject", "__delitem__", "(" + $pyObj + ")V"); @@ -1643,9 +1751,11 @@ @Override public Object visitExtSlice(ExtSlice node) throws Exception { + int dims = makeArray(node.dims); code.new_("org/python/core/PyTuple"); code.dup(); - makeArray(node.dims); + code.aload(dims); + code.freeLocal(dims); code.invokespecial("org/python/core/PyTuple", "<init>", "(" + $pyObjArr + ")V"); return null; } @@ -1716,11 +1826,14 @@ "augmented assign to tuple not possible", node); */ if (node.ctx == expr_contextType.Store) return seqSet(node.elts); if (node.ctx == expr_contextType.Del) return seqDel(node.elts); + + int content = makeArray(node.elts); code.new_("org/python/core/PyTuple"); code.dup(); - makeArray(node.elts); + code.aload(content); + code.freeLocal(content); code.invokespecial("org/python/core/PyTuple", "<init>", "(" + $pyObjArr + ")V"); return null; } @@ -1729,10 +1842,13 @@ public Object visitList(List node) throws Exception { if (node.ctx == expr_contextType.Store) return seqSet(node.elts); if (node.ctx == expr_contextType.Del) return seqDel(node.elts); + + int content = makeArray(node.elts); code.new_("org/python/core/PyList"); code.dup(); - makeArray(node.elts); + code.aload(content); + code.freeLocal(content); code.invokespecial("org/python/core/PyList", "<init>", "(" + $pyObjArr + ")V"); return null; } @@ -1773,15 +1889,17 @@ @Override public Object visitDict(Dict node) throws Exception { - code.new_("org/python/core/PyDictionary"); - - code.dup(); PythonTree[] elts = new PythonTree[node.keys.length * 2]; for (int i = 0; i < node.keys.length; i++) { elts[i * 2] = node.keys[i]; elts[i * 2 + 1] = node.values[i]; } - makeArray(elts); + int content = makeArray(elts); + + code.new_("org/python/core/PyDictionary"); + code.dup(); + code.aload(content); + code.freeLocal(content); code.invokespecial("org/python/core/PyDictionary", "<init>", "(" + $pyObjArr + ")V"); return null; } @@ -1805,12 +1923,13 @@ ScopeInfo scope = module.getScopeInfo(node); - makeArray(scope.ac.getDefaults()); + int defaultsArray = makeArray(scope.ac.getDefaults()); code.new_("org/python/core/PyFunction"); - code.dup_x1(); - code.swap(); + code.dup(); + code.aload(defaultsArray); + code.freeLocal(defaultsArray); loadFrame(); code.getfield("org/python/core/PyFrame", "f_globals", $pyObj); @@ -1840,12 +1959,20 @@ @Override public Object visitSlice(Slice node) throws Exception { + if (node.lower == null) getNone(); else visit(node.lower); stackProduce(); + if (node.upper == null) getNone(); else visit(node.upper); stackProduce(); + if (node.step == null) getNone(); else visit(node.step); + int step = storeTop(); + stackConsume(2); + code.new_("org/python/core/PySlice"); - code.dup(); - if (node.lower == null) getNone(); else visit(node.lower); - if (node.upper == null) getNone(); else visit(node.upper); - if (node.step == null) getNone(); else visit(node.step); + code.dup2_x2(); + code.pop2(); + + code.aload(step); + code.freeLocal(step); + code.invokespecial("org/python/core/PySlice", "<init>", "(" + $pyObj + $pyObj + $pyObj + ")V"); return null; } @@ -1854,12 +1981,15 @@ public Object visitClassDef(ClassDef node) throws Exception { setline(node); + int baseArray = makeArray(node.bases); + //Get class name String name = getName(node.name); code.ldc(name); + + code.aload(baseArray); + code.freeLocal(baseArray); - makeArray(node.bases); - ScopeInfo scope = module.getScopeInfo(node); scope.setup_closure(); @@ -2045,7 +2175,9 @@ ScopeInfo scope = module.getScopeInfo(node); - makeArray(new exprType[0]); + int emptyArray = makeArray(new exprType[0]); + code.aload(emptyArray); + code.freeLocal(emptyArray); scope.setup_closure(); scope.dump(); @@ -2079,8 +2211,9 @@ set(new Name(node, tmp_append, expr_contextType.Store)); + visit(iter); visit(new Name(node, tmp_append, expr_contextType.Load)); - visit(iter); + code.swap(); code.invokevirtual("org/python/core/PyObject", "__iter__", "()Lorg/python/core/PyObject;"); code.invokevirtual("org/python/core/PyObject", "__call__", "(" + $pyObj + ")" + $pyObj); @@ -2095,9 +2228,6 @@ throw new ParseException("'with' will become a reserved keyword in Python 2.6", node); } - int my_with_count = with_count; - with_count++; - Label label_body_start = new Label(); Label label_body_end = new Label(); Label label_catch = new Label(); @@ -2110,21 +2240,14 @@ // mgr = (EXPR) visit(node.context_expr); - int mgr_tmp = code.getLocal("org/python/core/PyObject"); - code.astore(mgr_tmp); - - // exit = mgr.__exit__ # Not calling it yet, so storing in the frame - loadFrame(); - code.getfield("org/python/core/PyFrame", "f_exits", $pyObjArr); - code.iconst(my_with_count); - code.aload(mgr_tmp); + code.dup(); + code.ldc("__exit__"); code.invokevirtual(Type.getType(PyObject.class).getInternalName(), getattr.getName(), getattr.getDescriptor()); - code.aastore(); + int __exit__ = code.getLocal("org/python/core/PyObject"); + code.astore(__exit__); // value = mgr.__enter__() - code.aload(mgr_tmp); - code.freeLocal(mgr_tmp); code.ldc("__enter__"); code.invokevirtual(Type.getType(PyObject.class).getInternalName(), getattr.getName(), getattr.getDescriptor()); code.invokevirtual(Type.getType(PyObject.class).getInternalName(), call.getName(), call.getDescriptor()); @@ -2166,10 +2289,7 @@ // # The exceptional case is handled here // exc = False # implicit // if not exit(*sys.exc_info()): - loadFrame(); - code.getfield("org/python/core/PyFrame", "f_exits", $pyObjArr); - code.iconst(my_with_count); - code.aaload(); + code.aload(__exit__); code.aload(ts_tmp); code.getfield("org/python/core/PyException", "type", $pyObj); code.aload(ts_tmp); @@ -2198,10 +2318,7 @@ code.label(label_finally); - loadFrame(); - code.getfield("org/python/core/PyFrame", "f_exits", $pyObjArr); - code.iconst(my_with_count); - code.aaload(); + code.aload(__exit__); getNone(); code.dup(); code.dup(); @@ -2209,7 +2326,7 @@ code.pop(); code.label(label_end); - with_count--; + code.freeLocal(__exit__); return null; } Modified: trunk/jython/src/org/python/compiler/Module.java =================================================================== --- trunk/jython/src/org/python/compiler/Module.java 2008-10-17 07:06:39 UTC (rev 5453) +++ trunk/jython/src/org/python/compiler/Module.java 2008-10-17 18:15:50 UTC (rev 5454) @@ -244,11 +244,14 @@ c.iconst(argcount); //Make all names + int nameArray; if (names != null) { - CodeCompiler.makeStrings(c, names, names.length); + nameArray = CodeCompiler.makeStrings(c, names, names.length); } else { // classdef - CodeCompiler.makeStrings(c, null, 0); + nameArray = CodeCompiler.makeStrings(c, null, 0); } + c.aload(nameArray); + c.freeLocal(nameArray); c.aload(1); c.ldc(co_name); c.iconst(co_firstlineno); @@ -260,13 +263,17 @@ c.iconst(id); - if (cellvars != null) - CodeCompiler.makeStrings(c, cellvars, cellvars.length); - else + if (cellvars != null) { + int strArray = CodeCompiler.makeStrings(c, cellvars, cellvars.length); + c.aload(strArray); + c.freeLocal(strArray); + } else c.aconst_null(); - if (freevars != null) - CodeCompiler.makeStrings(c, freevars, freevars.length); - else + if (freevars != null) { + int strArray = CodeCompiler.makeStrings(c, freevars, freevars.length); + c.aload(strArray); + c.freeLocal(strArray); + } else c.aconst_null(); c.iconst(jy_npurecell); Modified: trunk/jython/src/org/python/compiler/ProxyMaker.java =================================================================== --- trunk/jython/src/org/python/compiler/ProxyMaker.java 2008-10-17 07:06:39 UTC (rev 5453) +++ trunk/jython/src/org/python/compiler/ProxyMaker.java 2008-10-17 18:15:50 UTC (rev 5454) @@ -657,7 +657,9 @@ code.ldc("__supernames__"); String[] nameArray = supernames.toArray(new String[n]); - CodeCompiler.makeStrings(code, nameArray, n); + int strArray = CodeCompiler.makeStrings(code, nameArray, n); + code.aload(strArray); + code.freeLocal(strArray); code.invokestatic("org/python/core/Py", "java2py", "(" + $obj + ")" + $pyObj); code.invokevirtual("org/python/core/PyObject", "__setitem__", "(" + $str + $pyObj + ")V"); code.return_(); This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <cg...@us...> - 2008-10-17 07:06:42
|
Revision: 5453 http://jython.svn.sourceforge.net/jython/?rev=5453&view=rev Author: cgroves Date: 2008-10-17 07:06:39 +0000 (Fri, 17 Oct 2008) Log Message: ----------- A couple slices from Occam's razor, and speedups for items and keys by making arrays for PyList directly instead of making Lists and letting PyList turn them into arrays Modified Paths: -------------- trunk/jython/src/org/python/core/PyStringMap.java Modified: trunk/jython/src/org/python/core/PyStringMap.java =================================================================== --- trunk/jython/src/org/python/core/PyStringMap.java 2008-10-17 00:04:42 UTC (rev 5452) +++ trunk/jython/src/org/python/core/PyStringMap.java 2008-10-17 07:06:39 UTC (rev 5453) @@ -1,10 +1,8 @@ // Copyright (c) Corporation for National Research Initiatives package org.python.core; -import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; -import java.util.List; import java.util.Map; import java.util.Set; import java.util.Map.Entry; @@ -95,11 +93,7 @@ public void __setitem__(PyObject key, PyObject value) { if (value == null) { - if (key instanceof PyString) { - table.remove(((PyString)key).internedString()); - } else { - table.remove(key); - } + table.remove(pyToKey(key)); } else if (key instanceof PyString) { __setitem__(((PyString)key).internedString(), value); } else { @@ -205,15 +199,12 @@ } public boolean has_key(PyObject key) { - if (key instanceof PyString) { - return has_key(((PyString)key).internedString()); - } - return table.containsKey(key); + return table.containsKey(pyToKey(key)); } /** * Return this[key] if the key exists in the mapping, default_object is returned otherwise. - * + * * @param key * the key to lookup in the mapping. * @param default_object @@ -230,7 +221,7 @@ /** * Return this[key] if the key exists in the mapping, None is returned otherwise. - * + * * @param key * the key to lookup in the mapping. */ @@ -263,7 +254,7 @@ } for (int i = 0; i < keywords.length; i++) { __setitem__(keywords[i], args[nargs + i]); - } + } } /** @@ -325,7 +316,7 @@ /** * Return this[key] if the key exist, otherwise insert key with a None value and return None. - * + * * @param key * the key to lookup in the mapping. */ @@ -336,7 +327,7 @@ /** * Return this[key] if the key exist, otherwise insert key with the value of failobj and return * failobj - * + * * @param key * the key to lookup in the mapping. * @param failobj @@ -354,19 +345,11 @@ * Return a random (key, value) tuple pair and remove the pair from the mapping. */ public PyObject popitem() { - Iterator it = table.entrySet().iterator(); + Iterator<Entry<Object, PyObject>> it = table.entrySet().iterator(); if (!it.hasNext()) { throw Py.KeyError("popitem(): dictionary is empty"); } - Entry entry = (Entry)it.next(); - Object objKey = entry.getKey(); - PyObject value = (PyObject)entry.getValue(); - PyTuple tuple; - if (objKey instanceof String) { - tuple = new PyTuple(new PyString((String)objKey), value); - } else { - tuple = new PyTuple((PyObject)objKey, value); - } + PyTuple tuple = itemTuple(it.next()); it.remove(); return tuple; } @@ -380,13 +363,7 @@ } public PyObject pop(PyObject key, PyObject failobj) { - Object objKey; - if (key instanceof PyString) { - objKey = ((PyString)key).internedString(); - } else { - objKey = key; - } - PyObject value = table.remove(objKey); + PyObject value = table.remove(pyToKey(key)); if (value == null) { if (failobj == null) { throw Py.KeyError(key.__repr__().toString()); @@ -401,22 +378,11 @@ * Return a copy of the mappings list of (key, value) tuple pairs. */ public PyList items() { - List<PyObject> list = new ArrayList<PyObject>(table.size()); - for (Entry<Object, PyObject> entry : table.entrySet()) { - list.add(itemTuple(entry)); - } - return new PyList(list); + return new PyList(iteritems()); } private PyTuple itemTuple(Entry<Object, PyObject> entry) { - Object key = entry.getKey(); - PyObject pyKey; - if (key instanceof String) { - pyKey = PyString.fromInterned((String)key); - } else { - pyKey = (PyObject)key; - } - return new PyTuple(pyKey, entry.getValue()); + return new PyTuple(keyToPy(entry.getKey()), entry.getValue()); } /** @@ -424,16 +390,12 @@ * storing String or PyObject objects */ public PyList keys() { - List<PyObject> list = new ArrayList<PyObject>(table.size()); - for (Iterator it = table.keySet().iterator(); it.hasNext();) { - Object obj = it.next(); - if (obj instanceof String) { - list.add(PyString.fromInterned((String)obj)); - } else { - list.add((PyObject)obj); - } + PyObject[] keyArray = new PyObject[table.size()]; + int i = 0; + for (Object key : table.keySet()) { + keyArray[i++] = keyToPy(key); } - return new PyList(list); + return new PyList(keyArray); } /** @@ -466,13 +428,13 @@ return new ValuesIter(table.values()); } - private class ValuesIter extends PyIterator { + private abstract class StringMapIter<T> extends PyIterator { - private final Iterator<PyObject> iterator; + protected final Iterator<T> iterator; private final int size; - public ValuesIter(Collection<PyObject> c) { + public StringMapIter(Collection<T> c) { iterator = c.iterator(); size = c.size(); } @@ -484,58 +446,58 @@ if (!iterator.hasNext()) { return null; } - return iterator.next(); + return stringMapNext(); } + + protected abstract PyObject stringMapNext(); } - private class KeysIter extends PyIterator { + private class ValuesIter extends StringMapIter<PyObject> { - private final Iterator iterator; - - private final int size; - - public KeysIter(Set s) { - iterator = s.iterator(); - size = s.size(); + public ValuesIter(Collection<PyObject> c) { + super(c); } - public PyObject __iternext__() { - if (table.size() != size) { - throw Py.RuntimeError("dictionary changed size during iteration"); - } - if (!iterator.hasNext()) { - return null; - } - Object objKey = iterator.next(); - PyObject key = null; - if (objKey instanceof String) { - key = PyString.fromInterned((String)objKey); - } else { - key = (PyObject)objKey; - } - return key; + public PyObject stringMapNext() { + return iterator.next(); } } - private class ItemsIter extends PyIterator { + private class KeysIter extends StringMapIter<Object> { - private final Iterator<Entry<Object, PyObject>> iterator; + public KeysIter(Set<Object> s) { + super(s); + } - private final int size; + protected PyObject stringMapNext() { + return keyToPy(iterator.next()); + } + } + private class ItemsIter extends StringMapIter<Entry<Object, PyObject>> { + public ItemsIter(Set<Entry<Object, PyObject>> s) { - iterator = s.iterator(); - size = s.size(); + super(s); } - public PyObject __iternext__() { - if (table.size() != size) { - throw Py.RuntimeError("dictionary changed size during iteration"); - } - if (!iterator.hasNext()) { - return null; - } + public PyObject stringMapNext() { return itemTuple(iterator.next()); } } + + private static PyObject keyToPy(Object objKey){ + if (objKey instanceof String) { + return PyString.fromInterned((String)objKey); + } else { + return (PyObject)objKey; + } + } + + private static Object pyToKey(PyObject pyKey) { + if (pyKey instanceof PyString) { + return ((PyString)pyKey).internedString(); + } else { + return pyKey; + } + } } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <pj...@us...> - 2008-10-17 00:04:51
|
Revision: 5452 http://jython.svn.sourceforge.net/jython/?rev=5452&view=rev Author: pjenvey Date: 2008-10-17 00:04:42 +0000 (Fri, 17 Oct 2008) Log Message: ----------- minor xrange optimization: use the small int cache Modified Paths: -------------- trunk/jython/src/org/python/core/PyXRange.java Modified: trunk/jython/src/org/python/core/PyXRange.java =================================================================== --- trunk/jython/src/org/python/core/PyXRange.java 2008-10-16 23:25:28 UTC (rev 5451) +++ trunk/jython/src/org/python/core/PyXRange.java 2008-10-17 00:04:42 UTC (rev 5452) @@ -120,7 +120,7 @@ @Override protected PyObject pyget(int i) { - return new PyInteger(start + (i % len) * step); + return Py.newInteger(start + (i % len) * step); } @Override This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <otm...@us...> - 2008-10-16 23:25:34
|
Revision: 5451 http://jython.svn.sourceforge.net/jython/?rev=5451&view=rev Author: otmarhumbel Date: 2008-10-16 23:25:28 +0000 (Thu, 16 Oct 2008) Log Message: ----------- fixed auto switching to console mode Modified Paths: -------------- trunk/installer/src/java/org/python/util/install/InstallerCommandLine.java trunk/installer/test/java/org/python/util/install/InstallerCommandLineTest.java Modified: trunk/installer/src/java/org/python/util/install/InstallerCommandLine.java =================================================================== --- trunk/installer/src/java/org/python/util/install/InstallerCommandLine.java 2008-10-16 22:20:26 UTC (rev 5450) +++ trunk/installer/src/java/org/python/util/install/InstallerCommandLine.java 2008-10-16 23:25:28 UTC (rev 5451) @@ -21,13 +21,13 @@ protected static final String INEXCLUDE_DOCUMENTATION = "doc"; protected static final String INEXCLUDE_SOURCES = "src"; - private static final String CONSOLE_SHORT = "c"; - private static final String CONSOLE_LONG = "console"; + protected static final String CONSOLE_SHORT = "c"; + protected static final String CONSOLE_LONG = "console"; private static final String CONSOLE_DESC = "console based installation (user interaction)\n" + "any other options will be ignored (except 'verbose')"; - private static final String SILENT_SHORT = "s"; - private static final String SILENT_LONG = "silent"; + protected static final String SILENT_SHORT = "s"; + protected static final String SILENT_LONG = "silent"; private static final String SILENT_DESC = "silent installation (without user interaction)"; protected static final String VERBOSE_SHORT = "v"; @@ -130,15 +130,32 @@ public static final boolean hasVerboseOptionInArgs(String[] args) { String shortVerbose = "-".concat(VERBOSE_SHORT); String longVerbose = "--".concat(VERBOSE_LONG); - for (String arg : args) { - if (shortVerbose.equals(arg) || longVerbose.equals(arg)) { - return true; - } - } - return false; + return hasOptionInArgs(args, shortVerbose, longVerbose); } /** + * Pre-scan of the arguments to detect a console flag + * @param args + * @return <code>true</code> if there is a console option + */ + public static final boolean hasConsoleOptionInArgs(String[] args) { + String shortConsole = "-".concat(CONSOLE_SHORT); + String longConsole = "--".concat(CONSOLE_LONG); + return hasOptionInArgs(args, shortConsole, longConsole); + } + + /** + * Pre-scan of the arguments to detect a silent flag + * @param args + * @return <code>true</code> if there is a silent option + */ + public static final boolean hasSilentOptionInArgs(String[] args) { + String shortSilent = "-".concat(SILENT_SHORT); + String longSilent = "--".concat(SILENT_LONG); + return hasOptionInArgs(args, shortSilent, longSilent); + } + + /** * constructor intended for JUnit tests only. */ public InstallerCommandLine() { @@ -154,14 +171,20 @@ */ public boolean setArgs(String args[]) { _args = args; - if (args.length == 0) { - // switch to console mode if gui is not allowed - if (!Installation.isGuiAllowed()) { - _args = new String[] { "-" + CONSOLE_SHORT }; + if (!hasConsoleOptionInArgs(args) && !hasSilentOptionInArgs(args) + && !Installation.isGuiAllowed()) { + // 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; } try { - _commandLine = _parser.parse(_options, _args, false); // throw for missing or unknown options / arguments + // throws for missing or unknown options / arguments + _commandLine = _parser.parse(_options, _args, false); } catch (MissingArgumentException mae) { System.err.println(mae.getMessage()); return false; @@ -353,6 +376,18 @@ // // private methods // + + private static final boolean hasOptionInArgs(String[] args, String shortOption, String longOption) { + boolean hasOption = false; + int i = 0; + while (!hasOption && i < args.length) { + if (shortOption.equals(args[i]) || longOption.equals(args[i])) { + hasOption = true; + } + i++; + } + return hasOption; + } private void createOptions() { _options = new Options(); Modified: trunk/installer/test/java/org/python/util/install/InstallerCommandLineTest.java =================================================================== --- trunk/installer/test/java/org/python/util/install/InstallerCommandLineTest.java 2008-10-16 22:20:26 UTC (rev 5450) +++ trunk/installer/test/java/org/python/util/install/InstallerCommandLineTest.java 2008-10-16 23:25:28 UTC (rev 5451) @@ -1,5 +1,7 @@ package org.python.util.install; +import java.io.File; + import junit.framework.TestCase; public class InstallerCommandLineTest extends TestCase { @@ -203,7 +205,7 @@ assertTrue(commandLine.hasConsoleOption()); } - public void testHeadless() { + public void testGui() { String[] args; InstallerCommandLine commandLine; @@ -214,24 +216,64 @@ assertTrue(commandLine.setArgs(args)); assertFalse(commandLine.hasConsoleOption()); assertFalse(commandLine.hasSilentOption()); - - // simulate startup without any arguments on a headless system + } + + /** + * simulate startup on a headless system (auto-switch to console mode) + */ + public void testHeadless() { + String[] args; + InstallerCommandLine commandLine; boolean originalHeadless = Boolean.getBoolean(Installation.HEADLESS_PROPERTY_NAME); try { - if(!originalHeadless) { + if (!originalHeadless) { System.setProperty(Installation.HEADLESS_PROPERTY_NAME, "true"); - assertFalse(Installation.isGuiAllowed()); - args = new String[0]; - commandLine = new InstallerCommandLine(); - assertTrue(commandLine.setArgs(args)); - assertTrue(commandLine.hasConsoleOption()); - assertFalse(commandLine.hasSilentOption()); } + assertFalse(Installation.isGuiAllowed()); + + // without any arguments + args = new String[0]; + commandLine = new InstallerCommandLine(); + assertTrue(commandLine.setArgs(args)); + assertTrue(commandLine.hasConsoleOption()); // auto switch + assertFalse(commandLine.hasSilentOption()); + + // with one argument + args = new String[] {"-v"}; + commandLine = new InstallerCommandLine(); + assertTrue(commandLine.setArgs(args)); + assertTrue(commandLine.hasVerboseOption()); + assertTrue(commandLine.hasConsoleOption()); // auto switch + assertFalse(commandLine.hasSilentOption()); + + // with more arguments + args = new String[] {"-v", "-t", "minimum" }; + commandLine = new InstallerCommandLine(); + assertTrue(commandLine.setArgs(args)); + assertTrue(commandLine.hasVerboseOption()); + assertTrue(commandLine.hasConsoleOption()); // auto switch + assertFalse(commandLine.hasSilentOption()); + assertTrue(commandLine.hasTypeOption()); + InstallationType type = commandLine.getInstallationType(); + assertNotNull(type); + assertTrue(type.isMinimum()); + + // silent should override! + args = new String[] {"-v", "-s", "-d", "some_dir"}; + commandLine = new InstallerCommandLine(); + assertTrue(commandLine.setArgs(args)); + assertTrue(commandLine.hasVerboseOption()); + assertFalse(commandLine.hasConsoleOption()); // no auto switch + assertTrue(commandLine.hasSilentOption()); + assertTrue(commandLine.hasDirectoryOption()); + File dir = commandLine.getTargetDirectory(); + assertNotNull(dir); + assertEquals("some_dir", dir.getName()); } finally { - if(!originalHeadless) { + if (!originalHeadless) { System.setProperty(Installation.HEADLESS_PROPERTY_NAME, "false"); + assertTrue(Installation.isGuiAllowed()); } - assertTrue(Installation.isGuiAllowed()); } } @@ -533,5 +575,51 @@ args = new String[] {"a", "--" + InstallerCommandLine.VERBOSE_LONG, "c"}; assertTrue(InstallerCommandLine.hasVerboseOptionInArgs(args)); } + + public void testHasConsoleOptionInArgs() { + String[] args = new String[0]; + assertFalse(InstallerCommandLine.hasConsoleOptionInArgs(args)); + + args = new String[] {"a", "b", "c"}; + assertFalse(InstallerCommandLine.hasConsoleOptionInArgs(args)); + + args = new String[] {"a", InstallerCommandLine.CONSOLE_SHORT, "c"}; + assertFalse(InstallerCommandLine.hasConsoleOptionInArgs(args)); + + args = new String[] {"a", "-" + InstallerCommandLine.CONSOLE_SHORT, "c"}; + assertTrue(InstallerCommandLine.hasConsoleOptionInArgs(args)); + + args = new String[] {"a", InstallerCommandLine.CONSOLE_LONG, "c"}; + assertFalse(InstallerCommandLine.hasConsoleOptionInArgs(args)); + + args = new String[] {"a", "-" + InstallerCommandLine.CONSOLE_LONG, "c"}; + assertFalse(InstallerCommandLine.hasConsoleOptionInArgs(args)); + + args = new String[] {"a", "--" + InstallerCommandLine.CONSOLE_LONG, "c"}; + assertTrue(InstallerCommandLine.hasConsoleOptionInArgs(args)); + } + + public void testHasSilentOptionInArgs() { + String[] args = new String[0]; + assertFalse(InstallerCommandLine.hasSilentOptionInArgs(args)); + + args = new String[] {"a", "b", "c"}; + assertFalse(InstallerCommandLine.hasSilentOptionInArgs(args)); + + args = new String[] {"a", InstallerCommandLine.SILENT_SHORT, "c"}; + assertFalse(InstallerCommandLine.hasSilentOptionInArgs(args)); + + args = new String[] {"a", "-" + InstallerCommandLine.SILENT_SHORT, "c"}; + assertTrue(InstallerCommandLine.hasSilentOptionInArgs(args)); + + args = new String[] {"a", InstallerCommandLine.SILENT_LONG, "c"}; + assertFalse(InstallerCommandLine.hasSilentOptionInArgs(args)); + + args = new String[] {"a", "-" + InstallerCommandLine.SILENT_LONG, "c"}; + assertFalse(InstallerCommandLine.hasSilentOptionInArgs(args)); + + args = new String[] {"a", "--" + InstallerCommandLine.SILENT_LONG, "c"}; + assertTrue(InstallerCommandLine.hasSilentOptionInArgs(args)); + } } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |