From: <zy...@us...> - 2008-08-20 06:54:13
|
Revision: 5215 http://jython.svn.sourceforge.net/jython/?rev=5215&view=rev Author: zyasoft Date: 2008-08-20 06:54:10 +0000 (Wed, 20 Aug 2008) Log Message: ----------- A class definition needs to have __module__ set in frame locals, so that it is accessible by a metaclass, if defined. Fixes test_advice in zope.interfaces Modified Paths: -------------- trunk/jython/src/org/python/compiler/Module.java trunk/jython/src/org/python/core/PyFrame.java Modified: trunk/jython/src/org/python/compiler/Module.java =================================================================== --- trunk/jython/src/org/python/compiler/Module.java 2008-08-20 05:26:20 UTC (rev 5214) +++ trunk/jython/src/org/python/compiler/Module.java 2008-08-20 06:54:10 UTC (rev 5215) @@ -405,6 +405,29 @@ CodeCompiler compiler = new CodeCompiler(this, printResults); + if (classBody) { + Label label_got_name = new Label(); + int module_tmp = c.getLocal("org/python/core/PyObject"); + + c.aload(1); + c.ldc("__module__"); + c.invokevirtual("org/python/core/PyFrame", "getname_or_null", "(" + $str + ")" + $pyObj); + c.dup(); + c.ifnonnull(label_got_name); + + c.pop(); + c.aload(1); + c.ldc("__name__"); + c.invokevirtual("org/python/core/PyFrame", "getname_or_null", "(" + $str + ")" + $pyObj); + + c.label(label_got_name); + c.astore(module_tmp); + c.aload(1); + c.ldc("__module__"); + c.aload(module_tmp); + c.invokevirtual("org/python/core/PyFrame", "setlocal", "(" + $str + $pyObj + ")V"); + } + Label genswitch = new Label(); if (scope.generator) { c.goto_(genswitch); Modified: trunk/jython/src/org/python/core/PyFrame.java =================================================================== --- trunk/jython/src/org/python/core/PyFrame.java 2008-08-20 05:26:20 UTC (rev 5214) +++ trunk/jython/src/org/python/core/PyFrame.java 2008-08-20 06:54:10 UTC (rev 5215) @@ -282,6 +282,20 @@ throw Py.NameError(String.format(NAME_ERROR_MSG, index)); } + public PyObject getname_or_null(String index) { + PyObject ret; + if (f_locals == null || f_locals == f_globals) { + ret = doGetglobal(index); + } else { + ret = f_locals.__finditem__(index); + if (ret != null) { + return ret; + } + ret = doGetglobal(index); + } + return ret; + } + public PyObject getglobal(String index) { PyObject ret = doGetglobal(index); if (ret != null) { This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <zy...@us...> - 2008-10-06 19:00:39
|
Revision: 5361 http://jython.svn.sourceforge.net/jython/?rev=5361&view=rev Author: zyasoft Date: 2008-10-06 18:57:58 +0000 (Mon, 06 Oct 2008) Log Message: ----------- Fixed test_quopri by encoding space or tab before newline and resetting the column count upon a newline Fixed #1144 so that -mMODULE works and remaining args are passed in sys.argv Modified Paths: -------------- trunk/jython/src/org/python/modules/binascii.java trunk/jython/src/org/python/util/jython.java Modified: trunk/jython/src/org/python/modules/binascii.java =================================================================== --- trunk/jython/src/org/python/modules/binascii.java 2008-10-06 03:12:34 UTC (rev 5360) +++ trunk/jython/src/org/python/modules/binascii.java 2008-10-06 18:57:58 UTC (rev 5361) @@ -984,12 +984,25 @@ int count = 0; for (int i=0, m=s.length(); i<m; i++) { char c = s.charAt(i); - if (('!' <= c && c <= '<') + + // RFC 1521 requires that the line ending in a space or tab must have + // that trailing character encoded. + if (lineEnding(s, lineEnd, i)) { + count = 0; + sb.append(lineEnd); + if (lineEnd.length() > 1) i++; + } + else if ((c == '\t' || c == ' ' ) && endOfLine(s, lineEnd, i + 1)) { + count += 3; + qpEscape(sb, c); + } + else if (('!' <= c && c <= '<') || ('>' <= c && c <= '^') || ('`' <= c && c <= '~') || (c == '_' && !header) || (c == '\n' || c == '\r' && istext)) { - if (count == 75) { +// if (count == 75 && i < s.length() - 1) { + if (count == 75 && !endOfLine(s, lineEnd, i + 1)) { sb.append("=").append(lineEnd); count = 0; } @@ -1023,7 +1036,16 @@ } return sb.toString(); } - + + private static boolean endOfLine(String s, String lineEnd, int i) { + return (s.length() == i || lineEnding(s, lineEnd, i)); + } + + private static boolean lineEnding(String s, String lineEnd, int i) { + return + (s.length() > i && s.substring(i).startsWith(lineEnd)); + } + /* public static void main(String[] args) { String l = b2a_uu("Hello"); Modified: trunk/jython/src/org/python/util/jython.java =================================================================== --- trunk/jython/src/org/python/util/jython.java 2008-10-06 03:12:34 UTC (rev 5360) +++ trunk/jython/src/org/python/util/jython.java 2008-10-06 18:57:58 UTC (rev 5361) @@ -7,6 +7,7 @@ import java.io.InputStream; import java.nio.charset.Charset; import java.util.ArrayList; +import java.util.Arrays; import java.util.List; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; @@ -439,7 +440,10 @@ } else if (arg.startsWith("-m")) { runModule = true; - if ((index + 1) < args.length) { + if (arg.length() > 2) { + moduleName = arg.substring(2); + } + else if ((index + 1) < args.length) { moduleName = args[++index]; } else { System.err.println("Argument expected for the -m option"); @@ -450,6 +454,15 @@ if (!fixInteractive) { interactive = false; } + + index++; + int n = args.length-index+1; + argv = new String[n]; + argv[0] = moduleName; + for (int i = 1; index < args.length; i++, index++) { + argv[i] = args[index]; + } + return true; } else { String opt = args[index]; This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <fwi...@us...> - 2008-10-11 21:29:38
|
Revision: 5374 http://jython.svn.sourceforge.net/jython/?rev=5374&view=rev Author: fwierzbicki Date: 2008-10-11 21:29:29 +0000 (Sat, 11 Oct 2008) Log Message: ----------- A very basic start to supporting pep 328 style relative imports like from . import foo This patch just passes the "level" (that is number of dots) information from the compile to the import machinary without actually using it, and forbids from . import * As Python 2.5 does. Modified Paths: -------------- trunk/jython/src/org/python/compiler/CodeCompiler.java trunk/jython/src/org/python/core/imp.java Modified: trunk/jython/src/org/python/compiler/CodeCompiler.java =================================================================== --- trunk/jython/src/org/python/compiler/CodeCompiler.java 2008-10-11 20:54:47 UTC (rev 5373) +++ trunk/jython/src/org/python/compiler/CodeCompiler.java 2008-10-11 21:29:29 UTC (rev 5374) @@ -768,6 +768,9 @@ code.ldc(node.module); //Note: parser does not allow node.names.length == 0 if (node.names.length == 1 && node.names[0].name.equals("*")) { + if (node.level > 0) { + throw new ParseException("'import *' not allowed with 'from .'", node); + } if (my_scope.func_level > 0) { module.error("import * only allowed at module level", false, node); @@ -799,7 +802,8 @@ makeStrings(code, fromNames, fromNames.length); loadFrame(); - code.invokestatic("org/python/core/imp", "importFrom", "(" + $str + $strArr + $pyFrame + ")" + $pyObjArr); + code.iconst(node.level); + code.invokestatic("org/python/core/imp", "importFrom", "(" + $str + $strArr + $pyFrame + "I" + ")" + $pyObjArr); int tmp = storeTop(); for (int i = 0; i < node.names.length; i++) { code.aload(tmp); Modified: trunk/jython/src/org/python/core/imp.java =================================================================== --- trunk/jython/src/org/python/core/imp.java 2008-10-11 20:54:47 UTC (rev 5373) +++ trunk/jython/src/org/python/core/imp.java 2008-10-11 21:29:29 UTC (rev 5374) @@ -753,12 +753,30 @@ } /** + * replaced by importFrom with level param. Kept for backwards compatibility. + * @deprecated use importFrom with level param. + */ + public static PyObject[] importFrom(String mod, String[] names, + PyFrame frame) { + return importFromAs(mod, names, null, frame, 0); + } + + /** * Called from jython generated code when a statement like "from spam.eggs * import foo, bar" is executed. */ public static PyObject[] importFrom(String mod, String[] names, + PyFrame frame, int level) { + return importFromAs(mod, names, null, frame, level); + } + + /** + * replaced by importFromAs with level param. Kept for backwards compatibility. + * @deprecated use importFromAs with level param. + */ + public static PyObject[] importFromAs(String mod, String[] names, PyFrame frame) { - return importFromAs(mod, names, null, frame); + return importFromAs(mod, names, null, frame, 0); } /** @@ -766,7 +784,7 @@ * import foo as spam" is executed. */ public static PyObject[] importFromAs(String mod, String[] names, - String[] asnames, PyFrame frame) { + String[] asnames, PyFrame frame, int level) { PyObject[] pyNames = new PyObject[names.length]; for (int i = 0; i < names.length; i++) { pyNames[i] = Py.newString(names[i]); This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <fwi...@us...> - 2008-10-12 16:28:25
|
Revision: 5379 http://jython.svn.sourceforge.net/jython/?rev=5379&view=rev Author: fwierzbicki Date: 2008-10-12 16:28:15 +0000 (Sun, 12 Oct 2008) Log Message: ----------- More groundwork for absolute_import. Passing level info into most of the places it needs to go, also now sending the correct level information when "from __future__ import absolute_import" is issued. Added a constant in imp.java DEFAULT_LEVEL, so that it can be changed in one place when absolute import becomes the default behavior. Modified Paths: -------------- trunk/jython/src/org/python/compiler/CodeCompiler.java trunk/jython/src/org/python/compiler/Future.java trunk/jython/src/org/python/core/__builtin__.java trunk/jython/src/org/python/core/imp.java Modified: trunk/jython/src/org/python/compiler/CodeCompiler.java =================================================================== --- trunk/jython/src/org/python/compiler/CodeCompiler.java 2008-10-12 00:25:07 UTC (rev 5378) +++ trunk/jython/src/org/python/compiler/CodeCompiler.java 2008-10-12 16:28:15 UTC (rev 5379) @@ -802,7 +802,16 @@ makeStrings(code, fromNames, fromNames.length); loadFrame(); - code.iconst(node.level); + + if (node.level == 0) { + if (module.getFutures().isAbsoluteImportOn()) { + code.iconst_0(); + } else { + code.iconst_m1(); + } + } else { + code.iconst(node.level); + } code.invokestatic("org/python/core/imp", "importFrom", "(" + $str + $strArr + $pyFrame + "I" + ")" + $pyObjArr); int tmp = storeTop(); for (int i = 0; i < node.names.length; i++) { Modified: trunk/jython/src/org/python/compiler/Future.java =================================================================== --- trunk/jython/src/org/python/compiler/Future.java 2008-10-12 00:25:07 UTC (rev 5378) +++ trunk/jython/src/org/python/compiler/Future.java 2008-10-12 16:28:15 UTC (rev 5379) @@ -115,4 +115,8 @@ return with_statement; } + public boolean isAbsoluteImportOn() { + return absolute_import; + } + } Modified: trunk/jython/src/org/python/core/__builtin__.java =================================================================== --- trunk/jython/src/org/python/core/__builtin__.java 2008-10-12 00:25:07 UTC (rev 5378) +++ trunk/jython/src/org/python/core/__builtin__.java 2008-10-12 16:28:15 UTC (rev 5379) @@ -1198,18 +1198,22 @@ } public static PyObject __import__(String name) { - return __import__(name, null, null, null); + return __import__(name, null, null, null, imp.DEFAULT_LEVEL); } public static PyObject __import__(String name, PyObject globals) { - return __import__(name, globals, null, null); + return __import__(name, globals, null, null, imp.DEFAULT_LEVEL); } public static PyObject __import__(String name, PyObject globals, PyObject locals) { - return __import__(name, globals, locals, null); + return __import__(name, globals, locals, null, imp.DEFAULT_LEVEL); } public static PyObject __import__(String name, PyObject globals, PyObject locals, PyObject fromlist) { + return __import__(name, globals, locals, fromlist, imp.DEFAULT_LEVEL); + } + + public static PyObject __import__(String name, PyObject globals, PyObject locals, PyObject fromlist, int level) { PyFrame frame = Py.getFrame(); if (frame == null) { return null; @@ -1224,7 +1228,7 @@ return null; } - PyObject module = __import__.__call__(new PyObject[]{Py.newString(name), globals, locals, fromlist}); + PyObject module = __import__.__call__(new PyObject[]{Py.newString(name), globals, locals, fromlist, Py.newInteger(level)}); return module; } } @@ -1280,12 +1284,13 @@ PyObject globals = (argc > 1 && args[1] != null) ? args[1] : null; PyObject fromlist = (argc > 3 && args[3] != null) ? args[3] : Py.EmptyTuple; + int level = (argc > 4 && args[4] != null) ? Py.py2int(args[4]) : imp.DEFAULT_LEVEL; - return load(module, globals, fromlist); + return load(module, globals, fromlist, level); } - private PyObject load(String module, PyObject globals, PyObject fromlist) { - PyObject mod = imp.importName(module.intern(), fromlist.__len__() == 0, globals, fromlist); + 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; } Modified: trunk/jython/src/org/python/core/imp.java =================================================================== --- trunk/jython/src/org/python/core/imp.java 2008-10-12 00:25:07 UTC (rev 5378) +++ trunk/jython/src/org/python/core/imp.java 2008-10-12 16:28:15 UTC (rev 5379) @@ -24,6 +24,9 @@ public static final int APIVersion = 15; + //This should change to 0 for Python 2.7 and 3.0 see PEP 328 + public static final int DEFAULT_LEVEL = -1; + /** A non-empty fromlist for __import__'ing sub-modules. */ private static final PyObject nonEmptyFromlist = new PyTuple(Py.newString("__doc__")); @@ -518,9 +521,14 @@ * 'a.b.c' would return 'a.b'. * * @param dict the __dict__ of a loaded module + * @param level used for relative and absolute imports. -1 means try both, + * 0 means absolute only, positive ints represent the level to + * look upward for a relative path. See PEP 328 at + * http://www.python.org/dev/peps/pep-0328/ + * * @return the parent name for a module */ - private static String getParent(PyObject dict) { + private static String getParent(PyObject dict, int level) { PyObject tmp = dict.__finditem__("__name__"); if (tmp == null) { return null; @@ -639,7 +647,7 @@ * @return a module */ private static PyObject import_name(String name, boolean top, - PyObject modDict, PyObject fromlist) { + PyObject modDict, PyObject fromlist, int level) { if (name.length() == 0) { throw Py.ValueError("Empty module name"); } @@ -647,7 +655,7 @@ PyObject pkgMod = null; String pkgName = null; if (modDict != null && !(modDict instanceof PyNone)) { - pkgName = getParent(modDict); + pkgName = getParent(modDict, level); pkgMod = modules.__finditem__(pkgName); if (pkgMod != null && !(pkgMod instanceof PyModule)) { pkgMod = null; @@ -705,7 +713,7 @@ * @return an imported module (Java or Python) */ public static PyObject importName(String name, boolean top) { - return import_name(name, top, null, null); + return import_name(name, top, null, null, DEFAULT_LEVEL); } /** @@ -718,10 +726,10 @@ * @return an imported module (Java or Python) */ public static PyObject importName(String name, boolean top, - PyObject modDict, PyObject fromlist) { + PyObject modDict, PyObject fromlist, int level) { importLock.lock(); try { - return import_name(name, top, modDict, fromlist); + return import_name(name, top, modDict, fromlist, level); } finally { importLock.unlock(); } @@ -758,7 +766,7 @@ */ public static PyObject[] importFrom(String mod, String[] names, PyFrame frame) { - return importFromAs(mod, names, null, frame, 0); + return importFromAs(mod, names, null, frame, DEFAULT_LEVEL); } /** @@ -776,7 +784,7 @@ */ public static PyObject[] importFromAs(String mod, String[] names, PyFrame frame) { - return importFromAs(mod, names, null, frame, 0); + return importFromAs(mod, names, null, frame, DEFAULT_LEVEL); } /** @@ -791,7 +799,7 @@ } PyObject module = __builtin__.__import__(mod, frame.f_globals, frame.getLocals(), - new PyTuple(pyNames)); + new PyTuple(pyNames), level); PyObject[] submods = new PyObject[names.length]; for (int i = 0; i < names.length; i++) { PyObject submod = module.__findattr__(names[i]); This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <pj...@us...> - 2008-10-12 22:38:07
|
Revision: 5382 http://jython.svn.sourceforge.net/jython/?rev=5382&view=rev Author: pjenvey Date: 2008-10-12 22:37:53 +0000 (Sun, 12 Oct 2008) Log Message: ----------- update the deriveds for better unhashable TypeError messages Modified Paths: -------------- trunk/jython/src/org/python/core/PyArrayDerived.java trunk/jython/src/org/python/core/PyBaseExceptionDerived.java trunk/jython/src/org/python/core/PyBooleanDerived.java trunk/jython/src/org/python/core/PyClassMethodDerived.java trunk/jython/src/org/python/core/PyComplexDerived.java trunk/jython/src/org/python/core/PyDictionaryDerived.java trunk/jython/src/org/python/core/PyEnumerateDerived.java trunk/jython/src/org/python/core/PyFileDerived.java trunk/jython/src/org/python/core/PyFloatDerived.java trunk/jython/src/org/python/core/PyFrozenSetDerived.java trunk/jython/src/org/python/core/PyIntegerDerived.java trunk/jython/src/org/python/core/PyListDerived.java trunk/jython/src/org/python/core/PyLongDerived.java trunk/jython/src/org/python/core/PyModuleDerived.java trunk/jython/src/org/python/core/PyObjectDerived.java trunk/jython/src/org/python/core/PyPropertyDerived.java trunk/jython/src/org/python/core/PySetDerived.java trunk/jython/src/org/python/core/PySliceDerived.java trunk/jython/src/org/python/core/PyStringDerived.java trunk/jython/src/org/python/core/PySuperDerived.java trunk/jython/src/org/python/core/PyTupleDerived.java trunk/jython/src/org/python/core/PyTypeDerived.java trunk/jython/src/org/python/core/PyUnicodeDerived.java trunk/jython/src/org/python/modules/_collections/PyDefaultDictDerived.java trunk/jython/src/org/python/modules/_collections/PyDequeDerived.java trunk/jython/src/org/python/modules/_csv/PyDialectDerived.java trunk/jython/src/org/python/modules/_functools/PyPartialDerived.java trunk/jython/src/org/python/modules/_weakref/ReferenceTypeDerived.java trunk/jython/src/org/python/modules/random/PyRandomDerived.java trunk/jython/src/org/python/modules/thread/PyLocalDerived.java trunk/jython/src/org/python/modules/zipimport/zipimporterDerived.java Modified: trunk/jython/src/org/python/core/PyArrayDerived.java =================================================================== --- trunk/jython/src/org/python/core/PyArrayDerived.java 2008-10-12 22:18:06 UTC (rev 5381) +++ trunk/jython/src/org/python/core/PyArrayDerived.java 2008-10-12 22:37:53 UTC (rev 5382) @@ -744,7 +744,7 @@ throw Py.TypeError("__hash__ should return a int"); } if (self_type.lookup("__eq__")!=null||self_type.lookup("__cmp__")!=null) { - throw Py.TypeError("unhashable type"); + throw Py.TypeError(String.format("unhashable type: '%.200s'",getType().fastGetName())); } return super.hashCode(); } Modified: trunk/jython/src/org/python/core/PyBaseExceptionDerived.java =================================================================== --- trunk/jython/src/org/python/core/PyBaseExceptionDerived.java 2008-10-12 22:18:06 UTC (rev 5381) +++ trunk/jython/src/org/python/core/PyBaseExceptionDerived.java 2008-10-12 22:37:53 UTC (rev 5382) @@ -720,7 +720,7 @@ throw Py.TypeError("__hash__ should return a int"); } if (self_type.lookup("__eq__")!=null||self_type.lookup("__cmp__")!=null) { - throw Py.TypeError("unhashable type"); + throw Py.TypeError(String.format("unhashable type: '%.200s'",getType().fastGetName())); } return super.hashCode(); } Modified: trunk/jython/src/org/python/core/PyBooleanDerived.java =================================================================== --- trunk/jython/src/org/python/core/PyBooleanDerived.java 2008-10-12 22:18:06 UTC (rev 5381) +++ trunk/jython/src/org/python/core/PyBooleanDerived.java 2008-10-12 22:37:53 UTC (rev 5382) @@ -744,7 +744,7 @@ throw Py.TypeError("__hash__ should return a int"); } if (self_type.lookup("__eq__")!=null||self_type.lookup("__cmp__")!=null) { - throw Py.TypeError("unhashable type"); + throw Py.TypeError(String.format("unhashable type: '%.200s'",getType().fastGetName())); } return super.hashCode(); } Modified: trunk/jython/src/org/python/core/PyClassMethodDerived.java =================================================================== --- trunk/jython/src/org/python/core/PyClassMethodDerived.java 2008-10-12 22:18:06 UTC (rev 5381) +++ trunk/jython/src/org/python/core/PyClassMethodDerived.java 2008-10-12 22:37:53 UTC (rev 5382) @@ -744,7 +744,7 @@ throw Py.TypeError("__hash__ should return a int"); } if (self_type.lookup("__eq__")!=null||self_type.lookup("__cmp__")!=null) { - throw Py.TypeError("unhashable type"); + throw Py.TypeError(String.format("unhashable type: '%.200s'",getType().fastGetName())); } return super.hashCode(); } Modified: trunk/jython/src/org/python/core/PyComplexDerived.java =================================================================== --- trunk/jython/src/org/python/core/PyComplexDerived.java 2008-10-12 22:18:06 UTC (rev 5381) +++ trunk/jython/src/org/python/core/PyComplexDerived.java 2008-10-12 22:37:53 UTC (rev 5382) @@ -744,7 +744,7 @@ throw Py.TypeError("__hash__ should return a int"); } if (self_type.lookup("__eq__")!=null||self_type.lookup("__cmp__")!=null) { - throw Py.TypeError("unhashable type"); + throw Py.TypeError(String.format("unhashable type: '%.200s'",getType().fastGetName())); } return super.hashCode(); } Modified: trunk/jython/src/org/python/core/PyDictionaryDerived.java =================================================================== --- trunk/jython/src/org/python/core/PyDictionaryDerived.java 2008-10-12 22:18:06 UTC (rev 5381) +++ trunk/jython/src/org/python/core/PyDictionaryDerived.java 2008-10-12 22:37:53 UTC (rev 5382) @@ -744,7 +744,7 @@ throw Py.TypeError("__hash__ should return a int"); } if (self_type.lookup("__eq__")!=null||self_type.lookup("__cmp__")!=null) { - throw Py.TypeError("unhashable type"); + throw Py.TypeError(String.format("unhashable type: '%.200s'",getType().fastGetName())); } return super.hashCode(); } Modified: trunk/jython/src/org/python/core/PyEnumerateDerived.java =================================================================== --- trunk/jython/src/org/python/core/PyEnumerateDerived.java 2008-10-12 22:18:06 UTC (rev 5381) +++ trunk/jython/src/org/python/core/PyEnumerateDerived.java 2008-10-12 22:37:53 UTC (rev 5382) @@ -744,7 +744,7 @@ throw Py.TypeError("__hash__ should return a int"); } if (self_type.lookup("__eq__")!=null||self_type.lookup("__cmp__")!=null) { - throw Py.TypeError("unhashable type"); + throw Py.TypeError(String.format("unhashable type: '%.200s'",getType().fastGetName())); } return super.hashCode(); } Modified: trunk/jython/src/org/python/core/PyFileDerived.java =================================================================== --- trunk/jython/src/org/python/core/PyFileDerived.java 2008-10-12 22:18:06 UTC (rev 5381) +++ trunk/jython/src/org/python/core/PyFileDerived.java 2008-10-12 22:37:53 UTC (rev 5382) @@ -744,7 +744,7 @@ throw Py.TypeError("__hash__ should return a int"); } if (self_type.lookup("__eq__")!=null||self_type.lookup("__cmp__")!=null) { - throw Py.TypeError("unhashable type"); + throw Py.TypeError(String.format("unhashable type: '%.200s'",getType().fastGetName())); } return super.hashCode(); } Modified: trunk/jython/src/org/python/core/PyFloatDerived.java =================================================================== --- trunk/jython/src/org/python/core/PyFloatDerived.java 2008-10-12 22:18:06 UTC (rev 5381) +++ trunk/jython/src/org/python/core/PyFloatDerived.java 2008-10-12 22:37:53 UTC (rev 5382) @@ -744,7 +744,7 @@ throw Py.TypeError("__hash__ should return a int"); } if (self_type.lookup("__eq__")!=null||self_type.lookup("__cmp__")!=null) { - throw Py.TypeError("unhashable type"); + throw Py.TypeError(String.format("unhashable type: '%.200s'",getType().fastGetName())); } return super.hashCode(); } Modified: trunk/jython/src/org/python/core/PyFrozenSetDerived.java =================================================================== --- trunk/jython/src/org/python/core/PyFrozenSetDerived.java 2008-10-12 22:18:06 UTC (rev 5381) +++ trunk/jython/src/org/python/core/PyFrozenSetDerived.java 2008-10-12 22:37:53 UTC (rev 5382) @@ -744,7 +744,7 @@ throw Py.TypeError("__hash__ should return a int"); } if (self_type.lookup("__eq__")!=null||self_type.lookup("__cmp__")!=null) { - throw Py.TypeError("unhashable type"); + throw Py.TypeError(String.format("unhashable type: '%.200s'",getType().fastGetName())); } return super.hashCode(); } Modified: trunk/jython/src/org/python/core/PyIntegerDerived.java =================================================================== --- trunk/jython/src/org/python/core/PyIntegerDerived.java 2008-10-12 22:18:06 UTC (rev 5381) +++ trunk/jython/src/org/python/core/PyIntegerDerived.java 2008-10-12 22:37:53 UTC (rev 5382) @@ -744,7 +744,7 @@ throw Py.TypeError("__hash__ should return a int"); } if (self_type.lookup("__eq__")!=null||self_type.lookup("__cmp__")!=null) { - throw Py.TypeError("unhashable type"); + throw Py.TypeError(String.format("unhashable type: '%.200s'",getType().fastGetName())); } return super.hashCode(); } Modified: trunk/jython/src/org/python/core/PyListDerived.java =================================================================== --- trunk/jython/src/org/python/core/PyListDerived.java 2008-10-12 22:18:06 UTC (rev 5381) +++ trunk/jython/src/org/python/core/PyListDerived.java 2008-10-12 22:37:53 UTC (rev 5382) @@ -744,7 +744,7 @@ throw Py.TypeError("__hash__ should return a int"); } if (self_type.lookup("__eq__")!=null||self_type.lookup("__cmp__")!=null) { - throw Py.TypeError("unhashable type"); + throw Py.TypeError(String.format("unhashable type: '%.200s'",getType().fastGetName())); } return super.hashCode(); } Modified: trunk/jython/src/org/python/core/PyLongDerived.java =================================================================== --- trunk/jython/src/org/python/core/PyLongDerived.java 2008-10-12 22:18:06 UTC (rev 5381) +++ trunk/jython/src/org/python/core/PyLongDerived.java 2008-10-12 22:37:53 UTC (rev 5382) @@ -744,7 +744,7 @@ throw Py.TypeError("__hash__ should return a int"); } if (self_type.lookup("__eq__")!=null||self_type.lookup("__cmp__")!=null) { - throw Py.TypeError("unhashable type"); + throw Py.TypeError(String.format("unhashable type: '%.200s'",getType().fastGetName())); } return super.hashCode(); } Modified: trunk/jython/src/org/python/core/PyModuleDerived.java =================================================================== --- trunk/jython/src/org/python/core/PyModuleDerived.java 2008-10-12 22:18:06 UTC (rev 5381) +++ trunk/jython/src/org/python/core/PyModuleDerived.java 2008-10-12 22:37:53 UTC (rev 5382) @@ -720,7 +720,7 @@ throw Py.TypeError("__hash__ should return a int"); } if (self_type.lookup("__eq__")!=null||self_type.lookup("__cmp__")!=null) { - throw Py.TypeError("unhashable type"); + throw Py.TypeError(String.format("unhashable type: '%.200s'",getType().fastGetName())); } return super.hashCode(); } Modified: trunk/jython/src/org/python/core/PyObjectDerived.java =================================================================== --- trunk/jython/src/org/python/core/PyObjectDerived.java 2008-10-12 22:18:06 UTC (rev 5381) +++ trunk/jython/src/org/python/core/PyObjectDerived.java 2008-10-12 22:37:53 UTC (rev 5382) @@ -744,7 +744,7 @@ throw Py.TypeError("__hash__ should return a int"); } if (self_type.lookup("__eq__")!=null||self_type.lookup("__cmp__")!=null) { - throw Py.TypeError("unhashable type"); + throw Py.TypeError(String.format("unhashable type: '%.200s'",getType().fastGetName())); } return super.hashCode(); } Modified: trunk/jython/src/org/python/core/PyPropertyDerived.java =================================================================== --- trunk/jython/src/org/python/core/PyPropertyDerived.java 2008-10-12 22:18:06 UTC (rev 5381) +++ trunk/jython/src/org/python/core/PyPropertyDerived.java 2008-10-12 22:37:53 UTC (rev 5382) @@ -744,7 +744,7 @@ throw Py.TypeError("__hash__ should return a int"); } if (self_type.lookup("__eq__")!=null||self_type.lookup("__cmp__")!=null) { - throw Py.TypeError("unhashable type"); + throw Py.TypeError(String.format("unhashable type: '%.200s'",getType().fastGetName())); } return super.hashCode(); } Modified: trunk/jython/src/org/python/core/PySetDerived.java =================================================================== --- trunk/jython/src/org/python/core/PySetDerived.java 2008-10-12 22:18:06 UTC (rev 5381) +++ trunk/jython/src/org/python/core/PySetDerived.java 2008-10-12 22:37:53 UTC (rev 5382) @@ -744,7 +744,7 @@ throw Py.TypeError("__hash__ should return a int"); } if (self_type.lookup("__eq__")!=null||self_type.lookup("__cmp__")!=null) { - throw Py.TypeError("unhashable type"); + throw Py.TypeError(String.format("unhashable type: '%.200s'",getType().fastGetName())); } return super.hashCode(); } Modified: trunk/jython/src/org/python/core/PySliceDerived.java =================================================================== --- trunk/jython/src/org/python/core/PySliceDerived.java 2008-10-12 22:18:06 UTC (rev 5381) +++ trunk/jython/src/org/python/core/PySliceDerived.java 2008-10-12 22:37:53 UTC (rev 5382) @@ -744,7 +744,7 @@ throw Py.TypeError("__hash__ should return a int"); } if (self_type.lookup("__eq__")!=null||self_type.lookup("__cmp__")!=null) { - throw Py.TypeError("unhashable type"); + throw Py.TypeError(String.format("unhashable type: '%.200s'",getType().fastGetName())); } return super.hashCode(); } Modified: trunk/jython/src/org/python/core/PyStringDerived.java =================================================================== --- trunk/jython/src/org/python/core/PyStringDerived.java 2008-10-12 22:18:06 UTC (rev 5381) +++ trunk/jython/src/org/python/core/PyStringDerived.java 2008-10-12 22:37:53 UTC (rev 5382) @@ -744,7 +744,7 @@ throw Py.TypeError("__hash__ should return a int"); } if (self_type.lookup("__eq__")!=null||self_type.lookup("__cmp__")!=null) { - throw Py.TypeError("unhashable type"); + throw Py.TypeError(String.format("unhashable type: '%.200s'",getType().fastGetName())); } return super.hashCode(); } Modified: trunk/jython/src/org/python/core/PySuperDerived.java =================================================================== --- trunk/jython/src/org/python/core/PySuperDerived.java 2008-10-12 22:18:06 UTC (rev 5381) +++ trunk/jython/src/org/python/core/PySuperDerived.java 2008-10-12 22:37:53 UTC (rev 5382) @@ -744,7 +744,7 @@ throw Py.TypeError("__hash__ should return a int"); } if (self_type.lookup("__eq__")!=null||self_type.lookup("__cmp__")!=null) { - throw Py.TypeError("unhashable type"); + throw Py.TypeError(String.format("unhashable type: '%.200s'",getType().fastGetName())); } return super.hashCode(); } Modified: trunk/jython/src/org/python/core/PyTupleDerived.java =================================================================== --- trunk/jython/src/org/python/core/PyTupleDerived.java 2008-10-12 22:18:06 UTC (rev 5381) +++ trunk/jython/src/org/python/core/PyTupleDerived.java 2008-10-12 22:37:53 UTC (rev 5382) @@ -744,7 +744,7 @@ throw Py.TypeError("__hash__ should return a int"); } if (self_type.lookup("__eq__")!=null||self_type.lookup("__cmp__")!=null) { - throw Py.TypeError("unhashable type"); + throw Py.TypeError(String.format("unhashable type: '%.200s'",getType().fastGetName())); } return super.hashCode(); } Modified: trunk/jython/src/org/python/core/PyTypeDerived.java =================================================================== --- trunk/jython/src/org/python/core/PyTypeDerived.java 2008-10-12 22:18:06 UTC (rev 5381) +++ trunk/jython/src/org/python/core/PyTypeDerived.java 2008-10-12 22:37:53 UTC (rev 5382) @@ -720,7 +720,7 @@ throw Py.TypeError("__hash__ should return a int"); } if (self_type.lookup("__eq__")!=null||self_type.lookup("__cmp__")!=null) { - throw Py.TypeError("unhashable type"); + throw Py.TypeError(String.format("unhashable type: '%.200s'",getType().fastGetName())); } return super.hashCode(); } Modified: trunk/jython/src/org/python/core/PyUnicodeDerived.java =================================================================== --- trunk/jython/src/org/python/core/PyUnicodeDerived.java 2008-10-12 22:18:06 UTC (rev 5381) +++ trunk/jython/src/org/python/core/PyUnicodeDerived.java 2008-10-12 22:37:53 UTC (rev 5382) @@ -744,7 +744,7 @@ throw Py.TypeError("__hash__ should return a int"); } if (self_type.lookup("__eq__")!=null||self_type.lookup("__cmp__")!=null) { - throw Py.TypeError("unhashable type"); + throw Py.TypeError(String.format("unhashable type: '%.200s'",getType().fastGetName())); } return super.hashCode(); } Modified: trunk/jython/src/org/python/modules/_collections/PyDefaultDictDerived.java =================================================================== --- trunk/jython/src/org/python/modules/_collections/PyDefaultDictDerived.java 2008-10-12 22:18:06 UTC (rev 5381) +++ trunk/jython/src/org/python/modules/_collections/PyDefaultDictDerived.java 2008-10-12 22:37:53 UTC (rev 5382) @@ -746,7 +746,7 @@ throw Py.TypeError("__hash__ should return a int"); } if (self_type.lookup("__eq__")!=null||self_type.lookup("__cmp__")!=null) { - throw Py.TypeError("unhashable type"); + throw Py.TypeError(String.format("unhashable type: '%.200s'",getType().fastGetName())); } return super.hashCode(); } Modified: trunk/jython/src/org/python/modules/_collections/PyDequeDerived.java =================================================================== --- trunk/jython/src/org/python/modules/_collections/PyDequeDerived.java 2008-10-12 22:18:06 UTC (rev 5381) +++ trunk/jython/src/org/python/modules/_collections/PyDequeDerived.java 2008-10-12 22:37:53 UTC (rev 5382) @@ -746,7 +746,7 @@ throw Py.TypeError("__hash__ should return a int"); } if (self_type.lookup("__eq__")!=null||self_type.lookup("__cmp__")!=null) { - throw Py.TypeError("unhashable type"); + throw Py.TypeError(String.format("unhashable type: '%.200s'",getType().fastGetName())); } return super.hashCode(); } Modified: trunk/jython/src/org/python/modules/_csv/PyDialectDerived.java =================================================================== --- trunk/jython/src/org/python/modules/_csv/PyDialectDerived.java 2008-10-12 22:18:06 UTC (rev 5381) +++ trunk/jython/src/org/python/modules/_csv/PyDialectDerived.java 2008-10-12 22:37:53 UTC (rev 5382) @@ -722,7 +722,7 @@ throw Py.TypeError("__hash__ should return a int"); } if (self_type.lookup("__eq__")!=null||self_type.lookup("__cmp__")!=null) { - throw Py.TypeError("unhashable type"); + throw Py.TypeError(String.format("unhashable type: '%.200s'",getType().fastGetName())); } return super.hashCode(); } Modified: trunk/jython/src/org/python/modules/_functools/PyPartialDerived.java =================================================================== --- trunk/jython/src/org/python/modules/_functools/PyPartialDerived.java 2008-10-12 22:18:06 UTC (rev 5381) +++ trunk/jython/src/org/python/modules/_functools/PyPartialDerived.java 2008-10-12 22:37:53 UTC (rev 5382) @@ -722,7 +722,7 @@ throw Py.TypeError("__hash__ should return a int"); } if (self_type.lookup("__eq__")!=null||self_type.lookup("__cmp__")!=null) { - throw Py.TypeError("unhashable type"); + throw Py.TypeError(String.format("unhashable type: '%.200s'",getType().fastGetName())); } return super.hashCode(); } Modified: trunk/jython/src/org/python/modules/_weakref/ReferenceTypeDerived.java =================================================================== --- trunk/jython/src/org/python/modules/_weakref/ReferenceTypeDerived.java 2008-10-12 22:18:06 UTC (rev 5381) +++ trunk/jython/src/org/python/modules/_weakref/ReferenceTypeDerived.java 2008-10-12 22:37:53 UTC (rev 5382) @@ -746,7 +746,7 @@ throw Py.TypeError("__hash__ should return a int"); } if (self_type.lookup("__eq__")!=null||self_type.lookup("__cmp__")!=null) { - throw Py.TypeError("unhashable type"); + throw Py.TypeError(String.format("unhashable type: '%.200s'",getType().fastGetName())); } return super.hashCode(); } Modified: trunk/jython/src/org/python/modules/random/PyRandomDerived.java =================================================================== --- trunk/jython/src/org/python/modules/random/PyRandomDerived.java 2008-10-12 22:18:06 UTC (rev 5381) +++ trunk/jython/src/org/python/modules/random/PyRandomDerived.java 2008-10-12 22:37:53 UTC (rev 5382) @@ -746,7 +746,7 @@ throw Py.TypeError("__hash__ should return a int"); } if (self_type.lookup("__eq__")!=null||self_type.lookup("__cmp__")!=null) { - throw Py.TypeError("unhashable type"); + throw Py.TypeError(String.format("unhashable type: '%.200s'",getType().fastGetName())); } return super.hashCode(); } Modified: trunk/jython/src/org/python/modules/thread/PyLocalDerived.java =================================================================== --- trunk/jython/src/org/python/modules/thread/PyLocalDerived.java 2008-10-12 22:18:06 UTC (rev 5381) +++ trunk/jython/src/org/python/modules/thread/PyLocalDerived.java 2008-10-12 22:37:53 UTC (rev 5382) @@ -722,7 +722,7 @@ throw Py.TypeError("__hash__ should return a int"); } if (self_type.lookup("__eq__")!=null||self_type.lookup("__cmp__")!=null) { - throw Py.TypeError("unhashable type"); + throw Py.TypeError(String.format("unhashable type: '%.200s'",getType().fastGetName())); } return super.hashCode(); } Modified: trunk/jython/src/org/python/modules/zipimport/zipimporterDerived.java =================================================================== --- trunk/jython/src/org/python/modules/zipimport/zipimporterDerived.java 2008-10-12 22:18:06 UTC (rev 5381) +++ trunk/jython/src/org/python/modules/zipimport/zipimporterDerived.java 2008-10-12 22:37:53 UTC (rev 5382) @@ -722,7 +722,7 @@ throw Py.TypeError("__hash__ should return a int"); } if (self_type.lookup("__eq__")!=null||self_type.lookup("__cmp__")!=null) { - throw Py.TypeError("unhashable type"); + throw Py.TypeError(String.format("unhashable type: '%.200s'",getType().fastGetName())); } return super.hashCode(); } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <cg...@us...> - 2008-10-20 06:29:58
|
Revision: 5479 http://jython.svn.sourceforge.net/jython/?rev=5479&view=rev Author: cgroves Date: 2008-10-20 06:29:50 +0000 (Mon, 20 Oct 2008) Log Message: ----------- The pain of not having the generic inferring statics from Google collections finally got to the point where I felt the need to whip up version for Jython. Add Generic with static methods to make Lists, Maps and Sets that infer their generic types from the generics of whatever they're being assigned to. I went for brevity in naming the methods as I felt they'd be idiomatic enough in Jython to read well, but could be convinced that more descriptive names - newArrayList() instead of list() for example - would be better. Modified Paths: -------------- trunk/jython/src/org/python/compiler/AdapterMaker.java trunk/jython/src/org/python/compiler/ProxyMaker.java trunk/jython/src/org/python/core/BytecodeLoader.java trunk/jython/src/org/python/core/PyType.java trunk/jython/src/org/python/core/PyUnicode.java trunk/jython/src/org/python/expose/generate/ExposeTask.java trunk/jython/src/org/python/expose/generate/ExposedMethodFinder.java trunk/jython/src/org/python/expose/generate/ExposedTypeProcessor.java trunk/jython/src/org/python/expose/generate/TypeExposer.java trunk/jython/src/org/python/modules/_functools/PyPartial.java trunk/jython/src/org/python/util/NameUnionAntType.java trunk/jython/src/org/python/util/jython.java Added Paths: ----------- trunk/jython/src/org/python/util/Generic.java Modified: trunk/jython/src/org/python/compiler/AdapterMaker.java =================================================================== --- trunk/jython/src/org/python/compiler/AdapterMaker.java 2008-10-20 02:03:44 UTC (rev 5478) +++ trunk/jython/src/org/python/compiler/AdapterMaker.java 2008-10-20 06:29:50 UTC (rev 5479) @@ -8,6 +8,7 @@ import org.python.objectweb.asm.Label; import org.python.objectweb.asm.Opcodes; +import org.python.util.Generic; public class AdapterMaker extends ProxyMaker @@ -17,7 +18,7 @@ } public void build() throws Exception { - names = new HashSet<String>(); + names = Generic.set(); int access = Opcodes.ACC_PUBLIC | Opcodes.ACC_SYNCHRONIZED; classfile = new ClassFile(myClass, "java/lang/Object", access); Modified: trunk/jython/src/org/python/compiler/ProxyMaker.java =================================================================== --- trunk/jython/src/org/python/compiler/ProxyMaker.java 2008-10-20 02:03:44 UTC (rev 5478) +++ trunk/jython/src/org/python/compiler/ProxyMaker.java 2008-10-20 06:29:50 UTC (rev 5479) @@ -8,14 +8,13 @@ import java.lang.reflect.Constructor; import java.lang.reflect.Method; import java.lang.reflect.Modifier; -import java.util.HashMap; -import java.util.HashSet; import java.util.Map; import java.util.Set; import org.python.core.Py; import org.python.objectweb.asm.Label; import org.python.objectweb.asm.Opcodes; +import org.python.util.Generic; public class ProxyMaker implements ClassConstants, Opcodes { @@ -34,7 +33,7 @@ public static Map<Class<?>, Integer> types=fillTypes(); public static Map<Class<?>, Integer> fillTypes() { - Map<Class<?>, Integer> typeMap = new HashMap<Class<?>, Integer>(); + Map<Class<?>, Integer> typeMap = Generic.map(); typeMap.put(Boolean.TYPE, tBoolean); typeMap.put(Byte.TYPE, tByte); typeMap.put(Short.TYPE, tShort); @@ -57,7 +56,7 @@ Class<?> superclass; Class<?>[] interfaces; Set<String> names; - Set<String> supernames = new HashSet<String>(); + Set<String> supernames = Generic.set(); public ClassFile classfile; public String myClass; public boolean isAdapter=false; @@ -123,8 +122,8 @@ public static String makeSignature(Class<?>[] sig, Class<?> ret) { StringBuffer buf=new StringBuffer(); buf.append("("); - for (int i=0; i<sig.length; i++) { - buf.append(mapType(sig[i])); + for (Class<?> element : sig) { + buf.append(mapType(element)); } buf.append(")"); buf.append(mapType(ret)); @@ -315,7 +314,7 @@ Class<?>[] exceptions) throws Exception { Label start = null; Label end = null; - + String jcallName = "_jcall"; int instLocal = 0; @@ -374,7 +373,7 @@ boolean throwableFound = false; Label handlerStart = null; - for (int i = 0; i < exceptions.length; i++) { + for (Class<?> exception : exceptions) { handlerStart = new Label(); code.label(handlerStart); int excLocal = code.getLocal("java/lang/Throwable"); @@ -383,11 +382,11 @@ code.aload(excLocal); code.athrow(); - code.visitTryCatchBlock(start, end, handlerStart, mapClass(exceptions[i])); + code.visitTryCatchBlock(start, end, handlerStart, mapClass(exception)); doNullReturn(code, ret); code.freeLocal(excLocal); - if (exceptions[i] == Throwable.class) + if (exception == Throwable.class) throwableFound = true; } @@ -471,8 +470,8 @@ StringBuffer buf = new StringBuffer(m.getName()); buf.append(":"); Class<?>[] params = m.getParameterTypes(); - for (int i = 0; i < params.length; i++) { - buf.append(params[i].getName()); + for (Class<?> param : params) { + buf.append(param.getName()); buf.append(","); } return buf.toString(); @@ -480,8 +479,7 @@ protected void addMethods(Class<?> c, Set<String> t) throws Exception { Method[] methods = c.getDeclaredMethods(); - for (int i=0; i<methods.length; i++) { - Method method = methods[i]; + for (Method method : methods) { String s = methodString(method); if (t.contains(s)) continue; @@ -499,13 +497,13 @@ if (Modifier.isProtected(access)) { access = (access & ~Modifier.PROTECTED) | Modifier.PUBLIC; if (Modifier.isFinal(access)) { - addSuperMethod(methods[i], access); + addSuperMethod(method, access); continue; } } else if (Modifier.isFinal(access)) { continue; } - addMethod(methods[i], access); + addMethod(method, access); } Class<?> sc = c.getSuperclass(); @@ -513,8 +511,8 @@ addMethods(sc, t); Class<?>[] ifaces = c.getInterfaces(); - for (int j=0; j<ifaces.length; j++) { - addMethods(ifaces[j], t); + for (Class<?> iface : ifaces) { + addMethods(iface, t); } } @@ -530,15 +528,15 @@ public void addConstructors(Class<?> c) throws Exception { Constructor<?>[] constructors = c.getDeclaredConstructors(); String name = mapClass(c); - for (int i = 0; i < constructors.length; i++) { - int access = constructors[i].getModifiers(); + for (Constructor<?> constructor : constructors) { + int access = constructor.getModifiers(); if (Modifier.isPrivate(access)) continue; if (Modifier.isNative(access)) access = access & ~Modifier.NATIVE; if (Modifier.isProtected(access)) access = access & ~Modifier.PROTECTED | Modifier.PUBLIC; - Class<?>[] parameters = constructors[i].getParameterTypes(); + Class<?>[] parameters = constructor.getParameterTypes(); String sig = makeSignature(parameters, Void.TYPE); addConstructor(name, parameters, Void.TYPE, sig, access); } @@ -666,7 +664,7 @@ } public void build() throws Exception { - names = new HashSet<String>(); + names = Generic.set(); int access = superclass.getModifiers(); if ((access & Modifier.FINAL) != 0) { throw new InstantiationException("can't subclass final class"); @@ -678,17 +676,17 @@ addConstructors(superclass); classfile.addInterface("org/python/core/PyProxy"); - Set<String> seenmethods = new HashSet<String>(); + Set<String> seenmethods = Generic.set(); addMethods(superclass, seenmethods); - for (int i=0; i<interfaces.length; i++) { - if (interfaces[i].isAssignableFrom(superclass)) { + for (Class<?> iface : interfaces) { + if (iface.isAssignableFrom(superclass)) { Py.writeWarning("compiler", "discarding redundant interface: "+ - interfaces[i].getName()); + iface.getName()); continue; } - classfile.addInterface(mapClass(interfaces[i])); - addMethods(interfaces[i], seenmethods); + classfile.addInterface(mapClass(iface)); + addMethods(iface, seenmethods); } doConstants(); addClassDictInit(); Modified: trunk/jython/src/org/python/core/BytecodeLoader.java =================================================================== --- trunk/jython/src/org/python/core/BytecodeLoader.java 2008-10-20 02:03:44 UTC (rev 5478) +++ trunk/jython/src/org/python/core/BytecodeLoader.java 2008-10-20 06:29:50 UTC (rev 5479) @@ -2,10 +2,10 @@ package org.python.core; import java.security.SecureClassLoader; -import java.util.ArrayList; import java.util.List; import org.python.objectweb.asm.ClassReader; +import org.python.util.Generic; /** * Utility class for loading of compiled python modules and java classes defined in python modules. @@ -14,7 +14,7 @@ /** * Turn the java byte code in data into a java class. - * + * * @param name * the name of the class * @param data @@ -24,9 +24,9 @@ */ public static Class<?> makeClass(String name, byte[] data, Class<?>... referents) { Loader loader = new Loader(); - for (int i = 0; i < referents.length; i++) { + for (Class<?> referent : referents) { try { - ClassLoader cur = referents[i].getClassLoader(); + ClassLoader cur = referent.getClassLoader(); if (cur != null) { loader.addParent(cur); } @@ -37,7 +37,7 @@ /** * Turn the java byte code in data into a java class. - * + * * @param name * the name of the class * @param referents @@ -54,7 +54,7 @@ /** * Turn the java byte code for a compiled python module into a java class. - * + * * @param name * the name of the class * @param data @@ -73,7 +73,7 @@ public static class Loader extends SecureClassLoader { - private List<ClassLoader> parents = new ArrayList<ClassLoader>(); + private List<ClassLoader> parents = Generic.list(); public Loader() { parents.add(imp.getSyspathJavaLoader()); @@ -85,6 +85,7 @@ } } + @Override protected Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException { Class<?> c = findLoadedClass(name); if (c != null) { Modified: trunk/jython/src/org/python/core/PyType.java =================================================================== --- trunk/jython/src/org/python/core/PyType.java 2008-10-20 02:03:44 UTC (rev 5478) +++ trunk/jython/src/org/python/core/PyType.java 2008-10-20 06:29:50 UTC (rev 5479) @@ -8,12 +8,12 @@ import java.lang.reflect.Field; import java.lang.reflect.Method; import java.lang.reflect.Modifier; -import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; +import java.util.Set; import org.python.core.util.StringUtil; import org.python.expose.ExposeAsSuperclass; @@ -24,6 +24,7 @@ import org.python.expose.ExposedSet; import org.python.expose.ExposedType; import org.python.expose.TypeBuilder; +import org.python.util.Generic; /** * The Python Type object implementation. @@ -76,7 +77,7 @@ private int numSlots; private ReferenceQueue<PyType> subclasses_refq = new ReferenceQueue<PyType>(); - private HashSet<WeakReference<PyType>> subclasses = new HashSet<WeakReference<PyType>>(); + private Set<WeakReference<PyType>> subclasses = Generic.set(); private final static Class<?>[] O = {PyObject.class}; private final static Class<?>[] OO = {PyObject.class, PyObject.class}; @@ -548,7 +549,7 @@ PyObject[] savedBases = bases; PyType savedBase = base; PyObject[] savedMro = mro; - List<Object> savedSubMros = new ArrayList<Object>(); + List<Object> savedSubMros = Generic.list(); try { bases = newBases; base = newBase; @@ -695,7 +696,7 @@ } } - private static void fill_classic_mro(ArrayList<PyObject> acc, PyClass classic_cl) { + private static void fill_classic_mro(List<PyObject> acc, PyClass classic_cl) { if (!acc.contains(classic_cl)) { acc.add(classic_cl); } @@ -706,7 +707,7 @@ } private static PyObject[] classic_mro(PyClass classic_cl) { - ArrayList<PyObject> acc = new ArrayList<PyObject>(); + List<PyObject> acc = Generic.list(); fill_classic_mro(acc, classic_cl); return acc.toArray(new PyObject[acc.size()]); } @@ -785,7 +786,7 @@ to_merge[n] = bases; remain[n] = 0; - ArrayList<PyObject> acc = new ArrayList<PyObject>(); + List<PyObject> acc = Generic.list(); acc.add(this); int empty_cnt = 0; @@ -1050,7 +1051,7 @@ public static void addBuilder(Class<?> forClass, TypeBuilder builder) { if (classToBuilder == null) { - classToBuilder = new HashMap<Class<?>, TypeBuilder>(); + classToBuilder = Generic.map(); } classToBuilder.put(forClass, builder); @@ -1099,7 +1100,7 @@ public static synchronized PyType fromClass(Class<?> c) { if (class_to_type == null) { - class_to_type = new HashMap<Class<?>, PyType>(); + class_to_type = Generic.map(); addFromClass(PyType.class); } PyType type = class_to_type.get(c); Modified: trunk/jython/src/org/python/core/PyUnicode.java =================================================================== --- trunk/jython/src/org/python/core/PyUnicode.java 2008-10-20 02:03:44 UTC (rev 5478) +++ trunk/jython/src/org/python/core/PyUnicode.java 2008-10-20 06:29:50 UTC (rev 5479) @@ -1,18 +1,18 @@ package org.python.core; -import java.util.ArrayList; import java.util.Collection; import java.util.Collections; -import java.util.HashSet; +import java.util.Iterator; +import java.util.LinkedList; +import java.util.List; +import java.util.Set; + import org.python.expose.ExposedMethod; import org.python.expose.ExposedNew; import org.python.expose.ExposedType; import org.python.expose.MethodType; import org.python.modules._codecs; -import java.util.Iterator; -import java.util.LinkedList; -import java.util.List; -import java.util.Set; +import org.python.util.Generic; /** * a builtin python unicode string. @@ -39,9 +39,9 @@ public PyUnicode(String string, boolean isBasic) { this(TYPE, string); - plane = isBasic ? Plane.BASIC : Plane.UNKNOWN; + plane = isBasic ? Plane.BASIC : Plane.UNKNOWN; } - + public PyUnicode(PyType subtype, String string) { super(subtype, string); } @@ -77,7 +77,7 @@ } return buffer; } - + PyUnicode(Iterator<Integer> iter) { this(fromCodePoints(iter)); } @@ -96,18 +96,18 @@ } return codePoints; } - + // modified to know something about codepoints; we just need to return the // corresponding substring; darn UTF16! // TODO: we could avoid doing this unnecessary copy @Override public String substring(int start, int end) { if (isBasicPlane()) { - return super.substring(start, end); + return super.substring(start, end); } return new PyUnicode(newSubsequenceIterator(start, end, 1)).string; } - + /** * Creates a PyUnicode from an already interned String. Just means it won't * be reinterned if used in a place that requires interned Strings. @@ -132,9 +132,9 @@ // public boolean isBasicPlane() { // return false; // } - + // END RETAIN - + public int getCodePointCount() { if (codePointCount >= 0) { return codePointCount; @@ -201,7 +201,7 @@ protected PyString createInstance(String str, boolean isBasic) { return new PyUnicode(str, isBasic); } - + @Override public PyObject __mod__(PyObject other) { return unicode___mod__(other); @@ -304,7 +304,6 @@ while (i > 0) { int W1 = string.charAt(k); if (W1 >= 0xD800 && W1 < 0xDC00) { - int W2 = string.charAt(k + 1); k += 2; } else { k += 1; @@ -524,7 +523,7 @@ public StripIterator(PyUnicode sep, Iterator<Integer> iter) { this.iter = iter; if (sep != null) { - Set<Integer> sepSet = new HashSet<Integer>(); + Set<Integer> sepSet = Generic.set(); for (Iterator<Integer> sepIter = sep.newSubsequenceIterator(); sepIter.hasNext();) { sepSet.add(sepIter.next()); } @@ -732,7 +731,7 @@ private class ReversedIterator<T> implements Iterator { - private final List<T> reversed = new ArrayList<T>(); + private final List<T> reversed = Generic.list(); private final Iterator<T> iter; ReversedIterator(Iterator<T> iter) { @@ -807,7 +806,7 @@ super(maxsplit); this.sep = sep; } - + public PyUnicode next() { StringBuilder buffer = new StringBuilder(); @@ -857,7 +856,7 @@ return new SepSplitIterator(sep, maxsplit); } } - + @ExposedMethod final PyTuple unicode_rpartition(PyObject sep) { return unicodeRpartition(sep); @@ -882,7 +881,7 @@ return str_rsplit(null, maxsplit); } } - + @ExposedMethod(defaults = "false") final PyList unicode_splitlines(boolean keepends) { if (isBasicPlane()) { @@ -957,8 +956,8 @@ throw Py.TypeError(function + "() argument 2 must be char, not str"); } return fillchar.codePointAt(0); - } - + } + @ExposedMethod(defaults="null") final PyObject unicode_ljust(int width, String padding) { int n = width - getCodePointCount(); @@ -1065,20 +1064,20 @@ if (isBasicPlane() && newPiece.isBasicPlane() && oldPiece.isBasicPlane()) { return replace(oldPiece, newPiece, maxsplit); } - + StringBuilder buffer = new StringBuilder(); - + if (oldPiece.getCodePointCount() == 0) { Iterator<Integer> iter = newSubsequenceIterator(); for (int i = 1; (maxsplit == -1 || i < maxsplit) && iter.hasNext(); i++) { if (i == 1) { buffer.append(newPiece.string); } - buffer.appendCodePoint((Integer) iter.next()); + buffer.appendCodePoint(iter.next()); buffer.append(newPiece.string); } while (iter.hasNext()) { - buffer.appendCodePoint((Integer) iter.next()); + buffer.appendCodePoint(iter.next()); } return new PyUnicode(buffer); } else { @@ -1311,7 +1310,7 @@ public Iterator<Integer> iterator() { return newSubsequenceIterator(); } - + @ExposedMethod final String unicode_toString() { return toString(); Modified: trunk/jython/src/org/python/expose/generate/ExposeTask.java =================================================================== --- trunk/jython/src/org/python/expose/generate/ExposeTask.java 2008-10-20 02:03:44 UTC (rev 5478) +++ trunk/jython/src/org/python/expose/generate/ExposeTask.java 2008-10-20 06:29:50 UTC (rev 5479) @@ -4,7 +4,6 @@ import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; -import java.util.HashSet; import java.util.Set; import org.apache.tools.ant.BuildException; @@ -13,6 +12,7 @@ import org.apache.tools.ant.util.GlobPatternMapper; import org.apache.tools.ant.util.SourceFileScanner; import org.python.objectweb.asm.ClassWriter; +import org.python.util.Generic; public class ExposeTask extends MatchingTask { @@ -20,7 +20,7 @@ private File destDir; - private Set<File> toExpose = new HashSet<File>(); + private Set<File> toExpose = Generic.set(); /** * Set the source directories to find the class files to be exposed. @@ -42,7 +42,7 @@ /** * Set the destination directory into which the Java source files should be compiled. - * + * * @param destDir * the destination director */ @@ -52,7 +52,7 @@ /** * Gets the destination directory into which the java source files should be compiled. - * + * * @return the destination directory */ public File getDestdir() { Modified: trunk/jython/src/org/python/expose/generate/ExposedMethodFinder.java =================================================================== --- trunk/jython/src/org/python/expose/generate/ExposedMethodFinder.java 2008-10-20 02:03:44 UTC (rev 5478) +++ trunk/jython/src/org/python/expose/generate/ExposedMethodFinder.java 2008-10-20 06:29:50 UTC (rev 5479) @@ -1,14 +1,14 @@ package org.python.expose.generate; -import java.util.ArrayList; import java.util.List; +import org.python.expose.MethodType; import org.python.objectweb.asm.AnnotationVisitor; import org.python.objectweb.asm.MethodAdapter; import org.python.objectweb.asm.MethodVisitor; import org.python.objectweb.asm.Opcodes; import org.python.objectweb.asm.Type; -import org.python.expose.MethodType; +import org.python.util.Generic; /** * Visits a method passing all calls through to its delegate. If an ExposedNew or ExposedMethod @@ -131,7 +131,7 @@ public abstract void handleResult(String[] result); - List<String> vals = new ArrayList<String>(); + List<String> vals = Generic.list(); } class ExposedMethodVisitor extends RestrictiveAnnotationVisitor { Modified: trunk/jython/src/org/python/expose/generate/ExposedTypeProcessor.java =================================================================== --- trunk/jython/src/org/python/expose/generate/ExposedTypeProcessor.java 2008-10-20 02:03:44 UTC (rev 5478) +++ trunk/jython/src/org/python/expose/generate/ExposedTypeProcessor.java 2008-10-20 06:29:50 UTC (rev 5479) @@ -2,9 +2,7 @@ import java.io.IOException; import java.io.InputStream; -import java.util.ArrayList; import java.util.Collection; -import java.util.HashMap; import java.util.List; import java.util.Map; @@ -19,6 +17,7 @@ import org.python.objectweb.asm.MethodVisitor; import org.python.objectweb.asm.Opcodes; import org.python.objectweb.asm.Type; +import org.python.util.Generic; /** * Processes the bytecode of a Java class that has the {@link ExposedType} annotation on it and @@ -26,9 +25,9 @@ */ public class ExposedTypeProcessor implements Opcodes, PyTypes { - private List<MethodExposer> methodExposers = new ArrayList<MethodExposer>(); + private List<MethodExposer> methodExposers = Generic.list(); - private Map<String, DescriptorExposer> descExposers = new HashMap<String, DescriptorExposer>(); + private Map<String, DescriptorExposer> descExposers = Generic.map(); private Exposer newExposer; @@ -276,7 +275,7 @@ @Override public void handleResult(ClassMethodExposer exposer) { methodExposers.add(exposer); - + } }; } Modified: trunk/jython/src/org/python/expose/generate/TypeExposer.java =================================================================== --- trunk/jython/src/org/python/expose/generate/TypeExposer.java 2008-10-20 02:03:44 UTC (rev 5478) +++ trunk/jython/src/org/python/expose/generate/TypeExposer.java 2008-10-20 06:29:50 UTC (rev 5479) @@ -1,14 +1,14 @@ package org.python.expose.generate; import java.util.Collection; -import java.util.HashSet; import java.util.Set; -import org.python.objectweb.asm.Type; import org.python.core.BytecodeLoader; import org.python.expose.BaseTypeBuilder; import org.python.expose.ExposedType; import org.python.expose.TypeBuilder; +import org.python.objectweb.asm.Type; +import org.python.util.Generic; /** * Generates a subclass of TypeBuilder to expose a class with the {@link ExposedType} annotation as @@ -42,7 +42,7 @@ this.name = name; this.methods = methods; this.descriptors = descriptors; - Set<String> names = new HashSet<String>(); + Set<String> names = Generic.set(); for(DescriptorExposer exposer : descriptors) { if(!names.add(exposer.getName())) { throwDupe(exposer.getName()); Modified: trunk/jython/src/org/python/modules/_functools/PyPartial.java =================================================================== --- trunk/jython/src/org/python/modules/_functools/PyPartial.java 2008-10-20 02:03:44 UTC (rev 5478) +++ trunk/jython/src/org/python/modules/_functools/PyPartial.java 2008-10-20 06:29:50 UTC (rev 5479) @@ -1,14 +1,12 @@ /* Copyright (c) Jython Developers */ package org.python.modules._functools; -import java.util.HashMap; import java.util.Map; import org.python.core.Py; import org.python.core.PyDictionary; import org.python.core.PyNewWrapper; import org.python.core.PyObject; -import org.python.core.PyString; import org.python.core.PyStringMap; import org.python.core.PyTuple; import org.python.core.PyType; @@ -17,6 +15,7 @@ import org.python.expose.ExposedNew; import org.python.expose.ExposedSet; import org.python.expose.ExposedType; +import org.python.util.Generic; @ExposedType(name = "_functools.partial") public class PyPartial extends PyObject { @@ -93,7 +92,7 @@ kwAppl = this.keywords; } else { // first merge keywords to determine the keyword count - HashMap<String, PyObject> merged = new HashMap<String, PyObject>(); + Map<String, PyObject> merged = Generic.map(); int i; for (i = 0; i < this.keywords.length; i++) { String keyword = this.keywords[i]; @@ -149,12 +148,14 @@ return kwDict; } + @Override @ExposedGet(name = "__dict__") public PyObject getDict() { ensureDict(); return __dict__; } + @Override @ExposedSet(name = "__dict__") public void setDict(PyObject val) { if (!(val instanceof PyStringMap) && !(val instanceof PyDictionary)) { Added: trunk/jython/src/org/python/util/Generic.java =================================================================== --- trunk/jython/src/org/python/util/Generic.java (rev 0) +++ trunk/jython/src/org/python/util/Generic.java 2008-10-20 06:29:50 UTC (rev 5479) @@ -0,0 +1,37 @@ +package org.python.util; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +/** + * Static methods to make instances of collections with their generic types inferred from what + * they're being assigned to. The idea is stolen from <code>Sets</code>, <code>Lists</code> and + * <code>Maps</code> from <a href="http://code.google.com/p/google-collections/">Google + * Collections</a>. + */ +public class Generic { + /** + * Makes a List with its generic type inferred from whatever its being assigned to. + */ + public static <T> List<T> list() { + return new ArrayList<T>(); + } + + /** + * Makes a Map using generic types inferred from whatever this is being assigned to. + */ + public static <K, V> Map<K, V> map() { + return new HashMap<K, V>(); + } + + /** + * Makes a Set using the generic type inferred from whatever this is being assigned to. + */ + public static <T> Set<T> set() { + return new HashSet<T>(); + } +} Modified: trunk/jython/src/org/python/util/NameUnionAntType.java =================================================================== --- trunk/jython/src/org/python/util/NameUnionAntType.java 2008-10-20 02:03:44 UTC (rev 5478) +++ trunk/jython/src/org/python/util/NameUnionAntType.java 2008-10-20 06:29:50 UTC (rev 5479) @@ -20,7 +20,7 @@ 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>(); + Set<String> seenNames = Generic.set(); List<Resource> union = new ArrayList(); for (ResourceCollection rc : collections) { for (Iterator<Resource> resources = rc.iterator(); resources.hasNext();) { Modified: trunk/jython/src/org/python/util/jython.java =================================================================== --- trunk/jython/src/org/python/util/jython.java 2008-10-20 02:03:44 UTC (rev 5478) +++ trunk/jython/src/org/python/util/jython.java 2008-10-20 06:29:50 UTC (rev 5479) @@ -6,8 +6,6 @@ import java.io.FileInputStream; import java.io.InputStream; import java.nio.charset.Charset; -import java.util.ArrayList; -import java.util.Arrays; import java.util.List; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; @@ -32,10 +30,10 @@ private static final String COPYRIGHT = "Type \"help\", \"copyright\", \"credits\" or \"license\" for more information."; - static final String usageHeader = + static final String usageHeader = "usage: jython [option] ... [-c cmd | -m mod | file | -] [arg] ...\n"; - private static final String usage = usageHeader + + private static final String usage = usageHeader + "Options and arguments:\n" + //(and corresponding environment variables):\n" + "-c cmd : program passed in as string (terminates option list)\n" + //"-d : debug output from parser (also PYTHONDEBUG=x)\n" + @@ -84,15 +82,15 @@ throw Py.ValueError("jar file missing '__run__.py'"); PyStringMap locals = new PyStringMap(); - - // Stripping the stuff before the last File.separator fixes Bug - // #931129 by keeping illegal characters out of the generated - // proxy class name + + // Stripping the stuff before the last File.separator fixes Bug + // #931129 by keeping illegal characters out of the generated + // proxy class name int beginIndex; if ((beginIndex = filename.lastIndexOf(File.separator)) != -1) { filename = filename.substring(beginIndex + 1); } - + locals.__setitem__("__name__", new PyString(filename)); locals.__setitem__("zipfile", Py.java2py(zip)); @@ -153,7 +151,7 @@ systemState.ps1 = systemState.ps2 = new PyString(); } } - + // Print banner and copyright information (or not) if (opts.interactive && opts.notice && !opts.runModule) { System.err.println(InteractiveConsole.getDefaultBanner()); @@ -331,13 +329,13 @@ { public String filename; public boolean jar, interactive, notice; - public boolean runModule; + public boolean runModule; public boolean fixInteractive; public boolean help, version; public String[] argv; public java.util.Properties properties; public String command; - public List<String> warnoptions = new ArrayList<String>(); + public List<String> warnoptions = Generic.list(); public String encoding; public String division; public String moduleName; @@ -455,7 +453,7 @@ interactive = false; } - index++; + index++; int n = args.length-index+1; argv = new String[n]; argv[0] = moduleName; This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <pj...@us...> - 2008-10-30 02:49:50
|
Revision: 5527 http://jython.svn.sourceforge.net/jython/?rev=5527&view=rev Author: pjenvey Date: 2008-10-30 02:49:44 +0000 (Thu, 30 Oct 2008) Log Message: ----------- small cleanup Modified Paths: -------------- trunk/jython/src/org/python/core/PyFile.java trunk/jython/src/org/python/modules/zipimport/zipimporter.java Modified: trunk/jython/src/org/python/core/PyFile.java =================================================================== --- trunk/jython/src/org/python/core/PyFile.java 2008-10-30 02:48:30 UTC (rev 5526) +++ trunk/jython/src/org/python/core/PyFile.java 2008-10-30 02:49:44 UTC (rev 5527) @@ -19,7 +19,6 @@ import org.python.core.io.TextIOBase; import org.python.core.io.TextIOWrapper; import org.python.core.io.UniversalIOWrapper; -import org.python.core.util.FileUtil; import org.python.expose.ExposedDelete; import org.python.expose.ExposedGet; import org.python.expose.ExposedMethod; @@ -529,7 +528,7 @@ throw Py.TypeError("can't delete numeric/char attribute"); } - public Object __tojava__(Class cls) { + public Object __tojava__(Class<?> cls) { Object o = file.__tojava__(cls); if (o == null) { o = super.__tojava__(cls); Modified: trunk/jython/src/org/python/modules/zipimport/zipimporter.java =================================================================== --- trunk/jython/src/org/python/modules/zipimport/zipimporter.java 2008-10-30 02:48:30 UTC (rev 5526) +++ trunk/jython/src/org/python/modules/zipimport/zipimporter.java 2008-10-30 02:49:44 UTC (rev 5527) @@ -498,8 +498,9 @@ } PyObject files = new PyDictionary(); - for (Enumeration zipEntries = zipFile.entries(); zipEntries.hasMoreElements();) { - ZipEntry zipEntry = (ZipEntry)zipEntries.nextElement(); + for (Enumeration<? extends ZipEntry> zipEntries = zipFile.entries(); + zipEntries.hasMoreElements();) { + ZipEntry zipEntry = zipEntries.nextElement(); String name = zipEntry.getName().replace('/', File.separatorChar); PyObject __file__ = new PyString(archive + File.separator + name); @@ -664,9 +665,9 @@ */ protected static class SearchOrderEntry { public String suffix; - public EnumSet type; + public EnumSet<EntryType> type; - public SearchOrderEntry(String suffix, EnumSet type) { + public SearchOrderEntry(String suffix, EnumSet<EntryType> type) { this.suffix = suffix; this.type = type; } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <pj...@us...> - 2008-10-30 06:07:06
|
Revision: 5530 http://jython.svn.sourceforge.net/jython/?rev=5530&view=rev Author: pjenvey Date: 2008-10-30 06:07:01 +0000 (Thu, 30 Oct 2008) Log Message: ----------- Derived changes for r5529 __cmp__ results Modified Paths: -------------- trunk/jython/src/org/python/core/PyArrayDerived.java trunk/jython/src/org/python/core/PyBaseExceptionDerived.java trunk/jython/src/org/python/core/PyBooleanDerived.java trunk/jython/src/org/python/core/PyClassMethodDerived.java trunk/jython/src/org/python/core/PyComplexDerived.java trunk/jython/src/org/python/core/PyDictionaryDerived.java trunk/jython/src/org/python/core/PyEnumerateDerived.java trunk/jython/src/org/python/core/PyFileDerived.java trunk/jython/src/org/python/core/PyFloatDerived.java trunk/jython/src/org/python/core/PyFrozenSetDerived.java trunk/jython/src/org/python/core/PyIntegerDerived.java trunk/jython/src/org/python/core/PyListDerived.java trunk/jython/src/org/python/core/PyLongDerived.java trunk/jython/src/org/python/core/PyModuleDerived.java trunk/jython/src/org/python/core/PyObjectDerived.java trunk/jython/src/org/python/core/PyPropertyDerived.java trunk/jython/src/org/python/core/PySetDerived.java trunk/jython/src/org/python/core/PySliceDerived.java trunk/jython/src/org/python/core/PyStringDerived.java trunk/jython/src/org/python/core/PySuperDerived.java trunk/jython/src/org/python/core/PyTupleDerived.java trunk/jython/src/org/python/core/PyTypeDerived.java trunk/jython/src/org/python/core/PyUnicodeDerived.java trunk/jython/src/org/python/modules/_collections/PyDefaultDictDerived.java trunk/jython/src/org/python/modules/_collections/PyDequeDerived.java trunk/jython/src/org/python/modules/_csv/PyDialectDerived.java trunk/jython/src/org/python/modules/_functools/PyPartialDerived.java trunk/jython/src/org/python/modules/_weakref/ReferenceTypeDerived.java trunk/jython/src/org/python/modules/random/PyRandomDerived.java trunk/jython/src/org/python/modules/thread/PyLocalDerived.java trunk/jython/src/org/python/modules/zipimport/zipimporterDerived.java Modified: trunk/jython/src/org/python/core/PyArrayDerived.java =================================================================== --- trunk/jython/src/org/python/core/PyArrayDerived.java 2008-10-30 06:06:03 UTC (rev 5529) +++ trunk/jython/src/org/python/core/PyArrayDerived.java 2008-10-30 06:07:01 UTC (rev 5530) @@ -776,11 +776,11 @@ return super.__cmp__(other); } PyObject res=impl.__get__(this,self_type).__call__(other); - if (res instanceof PyInteger) { - int v=((PyInteger)res).getValue(); - return v<0?-1:v>0?1:0; + if (res==Py.NotImplemented) { + return-2; } - throw Py.TypeError("__cmp__ should return a int"); + int c=res.asInt(); + return c<0?-1:c>0?1:0; } public boolean __nonzero__() { Modified: trunk/jython/src/org/python/core/PyBaseExceptionDerived.java =================================================================== --- trunk/jython/src/org/python/core/PyBaseExceptionDerived.java 2008-10-30 06:06:03 UTC (rev 5529) +++ trunk/jython/src/org/python/core/PyBaseExceptionDerived.java 2008-10-30 06:07:01 UTC (rev 5530) @@ -752,11 +752,11 @@ return super.__cmp__(other); } PyObject res=impl.__get__(this,self_type).__call__(other); - if (res instanceof PyInteger) { - int v=((PyInteger)res).getValue(); - return v<0?-1:v>0?1:0; + if (res==Py.NotImplemented) { + return-2; } - throw Py.TypeError("__cmp__ should return a int"); + int c=res.asInt(); + return c<0?-1:c>0?1:0; } public boolean __nonzero__() { Modified: trunk/jython/src/org/python/core/PyBooleanDerived.java =================================================================== --- trunk/jython/src/org/python/core/PyBooleanDerived.java 2008-10-30 06:06:03 UTC (rev 5529) +++ trunk/jython/src/org/python/core/PyBooleanDerived.java 2008-10-30 06:07:01 UTC (rev 5530) @@ -776,11 +776,11 @@ return super.__cmp__(other); } PyObject res=impl.__get__(this,self_type).__call__(other); - if (res instanceof PyInteger) { - int v=((PyInteger)res).getValue(); - return v<0?-1:v>0?1:0; + if (res==Py.NotImplemented) { + return-2; } - throw Py.TypeError("__cmp__ should return a int"); + int c=res.asInt(); + return c<0?-1:c>0?1:0; } public boolean __nonzero__() { Modified: trunk/jython/src/org/python/core/PyClassMethodDerived.java =================================================================== --- trunk/jython/src/org/python/core/PyClassMethodDerived.java 2008-10-30 06:06:03 UTC (rev 5529) +++ trunk/jython/src/org/python/core/PyClassMethodDerived.java 2008-10-30 06:07:01 UTC (rev 5530) @@ -776,11 +776,11 @@ return super.__cmp__(other); } PyObject res=impl.__get__(this,self_type).__call__(other); - if (res instanceof PyInteger) { - int v=((PyInteger)res).getValue(); - return v<0?-1:v>0?1:0; + if (res==Py.NotImplemented) { + return-2; } - throw Py.TypeError("__cmp__ should return a int"); + int c=res.asInt(); + return c<0?-1:c>0?1:0; } public boolean __nonzero__() { Modified: trunk/jython/src/org/python/core/PyComplexDerived.java =================================================================== --- trunk/jython/src/org/python/core/PyComplexDerived.java 2008-10-30 06:06:03 UTC (rev 5529) +++ trunk/jython/src/org/python/core/PyComplexDerived.java 2008-10-30 06:07:01 UTC (rev 5530) @@ -776,11 +776,11 @@ return super.__cmp__(other); } PyObject res=impl.__get__(this,self_type).__call__(other); - if (res instanceof PyInteger) { - int v=((PyInteger)res).getValue(); - return v<0?-1:v>0?1:0; + if (res==Py.NotImplemented) { + return-2; } - throw Py.TypeError("__cmp__ should return a int"); + int c=res.asInt(); + return c<0?-1:c>0?1:0; } public boolean __nonzero__() { Modified: trunk/jython/src/org/python/core/PyDictionaryDerived.java =================================================================== --- trunk/jython/src/org/python/core/PyDictionaryDerived.java 2008-10-30 06:06:03 UTC (rev 5529) +++ trunk/jython/src/org/python/core/PyDictionaryDerived.java 2008-10-30 06:07:01 UTC (rev 5530) @@ -776,11 +776,11 @@ return super.__cmp__(other); } PyObject res=impl.__get__(this,self_type).__call__(other); - if (res instanceof PyInteger) { - int v=((PyInteger)res).getValue(); - return v<0?-1:v>0?1:0; + if (res==Py.NotImplemented) { + return-2; } - throw Py.TypeError("__cmp__ should return a int"); + int c=res.asInt(); + return c<0?-1:c>0?1:0; } public boolean __nonzero__() { Modified: trunk/jython/src/org/python/core/PyEnumerateDerived.java =================================================================== --- trunk/jython/src/org/python/core/PyEnumerateDerived.java 2008-10-30 06:06:03 UTC (rev 5529) +++ trunk/jython/src/org/python/core/PyEnumerateDerived.java 2008-10-30 06:07:01 UTC (rev 5530) @@ -776,11 +776,11 @@ return super.__cmp__(other); } PyObject res=impl.__get__(this,self_type).__call__(other); - if (res instanceof PyInteger) { - int v=((PyInteger)res).getValue(); - return v<0?-1:v>0?1:0; + if (res==Py.NotImplemented) { + return-2; } - throw Py.TypeError("__cmp__ should return a int"); + int c=res.asInt(); + return c<0?-1:c>0?1:0; } public boolean __nonzero__() { Modified: trunk/jython/src/org/python/core/PyFileDerived.java =================================================================== --- trunk/jython/src/org/python/core/PyFileDerived.java 2008-10-30 06:06:03 UTC (rev 5529) +++ trunk/jython/src/org/python/core/PyFileDerived.java 2008-10-30 06:07:01 UTC (rev 5530) @@ -776,11 +776,11 @@ return super.__cmp__(other); } PyObject res=impl.__get__(this,self_type).__call__(other); - if (res instanceof PyInteger) { - int v=((PyInteger)res).getValue(); - return v<0?-1:v>0?1:0; + if (res==Py.NotImplemented) { + return-2; } - throw Py.TypeError("__cmp__ should return a int"); + int c=res.asInt(); + return c<0?-1:c>0?1:0; } public boolean __nonzero__() { Modified: trunk/jython/src/org/python/core/PyFloatDerived.java =================================================================== --- trunk/jython/src/org/python/core/PyFloatDerived.java 2008-10-30 06:06:03 UTC (rev 5529) +++ trunk/jython/src/org/python/core/PyFloatDerived.java 2008-10-30 06:07:01 UTC (rev 5530) @@ -776,11 +776,11 @@ return super.__cmp__(other); } PyObject res=impl.__get__(this,self_type).__call__(other); - if (res instanceof PyInteger) { - int v=((PyInteger)res).getValue(); - return v<0?-1:v>0?1:0; + if (res==Py.NotImplemented) { + return-2; } - throw Py.TypeError("__cmp__ should return a int"); + int c=res.asInt(); + return c<0?-1:c>0?1:0; } public boolean __nonzero__() { Modified: trunk/jython/src/org/python/core/PyFrozenSetDerived.java =================================================================== --- trunk/jython/src/org/python/core/PyFrozenSetDerived.java 2008-10-30 06:06:03 UTC (rev 5529) +++ trunk/jython/src/org/python/core/PyFrozenSetDerived.java 2008-10-30 06:07:01 UTC (rev 5530) @@ -776,11 +776,11 @@ return super.__cmp__(other); } PyObject res=impl.__get__(this,self_type).__call__(other); - if (res instanceof PyInteger) { - int v=((PyInteger)res).getValue(); - return v<0?-1:v>0?1:0; + if (res==Py.NotImplemented) { + return-2; } - throw Py.TypeError("__cmp__ should return a int"); + int c=res.asInt(); + return c<0?-1:c>0?1:0; } public boolean __nonzero__() { Modified: trunk/jython/src/org/python/core/PyIntegerDerived.java =================================================================== --- trunk/jython/src/org/python/core/PyIntegerDerived.java 2008-10-30 06:06:03 UTC (rev 5529) +++ trunk/jython/src/org/python/core/PyIntegerDerived.java 2008-10-30 06:07:01 UTC (rev 5530) @@ -776,11 +776,11 @@ return super.__cmp__(other); } PyObject res=impl.__get__(this,self_type).__call__(other); - if (res instanceof PyInteger) { - int v=((PyInteger)res).getValue(); - return v<0?-1:v>0?1:0; + if (res==Py.NotImplemented) { + return-2; } - throw Py.TypeError("__cmp__ should return a int"); + int c=res.asInt(); + return c<0?-1:c>0?1:0; } public boolean __nonzero__() { Modified: trunk/jython/src/org/python/core/PyListDerived.java =================================================================== --- trunk/jython/src/org/python/core/PyListDerived.java 2008-10-30 06:06:03 UTC (rev 5529) +++ trunk/jython/src/org/python/core/PyListDerived.java 2008-10-30 06:07:01 UTC (rev 5530) @@ -776,11 +776,11 @@ return super.__cmp__(other); } PyObject res=impl.__get__(this,self_type).__call__(other); - if (res instanceof PyInteger) { - int v=((PyInteger)res).getValue(); - return v<0?-1:v>0?1:0; + if (res==Py.NotImplemented) { + return-2; } - throw Py.TypeError("__cmp__ should return a int"); + int c=res.asInt(); + return c<0?-1:c>0?1:0; } public boolean __nonzero__() { Modified: trunk/jython/src/org/python/core/PyLongDerived.java =================================================================== --- trunk/jython/src/org/python/core/PyLongDerived.java 2008-10-30 06:06:03 UTC (rev 5529) +++ trunk/jython/src/org/python/core/PyLongDerived.java 2008-10-30 06:07:01 UTC (rev 5530) @@ -776,11 +776,11 @@ return super.__cmp__(other); } PyObject res=impl.__get__(this,self_type).__call__(other); - if (res instanceof PyInteger) { - int v=((PyInteger)res).getValue(); - return v<0?-1:v>0?1:0; + if (res==Py.NotImplemented) { + return-2; } - throw Py.TypeError("__cmp__ should return a int"); + int c=res.asInt(); + return c<0?-1:c>0?1:0; } public boolean __nonzero__() { Modified: trunk/jython/src/org/python/core/PyModuleDerived.java =================================================================== --- trunk/jython/src/org/python/core/PyModuleDerived.java 2008-10-30 06:06:03 UTC (rev 5529) +++ trunk/jython/src/org/python/core/PyModuleDerived.java 2008-10-30 06:07:01 UTC (rev 5530) @@ -752,11 +752,11 @@ return super.__cmp__(other); } PyObject res=impl.__get__(this,self_type).__call__(other); - if (res instanceof PyInteger) { - int v=((PyInteger)res).getValue(); - return v<0?-1:v>0?1:0; + if (res==Py.NotImplemented) { + return-2; } - throw Py.TypeError("__cmp__ should return a int"); + int c=res.asInt(); + return c<0?-1:c>0?1:0; } public boolean __nonzero__() { Modified: trunk/jython/src/org/python/core/PyObjectDerived.java =================================================================== --- trunk/jython/src/org/python/core/PyObjectDerived.java 2008-10-30 06:06:03 UTC (rev 5529) +++ trunk/jython/src/org/python/core/PyObjectDerived.java 2008-10-30 06:07:01 UTC (rev 5530) @@ -776,11 +776,11 @@ return super.__cmp__(other); } PyObject res=impl.__get__(this,self_type).__call__(other); - if (res instanceof PyInteger) { - int v=((PyInteger)res).getValue(); - return v<0?-1:v>0?1:0; + if (res==Py.NotImplemented) { + return-2; } - throw Py.TypeError("__cmp__ should return a int"); + int c=res.asInt(); + return c<0?-1:c>0?1:0; } public boolean __nonzero__() { Modified: trunk/jython/src/org/python/core/PyPropertyDerived.java =================================================================== --- trunk/jython/src/org/python/core/PyPropertyDerived.java 2008-10-30 06:06:03 UTC (rev 5529) +++ trunk/jython/src/org/python/core/PyPropertyDerived.java 2008-10-30 06:07:01 UTC (rev 5530) @@ -776,11 +776,11 @@ return super.__cmp__(other); } PyObject res=impl.__get__(this,self_type).__call__(other); - if (res instanceof PyInteger) { - int v=((PyInteger)res).getValue(); - return v<0?-1:v>0?1:0; + if (res==Py.NotImplemented) { + return-2; } - throw Py.TypeError("__cmp__ should return a int"); + int c=res.asInt(); + return c<0?-1:c>0?1:0; } public boolean __nonzero__() { Modified: trunk/jython/src/org/python/core/PySetDerived.java =================================================================== --- trunk/jython/src/org/python/core/PySetDerived.java 2008-10-30 06:06:03 UTC (rev 5529) +++ trunk/jython/src/org/python/core/PySetDerived.java 2008-10-30 06:07:01 UTC (rev 5530) @@ -776,11 +776,11 @@ return super.__cmp__(other); } PyObject res=impl.__get__(this,self_type).__call__(other); - if (res instanceof PyInteger) { - int v=((PyInteger)res).getValue(); - return v<0?-1:v>0?1:0; + if (res==Py.NotImplemented) { + return-2; } - throw Py.TypeError("__cmp__ should return a int"); + int c=res.asInt(); + return c<0?-1:c>0?1:0; } public boolean __nonzero__() { Modified: trunk/jython/src/org/python/core/PySliceDerived.java =================================================================== --- trunk/jython/src/org/python/core/PySliceDerived.java 2008-10-30 06:06:03 UTC (rev 5529) +++ trunk/jython/src/org/python/core/PySliceDerived.java 2008-10-30 06:07:01 UTC (rev 5530) @@ -776,11 +776,11 @@ return super.__cmp__(other); } PyObject res=impl.__get__(this,self_type).__call__(other); - if (res instanceof PyInteger) { - int v=((PyInteger)res).getValue(); - return v<0?-1:v>0?1:0; + if (res==Py.NotImplemented) { + return-2; } - throw Py.TypeError("__cmp__ should return a int"); + int c=res.asInt(); + return c<0?-1:c>0?1:0; } public boolean __nonzero__() { Modified: trunk/jython/src/org/python/core/PyStringDerived.java =================================================================== --- trunk/jython/src/org/python/core/PyStringDerived.java 2008-10-30 06:06:03 UTC (rev 5529) +++ trunk/jython/src/org/python/core/PyStringDerived.java 2008-10-30 06:07:01 UTC (rev 5530) @@ -776,11 +776,11 @@ return super.__cmp__(other); } PyObject res=impl.__get__(this,self_type).__call__(other); - if (res instanceof PyInteger) { - int v=((PyInteger)res).getValue(); - return v<0?-1:v>0?1:0; + if (res==Py.NotImplemented) { + return-2; } - throw Py.TypeError("__cmp__ should return a int"); + int c=res.asInt(); + return c<0?-1:c>0?1:0; } public boolean __nonzero__() { Modified: trunk/jython/src/org/python/core/PySuperDerived.java =================================================================== --- trunk/jython/src/org/python/core/PySuperDerived.java 2008-10-30 06:06:03 UTC (rev 5529) +++ trunk/jython/src/org/python/core/PySuperDerived.java 2008-10-30 06:07:01 UTC (rev 5530) @@ -776,11 +776,11 @@ return super.__cmp__(other); } PyObject res=impl.__get__(this,self_type).__call__(other); - if (res instanceof PyInteger) { - int v=((PyInteger)res).getValue(); - return v<0?-1:v>0?1:0; + if (res==Py.NotImplemented) { + return-2; } - throw Py.TypeError("__cmp__ should return a int"); + int c=res.asInt(); + return c<0?-1:c>0?1:0; } public boolean __nonzero__() { Modified: trunk/jython/src/org/python/core/PyTupleDerived.java =================================================================== --- trunk/jython/src/org/python/core/PyTupleDerived.java 2008-10-30 06:06:03 UTC (rev 5529) +++ trunk/jython/src/org/python/core/PyTupleDerived.java 2008-10-30 06:07:01 UTC (rev 5530) @@ -776,11 +776,11 @@ return super.__cmp__(other); } PyObject res=impl.__get__(this,self_type).__call__(other); - if (res instanceof PyInteger) { - int v=((PyInteger)res).getValue(); - return v<0?-1:v>0?1:0; + if (res==Py.NotImplemented) { + return-2; } - throw Py.TypeError("__cmp__ should return a int"); + int c=res.asInt(); + return c<0?-1:c>0?1:0; } public boolean __nonzero__() { Modified: trunk/jython/src/org/python/core/PyTypeDerived.java =================================================================== --- trunk/jython/src/org/python/core/PyTypeDerived.java 2008-10-30 06:06:03 UTC (rev 5529) +++ trunk/jython/src/org/python/core/PyTypeDerived.java 2008-10-30 06:07:01 UTC (rev 5530) @@ -752,11 +752,11 @@ return super.__cmp__(other); } PyObject res=impl.__get__(this,self_type).__call__(other); - if (res instanceof PyInteger) { - int v=((PyInteger)res).getValue(); - return v<0?-1:v>0?1:0; + if (res==Py.NotImplemented) { + return-2; } - throw Py.TypeError("__cmp__ should return a int"); + int c=res.asInt(); + return c<0?-1:c>0?1:0; } public boolean __nonzero__() { Modified: trunk/jython/src/org/python/core/PyUnicodeDerived.java =================================================================== --- trunk/jython/src/org/python/core/PyUnicodeDerived.java 2008-10-30 06:06:03 UTC (rev 5529) +++ trunk/jython/src/org/python/core/PyUnicodeDerived.java 2008-10-30 06:07:01 UTC (rev 5530) @@ -776,11 +776,11 @@ return super.__cmp__(other); } PyObject res=impl.__get__(this,self_type).__call__(other); - if (res instanceof PyInteger) { - int v=((PyInteger)res).getValue(); - return v<0?-1:v>0?1:0; + if (res==Py.NotImplemented) { + return-2; } - throw Py.TypeError("__cmp__ should return a int"); + int c=res.asInt(); + return c<0?-1:c>0?1:0; } public boolean __nonzero__() { Modified: trunk/jython/src/org/python/modules/_collections/PyDefaultDictDerived.java =================================================================== --- trunk/jython/src/org/python/modules/_collections/PyDefaultDictDerived.java 2008-10-30 06:06:03 UTC (rev 5529) +++ trunk/jython/src/org/python/modules/_collections/PyDefaultDictDerived.java 2008-10-30 06:07:01 UTC (rev 5530) @@ -778,11 +778,11 @@ return super.__cmp__(other); } PyObject res=impl.__get__(this,self_type).__call__(other); - if (res instanceof PyInteger) { - int v=((PyInteger)res).getValue(); - return v<0?-1:v>0?1:0; + if (res==Py.NotImplemented) { + return-2; } - throw Py.TypeError("__cmp__ should return a int"); + int c=res.asInt(); + return c<0?-1:c>0?1:0; } public boolean __nonzero__() { Modified: trunk/jython/src/org/python/modules/_collections/PyDequeDerived.java =================================================================== --- trunk/jython/src/org/python/modules/_collections/PyDequeDerived.java 2008-10-30 06:06:03 UTC (rev 5529) +++ trunk/jython/src/org/python/modules/_collections/PyDequeDerived.java 2008-10-30 06:07:01 UTC (rev 5530) @@ -778,11 +778,11 @@ return super.__cmp__(other); } PyObject res=impl.__get__(this,self_type).__call__(other); - if (res instanceof PyInteger) { - int v=((PyInteger)res).getValue(); - return v<0?-1:v>0?1:0; + if (res==Py.NotImplemented) { + return-2; } - throw Py.TypeError("__cmp__ should return a int"); + int c=res.asInt(); + return c<0?-1:c>0?1:0; } public boolean __nonzero__() { Modified: trunk/jython/src/org/python/modules/_csv/PyDialectDerived.java =================================================================== --- trunk/jython/src/org/python/modules/_csv/PyDialectDerived.java 2008-10-30 06:06:03 UTC (rev 5529) +++ trunk/jython/src/org/python/modules/_csv/PyDialectDerived.java 2008-10-30 06:07:01 UTC (rev 5530) @@ -754,11 +754,11 @@ return super.__cmp__(other); } PyObject res=impl.__get__(this,self_type).__call__(other); - if (res instanceof PyInteger) { - int v=((PyInteger)res).getValue(); - return v<0?-1:v>0?1:0; + if (res==Py.NotImplemented) { + return-2; } - throw Py.TypeError("__cmp__ should return a int"); + int c=res.asInt(); + return c<0?-1:c>0?1:0; } public boolean __nonzero__() { Modified: trunk/jython/src/org/python/modules/_functools/PyPartialDerived.java =================================================================== --- trunk/jython/src/org/python/modules/_functools/PyPartialDerived.java 2008-10-30 06:06:03 UTC (rev 5529) +++ trunk/jython/src/org/python/modules/_functools/PyPartialDerived.java 2008-10-30 06:07:01 UTC (rev 5530) @@ -754,11 +754,11 @@ return super.__cmp__(other); } PyObject res=impl.__get__(this,self_type).__call__(other); - if (res instanceof PyInteger) { - int v=((PyInteger)res).getValue(); - return v<0?-1:v>0?1:0; + if (res==Py.NotImplemented) { + return-2; } - throw Py.TypeError("__cmp__ should return a int"); + int c=res.asInt(); + return c<0?-1:c>0?1:0; } public boolean __nonzero__() { Modified: trunk/jython/src/org/python/modules/_weakref/ReferenceTypeDerived.java =================================================================== --- trunk/jython/src/org/python/modules/_weakref/ReferenceTypeDerived.java 2008-10-30 06:06:03 UTC (rev 5529) +++ trunk/jython/src/org/python/modules/_weakref/ReferenceTypeDerived.java 2008-10-30 06:07:01 UTC (rev 5530) @@ -778,11 +778,11 @@ return super.__cmp__(other); } PyObject res=impl.__get__(this,self_type).__call__(other); - if (res instanceof PyInteger) { - int v=((PyInteger)res).getValue(); - return v<0?-1:v>0?1:0; + if (res==Py.NotImplemented) { + return-2; } - throw Py.TypeError("__cmp__ should return a int"); + int c=res.asInt(); + return c<0?-1:c>0?1:0; } public boolean __nonzero__() { Modified: trunk/jython/src/org/python/modules/random/PyRandomDerived.java =================================================================== --- trunk/jython/src/org/python/modules/random/PyRandomDerived.java 2008-10-30 06:06:03 UTC (rev 5529) +++ trunk/jython/src/org/python/modules/random/PyRandomDerived.java 2008-10-30 06:07:01 UTC (rev 5530) @@ -778,11 +778,11 @@ return super.__cmp__(other); } PyObject res=impl.__get__(this,self_type).__call__(other); - if (res instanceof PyInteger) { - int v=((PyInteger)res).getValue(); - return v<0?-1:v>0?1:0; + if (res==Py.NotImplemented) { + return-2; } - throw Py.TypeError("__cmp__ should return a int"); + int c=res.asInt(); + return c<0?-1:c>0?1:0; } public boolean __nonzero__() { Modified: trunk/jython/src/org/python/modules/thread/PyLocalDerived.java =================================================================== --- trunk/jython/src/org/python/modules/thread/PyLocalDerived.java 2008-10-30 06:06:03 UTC (rev 5529) +++ trunk/jython/src/org/python/modules/thread/PyLocalDerived.java 2008-10-30 06:07:01 UTC (rev 5530) @@ -754,11 +754,11 @@ return super.__cmp__(other); } PyObject res=impl.__get__(this,self_type).__call__(other); - if (res instanceof PyInteger) { - int v=((PyInteger)res).getValue(); - return v<0?-1:v>0?1:0; + if (res==Py.NotImplemented) { + return-2; } - throw Py.TypeError("__cmp__ should return a int"); + int c=res.asInt(); + return c<0?-1:c>0?1:0; } public boolean __nonzero__() { Modified: trunk/jython/src/org/python/modules/zipimport/zipimporterDerived.java =================================================================== --- trunk/jython/src/org/python/modules/zipimport/zipimporterDerived.java 2008-10-30 06:06:03 UTC (rev 5529) +++ trunk/jython/src/org/python/modules/zipimport/zipimporterDerived.java 2008-10-30 06:07:01 UTC (rev 5530) @@ -754,11 +754,11 @@ return super.__cmp__(other); } PyObject res=impl.__get__(this,self_type).__call__(other); - if (res instanceof PyInteger) { - int v=((PyInteger)res).getValue(); - return v<0?-1:v>0?1:0; + if (res==Py.NotImplemented) { + return-2; } - throw Py.TypeError("__cmp__ should return a int"); + int c=res.asInt(); + return c<0?-1:c>0?1:0; } public boolean __nonzero__() { This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <pj...@us...> - 2008-11-07 01:16:00
|
Revision: 5552 http://jython.svn.sourceforge.net/jython/?rev=5552&view=rev Author: pjenvey Date: 2008-11-07 01:15:50 +0000 (Fri, 07 Nov 2008) Log Message: ----------- unused imports, some coding standards Modified Paths: -------------- trunk/jython/src/org/python/antlr/BaseParser.java trunk/jython/src/org/python/antlr/ExpressionParser.java trunk/jython/src/org/python/antlr/FailFastHandler.java trunk/jython/src/org/python/antlr/InteractiveParser.java trunk/jython/src/org/python/antlr/ModuleParser.java trunk/jython/src/org/python/antlr/PythonTree.java trunk/jython/src/org/python/core/ParserFacade.java Modified: trunk/jython/src/org/python/antlr/BaseParser.java =================================================================== --- trunk/jython/src/org/python/antlr/BaseParser.java 2008-11-07 01:04:00 UTC (rev 5551) +++ trunk/jython/src/org/python/antlr/BaseParser.java 2008-11-07 01:15:50 UTC (rev 5552) @@ -1,31 +1,10 @@ package org.python.antlr; import org.antlr.runtime.CharStream; -import org.antlr.runtime.CommonToken; -import org.antlr.runtime.CommonTokenStream; -import org.antlr.runtime.RecognitionException; import org.antlr.runtime.Token; -import org.antlr.runtime.tree.CommonTree; -import org.antlr.runtime.tree.CommonTreeAdaptor; -import org.antlr.runtime.tree.CommonTreeNodeStream; -import org.antlr.runtime.tree.Tree; -import org.antlr.runtime.tree.TreeAdaptor; -import org.python.antlr.ast.modType; -import org.python.antlr.ast.Module; -import org.python.antlr.ast.stmtType; public class BaseParser { - public static class PyLexer extends PythonLexer { - public PyLexer(CharStream lexer) { - super(lexer); - } - public Token nextToken() { - startPos = getCharPositionInLine(); - return super.nextToken(); - } - } - protected CharStream charStream; protected boolean partial; protected String filename; @@ -35,4 +14,15 @@ public void setAntlrErrorHandler(ErrorHandler eh) { this.errorHandler = eh; } + + public static class PyLexer extends PythonLexer { + public PyLexer(CharStream lexer) { + super(lexer); + } + + public Token nextToken() { + startPos = getCharPositionInLine(); + return super.nextToken(); + } + } } Modified: trunk/jython/src/org/python/antlr/ExpressionParser.java =================================================================== --- trunk/jython/src/org/python/antlr/ExpressionParser.java 2008-11-07 01:04:00 UTC (rev 5551) +++ trunk/jython/src/org/python/antlr/ExpressionParser.java 2008-11-07 01:15:50 UTC (rev 5552) @@ -1,18 +1,9 @@ package org.python.antlr; import org.antlr.runtime.CharStream; -import org.antlr.runtime.CommonToken; import org.antlr.runtime.CommonTokenStream; import org.antlr.runtime.RecognitionException; -import org.antlr.runtime.Token; -import org.antlr.runtime.tree.CommonTree; -import org.antlr.runtime.tree.CommonTreeAdaptor; -import org.antlr.runtime.tree.CommonTreeNodeStream; -import org.antlr.runtime.tree.Tree; -import org.antlr.runtime.tree.TreeAdaptor; import org.python.antlr.ast.modType; -import org.python.antlr.ast.Module; -import org.python.antlr.ast.stmtType; public class ExpressionParser extends BaseParser { Modified: trunk/jython/src/org/python/antlr/FailFastHandler.java =================================================================== --- trunk/jython/src/org/python/antlr/FailFastHandler.java 2008-11-07 01:04:00 UTC (rev 5551) +++ trunk/jython/src/org/python/antlr/FailFastHandler.java 2008-11-07 01:15:50 UTC (rev 5552) @@ -6,11 +6,7 @@ import org.antlr.runtime.Lexer; import org.antlr.runtime.MismatchedTokenException; import org.antlr.runtime.RecognitionException; -import org.python.antlr.ast.ErrorMod; import org.python.antlr.ast.exprType; -import org.python.antlr.ast.ErrorExpr; -import org.python.antlr.ast.ErrorSlice; -import org.python.antlr.ast.ErrorStmt; import org.python.antlr.ast.modType; import org.python.antlr.ast.sliceType; import org.python.antlr.ast.stmtType; Modified: trunk/jython/src/org/python/antlr/InteractiveParser.java =================================================================== --- trunk/jython/src/org/python/antlr/InteractiveParser.java 2008-11-07 01:04:00 UTC (rev 5551) +++ trunk/jython/src/org/python/antlr/InteractiveParser.java 2008-11-07 01:15:50 UTC (rev 5552) @@ -3,19 +3,9 @@ import java.io.BufferedReader; import java.io.IOException; -import org.antlr.runtime.CharStream; -import org.antlr.runtime.CommonToken; import org.antlr.runtime.CommonTokenStream; import org.antlr.runtime.RecognitionException; -import org.antlr.runtime.Token; -import org.antlr.runtime.tree.CommonTree; -import org.antlr.runtime.tree.CommonTreeAdaptor; -import org.antlr.runtime.tree.CommonTreeNodeStream; -import org.antlr.runtime.tree.Tree; -import org.antlr.runtime.tree.TreeAdaptor; import org.python.antlr.ast.modType; -import org.python.antlr.ast.Module; -import org.python.antlr.ast.stmtType; public class InteractiveParser extends BaseParser { Modified: trunk/jython/src/org/python/antlr/ModuleParser.java =================================================================== --- trunk/jython/src/org/python/antlr/ModuleParser.java 2008-11-07 01:04:00 UTC (rev 5551) +++ trunk/jython/src/org/python/antlr/ModuleParser.java 2008-11-07 01:15:50 UTC (rev 5552) @@ -1,18 +1,9 @@ package org.python.antlr; import org.antlr.runtime.CharStream; -import org.antlr.runtime.CommonToken; import org.antlr.runtime.CommonTokenStream; import org.antlr.runtime.RecognitionException; -import org.antlr.runtime.Token; -import org.antlr.runtime.tree.CommonTree; -import org.antlr.runtime.tree.CommonTreeAdaptor; -import org.antlr.runtime.tree.CommonTreeNodeStream; -import org.antlr.runtime.tree.Tree; -import org.antlr.runtime.tree.TreeAdaptor; import org.python.antlr.ast.modType; -import org.python.antlr.ast.Module; -import org.python.antlr.ast.stmtType; public class ModuleParser extends BaseParser { public ModuleParser(CharStream cs, String filename, String encoding) { Modified: trunk/jython/src/org/python/antlr/PythonTree.java =================================================================== --- trunk/jython/src/org/python/antlr/PythonTree.java 2008-11-07 01:04:00 UTC (rev 5551) +++ trunk/jython/src/org/python/antlr/PythonTree.java 2008-11-07 01:15:50 UTC (rev 5552) @@ -5,9 +5,6 @@ import org.antlr.runtime.CommonToken; import org.antlr.runtime.Token; -import java.io.DataOutputStream; -import java.io.IOException; - import org.python.antlr.ast.VisitorIF; public class PythonTree extends BaseTree implements AST { Modified: trunk/jython/src/org/python/core/ParserFacade.java =================================================================== --- trunk/jython/src/org/python/core/ParserFacade.java 2008-11-07 01:04:00 UTC (rev 5551) +++ trunk/jython/src/org/python/core/ParserFacade.java 2008-11-07 01:15:50 UTC (rev 5552) @@ -12,7 +12,6 @@ import java.util.regex.Matcher; import java.util.regex.Pattern; -import org.antlr.runtime.ANTLRReaderStream; import org.antlr.runtime.CharStream; import org.antlr.runtime.CommonTokenStream; @@ -22,9 +21,7 @@ import org.python.antlr.ParseException; import org.python.antlr.ModuleParser; import org.python.antlr.NoCloseReaderStream; -import org.python.antlr.PythonParser; import org.python.antlr.PythonTree; -import org.python.antlr.PythonTree; import org.python.antlr.PythonLexer; import org.python.antlr.PythonPartial; import org.python.antlr.PythonTokenSource; This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <fwi...@us...> - 2008-11-27 04:01:32
|
Revision: 5645 http://jython.svn.sourceforge.net/jython/?rev=5645&view=rev Author: fwierzbicki Date: 2008-11-27 04:01:27 +0000 (Thu, 27 Nov 2008) Log Message: ----------- Make PythonTree (and thus most of the ast nodes) extend PyObject instead of Antlr's CommonTree. This required pulling in much of the CommonTree code for now. Hopefully I can prune some of it out in time. Also PythonTreeAdaptor had to override more of CommonTreeAdaptor's methods. Modified Paths: -------------- trunk/jython/src/org/python/antlr/GrammarActions.java trunk/jython/src/org/python/antlr/ParseException.java trunk/jython/src/org/python/antlr/PythonErrorNode.java trunk/jython/src/org/python/antlr/PythonTree.java trunk/jython/src/org/python/antlr/PythonTreeAdaptor.java trunk/jython/src/org/python/compiler/ScopesCompiler.java Modified: trunk/jython/src/org/python/antlr/GrammarActions.java =================================================================== --- trunk/jython/src/org/python/antlr/GrammarActions.java 2008-11-27 03:30:23 UTC (rev 5644) +++ trunk/jython/src/org/python/antlr/GrammarActions.java 2008-11-27 04:01:27 UTC (rev 5645) @@ -2,7 +2,6 @@ import org.antlr.runtime.CommonToken; import org.antlr.runtime.Token; -import org.antlr.runtime.tree.Tree; import org.python.core.Py; import org.python.core.PyComplex; @@ -300,7 +299,7 @@ return value; } - void recurseSetContext(Tree tree, expr_contextType context) { + void recurseSetContext(PythonTree tree, expr_contextType context) { if (tree instanceof Context) { ((Context)tree).setContext(context); } Modified: trunk/jython/src/org/python/antlr/ParseException.java =================================================================== --- trunk/jython/src/org/python/antlr/ParseException.java 2008-11-27 03:30:23 UTC (rev 5644) +++ trunk/jython/src/org/python/antlr/ParseException.java 2008-11-27 04:01:27 UTC (rev 5645) @@ -38,7 +38,7 @@ public ParseException(String message, PythonTree n) { this(message, n.getLine(), n.getCharPositionInLine()); this.node = n; - this.token = n.token; + this.token = n.getToken(); } public ParseException(String message, RecognitionException r) { Modified: trunk/jython/src/org/python/antlr/PythonErrorNode.java =================================================================== --- trunk/jython/src/org/python/antlr/PythonErrorNode.java 2008-11-27 03:30:23 UTC (rev 5644) +++ trunk/jython/src/org/python/antlr/PythonErrorNode.java 2008-11-27 04:01:27 UTC (rev 5645) @@ -24,7 +24,7 @@ return errorNode.isNil(); } - public int getType() { + public int getAntlrType() { return errorNode.getType(); } Modified: trunk/jython/src/org/python/antlr/PythonTree.java =================================================================== --- trunk/jython/src/org/python/antlr/PythonTree.java 2008-11-27 03:30:23 UTC (rev 5644) +++ trunk/jython/src/org/python/antlr/PythonTree.java 2008-11-27 04:01:27 UTC (rev 5645) @@ -1,35 +1,45 @@ package org.python.antlr; -import org.antlr.runtime.tree.BaseTree; -import org.antlr.runtime.tree.Tree; +import org.python.core.PyObject; import org.antlr.runtime.CommonToken; import org.antlr.runtime.Token; +import org.antlr.runtime.tree.CommonTree; import org.python.antlr.ast.VisitorIF; -public class PythonTree extends BaseTree implements AST { +import java.util.ArrayList; +import java.util.List; +public class PythonTree extends PyObject implements AST { + public boolean from_future_checked = false; private int charStartIndex = -1; private int charStopIndex = -1; - + private CommonTree node; + private PythonTree parent; + /** A single token is the payload */ - public Token token; + //private Token token; /** What token indexes bracket all tokens associated with this node * and below? */ - protected int startIndex=-1, stopIndex=-1; + //protected int startIndex=-1, stopIndex=-1; /** Who is the parent node of this node; if null, implies node is root */ - public PythonTree parent; + //private PythonTree parent; /** What index is this node in the child list? Range: 0..n-1 */ - public int childIndex = -1; + //private int childIndex = -1; public PythonTree() { + node = new CommonTree(); } + public PythonTree(Token t) { + node = new CommonTree(t); + } + public PythonTree(int ttype, Token t) { CommonToken c = new CommonToken(ttype, t.getText()); c.setLine(t.getLine()); @@ -38,59 +48,45 @@ c.setChannel(t.getChannel()); c.setStartIndex(((CommonToken)t).getStartIndex()); c.setStopIndex(((CommonToken)t).getStopIndex()); - token = c; + node = new CommonTree(c); } - public PythonTree(Token t) { - this.token = t; + public PythonTree(PythonTree tree) { + node = new CommonTree(tree.getNode()); + charStartIndex = tree.getCharStartIndex(); + charStopIndex = tree.getCharStopIndex(); } + + public CommonTree getNode() { + return node; + } - public PythonTree(PythonTree node) { - super(node); - token = node.token; - startIndex = node.startIndex; - stopIndex = node.stopIndex; - charStartIndex = node.getCharStartIndex(); - charStopIndex = node.getCharStopIndex(); - } - public Token getToken() { - return token; + return node.getToken(); } - public Tree dupNode() { + public PythonTree dupNode() { return new PythonTree(this); } public boolean isNil() { - return token==null; + return node.isNil(); } - public int getType() { - if (token==null) { - return Token.INVALID_TOKEN_TYPE; - } - return token.getType(); + public int getAntlrType() { + return node.getType(); } public String getText() { - if (token==null) { - return null; - } - return token.getText(); + return node.getText(); } public int getLine() { - if (token==null || token.getLine()==0) { - if ( getChildCount()>0 ) { - return getChild(0).getLine(); - } - return 0; - } - return token.getLine(); + return node.getLine(); } public int getCharPositionInLine() { + Token token = node.getToken(); if (token==null || token.getCharPositionInLine()==-1) { if (getChildCount()>0) { return getChild(0).getCharPositionInLine(); @@ -107,46 +103,24 @@ } public int getTokenStartIndex() { - if ( startIndex==-1 && token!=null ) { - return token.getTokenIndex(); - } - return startIndex; + return node.getTokenStartIndex(); } public void setTokenStartIndex(int index) { - startIndex = index; + node.setTokenStartIndex(index); } public int getTokenStopIndex() { - if ( stopIndex==-1 && token!=null ) { - return token.getTokenIndex(); - } - return stopIndex; + return node.getTokenStopIndex(); } public void setTokenStopIndex(int index) { - stopIndex = index; + node.setTokenStopIndex(index); } - public int getChildIndex() { - return childIndex; - } - - public Tree getParent() { - return parent; - } - - public void setParent(Tree t) { - this.parent = (PythonTree)t; - } - - public void setChildIndex(int index) { - this.childIndex = index; - } - public int getCharStartIndex() { - if (charStartIndex == -1 && token != null) { - return ((CommonToken)token).getStartIndex(); + if (charStartIndex == -1 && node.getToken() != null) { + return ((CommonToken)node.getToken()).getStartIndex(); } return charStartIndex ; } @@ -166,8 +140,8 @@ */ public int getCharStopIndex() { - if (charStopIndex == -1 && token != null) { - return ((CommonToken)token).getStopIndex() + 1; + if (charStopIndex == -1 && node.getToken() != null) { + return ((CommonToken)node.getToken()).getStopIndex() + 1; } return charStopIndex; } @@ -176,24 +150,36 @@ charStopIndex = index; } + public int getChildIndex() { + return node.getChildIndex(); + } + + public PythonTree getParent() { + return parent; + } + + public void setParent(PythonTree t) { + this.parent = t; + } + + public void setChildIndex(int index) { + node.setChildIndex(index); + } + public String toString() { if (isNil()) { return "None"; } - if ( getType()==Token.INVALID_TOKEN_TYPE ) { + if ( getAntlrType()==Token.INVALID_TOKEN_TYPE ) { return "<errornode>"; } - if ( token==null ) { + if ( node.getToken()==null ) { return null; } - return token.getText() + "(" + this.getLine() + "," + this.getCharPositionInLine() + ")"; + return node.getToken().getText() + "(" + this.getLine() + "," + this.getCharPositionInLine() + ")"; } - public String info() { - return this.getCharStartIndex() + ":" + this.getCharStopIndex(); - } - public String toStringTree() { if (children == null || children.size() == 0) { return this.toString();// + "[" + this.info() + "]"; @@ -205,7 +191,7 @@ buf.append(' '); } for (int i = 0; children != null && i < children.size(); i++) { - BaseTree t = (BaseTree)children.get(i); + PythonTree t = (PythonTree)children.get(i); if (i > 0) { buf.append(' '); } @@ -260,4 +246,205 @@ public String[] get_attributes() { return emptyStringArray; } + + //Copied from org.antlr.runtime.tree.BaseTree + protected List children; + + public PythonTree getChild(int i) { + if ( children==null || i>=children.size() ) { + return null; + } + return (PythonTree)children.get(i); + } + + /** Get the children internal List; note that if you directly mess with + * the list, do so at your own risk. + */ + public List getChildren() { + return children; + } + + public PythonTree getFirstChildWithType(int type) { + for (int i = 0; children!=null && i < children.size(); i++) { + PythonTree t = (PythonTree) children.get(i); + if ( t.getAntlrType()==type ) { + return t; + } + } + return null; + } + + public int getChildCount() { + if ( children==null ) { + return 0; + } + return children.size(); + } + + /** Add t as child of this node. + * + * Warning: if t has no children, but child does + * and child isNil then this routine moves children to t via + * t.children = child.children; i.e., without copying the array. + */ + public void addChild(PythonTree t) { + //System.out.println("add child "+t.toStringTree()+" "+this.toStringTree()); + //System.out.println("existing children: "+children); + if ( t==null ) { + return; // do nothing upon addChild(null) + } + PythonTree childTree = (PythonTree)t; + if ( childTree.isNil() ) { // t is an empty node possibly with children + if ( this.children!=null && this.children == childTree.children ) { + throw new RuntimeException("attempt to add child list to itself"); + } + // just add all of childTree's children to this + if ( childTree.children!=null ) { + if ( this.children!=null ) { // must copy, this has children already + int n = childTree.children.size(); + for (int i = 0; i < n; i++) { + PythonTree c = (PythonTree)childTree.children.get(i); + this.children.add(c); + // handle double-link stuff for each child of nil root + c.setParent(this); + c.setChildIndex(children.size()-1); + } + } + else { + // no children for this but t has children; just set pointer + // call general freshener routine + this.children = childTree.children; + this.freshenParentAndChildIndexes(); + } + } + } + else { // child is not nil (don't care about children) + if ( children==null ) { + children = createChildrenList(); // create children list on demand + } + children.add(t); + childTree.setParent(this); + childTree.setChildIndex(children.size()-1); + } + // System.out.println("now children are: "+children); + } + + /** Add all elements of kids list as children of this node */ + public void addChildren(List kids) { + for (int i = 0; i < kids.size(); i++) { + PythonTree t = (PythonTree) kids.get(i); + addChild(t); + } + } + + public void setChild(int i, PythonTree t) { + if ( t==null ) { + return; + } + if ( t.isNil() ) { + throw new IllegalArgumentException("Can't set single child to a list"); + } + if ( children==null ) { + children = createChildrenList(); + } + children.set(i, t); + t.setParent(this); + t.setChildIndex(i); + } + + public Object deleteChild(int i) { + if ( children==null ) { + return null; + } + PythonTree killed = (PythonTree)children.remove(i); + // walk rest and decrement their child indexes + this.freshenParentAndChildIndexes(i); + return killed; + } + + /** Delete children from start to stop and replace with t even if t is + * a list (nil-root tree). num of children can increase or decrease. + * For huge child lists, inserting children can force walking rest of + * children to set their childindex; could be slow. + */ + public void replaceChildren(int startChildIndex, int stopChildIndex, Object t) { + /* + System.out.println("replaceChildren "+startChildIndex+", "+stopChildIndex+ + " with "+((PythonTree)t).toStringTree()); + System.out.println("in="+toStringTree()); + */ + if ( children==null ) { + throw new IllegalArgumentException("indexes invalid; no children in list"); + } + int replacingHowMany = stopChildIndex - startChildIndex + 1; + int replacingWithHowMany; + PythonTree newTree = (PythonTree)t; + List newChildren = null; + // normalize to a list of children to add: newChildren + if ( newTree.isNil() ) { + newChildren = newTree.children; + } + else { + newChildren = new ArrayList(1); + newChildren.add(newTree); + } + replacingWithHowMany = newChildren.size(); + int numNewChildren = newChildren.size(); + int delta = replacingHowMany - replacingWithHowMany; + // if same number of nodes, do direct replace + if ( delta == 0 ) { + int j = 0; // index into new children + for (int i=startChildIndex; i<=stopChildIndex; i++) { + PythonTree child = (PythonTree)newChildren.get(j); + children.set(i, child); + child.setParent(this); + child.setChildIndex(i); + j++; + } + } + else if ( delta > 0 ) { // fewer new nodes than there were + // set children and then delete extra + for (int j=0; j<numNewChildren; j++) { + children.set(startChildIndex+j, newChildren.get(j)); + } + int indexToDelete = startChildIndex+numNewChildren; + for (int c=indexToDelete; c<=stopChildIndex; c++) { + // delete same index, shifting everybody down each time + PythonTree killed = (PythonTree)children.remove(indexToDelete); + } + freshenParentAndChildIndexes(startChildIndex); + } + else { // more new nodes than were there before + // fill in as many children as we can (replacingHowMany) w/o moving data + for (int j=0; j<replacingHowMany; j++) { + children.set(startChildIndex+j, newChildren.get(j)); + } + int numToInsert = replacingWithHowMany-replacingHowMany; + for (int j=replacingHowMany; j<replacingWithHowMany; j++) { + children.add(startChildIndex+j, newChildren.get(j)); + } + freshenParentAndChildIndexes(startChildIndex); + } + //System.out.println("out="+toStringTree()); + } + + /** Override in a subclass to change the impl of children list */ + protected List createChildrenList() { + return new ArrayList(); + } + + /** Set the parent and child index values for all child of t */ + public void freshenParentAndChildIndexes() { + freshenParentAndChildIndexes(0); + } + + public void freshenParentAndChildIndexes(int offset) { + int n = getChildCount(); + for (int c = offset; c < n; c++) { + PythonTree child = (PythonTree)getChild(c); + child.setChildIndex(c); + child.setParent(this); + } + } + } Modified: trunk/jython/src/org/python/antlr/PythonTreeAdaptor.java =================================================================== --- trunk/jython/src/org/python/antlr/PythonTreeAdaptor.java 2008-11-27 03:30:23 UTC (rev 5644) +++ trunk/jython/src/org/python/antlr/PythonTreeAdaptor.java 2008-11-27 04:01:27 UTC (rev 5645) @@ -49,6 +49,104 @@ if (t == null) { return null; } - return create(((PythonTree) t).token); + return create(((PythonTree) t).getToken()); } + + public boolean isNil(Object tree) { + return ((PythonTree)tree).isNil(); + } + + public void addChild(Object t, Object child) { + if ( t!=null && child!=null ) { + ((PythonTree)t).addChild((PythonTree)child); + } + } + + public Object becomeRoot(Object newRoot, Object oldRoot) { + //System.out.println("becomeroot new "+newRoot.toString()+" old "+oldRoot); + PythonTree newRootTree = (PythonTree)newRoot; + PythonTree oldRootTree = (PythonTree)oldRoot; + if ( oldRoot==null ) { + return newRoot; + } + // handle ^(nil real-node) + if ( newRootTree.isNil() ) { + int nc = newRootTree.getChildCount(); + if ( nc==1 ) newRootTree = (PythonTree)newRootTree.getChild(0); + else if ( nc >1 ) { + // TODO: make tree run time exceptions hierarchy + throw new RuntimeException("more than one node as root (TODO: make exception hierarchy)"); + } + } + // add oldRoot to newRoot; addChild takes care of case where oldRoot + // is a flat list (i.e., nil-rooted tree). All children of oldRoot + // are added to newRoot. + newRootTree.addChild(oldRootTree); + return newRootTree; + } + + public Object rulePostProcessing(Object root) { + //System.out.println("rulePostProcessing: "+((PythonTree)root).toStringTree()); + PythonTree r = (PythonTree)root; + if ( r!=null && r.isNil() ) { + if ( r.getChildCount()==0 ) { + r = null; + } + else if ( r.getChildCount()==1 ) { + r = (PythonTree)r.getChild(0); + // whoever invokes rule will set parent and child index + r.setParent(null); + r.setChildIndex(-1); + } + } + return r; + } + + public Object create(int tokenType, Token fromToken) { + fromToken = createToken(fromToken); + //((ClassicToken)fromToken).setType(tokenType); + fromToken.setType(tokenType); + PythonTree t = (PythonTree)create(fromToken); + return t; + } + + public Object create(int tokenType, Token fromToken, String text) { + fromToken = createToken(fromToken); + fromToken.setType(tokenType); + fromToken.setText(text); + PythonTree t = (PythonTree)create(fromToken); + return t; + } + + public Object create(int tokenType, String text) { + Token fromToken = createToken(tokenType, text); + PythonTree t = (PythonTree)create(fromToken); + return t; + } + + public int getType(Object t) { + ((PythonTree)t).getType(); + return 0; + } + + public String getText(Object t) { + return ((PythonTree)t).getText(); + } + + public Object getChild(Object t, int i) { + return ((PythonTree)t).getChild(i); + } + + public void setChild(Object t, int i, Object child) { + ((PythonTree)t).setChild(i, (PythonTree)child); + } + + public Object deleteChild(Object t, int i) { + return ((PythonTree)t).deleteChild(i); + } + + public int getChildCount(Object t) { + return ((PythonTree)t).getChildCount(); + } + } Modified: trunk/jython/src/org/python/compiler/ScopesCompiler.java =================================================================== --- trunk/jython/src/org/python/compiler/ScopesCompiler.java 2008-11-27 03:30:23 UTC (rev 5644) +++ trunk/jython/src/org/python/compiler/ScopesCompiler.java 2008-11-27 04:01:27 UTC (rev 5645) @@ -290,7 +290,7 @@ def(tmp); ArgListCompiler ac = new ArgListCompiler(); ac.visitArgs(new argumentsType(node, new exprType[] { new Name( - node.token, bound_exp, expr_contextType.Param) }, null, null, + node.getToken(), bound_exp, expr_contextType.Param) }, null, null, new exprType[0])); beginScope(tmp, FUNCSCOPE, node, ac); cur.addParam(bound_exp); This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <pj...@us...> - 2008-11-27 20:56:19
|
Revision: 5647 http://jython.svn.sourceforge.net/jython/?rev=5647&view=rev Author: pjenvey Date: 2008-11-27 20:56:10 +0000 (Thu, 27 Nov 2008) Log Message: ----------- o explicitly convert Strings returned from ExposedGet to str (instead of unicode), just as ExposedMethod does. restores the behavior it had before the big Java integration String/unicode change o add a TypeError message for PyDataDescr.__set__ failed conversions Modified Paths: -------------- trunk/jython/src/org/python/core/PyDataDescr.java trunk/jython/src/org/python/expose/generate/DescriptorExposer.java Modified: trunk/jython/src/org/python/core/PyDataDescr.java =================================================================== --- trunk/jython/src/org/python/core/PyDataDescr.java 2008-11-27 04:52:37 UTC (rev 5646) +++ trunk/jython/src/org/python/core/PyDataDescr.java 2008-11-27 20:56:10 UTC (rev 5647) @@ -75,9 +75,12 @@ @ExposedMethod public void getset_descriptor___set__(PyObject obj, PyObject value) { checkGetterType(obj.getType()); + // XXX: We may want to special case value being PyUnicode and ofType being String + // (then explicitly value.encode() first) Object converted = value.__tojava__(ofType); if(converted == Py.NoConversion) { - throw Py.TypeError(""); // xxx + throw Py.TypeError(String.format("unsupported type for assignment to %s: '%.200s'", + name, value.getType().fastGetName())); } invokeSet(obj, converted); } Modified: trunk/jython/src/org/python/expose/generate/DescriptorExposer.java =================================================================== --- trunk/jython/src/org/python/expose/generate/DescriptorExposer.java 2008-11-27 04:52:37 UTC (rev 5646) +++ trunk/jython/src/org/python/expose/generate/DescriptorExposer.java 2008-11-27 20:56:10 UTC (rev 5647) @@ -139,7 +139,7 @@ mv.visitVarInsn(ALOAD, 1); mv.visitTypeInsn(CHECKCAST, onType.getInternalName()); call(onType, getterMethodName, ofType); - if(PRIMITIVES.containsKey(ofType)) { + if(PRIMITIVES.containsKey(ofType) || ofType.equals(STRING)) { toPy(ofType); } endMethod(ARETURN); @@ -153,7 +153,7 @@ onType.getInternalName(), getterFieldName, ofType.getDescriptor()); - if(PRIMITIVES.containsKey(ofType)) { + if(PRIMITIVES.containsKey(ofType) || ofType.equals(STRING)) { toPy(ofType); } endMethod(ARETURN); This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <fwi...@us...> - 2008-12-07 04:15:29
|
Revision: 5719 http://jython.svn.sourceforge.net/jython/?rev=5719&view=rev Author: fwierzbicki Date: 2008-12-07 04:15:26 +0000 (Sun, 07 Dec 2008) Log Message: ----------- Fixed bugs in mutable ast revealed by running sympy tests. Modified Paths: -------------- trunk/jython/src/org/python/antlr/adapter/CmpopAdapter.java trunk/jython/src/org/python/core/AstList.java Modified: trunk/jython/src/org/python/antlr/adapter/CmpopAdapter.java =================================================================== --- trunk/jython/src/org/python/antlr/adapter/CmpopAdapter.java 2008-12-06 22:50:19 UTC (rev 5718) +++ trunk/jython/src/org/python/antlr/adapter/CmpopAdapter.java 2008-12-07 04:15:26 UTC (rev 5719) @@ -22,12 +22,31 @@ public class CmpopAdapter implements AstAdapter { public Object py2ast(PyObject o) { - if (o == null) { - return o; + switch (((PyObject)o).asInt()) { + case 1: + return cmpopType.Eq; + case 2: + return cmpopType.NotEq; + case 3: + return cmpopType.Lt; + case 4: + return cmpopType.LtE; + case 5: + return cmpopType.Gt; + case 6: + return cmpopType.GtE; + case 7: + return cmpopType.Is; + case 8: + return cmpopType.IsNot; + case 9: + return cmpopType.In; + case 10: + return cmpopType.NotIn; } - return o; + //FIXME: investigate the right exception - //throw Py.TypeError("Can't convert " + o.getClass().getName() + " to cmpop node"); + throw Py.TypeError("Can't convert " + o.getClass().getName() + " to cmpop node"); } public PyObject ast2py(Object o) { Modified: trunk/jython/src/org/python/core/AstList.java =================================================================== --- trunk/jython/src/org/python/core/AstList.java 2008-12-06 22:50:19 UTC (rev 5718) +++ trunk/jython/src/org/python/core/AstList.java 2008-12-07 04:15:26 UTC (rev 5719) @@ -430,7 +430,12 @@ @ExposedMethod(defaults = "-1") final PyObject astlist_pop(int n) { - return (PyObject)data.remove(n); + if (adapter == null) { + return (PyObject)data.remove(n); + } + Object element = data.remove(n); + return (PyObject)adapter.ast2py(element); + } protected PyObject repeat(int count) { @@ -584,7 +589,12 @@ } public PyObject pyset(int index, PyObject element) { - return (PyObject)data.set(index, element); + if (adapter == null) { + return (PyObject)data.set(index, element); + } + Object o = adapter.py2ast(element); + data.set(index, o); + return element; } public Object remove(int index) { This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <zy...@us...> - 2008-12-19 07:14:01
|
Revision: 5780 http://jython.svn.sourceforge.net/jython/?rev=5780&view=rev Author: zyasoft Date: 2008-12-19 07:13:56 +0000 (Fri, 19 Dec 2008) Log Message: ----------- For org.python.core and modules: * Replaced Vector and Hashtable with ArrayList and HashMap respectively. * Converted StringBuffer to StringBuilder where thread confined. Modified Paths: -------------- trunk/jython/src/org/python/core/AbstractArray.java trunk/jython/src/org/python/core/BaseSet.java trunk/jython/src/org/python/core/Py.java trunk/jython/src/org/python/core/PyDictionary.java trunk/jython/src/org/python/core/PyFile.java trunk/jython/src/org/python/core/PyInstance.java trunk/jython/src/org/python/core/PyList.java trunk/jython/src/org/python/core/PyStringMap.java trunk/jython/src/org/python/core/PySystemState.java trunk/jython/src/org/python/core/PyTraceback.java trunk/jython/src/org/python/core/PyTuple.java trunk/jython/src/org/python/core/PyType.java trunk/jython/src/org/python/core/imp.java trunk/jython/src/org/python/core/packagecache/CachedJarsPackageManager.java trunk/jython/src/org/python/modules/_collections/PyDeque.java trunk/jython/src/org/python/modules/_weakref/GlobalRef.java trunk/jython/src/org/python/modules/binascii.java trunk/jython/src/org/python/modules/cPickle.java trunk/jython/src/org/python/modules/sre/PatternObject.java trunk/jython/src/org/python/modules/time/Time.java trunk/jython/src/org/python/modules/ucnhash.java Modified: trunk/jython/src/org/python/core/AbstractArray.java =================================================================== --- trunk/jython/src/org/python/core/AbstractArray.java 2008-12-19 06:00:48 UTC (rev 5779) +++ trunk/jython/src/org/python/core/AbstractArray.java 2008-12-19 07:13:56 UTC (rev 5780) @@ -533,7 +533,7 @@ * @see java.lang.Object#toString() */ public String toString() { - StringBuffer buf = new StringBuffer(); + StringBuilder buf = new StringBuilder(); buf.append("["); Object base = getArray(); Modified: trunk/jython/src/org/python/core/BaseSet.java =================================================================== --- trunk/jython/src/org/python/core/BaseSet.java 2008-12-19 06:00:48 UTC (rev 5779) +++ trunk/jython/src/org/python/core/BaseSet.java 2008-12-19 07:13:56 UTC (rev 5780) @@ -387,7 +387,7 @@ if (!ts.enterRepr(this)) { return name + "(...)"; } - StringBuffer buf = new StringBuffer(name).append("(["); + StringBuilder buf = new StringBuilder(name).append("(["); for (Iterator i = _set.iterator(); i.hasNext();) { buf.append(((PyObject)i.next()).__repr__().toString()); if (i.hasNext()) { Modified: trunk/jython/src/org/python/core/Py.java =================================================================== --- trunk/jython/src/org/python/core/Py.java 2008-12-19 06:00:48 UTC (rev 5779) +++ trunk/jython/src/org/python/core/Py.java 2008-12-19 07:13:56 UTC (rev 5780) @@ -1056,7 +1056,7 @@ } static String formatException(PyObject type, PyObject value, PyObject tb) { - StringBuffer buf = new StringBuffer(); + StringBuilder buf = new StringBuilder(); if (PyException.isExceptionClass(type)) { String className = PyException.exceptionClassName(type); Modified: trunk/jython/src/org/python/core/PyDictionary.java =================================================================== --- trunk/jython/src/org/python/core/PyDictionary.java 2008-12-19 06:00:48 UTC (rev 5779) +++ trunk/jython/src/org/python/core/PyDictionary.java 2008-12-19 07:13:56 UTC (rev 5780) @@ -187,7 +187,7 @@ return "{...}"; } - StringBuffer buf = new StringBuffer("{"); + StringBuilder buf = new StringBuilder("{"); for (Entry<PyObject, PyObject> entry : table.entrySet()) { buf.append((entry.getKey()).__repr__().toString()); Modified: trunk/jython/src/org/python/core/PyFile.java =================================================================== --- trunk/jython/src/org/python/core/PyFile.java 2008-12-19 06:00:48 UTC (rev 5779) +++ trunk/jython/src/org/python/core/PyFile.java 2008-12-19 07:13:56 UTC (rev 5780) @@ -490,7 +490,7 @@ @ExposedMethod(names = {"__str__", "__repr__"}) final String file_toString() { - StringBuffer s = new StringBuffer("<"); + StringBuilder s = new StringBuilder("<"); if (file.closed()) { s.append("closed "); } else { Modified: trunk/jython/src/org/python/core/PyInstance.java =================================================================== --- trunk/jython/src/org/python/core/PyInstance.java 2008-12-19 06:00:48 UTC (rev 5779) +++ trunk/jython/src/org/python/core/PyInstance.java 2008-12-19 07:13:56 UTC (rev 5780) @@ -1,6 +1,5 @@ // Copyright (c) Corporation for National Research Initiatives package org.python.core; -import java.util.Hashtable; /** * A python class instance. @@ -76,8 +75,6 @@ public PyInstance() {} - private static Hashtable primitiveMap; - public Object __tojava__(Class c) { if (c.isInstance(this)) return this; Modified: trunk/jython/src/org/python/core/PyList.java =================================================================== --- trunk/jython/src/org/python/core/PyList.java 2008-12-19 06:00:48 UTC (rev 5779) +++ trunk/jython/src/org/python/core/PyList.java 2008-12-19 07:13:56 UTC (rev 5780) @@ -417,7 +417,7 @@ if(!ts.enterRepr(this)) { return "[...]"; } - StringBuffer buf = new StringBuffer("["); + StringBuilder buf = new StringBuilder("["); int length = size(); PyObject[] array = getArray(); for(int i = 0; i < length - 1; i++) { Modified: trunk/jython/src/org/python/core/PyStringMap.java =================================================================== --- trunk/jython/src/org/python/core/PyStringMap.java 2008-12-19 06:00:48 UTC (rev 5779) +++ trunk/jython/src/org/python/core/PyStringMap.java 2008-12-19 07:13:56 UTC (rev 5780) @@ -131,7 +131,7 @@ if (!ts.enterRepr(this)) { return "{...}"; } - StringBuffer buf = new StringBuffer("{"); + StringBuilder buf = new StringBuilder("{"); for (Entry<Object, PyObject> entry : table.entrySet()) { Object key = entry.getKey(); if (key instanceof String) { Modified: trunk/jython/src/org/python/core/PySystemState.java =================================================================== --- trunk/jython/src/org/python/core/PySystemState.java 2008-12-19 06:00:48 UTC (rev 5779) +++ trunk/jython/src/org/python/core/PySystemState.java 2008-12-19 07:13:56 UTC (rev 5780) @@ -7,8 +7,7 @@ import java.net.URL; import java.net.URLDecoder; import java.security.AccessControlException; -import java.util.Enumeration; -import java.util.Hashtable; +import java.util.HashMap; import java.util.Map; import java.util.Properties; import java.util.StringTokenizer; @@ -72,7 +71,7 @@ "Amsterdam.\n" + "All Rights Reserved.\n\n"); - private static Hashtable builtinNames; + private static Map<String,String> builtinNames; public static PyTuple builtin_module_names = null; public static PackageManager packageManager; @@ -160,22 +159,13 @@ __displayhook__ = new PySystemStateFunctions("displayhook", 10, 1, 1); __excepthook__ = new PySystemStateFunctions("excepthook", 30, 3, 3); - // This isn't quite right... if(builtins == null){ builtins = new PyStringMap(); __builtin__.fillWithBuiltins(builtins); } PyModule __builtin__ = new PyModule("__builtin__", builtins); modules.__setitem__("__builtin__", __builtin__); - __dict__ = new PyStringMap(); - - // This isn't right either, because __dict__ can be directly - // accessed from Python, for example: - // - // >>> sys.__dict__['settrace'] - // <java function settrace 81> - __dict__.invoke("update", getType().fastGetDict()); __dict__.__setitem__("displayhook", __displayhook__); __dict__.__setitem__("excepthook", __excepthook__); @@ -707,7 +697,7 @@ } private static void initBuiltins(Properties props) { - builtinNames = new Hashtable(); + builtinNames = new HashMap<String,String>(); // add the oddball builtins that are specially handled builtinNames.put("__builtin__", ""); @@ -724,10 +714,11 @@ addBuiltin(tok.nextToken()); int n = builtinNames.size(); - PyObject [] built_mod = new PyObject[n]; - Enumeration keys = builtinNames.keys(); - for (int i=0; i<n; i++) - built_mod[i] = Py.newString((String)keys.nextElement()); + PyObject [] built_mod = new PyObject[n]; + int i = 0; + for (String key : builtinNames.keySet()) { + built_mod[i++] = Py.newString(key); + } builtin_module_names = new PyTuple(built_mod); } Modified: trunk/jython/src/org/python/core/PyTraceback.java =================================================================== --- trunk/jython/src/org/python/core/PyTraceback.java 2008-12-19 06:00:48 UTC (rev 5779) +++ trunk/jython/src/org/python/core/PyTraceback.java 2008-12-19 07:13:56 UTC (rev 5780) @@ -101,7 +101,7 @@ return line; } - public void dumpStack(StringBuffer buf) { + public void dumpStack(StringBuilder buf) { buf.append(tracebackInfo()); if (tb_next != Py.None && tb_next != this) { ((PyTraceback)tb_next).dumpStack(buf); @@ -111,7 +111,7 @@ } public String dumpStack() { - StringBuffer buf = new StringBuffer(); + StringBuilder buf = new StringBuilder(); buf.append("Traceback (most recent call last):\n"); dumpStack(buf); return buf.toString(); Modified: trunk/jython/src/org/python/core/PyTuple.java =================================================================== --- trunk/jython/src/org/python/core/PyTuple.java 2008-12-19 06:00:48 UTC (rev 5779) +++ trunk/jython/src/org/python/core/PyTuple.java 2008-12-19 07:13:56 UTC (rev 5780) @@ -272,7 +272,7 @@ @ExposedMethod final String tuple___repr__() { - StringBuffer buf = new StringBuffer("("); + StringBuilder buf = new StringBuilder("("); PyObject[] array = getArray(); int arrayLen = size(); for (int i = 0; i < arrayLen-1; i++) { Modified: trunk/jython/src/org/python/core/PyType.java =================================================================== --- trunk/jython/src/org/python/core/PyType.java 2008-12-19 06:00:48 UTC (rev 5779) +++ trunk/jython/src/org/python/core/PyType.java 2008-12-19 07:13:56 UTC (rev 5780) @@ -651,7 +651,7 @@ } private static PyException mro_error(PyObject[][] to_merge, int[] remain) { - StringBuffer msg = new StringBuffer("Cannot create a consistent method resolution\n" + StringBuilder msg = new StringBuilder("Cannot create a consistent method resolution\n" + "order (MRO) for bases "); PyDictionary set = new PyDictionary(); for (int i = 0; i < to_merge.length; i++) { Modified: trunk/jython/src/org/python/core/imp.java =================================================================== --- trunk/jython/src/org/python/core/imp.java 2008-12-19 06:00:48 UTC (rev 5779) +++ trunk/jython/src/org/python/core/imp.java 2008-12-19 07:13:56 UTC (rev 5780) @@ -503,7 +503,7 @@ * @return the loaded module */ public static PyObject load(String name) { - return import_first(name, new StringBuffer()); + return import_first(name, new StringBuilder()); } /** @@ -560,7 +560,7 @@ * @return null or None */ private static PyObject import_next(PyObject mod, - StringBuffer parentNameBuffer, String name, String outerFullName, PyObject fromlist) { + StringBuilder parentNameBuffer, String name, String outerFullName, PyObject fromlist) { if (parentNameBuffer.length() > 0) { parentNameBuffer.append('.'); } @@ -594,7 +594,7 @@ // never returns null or None private static PyObject import_first(String name, - StringBuffer parentNameBuffer) { + StringBuilder parentNameBuffer) { PyObject ret = import_next(null, parentNameBuffer, name, null, null); if (ret == null || ret == Py.None) { throw Py.ImportError("No module named " + name); @@ -603,7 +603,7 @@ } - private static PyObject import_first(String name, StringBuffer parentNameBuffer, String fullName, PyObject fromlist) { + private static PyObject import_first(String name, StringBuilder parentNameBuffer, String fullName, PyObject fromlist) { PyObject ret = import_next(null, parentNameBuffer, name, fullName, fromlist); if (ret == null || ret == Py.None) { if (JavaImportHelper.tryAddPackage(fullName, fromlist)) { @@ -621,7 +621,7 @@ // never returns null or None // ??pending: check if result is really a module/jpkg/jclass? private static PyObject import_logic(PyObject mod, - StringBuffer parentNameBuffer, String dottedName, String fullName, PyObject fromlist) { + StringBuilder parentNameBuffer, String dottedName, String fullName, PyObject fromlist) { int dot = 0; int last_dot = 0; @@ -673,7 +673,7 @@ } else { firstName = name.substring(0, dot); } - StringBuffer parentNameBuffer = new StringBuffer(pkgMod != null ? pkgName : ""); + StringBuilder parentNameBuffer = new StringBuilder(pkgMod != null ? pkgName : ""); PyObject topMod = import_next(pkgMod, parentNameBuffer, firstName, name, fromlist); if (topMod == Py.None || topMod == null) { // Add None to sys.modules for submodule or subpackage names that aren't found, but @@ -682,7 +682,7 @@ if (topMod == null && pkgMod != null) { modules.__setitem__(parentNameBuffer.toString().intern(), Py.None); } - parentNameBuffer = new StringBuffer(""); + parentNameBuffer = new StringBuilder(""); // could throw ImportError topMod = import_first(firstName, parentNameBuffer, name, fromlist); } @@ -697,7 +697,7 @@ } if (fromlist != null && fromlist != Py.None) { - StringBuffer modNameBuffer = new StringBuffer(name); + StringBuilder modNameBuffer = new StringBuilder(name); for (PyObject submodName : fromlist.asIterable()) { if (mod.__findattr__(submodName.toString()) != null || submodName.toString().equals("*")) { Modified: trunk/jython/src/org/python/core/packagecache/CachedJarsPackageManager.java =================================================================== --- trunk/jython/src/org/python/core/packagecache/CachedJarsPackageManager.java 2008-12-19 06:00:48 UTC (rev 5779) +++ trunk/jython/src/org/python/core/packagecache/CachedJarsPackageManager.java 2008-12-19 07:13:56 UTC (rev 5780) @@ -20,8 +20,11 @@ import java.net.URLConnection; import java.security.AccessControlException; import java.util.Enumeration; -import java.util.Hashtable; -import java.util.Vector; +import java.util.HashMap; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; @@ -95,13 +98,13 @@ private boolean indexModified; - private Hashtable jarfiles; + private Map<String,JarXEntry> jarfiles; - private static String vectorToString(Vector vec) { + private static String vectorToString(List vec) { int n = vec.size(); - StringBuffer ret = new StringBuffer(); + StringBuilder ret = new StringBuilder(); for (int i = 0; i < n; i++) { - ret.append((String) vec.elementAt(i)); + ret.append((String) vec.get(i)); if (i < n - 1) { ret.append(","); } @@ -111,7 +114,7 @@ // Add a single class from zipFile to zipPackages // Only add valid, public classes - private void addZipEntry(Hashtable zipPackages, ZipEntry entry, + private void addZipEntry(Map zipPackages, ZipEntry entry, ZipInputStream zip) throws IOException { String name = entry.getName(); // System.err.println("entry: "+name); @@ -139,22 +142,22 @@ return; } - Vector[] vec = (Vector[]) zipPackages.get(packageName); + List[] vec = (List[]) zipPackages.get(packageName); if (vec == null) { - vec = new Vector[] { new Vector(), new Vector() }; + vec = new ArrayList[] { new ArrayList(), new ArrayList() }; zipPackages.put(packageName, vec); } int access = checkAccess(zip); if ((access != -1) && !filterByAccess(name, access)) { - vec[0].addElement(className); + vec[0].add(className); } else { - vec[1].addElement(className); + vec[1].add(className); } } // Extract all of the packages in a single jarfile - private Hashtable getZipPackages(InputStream jarin) throws IOException { - Hashtable zipPackages = new Hashtable(); + private Map getZipPackages(InputStream jarin) throws IOException { + Map zipPackages = new HashMap(); ZipInputStream zip = new ZipInputStream(jarin); @@ -165,9 +168,8 @@ } // Turn each vector into a comma-separated String - for (Enumeration e = zipPackages.keys(); e.hasMoreElements();) { - Object key = e.nextElement(); - Vector[] vec = (Vector[]) zipPackages.get(key); + for (Object key : zipPackages.keySet()) { + List[] vec = (List[]) zipPackages.get(key); String classes = vectorToString(vec[0]); if (vec[1].size() > 0) { classes += '@' + vectorToString(vec[1]); @@ -245,7 +247,7 @@ return; } - Hashtable zipPackages = null; + Map zipPackages = null; long mtime = 0; String jarcanon = null; @@ -327,10 +329,10 @@ } - private void addPackages(Hashtable zipPackages, String jarfile) { - for (Enumeration e = zipPackages.keys(); e.hasMoreElements();) { - String pkg = (String) e.nextElement(); - String classes = (String) zipPackages.get(pkg); + private void addPackages(Map<String,String> zipPackages, String jarfile) { + for (Entry<String,String> entry : zipPackages.entrySet()) { + String pkg = entry.getKey(); + String classes = entry.getValue(); int idx = classes.indexOf('@'); if (idx >= 0 && Options.respectJavaAccessibility) { @@ -343,7 +345,7 @@ // Read in cache file storing package info for a single .jar // Return null and delete this cachefile if it is invalid - private Hashtable readCacheFile(JarXEntry entry, String jarcanon) { + private Map readCacheFile(JarXEntry entry, String jarcanon) { String cachefile = entry.cachefile; long mtime = entry.mtime; @@ -359,7 +361,7 @@ deleteCacheFile(cachefile); return null; } - Hashtable packs = new Hashtable(); + Map packs = new HashMap(); try { while (true) { String packageName = istream.readUTF(); @@ -380,16 +382,15 @@ // Write a cache file storing package info for a single .jar private void writeCacheFile(JarXEntry entry, String jarcanon, - Hashtable zipPackages, boolean brandNew) { + Map<String,String> zipPackages, boolean brandNew) { try { DataOutputStream ostream = outCreateCacheFile(entry, brandNew); ostream.writeUTF(jarcanon); ostream.writeLong(entry.mtime); comment("rewriting cachefile for '" + jarcanon + "'"); - for (Enumeration e = zipPackages.keys(); e.hasMoreElements();) { - String packageName = (String) e.nextElement(); - String classes = (String) zipPackages.get(packageName); + for (String packageName : zipPackages.keySet()) { + String classes = zipPackages.get(packageName); ostream.writeUTF(packageName); ostream.writeUTF(classes); } @@ -405,7 +406,7 @@ */ protected void initCache() { this.indexModified = false; - this.jarfiles = new Hashtable(); + this.jarfiles = new HashMap(); try { DataInputStream istream = inOpenIndex(); @@ -436,22 +437,22 @@ * outOpenIndex(). */ public void saveCache() { - if (this.jarfiles == null || !this.indexModified) { + if (jarfiles == null || !indexModified) { return; } - this.indexModified = false; + indexModified = false; comment("writing modified index file"); try { DataOutputStream ostream = outOpenIndex(); - for (Enumeration e = this.jarfiles.keys(); e.hasMoreElements();) { - String jarcanon = (String) e.nextElement(); - JarXEntry entry = (JarXEntry) this.jarfiles.get(jarcanon); + for (Entry<String,JarXEntry> entry : jarfiles.entrySet()) { + String jarcanon = entry.getKey(); + JarXEntry xentry = entry.getValue(); ostream.writeUTF(jarcanon); - ostream.writeUTF(entry.cachefile); - ostream.writeLong(entry.mtime); + ostream.writeUTF(xentry.cachefile); + ostream.writeLong(xentry.mtime); } ostream.close(); } catch (IOException ioe) { Modified: trunk/jython/src/org/python/modules/_collections/PyDeque.java =================================================================== --- trunk/jython/src/org/python/modules/_collections/PyDeque.java 2008-12-19 06:00:48 UTC (rev 5779) +++ trunk/jython/src/org/python/modules/_collections/PyDeque.java 2008-12-19 07:13:56 UTC (rev 5780) @@ -228,7 +228,7 @@ if (!ts.enterRepr(this)) { return "[...]"; } - StringBuffer buf = new StringBuffer("deque").append("(["); + StringBuilder buf = new StringBuilder("deque").append("(["); for (Node tmp = header.right; tmp != header; tmp = tmp.right) { buf.append(tmp.data.__repr__().toString()); if (tmp.right != header) { Modified: trunk/jython/src/org/python/modules/_weakref/GlobalRef.java =================================================================== --- trunk/jython/src/org/python/modules/_weakref/GlobalRef.java 2008-12-19 06:00:48 UTC (rev 5779) +++ trunk/jython/src/org/python/modules/_weakref/GlobalRef.java 2008-12-19 07:13:56 UTC (rev 5780) @@ -4,9 +4,10 @@ import java.lang.ref.Reference; import java.lang.ref.ReferenceQueue; import java.lang.ref.WeakReference; +import java.util.ArrayList; import java.util.HashMap; import java.util.Map; -import java.util.Vector; +import java.util.List; import org.python.core.Py; import org.python.core.PyException; @@ -20,7 +21,7 @@ /** Whether the hash value was calculated by the underlying object. */ boolean realHash; - private Vector references = new Vector(); + private List references = new ArrayList(); private static ReferenceQueue referenceQueue = new ReferenceQueue(); @@ -59,11 +60,11 @@ public synchronized void add(AbstractReference ref) { Reference r = new WeakReference(ref); - references.addElement(r); + references.add(r); } private final AbstractReference getReferenceAt(int idx) { - WeakReference wref = (WeakReference)references.elementAt(idx); + WeakReference wref = (WeakReference)references.get(idx); return (AbstractReference)wref.get(); } @@ -75,7 +76,7 @@ for (int i = references.size() - 1; i >= 0; i--) { AbstractReference r = getReferenceAt(i); if (r == null) { - references.removeElementAt(i); + references.remove(i); } else if (r.callback == null && r.getClass() == cls) { return r; } @@ -90,7 +91,7 @@ for (int i = references.size() - 1; i >= 0; i--) { AbstractReference r = getReferenceAt(i); if (r == null) { - references.removeElementAt(i); + references.remove(i); } else { r.call(); } @@ -101,20 +102,20 @@ for (int i = references.size() - 1; i >= 0; i--) { AbstractReference r = getReferenceAt(i); if (r == null) { - references.removeElementAt(i); + references.remove(i); } } return references.size(); } synchronized public PyList refs() { - Vector list = new Vector(); + List list = new ArrayList(); for (int i = references.size() - 1; i >= 0; i--) { AbstractReference r = getReferenceAt(i); if (r == null) { - references.removeElementAt(i); + references.remove(i); } else { - list.addElement(r); + list.add(r); } } return new PyList(list); Modified: trunk/jython/src/org/python/modules/binascii.java =================================================================== --- trunk/jython/src/org/python/modules/binascii.java 2008-12-19 06:00:48 UTC (rev 5779) +++ trunk/jython/src/org/python/modules/binascii.java 2008-12-19 07:13:56 UTC (rev 5780) @@ -279,7 +279,7 @@ if (ascii_data.length() == 0) return new PyString(""); - StringBuffer bin_data = new StringBuffer(); + StringBuilder bin_data = new StringBuilder(); char this_ch; int i; @@ -357,7 +357,7 @@ throw new PyException(Error, "At most 45 bytes at once"); } - StringBuffer ascii_data = new StringBuffer(); + StringBuilder ascii_data = new StringBuilder(); // Store the length */ ascii_data.append((char)(' ' + (bin_len & 077))); @@ -426,7 +426,7 @@ int ascii_len = ascii_data.length(); int bin_len = 0; - StringBuffer bin_data = new StringBuffer(); + StringBuilder bin_data = new StringBuilder(); for(int i = 0; ascii_len > 0 ; ascii_len--, i++) { // Skip some punctuation @@ -487,7 +487,7 @@ char this_ch; int leftchar = 0; - StringBuffer ascii_data = new StringBuffer(); + StringBuilder ascii_data = new StringBuilder(); int bin_len = bin_data.length(); if (bin_len > BASE64_MAXBIN) { @@ -539,7 +539,7 @@ int len = ascii_data.length(); - StringBuffer bin_data = new StringBuffer(); + StringBuilder bin_data = new StringBuilder(); for(int i = 0; len > 0 ; len--, i++) { // Get the byte and look it up @@ -585,7 +585,7 @@ static public String rlecode_hqx(String in_data) { int len = in_data.length(); - StringBuffer out_data = new StringBuffer(); + StringBuilder out_data = new StringBuilder(); for (int in=0; in < len; in++) { char ch = in_data.charAt(in); @@ -632,7 +632,7 @@ int len = bin_data.length(); - StringBuffer ascii_data = new StringBuffer(); + StringBuilder ascii_data = new StringBuilder(); for(int i = 0; len > 0; len--, i++) { // Shift into our buffer, and output any 6bits ready @@ -677,7 +677,7 @@ if (in_len == 0) return ""; - StringBuffer out_data = new StringBuffer(); + StringBuilder out_data = new StringBuilder(); // Handle first byte separately (since we have to get angry // in case of an orphaned RLE code). @@ -837,7 +837,7 @@ public static PyString b2a_hex(String argbuf) { int arglen = argbuf.length(); - StringBuffer retbuf = new StringBuffer(arglen*2); + StringBuilder retbuf = new StringBuilder(arglen*2); /* make hex version of string, taken from shamodule.c */ for (int i = 0; i < arglen; i++) { @@ -874,7 +874,7 @@ if (arglen % 2 != 0) throw Py.TypeError("Odd-length string"); - StringBuffer retbuf = new StringBuffer(arglen/2); + StringBuilder retbuf = new StringBuilder(arglen/2); for (int i = 0; i < arglen; i += 2) { int top = Character.digit(argbuf.charAt(i), 16); @@ -893,7 +893,7 @@ final private static char[] upper_hexdigit = "0123456789ABCDEF".toCharArray(); - private static StringBuffer qpEscape(StringBuffer sb, char c) + private static StringBuilder qpEscape(StringBuilder sb, char c) { sb.append('='); sb.append(upper_hexdigit[(c >>> 4) & 0xF]); @@ -921,7 +921,7 @@ { ArgParser ap = new ArgParser("a2b_qp", arg, kws, new String[] {"s", "header"}); String s = ap.getString(0); - StringBuffer sb = new StringBuffer(); + StringBuilder sb = new StringBuilder(); boolean header = getIntFlagAsBool(ap, 1, 0, "an integer is required"); if (header) @@ -979,7 +979,7 @@ lineEnd = "\n"; s = RN_TO_N.matcher(s).replaceAll("\n"); } - StringBuffer sb = new StringBuffer(); + StringBuilder sb = new StringBuilder(); int count = 0; for (int i=0, m=s.length(); i<m; i++) { char c = s.charAt(i); Modified: trunk/jython/src/org/python/modules/cPickle.java =================================================================== --- trunk/jython/src/org/python/modules/cPickle.java 2008-12-19 06:00:48 UTC (rev 5779) +++ trunk/jython/src/org/python/modules/cPickle.java 2008-12-19 07:13:56 UTC (rev 5780) @@ -13,7 +13,8 @@ package org.python.modules; import java.math.BigInteger; -import java.util.Hashtable; +import java.util.HashMap; +import java.util.Map; import org.python.core.ClassDictInit; import org.python.core.Py; @@ -746,7 +747,7 @@ // Use any python object as a file. static class ObjectIOFile implements IOFile { char[] charr = new char[1]; - StringBuffer buff = new StringBuffer(); + StringBuilder buff = new StringBuilder(); PyObject write; PyObject read; PyObject readline; @@ -1514,12 +1515,12 @@ - private static Hashtable classmap = new Hashtable(); + private static Map<PyObject,PyObject> classmap = new HashMap<PyObject,PyObject>(); final private static PyObject whichmodule(PyObject cls, PyObject clsname) { - PyObject name = (PyObject)classmap.get(cls); + PyObject name = classmap.get(cls); if (name != null) return name; @@ -1704,7 +1705,7 @@ private IOFile file; - public Hashtable memo = new Hashtable(); + public Map<String,PyObject> memo = new HashMap<String,PyObject>(); /** * For the benefit of persistency modules written using pickle, @@ -2193,7 +2194,7 @@ final private void load_get() { String py_str = file.readlineNoNl(); - PyObject value = (PyObject)memo.get(py_str); + PyObject value = memo.get(py_str); if (value == null) throw new PyException(BadPickleGet, py_str); push(value); @@ -2201,7 +2202,7 @@ final private void load_binget() { String py_key = String.valueOf((int)file.read(1).charAt(0)); - PyObject value = (PyObject)memo.get(py_key); + PyObject value = memo.get(py_key); if (value == null) throw new PyException(BadPickleGet, py_key); push(value); @@ -2210,7 +2211,7 @@ final private void load_long_binget() { int i = read_binint(); String py_key = String.valueOf(i); - PyObject value = (PyObject)memo.get(py_key); + PyObject value = memo.get(py_key); if (value == null) throw new PyException(BadPickleGet, py_key); push(value); Modified: trunk/jython/src/org/python/modules/sre/PatternObject.java =================================================================== --- trunk/jython/src/org/python/modules/sre/PatternObject.java 2008-12-19 06:00:48 UTC (rev 5779) +++ trunk/jython/src/org/python/modules/sre/PatternObject.java 2008-12-19 07:13:56 UTC (rev 5780) @@ -246,7 +246,7 @@ SRE_STATE state = new SRE_STATE(string, start, end, flags); - Vector list = new Vector(); + final List list = new ArrayList(); while (state.start <= state.end) { state.state_reset(); @@ -271,7 +271,7 @@ break; } - list.addElement(item); + list.add(item); if (state.ptr == state.start) state.start = state.ptr + 1; Modified: trunk/jython/src/org/python/modules/time/Time.java =================================================================== --- trunk/jython/src/org/python/modules/time/Time.java 2008-12-19 06:00:48 UTC (rev 5779) +++ trunk/jython/src/org/python/modules/time/Time.java 2008-12-19 07:13:56 UTC (rev 5780) @@ -411,7 +411,7 @@ } public static PyString asctime(PyTuple tup) { - StringBuffer buf = new StringBuffer(25); + StringBuilder buf = new StringBuilder(25); buf.append(enshortdays[item(tup, 6)]).append(' '); buf.append(enshortmonths[item(tup, 1)]).append(' '); int dayOfMonth = item(tup, 2); Modified: trunk/jython/src/org/python/modules/ucnhash.java =================================================================== --- trunk/jython/src/org/python/modules/ucnhash.java 2008-12-19 06:00:48 UTC (rev 5779) +++ trunk/jython/src/org/python/modules/ucnhash.java 2008-12-19 07:13:56 UTC (rev 5780) @@ -163,7 +163,7 @@ int end = worddata.length; if (idx < wordoffs.length-1) end = wordoffs[idx+1]; - StringBuffer buf = new StringBuffer(); + StringBuilder buf = new StringBuilder(); for (int i = offset; i < end; i++) buf.append(charmap[worddata[i]]); return buf.toString(); This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <cg...@us...> - 2008-12-31 22:55:19
|
Revision: 5819 http://jython.svn.sourceforge.net/jython/?rev=5819&view=rev Author: cgroves Date: 2008-12-31 21:36:03 +0000 (Wed, 31 Dec 2008) Log Message: ----------- Abbreviating package to pkg makes it sound like it's going in a field named pkg. Modified Paths: -------------- trunk/jython/src/org/python/core/ClasspathPyImporter.java trunk/jython/src/org/python/core/util/importer.java trunk/jython/src/org/python/modules/zipimport/zipimporter.java Modified: trunk/jython/src/org/python/core/ClasspathPyImporter.java =================================================================== --- trunk/jython/src/org/python/core/ClasspathPyImporter.java 2008-12-30 21:09:17 UTC (rev 5818) +++ trunk/jython/src/org/python/core/ClasspathPyImporter.java 2008-12-31 21:36:03 UTC (rev 5819) @@ -110,7 +110,7 @@ } @Override - protected String makePkgPath(String fullname) { + protected String makePackagePath(String fullname) { return path; } Modified: trunk/jython/src/org/python/core/util/importer.java =================================================================== --- trunk/jython/src/org/python/core/util/importer.java 2008-12-30 21:09:17 UTC (rev 5818) +++ trunk/jython/src/org/python/core/util/importer.java 2008-12-31 21:36:03 UTC (rev 5819) @@ -46,7 +46,7 @@ * Returns the value to fill in __path__ on a module with the given full module name created by * this importer. */ - protected abstract String makePkgPath(String fullname); + protected abstract String makePackagePath(String fullname); /** * Given a full module name, return the potential file path in the archive (without extension). @@ -95,7 +95,7 @@ if (moduleCodeData.ispackage) { // add __path__ to the module *before* the code gets executed PyList pkgpath = new PyList(); - pkgpath.add(makePkgPath(fullname)); + pkgpath.add(makePackagePath(fullname)); mod.__dict__.__setitem__("__path__", pkgpath); } imp.createFromCode(fullname, moduleCodeData.code, moduleCodeData.path); @@ -155,7 +155,7 @@ */ protected final ModuleCodeData getModuleCode(String fullname) { String path = makeFilename(fullname); - String fullPath = makePkgPath(fullname); + String fullPath = makePackagePath(fullname); if (path.length() < 0) { return null; Modified: trunk/jython/src/org/python/modules/zipimport/zipimporter.java =================================================================== --- trunk/jython/src/org/python/modules/zipimport/zipimporter.java 2008-12-30 21:09:17 UTC (rev 5818) +++ trunk/jython/src/org/python/modules/zipimport/zipimporter.java 2008-12-31 21:36:03 UTC (rev 5819) @@ -418,7 +418,7 @@ } @Override - protected String makePkgPath(String fullname) { + protected String makePackagePath(String fullname) { return archive + File.separator + prefix + getSubname(fullname); } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <cg...@us...> - 2009-01-21 21:26:59
|
Revision: 5954 http://jython.svn.sourceforge.net/jython/?rev=5954&view=rev Author: cgroves Date: 2009-01-21 21:26:50 +0000 (Wed, 21 Jan 2009) Log Message: ----------- Turn includeJavaStackInExceptions on by default as it was always done in previous versions. Modified Paths: -------------- trunk/jython/src/org/python/compiler/JavaMaker.java trunk/jython/src/org/python/core/Options.java trunk/jython/src/org/python/util/jython.java Modified: trunk/jython/src/org/python/compiler/JavaMaker.java =================================================================== --- trunk/jython/src/org/python/compiler/JavaMaker.java 2009-01-21 20:47:19 UTC (rev 5953) +++ trunk/jython/src/org/python/compiler/JavaMaker.java 2009-01-21 21:26:50 UTC (rev 5954) @@ -46,13 +46,12 @@ super.addProxy(); // _initProxy method - Code code = classfile.addMethod("__initProxy__", - "([Ljava/lang/Object;)V", Modifier.PUBLIC); + Code code = classfile.addMethod("__initProxy__", "([Ljava/lang/Object;)V", Modifier.PUBLIC); code.visitVarInsn(ALOAD, 0); code.visitLdcInsn(pythonModule); code.visitLdcInsn(pythonClass); - + code.visitVarInsn(ALOAD, 1); code.visitMethodInsn(INVOKESTATIC, "org/python/core/Py", "initProxy", "(" + $pyProxy + $str + $str + $objArr + ")V"); code.visitInsn(RETURN); Modified: trunk/jython/src/org/python/core/Options.java =================================================================== --- trunk/jython/src/org/python/core/Options.java 2009-01-21 20:47:19 UTC (rev 5953) +++ trunk/jython/src/org/python/core/Options.java 2009-01-21 21:26:50 UTC (rev 5954) @@ -21,7 +21,7 @@ * trace in addition to the Python traceback. This can slow raising * considerably. */ - public static boolean includeJavaStackInExceptions = false; + public static boolean includeJavaStackInExceptions = true; /** * When true, python exception raised in overridden methods will be shown on @@ -63,7 +63,7 @@ * A directory where the dynamically generated classes are written. Nothing is * ever read from here, it is only for debugging purposes. */ - public static String proxyDebugDirectory = null; + public static String proxyDebugDirectory; /** * If true, Jython will use the first module found on sys.path where java Modified: trunk/jython/src/org/python/util/jython.java =================================================================== --- trunk/jython/src/org/python/util/jython.java 2009-01-21 20:47:19 UTC (rev 5953) +++ trunk/jython/src/org/python/util/jython.java 2009-01-21 21:26:50 UTC (rev 5954) @@ -7,6 +7,7 @@ import java.io.InputStream; import java.nio.charset.Charset; import java.util.List; +import java.util.Properties; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; @@ -131,8 +132,7 @@ } // Setup the basic python system state from these options - PySystemState.initialize(PySystemState.getBaseProperties(), - opts.properties, opts.argv); + PySystemState.initialize(PySystemState.getBaseProperties(), opts.properties, opts.argv); // Now create an interpreter InteractiveConsole interp = newInterpreter(); @@ -339,7 +339,7 @@ public boolean fixInteractive; public boolean help, version; public String[] argv; - public java.util.Properties properties; + public Properties properties; public String command; public List<String> warnoptions = Generic.list(); public String encoding; @@ -351,7 +351,7 @@ jar = fixInteractive = false; interactive = notice = true; runModule = false; - properties = new java.util.Properties(); + properties = new Properties(); help = version = false; } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <zy...@us...> - 2009-03-07 04:05:17
|
Revision: 6078 http://jython.svn.sourceforge.net/jython/?rev=6078&view=rev Author: zyasoft Date: 2009-03-07 04:05:04 +0000 (Sat, 07 Mar 2009) Log Message: ----------- Now uses CompilerFlags instead of the co_flags bit vector uniformly in the code. This change enables more programmatic direction of the compiler, including at the very least the desired compiler (once we include more than one!). Removed unnecessary fields in PyFrame that supported the former newcompiler. Made public some additional PyUnicode constructors to support the Java version of unicodedata, whenever that happens. Fixed a memory leak in PyBytecode. Modified Paths: -------------- trunk/jython/src/org/python/core/CompilerFlags.java trunk/jython/src/org/python/core/Py.java trunk/jython/src/org/python/core/PyBaseCode.java trunk/jython/src/org/python/core/PyBytecode.java trunk/jython/src/org/python/core/PyFrame.java trunk/jython/src/org/python/core/PyTableCode.java trunk/jython/src/org/python/core/PyUnicode.java trunk/jython/src/org/python/core/__builtin__.java trunk/jython/src/org/python/modules/_marshal.java Modified: trunk/jython/src/org/python/core/CompilerFlags.java =================================================================== --- trunk/jython/src/org/python/core/CompilerFlags.java 2009-03-06 22:18:24 UTC (rev 6077) +++ trunk/jython/src/org/python/core/CompilerFlags.java 2009-03-07 04:05:04 UTC (rev 6078) @@ -1,3 +1,6 @@ +// At some future point this will also be extended - in conjunction with Py#compileFlags - to add +// support for a compiler factory that user code can choose in place of the normal compiler. +// (Perhaps a better name might have been "CompilerOptions".) package org.python.core; @@ -5,6 +8,12 @@ private int co_flags; + public boolean optimized; + public boolean newlocals; + public boolean varargs; + public boolean varkeywords; + public boolean generator; + public boolean nested_scopes = true; public boolean division; public boolean generator_allowed = true; @@ -21,20 +30,26 @@ public CompilerFlags(int co_flags) { this.co_flags = co_flags; - nested_scopes = isEnabled(PyTableCode.CO_NESTED); - division = isEnabled(PyTableCode.CO_FUTUREDIVISION); - generator_allowed = isEnabled(PyTableCode.CO_GENERATOR_ALLOWED); - absolute_import = isEnabled(PyTableCode.CO_FUTURE_ABSOLUTE_IMPORT); - with_statement = isEnabled(PyTableCode.CO_WITH_STATEMENT); - only_ast = isEnabled(PyTableCode.PyCF_ONLY_AST); - dont_imply_dedent = isEnabled(PyTableCode.PyCF_DONT_IMPLY_DEDENT); - source_is_utf8 = isEnabled(PyTableCode.PyCF_SOURCE_IS_UTF8); + optimized = isEnabled(PyBaseCode.CO_OPTIMIZED); + newlocals = isEnabled(PyBaseCode.CO_NEWLOCALS); + varargs = isEnabled(PyBaseCode.CO_VARARGS); + varkeywords = isEnabled(PyBaseCode.CO_VARKEYWORDS); + generator = isEnabled(PyBaseCode.CO_GENERATOR); + nested_scopes = isEnabled(PyBaseCode.CO_NESTED); + division = isEnabled(PyBaseCode.CO_FUTUREDIVISION); + generator_allowed = isEnabled(PyBaseCode.CO_GENERATOR_ALLOWED); + absolute_import = isEnabled(PyBaseCode.CO_FUTURE_ABSOLUTE_IMPORT); + with_statement = isEnabled(PyBaseCode.CO_WITH_STATEMENT); + only_ast = isEnabled(PyBaseCode.PyCF_ONLY_AST); + dont_imply_dedent = isEnabled(PyBaseCode.PyCF_DONT_IMPLY_DEDENT); + source_is_utf8 = isEnabled(PyBaseCode.PyCF_SOURCE_IS_UTF8); } private boolean isEnabled(int codeConstant) { return (co_flags & codeConstant) != 0; } + @Override public String toString() { return String.format("CompilerFlags[division=%s nested_scopes=%s generators=%s " + "with_statement=%s absolute_import=%s only_ast=%s " @@ -43,4 +58,29 @@ dont_imply_dedent, source_is_utf8); } + public int toBits() { + return (optimized ? PyBaseCode.CO_OPTIMIZED : 0) | + (newlocals ? PyBaseCode.CO_NEWLOCALS : 0) | + (varargs ? PyBaseCode.CO_VARARGS : 0) | + (varkeywords ? PyBaseCode.CO_VARKEYWORDS : 0) | + (generator ? PyBaseCode.CO_GENERATOR : 0) | + (nested_scopes ? PyBaseCode.CO_NESTED : 0) | + (division ? PyBaseCode.CO_FUTUREDIVISION : 0) | + (generator_allowed ? PyBaseCode.CO_GENERATOR_ALLOWED : 0) | + (absolute_import ? PyBaseCode.CO_FUTURE_ABSOLUTE_IMPORT : 0) | + (with_statement ? PyBaseCode.CO_WITH_STATEMENT : 0) | + (only_ast ? PyBaseCode.PyCF_ONLY_AST : 0) | + (dont_imply_dedent ? PyBaseCode.PyCF_DONT_IMPLY_DEDENT : 0) | + (source_is_utf8 ? PyBaseCode.PyCF_SOURCE_IS_UTF8 : 0); + } + + // this will not strictly be an OR once we have other options, like a compiler factory + // in that case, we would assume + public CompilerFlags combine(CompilerFlags flags) { + return new CompilerFlags(this.toBits() | flags.toBits()); + } + + public CompilerFlags combine(int flags) { + return new CompilerFlags(this.toBits() | flags); + } } Modified: trunk/jython/src/org/python/core/Py.java =================================================================== --- trunk/jython/src/org/python/core/Py.java 2009-03-06 22:18:24 UTC (rev 6077) +++ trunk/jython/src/org/python/core/Py.java 2009-03-07 04:05:04 UTC (rev 6078) @@ -1613,7 +1613,7 @@ } else { PyFrame frame = Py.getFrame(); if (frame != null && frame.f_code != null) { - cflags = new CompilerFlags(frame.f_code.co_flags | flags); + cflags = frame.f_code.co_flags.combine(flags); } else { cflags = new CompilerFlags(flags); } @@ -1621,6 +1621,21 @@ return cflags; } + public static CompilerFlags getCompilerFlags(CompilerFlags flags, boolean dont_inherit) { + CompilerFlags cflags = null; + if (dont_inherit) { + cflags = flags; + } else { + PyFrame frame = Py.getFrame(); + if (frame != null && frame.f_code != null) { + cflags = frame.f_code.co_flags.combine(flags); + } else { + cflags = flags; + } + } + return cflags; + } + // w/o compiler-flags public static PyObject compile(InputStream istream, String filename, String kind) { return compile_flags(istream, filename, kind, new CompilerFlags()); Modified: trunk/jython/src/org/python/core/PyBaseCode.java =================================================================== --- trunk/jython/src/org/python/core/PyBaseCode.java 2009-03-06 22:18:24 UTC (rev 6077) +++ trunk/jython/src/org/python/core/PyBaseCode.java 2009-03-07 04:05:04 UTC (rev 6078) @@ -13,7 +13,7 @@ public int jy_npurecell; // internal: jython specific public String co_freevars[]; public String co_filename; - public int co_flags; + public CompilerFlags co_flags = new CompilerFlags(); public int co_nlocals; public boolean varargs, varkwargs; @@ -135,7 +135,7 @@ return call(Py.EmptyObjects, Py.NoKeywords, globals, defaults, closure); PyFrame frame = new PyFrame(this, globals); - if ((co_flags & CO_GENERATOR) != 0) { + if (co_flags.generator) { return new PyGenerator(frame, closure); } return call(frame, closure); @@ -149,7 +149,7 @@ Py.NoKeywords, globals, defaults, closure); PyFrame frame = new PyFrame(this, globals); frame.f_fastlocals[0] = arg1; - if ((co_flags & CO_GENERATOR) != 0) { + if (co_flags.generator) { return new PyGenerator(frame, closure); } return call(frame, closure); @@ -164,7 +164,7 @@ PyFrame frame = new PyFrame(this, globals); frame.f_fastlocals[0] = arg1; frame.f_fastlocals[1] = arg2; - if ((co_flags & CO_GENERATOR) != 0) { + if (co_flags.generator) { return new PyGenerator(frame, closure); } return call(frame, closure); @@ -181,7 +181,7 @@ frame.f_fastlocals[0] = arg1; frame.f_fastlocals[1] = arg2; frame.f_fastlocals[2] = arg3; - if ((co_flags & CO_GENERATOR) != 0) { + if (co_flags.generator) { return new PyGenerator(frame, closure); } return call(frame, closure); @@ -297,7 +297,7 @@ co_name, argcount)); } - if ((co_flags & CO_GENERATOR) != 0) { + if (co_flags.generator) { return new PyGenerator(frame, closure); } return call(frame, closure); @@ -313,4 +313,9 @@ protected int getline(PyFrame f) { return f.f_lineno; } + + // returns the augmented version of CompilerFlags (instead of just as a bit vector int) + public CompilerFlags getCompilerFlags() { + return co_flags; + } } Modified: trunk/jython/src/org/python/core/PyBytecode.java =================================================================== --- trunk/jython/src/org/python/core/PyBytecode.java 2009-03-06 22:18:24 UTC (rev 6077) +++ trunk/jython/src/org/python/core/PyBytecode.java 2009-03-07 04:05:04 UTC (rev 6078) @@ -74,9 +74,9 @@ co_cellvars = cellvars; co_freevars = freevars; co_name = name; - varargs = (flags & CO_VARARGS) != 0; - varkwargs = (flags & CO_VARKEYWORDS) != 0; - co_flags |= flags; + co_flags = new CompilerFlags(flags); + varargs = co_flags.varargs; + varkwargs = co_flags.varkeywords; co_stacksize = stacksize; co_consts = constants; @@ -156,6 +156,9 @@ if (name == "co_consts") { return new PyTuple(co_consts); } + if (name == "co_flags") { + return Py.newInteger(co_flags.toBits()); + } return super.__findattr_ex__(name); } @@ -201,11 +204,11 @@ } private static String stringify_blocks(PyFrame f) { - if (f.f_exits == null || f.f_blockstate[0] == 0) { + if (f.f_exits == null || f.f_lineno == 0) { return "[]"; } StringBuilder buf = new StringBuilder("["); - int len = f.f_blockstate[0]; + int len = f.f_lineno; for (int i = 0; i < len; i++) { buf.append(f.f_exits[i].toString()); if (i < len - 1) { @@ -227,21 +230,26 @@ } } + // the following code exploits the fact that f_exits and f_lineno are only used by code compiled to Java bytecode; + // in their place we implement the block stack for PBC-VM, as mapped below in the comments of pushBlock + private static PyTryBlock popBlock(PyFrame f) { - return (PyTryBlock) (f.f_exits[--f.f_blockstate[0]]); + PyTryBlock block = (PyTryBlock) (f.f_exits[--f.f_lineno]); + f.f_exits[f.f_lineno] = null; // ensure eventual GC of this reference + return block; } private static void pushBlock(PyFrame f, PyTryBlock block) { - if (f.f_exits == null) { // allocate in the frame where they can fit! consider supporting directly in the frame + if (f.f_exits == null) { // allocate in the frame where they can fit! TODO consider supporting directly in the frame f.f_exits = new PyObject[CO_MAXBLOCKS]; // f_blockstack in CPython - a simple ArrayList might be best - f.f_blockstate = new int[]{0}; // f_iblock in CPython - f_blockstate is likely go away soon + f.f_lineno = 0; // f_iblock in CPython } - f.f_exits[f.f_blockstate[0]++] = block; + f.f_exits[f.f_lineno++] = block; } private boolean blocksLeft(PyFrame f) { if (f.f_exits != null) { - return f.f_blockstate[0] > 0; + return f.f_lineno > 0; } else { return false; } @@ -414,7 +422,7 @@ PyObject b = stack.pop(); PyObject a = stack.pop(); - if ((co_flags & CO_FUTUREDIVISION) == 0) { + if (!co_flags.division) { stack.push(a._div(b)); } else { stack.push(a._truediv(b)); @@ -524,7 +532,7 @@ case Opcode.INPLACE_DIVIDE: { PyObject b = stack.pop(); PyObject a = stack.pop(); - if ((co_flags & CO_FUTUREDIVISION) == 0) { + if (!co_flags.division) { stack.push(a._idiv(b)); } else { stack.push(a._itruediv(b)); @@ -1242,7 +1250,7 @@ throw ts.exception; } - if ((co_flags & CO_GENERATOR) != 0 && why == Why.RETURN && retval == Py.None) { + if (co_flags.generator && why == Why.RETURN && retval == Py.None) { f.f_lasti = -1; } Modified: trunk/jython/src/org/python/core/PyFrame.java =================================================================== --- trunk/jython/src/org/python/core/PyFrame.java 2009-03-06 22:18:24 UTC (rev 6077) +++ trunk/jython/src/org/python/core/PyFrame.java 2009-03-07 04:05:04 UTC (rev 6078) @@ -31,12 +31,6 @@ public Object[] f_savedlocals; - /** newcompiler uses this to allow yield in loops. */ - public PyObject[] f_stackstate; - - /** newcompiler uses this to allow yield in finally. */ - public int[] f_blockstate; - private int env_j = 0; private Object generatorInput = Py.None; @@ -68,7 +62,7 @@ // This needs work to be efficient with multiple interpreter states if (locals == null && code != null) { // ! f_fastlocals needed for arg passing too - if ((code.co_flags & PyBaseCode.CO_OPTIMIZED) != 0 || code.nargs > 0) { + if (code.co_flags.optimized || code.nargs > 0) { if (code.co_nlocals > 0) { // internal: may change f_fastlocals = new PyObject[code.co_nlocals - code.jy_npurecell]; @@ -197,7 +191,7 @@ PyObject o = f_fastlocals[i]; if (o != null) f_locals.__setitem__(f_code.co_varnames[i], o); } - if ((f_code.co_flags & PyBaseCode.CO_OPTIMIZED) == 0) { + if (!f_code.co_flags.optimized) { f_fastlocals = null; } } Modified: trunk/jython/src/org/python/core/PyTableCode.java =================================================================== --- trunk/jython/src/org/python/core/PyTableCode.java 2009-03-06 22:18:24 UTC (rev 6077) +++ trunk/jython/src/org/python/core/PyTableCode.java 2009-03-07 04:05:04 UTC (rev 6078) @@ -45,14 +45,14 @@ co_name = name; if (varargs) { co_argcount -= 1; - co_flags |= CO_VARARGS; + co_flags.varargs = true; } this.varkwargs = varkwargs; if (varkwargs) { co_argcount -= 1; - co_flags |= CO_VARKEYWORDS; + co_flags.varkeywords = true; } - co_flags |= moreflags; + co_flags = new CompilerFlags(co_flags.toBits() | moreflags); this.funcs = funcs; this.func_id = func_id; } @@ -115,6 +115,9 @@ if (name == "co_name") { return new PyString(co_name); } + if (name == "co_flags") { + return Py.newInteger(co_flags.toBits()); + } return super.__findattr_ex__(name); } Modified: trunk/jython/src/org/python/core/PyUnicode.java =================================================================== --- trunk/jython/src/org/python/core/PyUnicode.java 2009-03-06 22:18:24 UTC (rev 6077) +++ trunk/jython/src/org/python/core/PyUnicode.java 2009-03-07 04:05:04 UTC (rev 6078) @@ -78,11 +78,11 @@ return buffer; } - PyUnicode(Iterator<Integer> iter) { + public PyUnicode(Iterator<Integer> iter) { this(fromCodePoints(iter)); } - PyUnicode(Collection<Integer> ucs4) { + public PyUnicode(Collection<Integer> ucs4) { this(ucs4.iterator()); } Modified: trunk/jython/src/org/python/core/__builtin__.java =================================================================== --- trunk/jython/src/org/python/core/__builtin__.java 2009-03-06 22:18:24 UTC (rev 6077) +++ trunk/jython/src/org/python/core/__builtin__.java 2009-03-07 04:05:04 UTC (rev 6078) @@ -1526,7 +1526,7 @@ public static PyObject compile(PyObject source, String filename, String mode, int flags, boolean dont_inherit) { - if ((flags & ~PyTableCode.CO_ALL_FEATURES) != 0) { + if ((flags & ~PyBaseCode.CO_ALL_FEATURES) != 0) { throw Py.ValueError("compile(): unrecognised flags"); } if (!mode.equals("exec") && !mode.equals("eval") && !mode.equals("single")) { @@ -1542,12 +1542,31 @@ throw Py.TypeError("expected a readable buffer object"); } if (source instanceof PyUnicode) { - flags |= PyTableCode.PyCF_SOURCE_IS_UTF8; + flags |= PyBaseCode.PyCF_SOURCE_IS_UTF8; } return Py.compile_flags(((PyString)source).toString(), filename, mode, Py.getCompilerFlags(flags, dont_inherit)); } + public static PyObject compile(PyObject source, String filename, String mode, CompilerFlags flags, + boolean dont_inherit) { + if (!mode.equals("exec") && !mode.equals("eval") && !mode.equals("single")) { + throw Py.ValueError("compile() arg 3 must be 'exec' or 'eval' or 'single'"); + } + + mod ast = py2node(source); + if (ast != null) { + return Py.compile_flags(ast, filename, mode, Py.getCompilerFlags(flags, dont_inherit)); + } + + if (!(source instanceof PyString)) { + throw Py.TypeError("expected a readable buffer object"); + } + flags.source_is_utf8 = source instanceof PyUnicode; + return Py.compile_flags(((PyString)source).toString(), filename, mode, + Py.getCompilerFlags(flags, dont_inherit)); + } + /** * @returns mod if obj is a wrapper around an AST mod else returns * null Modified: trunk/jython/src/org/python/modules/_marshal.java =================================================================== --- trunk/jython/src/org/python/modules/_marshal.java 2009-03-06 22:18:24 UTC (rev 6077) +++ trunk/jython/src/org/python/modules/_marshal.java 2009-03-07 04:05:04 UTC (rev 6078) @@ -226,7 +226,7 @@ write_int(code.co_argcount); write_int(code.co_nlocals); write_int(code.co_stacksize); - write_int(code.co_flags); + write_int(code.co_flags.toBits()); write_object(Py.newString(new String(code.co_code)), depth + 1); write_object(new PyTuple(code.co_consts), depth + 1); write_strings(code.co_names, depth + 1); This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <pj...@us...> - 2009-03-27 21:45:11
|
Revision: 6111 http://jython.svn.sourceforge.net/jython/?rev=6111&view=rev Author: pjenvey Date: 2009-03-27 21:44:57 +0000 (Fri, 27 Mar 2009) Log Message: ----------- reduce our CHMs' concurrencyLevel to 2 from 16 to reduce allocation. speeds up pybench by 10% Modified Paths: -------------- trunk/jython/src/org/python/core/PyDictionary.java trunk/jython/src/org/python/core/PySet.java trunk/jython/src/org/python/core/PyStringMap.java trunk/jython/src/org/python/modules/PyTeeIterator.java trunk/jython/src/org/python/util/Generic.java Modified: trunk/jython/src/org/python/core/PyDictionary.java =================================================================== --- trunk/jython/src/org/python/core/PyDictionary.java 2009-03-27 20:34:45 UTC (rev 6110) +++ trunk/jython/src/org/python/core/PyDictionary.java 2009-03-27 21:44:57 UTC (rev 6111) @@ -4,20 +4,19 @@ import java.util.AbstractSet; import java.util.ArrayList; import java.util.Collection; -import java.util.Hashtable; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; -import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentMap; -import java.util.concurrent.ConcurrentMap; import org.python.expose.ExposedClassMethod; import org.python.expose.ExposedMethod; import org.python.expose.ExposedNew; import org.python.expose.ExposedType; import org.python.expose.MethodType; +import org.python.util.Generic; /** @@ -34,7 +33,7 @@ * Create an empty dictionary. */ public PyDictionary() { - table = new ConcurrentHashMap<PyObject, PyObject>(); + table = Generic.concurrentMap(); } /** @@ -42,14 +41,15 @@ */ public PyDictionary(PyType subtype) { super(subtype); - table = new ConcurrentHashMap<PyObject, PyObject>(); + table = Generic.concurrentMap(); } /** * Create a new dictionary which is based on given map. */ public PyDictionary(Map<PyObject, PyObject> t) { - table = new ConcurrentHashMap<PyObject, PyObject>(t); + table = Generic.concurrentMap(); + table.putAll(t); } /** @@ -57,7 +57,8 @@ */ public PyDictionary(PyType subtype, Map<PyObject, PyObject> t) { super(subtype); - table = new ConcurrentHashMap<PyObject, PyObject>(t); + table = Generic.concurrentMap(); + table.putAll(t); } Modified: trunk/jython/src/org/python/core/PySet.java =================================================================== --- trunk/jython/src/org/python/core/PySet.java 2009-03-27 20:34:45 UTC (rev 6110) +++ trunk/jython/src/org/python/core/PySet.java 2009-03-27 21:44:57 UTC (rev 6111) @@ -2,12 +2,13 @@ import java.util.Iterator; import java.util.NoSuchElementException; +import java.util.Set; -import org.python.core.util.ConcurrentHashSet; import org.python.expose.ExposedMethod; import org.python.expose.ExposedNew; import org.python.expose.ExposedType; import org.python.expose.MethodType; +import org.python.util.Generic; @ExposedType(name = "set", base = PyObject.class) public class PySet extends BaseSet { @@ -15,17 +16,22 @@ public static final PyType TYPE = PyType.fromClass(PySet.class); public PySet() { - super(new ConcurrentHashSet<PyObject>()); + super(concurrentSet()); } public PySet(PyType type) { - super(type, new ConcurrentHashSet<PyObject>()); + super(type, concurrentSet()); } public PySet(PyObject data) { - super(_update(new ConcurrentHashSet<PyObject>(), data)); + super(_update(concurrentSet(), data)); } + /** Contextualize the needed Set<PyObject> type paramaters (generics workaround). */ + private static Set<PyObject> concurrentSet() { + return Generic.concurrentSet(); + } + @ExposedNew @ExposedMethod final void set___init__(PyObject[] args, String[] kwds) { Modified: trunk/jython/src/org/python/core/PyStringMap.java =================================================================== --- trunk/jython/src/org/python/core/PyStringMap.java 2009-03-27 20:34:45 UTC (rev 6110) +++ trunk/jython/src/org/python/core/PyStringMap.java 2009-03-27 21:44:57 UTC (rev 6111) @@ -9,6 +9,8 @@ import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; +import org.python.util.Generic; + /** * Special fast dict implementation for __dict__ instances. Allows interned String keys in addition * to PyObject unlike PyDictionary. @@ -22,11 +24,13 @@ } public PyStringMap(int capacity) { - table = new ConcurrentHashMap<Object, PyObject>(capacity); + table = new ConcurrentHashMap<Object, PyObject>(capacity, Generic.CHM_LOAD_FACTOR, + Generic.CHM_CONCURRENCY_LEVEL); } public PyStringMap(Map<Object, PyObject> map) { - table = new ConcurrentHashMap<Object, PyObject>(map); + table = Generic.concurrentMap(); + table.putAll(map); } public PyStringMap(PyObject elements[]) { Modified: trunk/jython/src/org/python/modules/PyTeeIterator.java =================================================================== --- trunk/jython/src/org/python/modules/PyTeeIterator.java 2009-03-27 20:34:45 UTC (rev 6110) +++ trunk/jython/src/org/python/modules/PyTeeIterator.java 2009-03-27 21:44:57 UTC (rev 6111) @@ -1,7 +1,6 @@ package org.python.modules; import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; import org.python.core.Py; import org.python.core.PyException; @@ -12,6 +11,7 @@ import org.python.expose.ExposedMethod; import org.python.expose.ExposedNew; import org.python.expose.ExposedType; +import org.python.util.Generic; @ExposedType(name = "itertools.tee", base = PyObject.class, isBaseType = false) public class PyTeeIterator extends PyIterator { @@ -45,7 +45,7 @@ throw Py.ValueError("n must be >= 0"); } PyObject iterator = iterable.__iter__(); - Map<Integer, PyObject> buffer = new ConcurrentHashMap<Integer, PyObject>(); + Map<Integer, PyObject> buffer = Generic.concurrentMap(); int[] offsets = new int[n]; PyTeeIterator[] tees = new PyTeeIterator[n]; for (int i = 0; i < n; i++) { Modified: trunk/jython/src/org/python/util/Generic.java =================================================================== --- trunk/jython/src/org/python/util/Generic.java 2009-03-27 20:34:45 UTC (rev 6110) +++ trunk/jython/src/org/python/util/Generic.java 2009-03-27 21:44:57 UTC (rev 6111) @@ -6,7 +6,11 @@ import java.util.List; import java.util.Map; import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentMap; +import org.python.core.util.ConcurrentHashSet; + /** * Static methods to make instances of collections with their generic types inferred from what * they're being assigned to. The idea is stolen from <code>Sets</code>, <code>Lists</code> and @@ -14,7 +18,16 @@ * Collections</a>. */ public class Generic { + /** + * Our default ConcurrentHashMap sizes. Only concurreny level differs from + * ConcurrentHashMap's defaults: it's significantly lower to reduce allocation cost. + */ + public static final int CHM_INITIAL_CAPACITY = 16; + public static final float CHM_LOAD_FACTOR = 0.75f; + public static final int CHM_CONCURRENCY_LEVEL = 2; + + /** * Makes a List with its generic type inferred from whatever it's being assigned to. */ public static <T> List<T> list() { @@ -40,6 +53,15 @@ } /** + * Makes a ConcurrentMap using generic types inferred from whatever this is being + * assigned to. + */ + public static <K, V> ConcurrentMap<K, V> concurrentMap() { + return new ConcurrentHashMap<K, V>(CHM_INITIAL_CAPACITY, CHM_LOAD_FACTOR, + CHM_CONCURRENCY_LEVEL); + } + + /** * Makes a Set using the generic type inferred from whatever this is being assigned to. */ public static <T> Set<T> set() { @@ -57,4 +79,13 @@ } return s; } + + /** + * Makes a Set, ensuring safe concurrent operations, using generic types inferred from + * whatever this is being assigned to. + */ + public static <T> Set<T> concurrentSet() { + return new ConcurrentHashSet<T>(CHM_INITIAL_CAPACITY, CHM_LOAD_FACTOR, + CHM_CONCURRENCY_LEVEL); + } } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <th...@us...> - 2009-03-29 22:13:53
|
Revision: 6116 http://jython.svn.sourceforge.net/jython/?rev=6116&view=rev Author: thobes Date: 2009-03-29 22:13:47 +0000 (Sun, 29 Mar 2009) Log Message: ----------- Decoupled the compiler. Added a compiler facade and added a dispatcher that enables loading different kinds of code objects from .class-files. This enables having multiple compilers and different code implementations. Modified Paths: -------------- trunk/jython/src/org/python/compiler/Module.java trunk/jython/src/org/python/core/Py.java Added Paths: ----------- trunk/jython/src/org/python/compiler/LegacyCompiler.java trunk/jython/src/org/python/core/CodeBootstrap.java trunk/jython/src/org/python/core/CodeLoader.java trunk/jython/src/org/python/core/CompilerFacade.java trunk/jython/src/org/python/core/PyRunnableBootstrap.java trunk/jython/src/org/python/core/PythonCodeBundle.java trunk/jython/src/org/python/core/PythonCompiler.java Added: trunk/jython/src/org/python/compiler/LegacyCompiler.java =================================================================== --- trunk/jython/src/org/python/compiler/LegacyCompiler.java (rev 0) +++ trunk/jython/src/org/python/compiler/LegacyCompiler.java 2009-03-29 22:13:47 UTC (rev 6116) @@ -0,0 +1,72 @@ +package org.python.compiler; + +import java.io.ByteArrayOutputStream; +import java.io.OutputStream; + +import org.python.antlr.base.mod; +import org.python.core.BytecodeLoader; +import org.python.core.CompilerFlags; +import org.python.core.Py; +import org.python.core.PyCode; +import org.python.core.PythonCodeBundle; +import org.python.core.PythonCompiler; + +public class LegacyCompiler implements PythonCompiler { + + public PythonCodeBundle compile(mod node, String name, String filename, + boolean linenumbers, boolean printResults, CompilerFlags cflags) { + return new LazyLegacyBundle(node, name, filename, linenumbers, + printResults, cflags); + } + + private static class LazyLegacyBundle implements PythonCodeBundle { + + private final mod node; + private final String name; + private final String filename; + private final boolean linenumbers; + private final boolean printResults; + private final CompilerFlags cflags; + private ByteArrayOutputStream ostream = null; + + public LazyLegacyBundle(mod node, String name, String filename, + boolean linenumbers, boolean printResults, CompilerFlags cflags) { + this.node = node; + this.name = name; + this.filename = filename; + this.linenumbers = linenumbers; + this.printResults = printResults; + this.cflags = cflags; + } + + public PyCode loadCode() throws Exception { + return BytecodeLoader.makeCode(name, ostream().toByteArray(), + filename); + } + + public void writeTo(OutputStream stream) throws Exception { + if (this.ostream != null) { + stream.write(ostream.toByteArray()); + } else { + Module.compile(node, stream, name, filename, linenumbers, + printResults, cflags); + } + } + + public void saveCode(String directory) throws Exception { + // FIXME: this is slightly broken, it should use the directory + Py.saveClassFile(name, ostream()); + } + + private ByteArrayOutputStream ostream() throws Exception { + if (ostream == null) { + ostream = new ByteArrayOutputStream(); + Module.compile(node, ostream, name, filename, linenumbers, + printResults, cflags); + } + return ostream; + } + + } + +} Modified: trunk/jython/src/org/python/compiler/Module.java =================================================================== --- trunk/jython/src/org/python/compiler/Module.java 2009-03-29 22:11:34 UTC (rev 6115) +++ trunk/jython/src/org/python/compiler/Module.java 2009-03-29 22:13:47 UTC (rev 6116) @@ -12,10 +12,14 @@ import org.objectweb.asm.Label; import org.objectweb.asm.Opcodes; +import org.python.core.CodeBootstrap; import org.python.core.CodeFlag; +import org.python.core.CodeLoader; import org.python.core.CompilerFlags; import org.python.core.Py; import org.python.core.PyException; +import org.python.core.PyRunnableBootstrap; +import org.objectweb.asm.Type; import org.python.antlr.ParseException; import org.python.antlr.PythonTree; import org.python.antlr.ast.Suite; @@ -547,10 +551,26 @@ c.dup(); c.ldc(classfile.name); c.invokespecial(classfile.name, "<init>", "(" + $str + ")V"); + c.invokevirtual(classfile.name, "getMain", "()" + $pyCode); + String bootstrap = Type.getDescriptor(CodeBootstrap.class); + c.invokestatic(Type.getInternalName(CodeLoader.class), + CodeLoader.SIMPLE_FACTORY_METHOD_NAME, + "(" + $pyCode + ")" + bootstrap); c.aload(0); - c.invokestatic("org/python/core/Py", "runMain", "(" + $pyRunnable + $strArr + ")V"); + c.invokestatic("org/python/core/Py", "runMain", "(" + bootstrap + $strArr + ")V"); c.return_(); } + + public void addBootstrap() throws IOException { + Code c = classfile.addMethod(CodeLoader.GET_BOOTSTRAP_METHOD_NAME, + "()" + Type.getDescriptor(CodeBootstrap.class), + ACC_PUBLIC | ACC_STATIC); + c.ldc(Type.getType("L" + classfile.name + ";")); + c.invokestatic(Type.getInternalName(PyRunnableBootstrap.class), + PyRunnableBootstrap.REFLECTION_METHOD_NAME, + "(" + $clss + ")" + Type.getDescriptor(CodeBootstrap.class)); + c.areturn(); + } public void addConstants(Code c) throws IOException { classfile.addField("self", "L"+classfile.name+";", @@ -605,6 +625,7 @@ addInit(); addRunnable(); addMain(); + addBootstrap(); addFunctions(); Added: trunk/jython/src/org/python/core/CodeBootstrap.java =================================================================== --- trunk/jython/src/org/python/core/CodeBootstrap.java (rev 0) +++ trunk/jython/src/org/python/core/CodeBootstrap.java 2009-03-29 22:13:47 UTC (rev 6116) @@ -0,0 +1,7 @@ +package org.python.core; + +public interface CodeBootstrap { + + PyCode loadCode(CodeLoader loader); + +} Added: trunk/jython/src/org/python/core/CodeLoader.java =================================================================== --- trunk/jython/src/org/python/core/CodeLoader.java (rev 0) +++ trunk/jython/src/org/python/core/CodeLoader.java 2009-03-29 22:13:47 UTC (rev 6116) @@ -0,0 +1,60 @@ +package org.python.core; + +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; + +public final class CodeLoader { + + public static final String GET_BOOTSTRAP_METHOD_NAME = "getCodeBootstrap"; + public final String name; + public final String filename; + + private CodeLoader(String name, String filename) { + this.name = name; + this.filename = filename; + } + + public static boolean canLoad(Class<?> cls) { + try { + Method getBootstrap = cls.getMethod(GET_BOOTSTRAP_METHOD_NAME); + return Modifier.isStatic(getBootstrap.getModifiers()); + } catch (Exception e) { + return false; + } + } + + public static PyCode loadCode(Class<?> cls, String name, String filename) + throws SecurityException, NoSuchMethodException, + IllegalArgumentException, IllegalAccessException, + InvocationTargetException { + Method getBootstrap = cls.getMethod(GET_BOOTSTRAP_METHOD_NAME); + CodeBootstrap bootstrap = (CodeBootstrap) getBootstrap.invoke(null); + return loadCode(bootstrap, name, filename); + } + + public static PyCode loadCode(Class<?> cls) throws SecurityException, + IllegalArgumentException, NoSuchMethodException, + IllegalAccessException, InvocationTargetException { + return loadCode(cls, null, null); + } + + public static PyCode loadCode(CodeBootstrap bootstrap, String name, + String filename) { + return bootstrap.loadCode(new CodeLoader(name, filename)); + } + + public static PyCode loadCode(CodeBootstrap bootstrap) { + return loadCode(bootstrap, null, null); + } + + public static final String SIMPLE_FACTORY_METHOD_NAME = "createSimpleBootstrap"; + + public static CodeBootstrap createSimpleBootstrap(final PyCode code) { + return new CodeBootstrap() { + public PyCode loadCode(CodeLoader loader) { + return code; + } + }; + } +} Added: trunk/jython/src/org/python/core/CompilerFacade.java =================================================================== --- trunk/jython/src/org/python/core/CompilerFacade.java (rev 0) +++ trunk/jython/src/org/python/core/CompilerFacade.java 2009-03-29 22:13:47 UTC (rev 6116) @@ -0,0 +1,39 @@ +package org.python.core; + +import org.python.antlr.base.mod; +import org.python.compiler.LegacyCompiler; + +/** + * Facade for different compiler implementations. + * + * The static methods of this class act as a Facade for the compiler subsystem. + * This is so that the rest of Jython (even generated code) can statically link + * to the static interface of this class, while allowing for different + * implementations of the various components of the compiler subsystem. + * + * @author Tobias Ivarsson + */ +public class CompilerFacade { + + private static volatile PythonCompiler compiler = loadDefaultCompiler(); + + public static void setCompiler(PythonCompiler compiler) { + CompilerFacade.compiler = compiler; + } + + private static PythonCompiler loadDefaultCompiler() { + return new LegacyCompiler(); + } + + public static PyCode compile(mod node, String name, String filename, + boolean linenumbers, boolean printResults, CompilerFlags cflags) { + try { + PythonCodeBundle bundle = compiler.compile(node, name, filename, + linenumbers, printResults, cflags); + bundle.saveCode(Options.proxyDebugDirectory); + return bundle.loadCode(); + } catch (Throwable t) { + throw ParserFacade.fixParseError(null, t, filename); + } + } +} Modified: trunk/jython/src/org/python/core/Py.java =================================================================== --- trunk/jython/src/org/python/core/Py.java 2009-03-29 22:11:34 UTC (rev 6115) +++ trunk/jython/src/org/python/core/Py.java 2009-03-29 22:13:47 UTC (rev 6116) @@ -862,9 +862,19 @@ * Called by the code generated in {@link Module#addMain()} */ public static void runMain(PyRunnable main, String[] args) throws Exception { + runMain(new PyRunnableBootstrap(main), args); + } + + /** + * Initializes a default PythonInterpreter and runs the code loaded from the + * {@link CodeBootstrap} as __main__ Called by the code generated in + * {@link Module#addMain()} + */ + public static void runMain(CodeBootstrap main, String[] args) + throws Exception { PySystemState.initialize(null, null, args, main.getClass().getClassLoader()); try { - imp.createFromCode("__main__", main.getMain()); + imp.createFromCode("__main__", CodeLoader.loadCode(main)); } catch (PyException e) { Py.getSystemState().callExitFunc(); if (Py.matchException(e, Py.SystemExit)) { @@ -1648,6 +1658,8 @@ public static PyCode compile_flags(mod node, String name, String filename, boolean linenumbers, boolean printResults, CompilerFlags cflags) { + return CompilerFacade.compile(node, name, filename, linenumbers, printResults, cflags); + /* try { ByteArrayOutputStream ostream = new ByteArrayOutputStream(); Module.compile(node, ostream, name, filename, linenumbers, printResults, cflags); @@ -1658,6 +1670,7 @@ } catch (Throwable t) { throw ParserFacade.fixParseError(null, t, filename); } + */ } public static PyCode compile_flags(mod node, String filename, Added: trunk/jython/src/org/python/core/PyRunnableBootstrap.java =================================================================== --- trunk/jython/src/org/python/core/PyRunnableBootstrap.java (rev 0) +++ trunk/jython/src/org/python/core/PyRunnableBootstrap.java 2009-03-29 22:13:47 UTC (rev 6116) @@ -0,0 +1,43 @@ +package org.python.core; + +import java.lang.reflect.Constructor; + +public class PyRunnableBootstrap implements CodeBootstrap { + + public static final String REFLECTION_METHOD_NAME = "getFilenameConstructorReflectionBootstrap"; + private final PyRunnable runnable; + + PyRunnableBootstrap(PyRunnable runnable) { + this.runnable = runnable; + } + + public PyCode loadCode(CodeLoader loader) { + return runnable.getMain(); + } + + public static CodeBootstrap getFilenameConstructorReflectionBootstrap( + Class<? extends PyRunnable> cls) { + final Constructor<? extends PyRunnable> constructor; + try { + constructor = cls.getConstructor(String.class); + } catch (Exception e) { + throw new IllegalArgumentException( + "PyRunnable class does not specify apropriate constructor.", + e); + } + return new CodeBootstrap() { + + public PyCode loadCode(CodeLoader loader) { + try { + return constructor.newInstance(loader.filename).getMain(); + } catch (Exception e) { + throw new IllegalArgumentException( + "PyRunnable class constructor does not support instantiation protocol.", + e); + } + } + + }; + } + +} Added: trunk/jython/src/org/python/core/PythonCodeBundle.java =================================================================== --- trunk/jython/src/org/python/core/PythonCodeBundle.java (rev 0) +++ trunk/jython/src/org/python/core/PythonCodeBundle.java 2009-03-29 22:13:47 UTC (rev 6116) @@ -0,0 +1,13 @@ +package org.python.core; + +import java.io.OutputStream; + +public interface PythonCodeBundle { + + PyCode loadCode() throws Exception; + + void writeTo(OutputStream stream) throws Exception; + + void saveCode(String directory) throws Exception; + +} Added: trunk/jython/src/org/python/core/PythonCompiler.java =================================================================== --- trunk/jython/src/org/python/core/PythonCompiler.java (rev 0) +++ trunk/jython/src/org/python/core/PythonCompiler.java 2009-03-29 22:13:47 UTC (rev 6116) @@ -0,0 +1,11 @@ +package org.python.core; + +import org.python.antlr.base.mod; + +public interface PythonCompiler { + + PythonCodeBundle compile(mod node, String name, String filename, + boolean linenumbers, boolean printResults, CompilerFlags cflags) + throws Exception; + +} This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <th...@us...> - 2009-03-31 15:02:01
|
Revision: 6135 http://jython.svn.sourceforge.net/jython/?rev=6135&view=rev Author: thobes Date: 2009-03-31 15:01:43 +0000 (Tue, 31 Mar 2009) Log Message: ----------- Applying my callpath.patch (from previous commit). This is probably the only performance improvement I'll add before 2.5 goes RC. Modified Paths: -------------- trunk/jython/src/org/python/compiler/ClassConstants.java trunk/jython/src/org/python/compiler/CodeCompiler.java trunk/jython/src/org/python/compiler/Module.java trunk/jython/src/org/python/core/Py.java trunk/jython/src/org/python/core/PyBaseCode.java trunk/jython/src/org/python/core/PyCode.java trunk/jython/src/org/python/core/PyFunction.java trunk/jython/src/org/python/core/PyFunctionTable.java trunk/jython/src/org/python/core/PyGenerator.java trunk/jython/src/org/python/core/PyMethod.java trunk/jython/src/org/python/core/PyObject.java trunk/jython/src/org/python/core/PyReflectedFunction.java trunk/jython/src/org/python/core/PyTableCode.java trunk/jython/src/org/python/core/ReflectedArgs.java trunk/jython/src/org/python/core/imp.java Modified: trunk/jython/src/org/python/compiler/ClassConstants.java =================================================================== --- trunk/jython/src/org/python/compiler/ClassConstants.java 2009-03-31 14:56:30 UTC (rev 6134) +++ trunk/jython/src/org/python/compiler/ClassConstants.java 2009-03-31 15:01:43 UTC (rev 6135) @@ -8,6 +8,7 @@ final static String $pyUnicode = "Lorg/python/core/PyUnicode;"; final static String $pyExc = "Lorg/python/core/PyException;"; final static String $pyFrame = "Lorg/python/core/PyFrame;"; + final static String $threadState= "Lorg/python/core/ThreadState;"; final static String $pyCode = "Lorg/python/core/PyCode;"; final static String $pyInteger = "Lorg/python/core/PyInteger;"; final static String $pyLong = "Lorg/python/core/PyLong;"; Modified: trunk/jython/src/org/python/compiler/CodeCompiler.java =================================================================== --- trunk/jython/src/org/python/compiler/CodeCompiler.java 2009-03-31 14:56:30 UTC (rev 6134) +++ trunk/jython/src/org/python/compiler/CodeCompiler.java 2009-03-31 15:01:43 UTC (rev 6135) @@ -135,7 +135,7 @@ int yield_count = 0; - private int stackDepth = 0; + private Stack<String> stack = new Stack<String>(); public CodeCompiler(Module module, boolean print_results) { this.module = module; @@ -157,6 +157,10 @@ code.aload(1); } + public void loadThreadState() throws Exception { + code.aload(2); + } + public void setLastI(int idx) throws Exception { loadFrame(); code.iconst(idx); @@ -587,24 +591,30 @@ } private void stackProduce() { - stackDepth++; + stackProduce("org/python/core/PyObject"); } + private void stackProduce(String signature) { + stack.push(signature); + } + private void stackConsume() { - stackDepth--; + stackConsume(1); } private void stackConsume(int numItems) { - stackDepth -= numItems; + for (int i = 0; i < numItems; i++) { + stack.pop(); + } } 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"); + if (stack.size() > 0) { + int array = code.getLocal("[Ljava/lang/Object;"); + code.iconst(stack.size()); + code.anewarray("java/lang/Object"); code.astore(array); - for (int i = 0; i < stackDepth; i++) { + for (int i = 0; i < stack.size(); i++) { code.aload(array); // Stack: |- ... value array code.swap(); @@ -621,13 +631,15 @@ } private void restoreStack(int array) throws Exception { - if (stackDepth > 0) { - for (int i = stackDepth - 1; i >= 0; i--) { + if (stack.size() > 0) { + int i = stack.size() -1; + for (String signature : stack) { code.aload(array); // Stack: |- ... array code.iconst(i); code.aaload(); // Stack: |- ... value + code.checkcast(signature); } code.freeLocal(array); } @@ -1507,44 +1519,45 @@ visit(node.getInternalValue()); stackProduce(); code.ldc(name); code.invokevirtual("org/python/core/PyObject", "__getattr__", "(" + $str + ")" + $pyObj); + loadThreadState(); stackProduce("org/python/core/ThreadState"); switch (values.size()) { case 0: - stackConsume(); // target - code.invokevirtual("org/python/core/PyObject", "__call__", "()" + $pyObj); + stackConsume(2); // target + ts + code.invokevirtual("org/python/core/PyObject", "__call__", "(" + $threadState + ")" + $pyObj); break; case 1: visit(values.get(0)); - stackConsume(); // target - code.invokevirtual("org/python/core/PyObject", "__call__", "(" + $pyObj + ")" + $pyObj); + stackConsume(2); // target + ts + code.invokevirtual("org/python/core/PyObject", "__call__", "(" + $threadState + $pyObj + ")" + $pyObj); break; case 2: visit(values.get(0)); stackProduce(); visit(values.get(1)); - stackConsume(2); // target + arguments - code.invokevirtual("org/python/core/PyObject", "__call__", "(" + $pyObj + $pyObj + ")" + $pyObj); + stackConsume(3); // target + ts + arguments + code.invokevirtual("org/python/core/PyObject", "__call__", "(" + $threadState + $pyObj + $pyObj + ")" + $pyObj); break; case 3: visit(values.get(0)); stackProduce(); visit(values.get(1)); stackProduce(); visit(values.get(2)); - stackConsume(3); // target + arguments - code.invokevirtual("org/python/core/PyObject", "__call__", "(" + $pyObj + $pyObj + $pyObj + ")" + $pyObj); + stackConsume(4); // target + ts + arguments + code.invokevirtual("org/python/core/PyObject", "__call__", "(" + $threadState + $pyObj + $pyObj + $pyObj + ")" + $pyObj); break; case 4: visit(values.get(0)); stackProduce(); visit(values.get(1)); stackProduce(); visit(values.get(2)); stackProduce(); visit(values.get(3)); - stackConsume(4); // target + arguments - code.invokevirtual("org/python/core/PyObject", "__call__", "(" + $pyObj + $pyObj + $pyObj + $pyObj + ")" + $pyObj); + stackConsume(5); // target + ts + arguments + code.invokevirtual("org/python/core/PyObject", "__call__", "(" + $threadState + $pyObj + $pyObj + $pyObj + $pyObj + ")" + $pyObj); break; default: int argArray = makeArray(values); code.aload(argArray); code.freeLocal(argArray); - stackConsume(); // target - code.invokevirtual("org/python/core/PyObject", "__call__", "(" + $pyObjArr + ")" + $pyObj); + stackConsume(2); // target + ts + code.invokevirtual("org/python/core/PyObject", "__call__", "(" + $threadState + $pyObjArr + ")" + $pyObj); break; } return null; @@ -1596,52 +1609,54 @@ code.invokevirtual("org/python/core/PyObject", "_callextra", "(" + $pyObjArr + $strArr + $pyObj + $pyObj + ")" + $pyObj); } else if (keys.size() > 0) { + loadThreadState(); stackProduce("org/python/core/ThreadState"); int argArray = makeArray(values); int strArray = makeStrings(code, keys); code.aload(argArray); code.aload(strArray); code.freeLocal(argArray); code.freeLocal(strArray); - stackConsume(); // target - code.invokevirtual("org/python/core/PyObject", "__call__", "(" + $pyObjArr + $strArr + ")" + $pyObj); + stackConsume(2); // target + ts + code.invokevirtual("org/python/core/PyObject", "__call__", "(" + $threadState + $pyObjArr + $strArr + ")" + $pyObj); } else { + loadThreadState(); stackProduce("org/python/core/ThreadState"); switch (values.size()) { case 0: - stackConsume(); // target - code.invokevirtual("org/python/core/PyObject", "__call__", "()" + $pyObj); + stackConsume(2); // target + ts + code.invokevirtual("org/python/core/PyObject", "__call__", "(" + $threadState + ")" + $pyObj); break; case 1: visit(values.get(0)); - stackConsume(); // target - code.invokevirtual("org/python/core/PyObject", "__call__", "(" + $pyObj + ")" + $pyObj); + stackConsume(2); // target + ts + code.invokevirtual("org/python/core/PyObject", "__call__", "(" + $threadState + $pyObj + ")" + $pyObj); break; case 2: visit(values.get(0)); stackProduce(); visit(values.get(1)); - stackConsume(2); // target + arguments - code.invokevirtual("org/python/core/PyObject", "__call__", "(" + $pyObj + $pyObj + ")" + $pyObj); + stackConsume(3); // target + ts + arguments + code.invokevirtual("org/python/core/PyObject", "__call__", "(" + $threadState + $pyObj + $pyObj + ")" + $pyObj); break; case 3: visit(values.get(0)); stackProduce(); visit(values.get(1)); stackProduce(); visit(values.get(2)); - stackConsume(3); // target + arguments - code.invokevirtual("org/python/core/PyObject", "__call__", "(" + $pyObj + $pyObj + $pyObj + ")" + $pyObj); + stackConsume(4); // target + ts + arguments + code.invokevirtual("org/python/core/PyObject", "__call__", "(" + $threadState + $pyObj + $pyObj + $pyObj + ")" + $pyObj); break; case 4: visit(values.get(0)); stackProduce(); visit(values.get(1)); stackProduce(); visit(values.get(2)); stackProduce(); visit(values.get(3)); - stackConsume(4); // target + arguments - code.invokevirtual("org/python/core/PyObject", "__call__", "(" + $pyObj + $pyObj + $pyObj + $pyObj + ")" + $pyObj); + stackConsume(5); // target + ts + arguments + code.invokevirtual("org/python/core/PyObject", "__call__", "(" + $threadState + $pyObj + $pyObj + $pyObj + $pyObj + ")" + $pyObj); break; default: int argArray = makeArray(values); code.aload(argArray); code.freeLocal(argArray); - stackConsume(); // target - code.invokevirtual("org/python/core/PyObject", "__call__", "(" + $pyObjArr + ")" + $pyObj); + stackConsume(2); // target + ts + code.invokevirtual("org/python/core/PyObject", "__call__", "(" + $threadState + $pyObjArr + ")" + $pyObj); break; } } @@ -1677,9 +1692,9 @@ saveAugTmps(node, 4); ctx = expr_contextType.Load; } + stackConsume(4); } - stackConsume(4); switch (ctx) { case Del: code.invokevirtual("org/python/core/PyObject", "__delslice__", "(" + $pyObj + $pyObj + $pyObj + ")V"); @@ -1711,6 +1726,7 @@ } else { visit(node.getInternalValue()); stackProduce(); visit(node.getInternalSlice()); + stackConsume(); if (node.getInternalCtx() == expr_contextType.AugStore && augmode == expr_contextType.Load) { saveAugTmps(node, 2); @@ -1718,7 +1734,6 @@ } } - stackConsume(); switch (ctx) { case Del: code.invokevirtual("org/python/core/PyObject", "__delitem__", "(" + $pyObj + ")V"); @@ -2222,7 +2237,9 @@ code.freeLocal(genExp); code.swap(); code.invokevirtual("org/python/core/PyObject", "__iter__", "()Lorg/python/core/PyObject;"); - code.invokevirtual("org/python/core/PyObject", "__call__", "(" + $pyObj + ")" + $pyObj); + loadThreadState(); + code.swap(); + code.invokevirtual("org/python/core/PyObject", "__call__", "(" + $threadState + $pyObj + ")" + $pyObj); return null; } @@ -2239,8 +2256,8 @@ final Label label_end = new Label(); final Method getattr = Method.getMethod("org.python.core.PyObject __getattr__ (String)"); - final Method call = Method.getMethod("org.python.core.PyObject __call__ ()"); - final Method call3 = Method.getMethod("org.python.core.PyObject __call__ (org.python.core.PyObject,org.python.core.PyObject,org.python.core.PyObject)"); + final Method call = Method.getMethod("org.python.core.PyObject __call__ (org.python.core.ThreadState)"); + final Method call3 = Method.getMethod("org.python.core.PyObject __call__ (org.python.core.ThreadState,org.python.core.PyObject,org.python.core.PyObject,org.python.core.PyObject)"); // mgr = (EXPR) visit(node.getInternalContext_expr()); @@ -2254,6 +2271,7 @@ // value = mgr.__enter__() code.ldc("__enter__"); code.invokevirtual(Type.getType(PyObject.class).getInternalName(), getattr.getName(), getattr.getDescriptor()); + loadThreadState(); code.invokevirtual(Type.getType(PyObject.class).getInternalName(), call.getName(), call.getDescriptor()); int value_tmp = code.getLocal("org/python/core/PyObject"); code.astore(value_tmp); @@ -2273,6 +2291,7 @@ @Override public void finalBody(CodeCompiler compiler) throws Exception { compiler.code.aload(__exit__); + loadThreadState(); compiler.getNone(); compiler.code.dup(); compiler.code.dup(); @@ -2317,8 +2336,7 @@ loadFrame(); code.invokestatic("org/python/core/Py", "setException", "(" + $throwable + $pyFrame + ")" + $pyExc); code.pop(); - - code.invokestatic("org/python/core/Py", "getThreadState", "()Lorg/python/core/ThreadState;"); + loadThreadState(); code.getfield("org/python/core/ThreadState", "exception", $pyExc); int ts_tmp = storeTop(); @@ -2326,11 +2344,13 @@ // exc = False # implicit // if not exit(*sys.exc_info()): code.aload(__exit__); + loadThreadState(); code.aload(ts_tmp); code.getfield("org/python/core/PyException", "type", $pyObj); code.aload(ts_tmp); code.getfield("org/python/core/PyException", "value", $pyObj); code.aload(ts_tmp); + code.freeLocal(ts_tmp); code.getfield("org/python/core/PyException", "traceback", "Lorg/python/core/PyTraceback;"); code.checkcast("org/python/core/PyObject"); code.invokevirtual(Type.getType(PyObject.class).getInternalName(), call3.getName(), call3.getDescriptor()); @@ -2341,7 +2361,6 @@ code.invokestatic("org/python/core/Py", "makeException", "()Lorg/python/core/PyException;"); code.checkcast("java/lang/Throwable"); code.athrow(); - code.freeLocal(ts_tmp); code.label(label_end); code.freeLocal(__exit__); Modified: trunk/jython/src/org/python/compiler/Module.java =================================================================== --- trunk/jython/src/org/python/compiler/Module.java 2009-03-31 14:56:30 UTC (rev 6134) +++ trunk/jython/src/org/python/compiler/Module.java 2009-03-31 15:01:43 UTC (rev 6135) @@ -432,7 +432,7 @@ Code c = classfile.addMethod( code.fname, - "(" + $pyFrame + ")" + $pyObj, + "(" + $pyFrame + $threadState + ")" + $pyObj, ACC_PUBLIC); CodeCompiler compiler = new CodeCompiler(this, printResults); @@ -595,11 +595,12 @@ public void addFunctions() throws IOException { Code code = classfile.addMethod( "call_function", - "(I" + $pyFrame + ")" + $pyObj, + "(I" + $pyFrame + $threadState + ")" + $pyObj, ACC_PUBLIC); - code.aload(0); - code.aload(2); + code.aload(0); // this + code.aload(2); // frame + code.aload(3); // thread state Label def = new Label(); Label[] labels = new Label[codes.size()]; int i; @@ -611,7 +612,7 @@ code.tableswitch(0, labels.length - 1, def, labels); for(i=0; i<labels.length; i++) { code.label(labels[i]); - code.invokevirtual(classfile.name, ((PyCodeConstant)codes.get(i)).fname, "(" + $pyFrame + ")" + $pyObj); + code.invokevirtual(classfile.name, ((PyCodeConstant)codes.get(i)).fname, "(" + $pyFrame + $threadState + ")" + $pyObj); code.areturn(); } code.label(def); Modified: trunk/jython/src/org/python/core/Py.java =================================================================== --- trunk/jython/src/org/python/core/Py.java 2009-03-31 14:56:30 UTC (rev 6134) +++ trunk/jython/src/org/python/core/Py.java 2009-03-31 15:01:43 UTC (rev 6135) @@ -1194,16 +1194,17 @@ public static PyObject runCode(PyCode code, PyObject locals, PyObject globals) { PyFrame f; + ThreadState ts = getThreadState(); if (locals == null || locals == Py.None) { if (globals != null && globals != Py.None) { locals = globals; } else { - locals = Py.getFrame().getLocals(); + locals = ts.frame.getLocals(); } } if (globals == null || globals == Py.None) { - globals = Py.getFrame().f_globals; + globals = ts.frame.f_globals; } PyTableCode tc = null; @@ -1213,7 +1214,7 @@ f = new PyFrame(tc, locals, globals, Py.getSystemState().getBuiltins()); - return code.call(f); + return code.call(ts, f); } public static void exec(PyObject o, PyObject globals, PyObject locals) { @@ -1543,9 +1544,9 @@ public static PyObject makeClass(String name, PyObject[] bases, PyCode code, PyObject doc, PyObject[] closure_cells) { - PyObject globals = getFrame().f_globals; - PyObject dict = code.call(Py.EmptyObjects, Py.NoKeywords, globals, Py.EmptyObjects, - new PyTuple(closure_cells)); + ThreadState state = getThreadState(); + PyObject dict = code.call(state, Py.EmptyObjects, Py.NoKeywords, + state.frame.f_globals, Py.EmptyObjects, new PyTuple(closure_cells)); if (doc != null && dict.__finditem__("__doc__") == null) { dict.__setitem__("__doc__", doc); } @@ -1997,45 +1998,51 @@ } } - public PyObject call(PyFrame frame, PyObject closure) { + public PyObject call(ThreadState state, PyFrame frame, PyObject closure) { //XXX: what the heck is this? Looks like debug code, but it's // been here a long time... System.out.println("call #1"); return Py.None; } - public PyObject call(PyObject args[], String keywords[], + public PyObject call(ThreadState state, PyObject args[], String keywords[], PyObject globals, PyObject[] defaults, PyObject closure) { return func.__call__(args, keywords); } - public PyObject call(PyObject self, PyObject args[], String keywords[], + public PyObject call(ThreadState state, PyObject self, PyObject args[], String keywords[], PyObject globals, PyObject[] defaults, PyObject closure) { return func.__call__(self, args, keywords); } - public PyObject call(PyObject globals, PyObject[] defaults, + public PyObject call(ThreadState state, PyObject globals, PyObject[] defaults, PyObject closure) { return func.__call__(); } - public PyObject call(PyObject arg1, PyObject globals, + public PyObject call(ThreadState state, PyObject arg1, PyObject globals, PyObject[] defaults, PyObject closure) { return func.__call__(arg1); } - public PyObject call(PyObject arg1, PyObject arg2, PyObject globals, + public PyObject call(ThreadState state, PyObject arg1, PyObject arg2, PyObject globals, PyObject[] defaults, PyObject closure) { return func.__call__(arg1, arg2); } - public PyObject call(PyObject arg1, PyObject arg2, PyObject arg3, + public PyObject call(ThreadState state, PyObject arg1, PyObject arg2, PyObject arg3, PyObject globals, PyObject[] defaults, PyObject closure) { return func.__call__(arg1, arg2, arg3); } + + public PyObject call(ThreadState state, PyObject arg1, PyObject arg2, + PyObject arg3, PyObject arg4, PyObject globals, + PyObject[] defaults, PyObject closure) { + return func.__call__(arg1, arg2, arg3, arg4); + } } /** Modified: trunk/jython/src/org/python/core/PyBaseCode.java =================================================================== --- trunk/jython/src/org/python/core/PyBaseCode.java 2009-03-31 14:56:30 UTC (rev 6134) +++ trunk/jython/src/org/python/core/PyBaseCode.java 2009-03-31 15:01:43 UTC (rev 6135) @@ -22,9 +22,8 @@ return co_freevars != null && co_freevars.length > 0; } - public PyObject call(PyFrame frame, PyObject closure) { + public PyObject call(ThreadState ts, PyFrame frame, PyObject closure) { // System.err.println("tablecode call: "+co_name); - ThreadState ts = Py.getThreadState(); if (ts.systemState == null) { ts.systemState = Py.defaultSystemState; } @@ -105,38 +104,38 @@ return ret; } - public PyObject call(PyObject globals, PyObject[] defaults, + public PyObject call(ThreadState state, PyObject globals, PyObject[] defaults, PyObject closure) { if (co_argcount != 0 || varargs || varkwargs) - return call(Py.EmptyObjects, Py.NoKeywords, globals, defaults, + return call(state, Py.EmptyObjects, Py.NoKeywords, globals, defaults, closure); PyFrame frame = new PyFrame(this, globals); if (co_flags.isFlagSet(CodeFlag.CO_GENERATOR)) { return new PyGenerator(frame, closure); } - return call(frame, closure); + return call(state, frame, closure); } - public PyObject call(PyObject arg1, PyObject globals, PyObject[] defaults, + public PyObject call(ThreadState state, PyObject arg1, PyObject globals, PyObject[] defaults, PyObject closure) { if (co_argcount != 1 || varargs || varkwargs) - return call(new PyObject[] {arg1}, + return call(state, new PyObject[] {arg1}, Py.NoKeywords, globals, defaults, closure); PyFrame frame = new PyFrame(this, globals); frame.f_fastlocals[0] = arg1; if (co_flags.isFlagSet(CodeFlag.CO_GENERATOR)) { return new PyGenerator(frame, closure); } - return call(frame, closure); + return call(state, frame, closure); } - public PyObject call(PyObject arg1, PyObject arg2, PyObject globals, + public PyObject call(ThreadState state, PyObject arg1, PyObject arg2, PyObject globals, PyObject[] defaults, PyObject closure) { if (co_argcount != 2 || varargs || varkwargs) - return call(new PyObject[] {arg1, arg2}, + return call(state, new PyObject[] {arg1, arg2}, Py.NoKeywords, globals, defaults, closure); PyFrame frame = new PyFrame(this, globals); frame.f_fastlocals[0] = arg1; @@ -144,15 +143,15 @@ if (co_flags.isFlagSet(CodeFlag.CO_GENERATOR)) { return new PyGenerator(frame, closure); } - return call(frame, closure); + return call(state, frame, closure); } - public PyObject call(PyObject arg1, PyObject arg2, PyObject arg3, + public PyObject call(ThreadState state, PyObject arg1, PyObject arg2, PyObject arg3, PyObject globals, PyObject[] defaults, PyObject closure) { if (co_argcount != 3 || varargs || varkwargs) - return call(new PyObject[] {arg1, arg2, arg3}, + return call(state, new PyObject[] {arg1, arg2, arg3}, Py.NoKeywords, globals, defaults, closure); PyFrame frame = new PyFrame(this, globals); frame.f_fastlocals[0] = arg1; @@ -161,20 +160,38 @@ if (co_flags.isFlagSet(CodeFlag.CO_GENERATOR)) { return new PyGenerator(frame, closure); } - return call(frame, closure); + return call(state, frame, closure); } + + @Override + public PyObject call(ThreadState state, PyObject arg1, PyObject arg2, + PyObject arg3, PyObject arg4, PyObject globals, + PyObject[] defaults, PyObject closure) { + if (co_argcount != 4 || varargs || varkwargs) + return call(state, new PyObject[]{arg1, arg2, arg3, arg4}, + Py.NoKeywords, globals, defaults, closure); + PyFrame frame = new PyFrame(this, globals); + frame.f_fastlocals[0] = arg1; + frame.f_fastlocals[1] = arg2; + frame.f_fastlocals[2] = arg3; + frame.f_fastlocals[3] = arg4; + if (co_flags.isFlagSet(CodeFlag.CO_GENERATOR)) { + return new PyGenerator(frame, closure); + } + return call(state, frame, closure); + } - public PyObject call(PyObject self, PyObject args[], + public PyObject call(ThreadState state, PyObject self, PyObject args[], String keywords[], PyObject globals, PyObject[] defaults, PyObject closure) { PyObject[] os = new PyObject[args.length+1]; os[0] = self; System.arraycopy(args, 0, os, 1, args.length); - return call(os, keywords, globals, defaults, closure); + return call(state, os, keywords, globals, defaults, closure); } - public PyObject call(PyObject args[], String kws[], PyObject globals, PyObject[] defs, + public PyObject call(ThreadState state, PyObject args[], String kws[], PyObject globals, PyObject[] defs, PyObject closure) { PyFrame frame = new PyFrame(this, globals); int argcount = args.length - kws.length; @@ -277,7 +294,7 @@ if (co_flags.isFlagSet(CodeFlag.CO_GENERATOR)) { return new PyGenerator(frame, closure); } - return call(frame, closure); + return call(state, frame, closure); } public String toString() { Modified: trunk/jython/src/org/python/core/PyCode.java =================================================================== --- trunk/jython/src/org/python/core/PyCode.java 2009-03-31 14:56:30 UTC (rev 6134) +++ trunk/jython/src/org/python/core/PyCode.java 2009-03-31 15:01:43 UTC (rev 6135) @@ -8,33 +8,44 @@ { public String co_name; - abstract public PyObject call(PyFrame frame, PyObject closure); + abstract public PyObject call(ThreadState state, PyFrame frame, PyObject closure); - public PyObject call(PyFrame frame) { - return call(frame, null); + public PyObject call(ThreadState state, PyFrame frame) { + return call(state, frame, null); } - abstract public PyObject call(PyObject args[], String keywords[], + abstract public PyObject call(ThreadState state, + PyObject args[], String keywords[], PyObject globals, PyObject[] defaults, PyObject closure); - abstract public PyObject call(PyObject self, PyObject args[], + abstract public PyObject call(ThreadState state, + PyObject self, PyObject args[], String keywords[], PyObject globals, PyObject[] defaults, PyObject closure); - abstract public PyObject call(PyObject globals, PyObject[] defaults, + abstract public PyObject call(ThreadState state, + PyObject globals, PyObject[] defaults, PyObject closure); - abstract public PyObject call(PyObject arg1, PyObject globals, + abstract public PyObject call(ThreadState state, + PyObject arg1, PyObject globals, PyObject[] defaults, PyObject closure); - abstract public PyObject call(PyObject arg1, PyObject arg2, + abstract public PyObject call(ThreadState state, + PyObject arg1, PyObject arg2, PyObject globals, PyObject[] defaults, PyObject closure); - abstract public PyObject call(PyObject arg1, PyObject arg2, PyObject arg3, + abstract public PyObject call(ThreadState state, + PyObject arg1, PyObject arg2, PyObject arg3, PyObject globals, PyObject[] defaults, PyObject closure); + abstract public PyObject call(ThreadState state, + PyObject arg1, PyObject arg2, PyObject arg3, PyObject arg4, + PyObject globals, PyObject[] defaults, + PyObject closure); + } Modified: trunk/jython/src/org/python/core/PyFunction.java =================================================================== --- trunk/jython/src/org/python/core/PyFunction.java 2009-03-31 14:56:30 UTC (rev 6134) +++ trunk/jython/src/org/python/core/PyFunction.java 2009-03-31 15:01:43 UTC (rev 6135) @@ -299,39 +299,91 @@ @Override public PyObject __call__() { - return func_code.call(func_globals, func_defaults, func_closure); + return __call__(Py.getThreadState()); } + + @Override + public PyObject __call__(ThreadState state) { + return func_code.call(state, func_globals, func_defaults, func_closure); + } @Override public PyObject __call__(PyObject arg) { - return func_code.call(arg, func_globals, func_defaults, func_closure); + return __call__(Py.getThreadState(), arg); } + + @Override + public PyObject __call__(ThreadState state, PyObject arg0) { + return func_code.call(state, arg0, func_globals, func_defaults, func_closure); + } @Override public PyObject __call__(PyObject arg1, PyObject arg2) { - return func_code.call(arg1, arg2, func_globals, func_defaults, func_closure); + return __call__(Py.getThreadState(), arg1, arg2); } + + @Override + public PyObject __call__(ThreadState state, PyObject arg0, PyObject arg1) { + return func_code.call(state, arg0, arg1, func_globals, func_defaults, func_closure); + } @Override public PyObject __call__(PyObject arg1, PyObject arg2, PyObject arg3) { - return func_code.call(arg1, arg2, arg3, func_globals, func_defaults, - func_closure); + return __call__(Py.getThreadState(), arg1, arg2, arg3); } + + @Override + public PyObject __call__(ThreadState state, PyObject arg0, PyObject arg1, + PyObject arg2) { + return func_code.call(state, arg0, arg1, arg2, func_globals, func_defaults, func_closure); + } + + @Override + public PyObject __call__(PyObject arg0, PyObject arg1, PyObject arg2, + PyObject arg3) { + return __call__(Py.getThreadState(), arg0, arg1, arg2, arg3); + } + + @Override + public PyObject __call__(ThreadState state, PyObject arg0, PyObject arg1, + PyObject arg2, PyObject arg3) { + return func_code.call(state, arg0, arg1, arg2, arg3, func_globals, func_defaults, func_closure); + } + + @Override + public PyObject __call__(PyObject[] args) { + return __call__(Py.getThreadState(), args); + } + + @Override + public PyObject __call__(ThreadState state, PyObject[] args) { + return __call__(state, args, Py.NoKeywords); + } @Override public PyObject __call__(PyObject[] args, String[] keywords) { return function___call__(args, keywords); } + + @Override + public PyObject __call__(ThreadState state, PyObject[] args, String[] keywords) { + return func_code.call(state, args, keywords, func_globals, func_defaults, func_closure); + } @ExposedMethod(doc = BuiltinDocs.function___call___doc) final PyObject function___call__(PyObject[] args, String[] keywords) { - return func_code.call(args, keywords, func_globals, func_defaults, func_closure); + return __call__(Py.getThreadState(), args, keywords); } @Override public PyObject __call__(PyObject arg1, PyObject[] args, String[] keywords) { - return func_code.call(arg1, args, keywords, func_globals, func_defaults, func_closure); + return __call__(Py.getThreadState(), arg1, args, keywords); } + + @Override + public PyObject __call__(ThreadState state, PyObject arg1, PyObject[] args, String[] keywords) { + return func_code.call(state, arg1, args, keywords, func_globals, func_defaults, func_closure); + } @Override public String toString() { Modified: trunk/jython/src/org/python/core/PyFunctionTable.java =================================================================== --- trunk/jython/src/org/python/core/PyFunctionTable.java 2009-03-31 14:56:30 UTC (rev 6134) +++ trunk/jython/src/org/python/core/PyFunctionTable.java 2009-03-31 15:01:43 UTC (rev 6135) @@ -10,5 +10,5 @@ */ public abstract class PyFunctionTable { - abstract public PyObject call_function(int index, PyFrame frame); + abstract public PyObject call_function(int index, PyFrame frame, ThreadState ts); } Modified: trunk/jython/src/org/python/core/PyGenerator.java =================================================================== --- trunk/jython/src/org/python/core/PyGenerator.java 2009-03-31 14:56:30 UTC (rev 6134) +++ trunk/jython/src/org/python/core/PyGenerator.java 2009-03-31 15:01:43 UTC (rev 6135) @@ -106,8 +106,13 @@ super.finalize(); } } + + @Override + public PyObject __iternext__() { + return __iternext__(Py.getThreadState()); + } - public PyObject __iternext__() { + public PyObject __iternext__(ThreadState state) { if (gi_running) throw Py.ValueError("generator already executing"); if (gi_frame == null) { @@ -121,7 +126,7 @@ gi_running = true; PyObject result = null; try { - result = gi_frame.f_code.call(gi_frame, closure); + result = gi_frame.f_code.call(state, gi_frame, closure); } catch(PyException e) { if (!(e.type == Py.StopIteration || e.type == Py.GeneratorExit)) { gi_frame = null; Modified: trunk/jython/src/org/python/core/PyMethod.java =================================================================== --- trunk/jython/src/org/python/core/PyMethod.java 2009-03-31 14:56:30 UTC (rev 6134) +++ trunk/jython/src/org/python/core/PyMethod.java 2009-03-31 15:01:43 UTC (rev 6135) @@ -93,21 +93,143 @@ return this; } } - + /*// This has been disabled since JavaFunc expects to be called with self + boxed args @Override + public PyObject __call__() { + return __call__(Py.getThreadState()); + } + + @Override + public PyObject __call__(ThreadState state) { + PyObject self = checkSelf(null, null); + if (self == null) { + return im_func.__call__(state); + } else { + return im_func.__call__(state, self); + } + } + + @Override + public PyObject __call__(PyObject arg0) { + return __call__(Py.getThreadState(), arg0); + } + + @Override + public PyObject __call__(ThreadState state, PyObject arg0) { + PyObject self = checkSelf(arg0, null); + if (self == null) { + return im_func.__call__(state, arg0); + } else { + return im_func.__call__(state, self, arg0); + } + } + + @Override + public PyObject __call__(PyObject arg0, PyObject arg1) { + return __call__(Py.getThreadState(), arg0, arg1); + } + + @Override + public PyObject __call__(ThreadState state, PyObject arg0, PyObject arg1) { + PyObject self = checkSelf(arg0, null); + if (self == null) { + return im_func.__call__(state, arg0, arg1); + } else { + return im_func.__call__(state, self, arg0, arg1); + } + } + + @Override + public PyObject __call__(PyObject arg0, PyObject arg1, PyObject arg2) { + return __call__(Py.getThreadState(), arg0, arg1, arg2); + } + + @Override + public PyObject __call__(ThreadState state, PyObject arg0, PyObject arg1, + PyObject arg2) { + PyObject self = checkSelf(arg0, null); + if (self == null) { + return im_func.__call__(state, arg0, arg1, arg2); + } else { + return im_func.__call__(state, self, arg0, arg1, arg2); + } + } + + @Override + public PyObject __call__(PyObject arg0, PyObject arg1, PyObject arg2, PyObject arg3) { + return __call__(Py.getThreadState(), arg0, arg1, arg2, arg3); + } + + @Override + public PyObject __call__(ThreadState state, PyObject arg0, PyObject arg1, + PyObject arg2, PyObject arg3) { + PyObject self = checkSelf(arg0, null); + if (self == null) { + return im_func.__call__(state, arg0, arg1, arg2, arg3); + } else { + return im_func.__call__(state, self, new PyObject[]{arg0, arg1, arg2, arg3}, Py.NoKeywords); + } + } + + + @Override + public PyObject __call__(PyObject arg1, PyObject[] args, String[] keywords) { + return __call__(Py.getThreadState(), arg1, args, keywords); + } + + @Override + public PyObject __call__(ThreadState state, PyObject arg1, PyObject[] args, + String[] keywords) { + PyObject self = checkSelf(arg1, args); + if (self == null) { + return im_func.__call__(state, arg1, args, keywords); + } else { + PyObject[] new_args = new PyObject[args.length+1]; + System.arraycopy(args, 0, new_args, 1, args.length); + new_args[0] = arg1; + return im_func.__call__(state, self, new_args, keywords); + } + } + + @Override + public PyObject __call__(PyObject[] args) { + return __call__(Py.getThreadState(), args); + } + + @Override + public PyObject __call__(ThreadState state, PyObject[] args) { + return __call__(state, args, Py.NoKeywords); + } + */ + @Override public PyObject __call__(PyObject[] args, String[] keywords) { return instancemethod___call__(args, keywords); } - + + @Override + public PyObject __call__(ThreadState state, PyObject[] args, String[] keywords) { + PyObject self = checkSelf(null, args); + if (self == null) { + return im_func.__call__(state, args, keywords); + } else { + return im_func.__call__(state, self, args, keywords); + } + } + @ExposedMethod(doc = BuiltinDocs.instancemethod___call___doc) final PyObject instancemethod___call__(PyObject[] args, String[] keywords) { + return __call__(Py.getThreadState(), args, keywords); + } + + private PyObject checkSelf(PyObject arg, PyObject[] args) { PyObject self = im_self; - if (self == null) { // Unbound methods must be called with an instance of the // class (or a derived class) as first argument boolean ok; - if (args.length >= 1) { + if (arg != null) { + self = arg; + } else if (args != null && args.length >= 1) { self = args[0]; } if (self == null) { @@ -125,9 +247,9 @@ self == null ? "" : " instance"); throw Py.TypeError(msg); } - return im_func.__call__(args, keywords); + return null; } else { - return im_func.__call__(self, args, keywords); + return self; } } Modified: trunk/jython/src/org/python/core/PyObject.java =================================================================== --- trunk/jython/src/org/python/core/PyObject.java 2009-03-31 14:56:30 UTC (rev 6134) +++ trunk/jython/src/org/python/core/PyObject.java 2009-03-31 15:01:43 UTC (rev 6135) @@ -314,6 +314,10 @@ public PyObject __call__(PyObject args[], String keywords[]) { throw Py.TypeError(String.format("'%s' object is not callable", getType().fastGetName())); } + + public PyObject __call__(ThreadState state, PyObject args[], String keywords[]) { + return __call__(args, keywords); + } /** * A variant of the __call__ method with one extra initial argument. @@ -329,15 +333,16 @@ * keyword arguments). * @param keywords the keywords used for all keyword arguments. **/ - public PyObject __call__( - PyObject arg1, - PyObject args[], - String keywords[]) { + public PyObject __call__(PyObject arg1, PyObject args[], String keywords[]) { PyObject[] newArgs = new PyObject[args.length + 1]; System.arraycopy(args, 0, newArgs, 1, args.length); newArgs[0] = arg1; return __call__(newArgs, keywords); } + + public PyObject __call__(ThreadState state, PyObject arg1, PyObject args[], String keywords[]) { + return __call__(arg1, args, keywords); + } /** * A variant of the __call__ method when no keywords are passed. The @@ -350,6 +355,10 @@ public PyObject __call__(PyObject args[]) { return __call__(args, Py.NoKeywords); } + + public PyObject __call__(ThreadState state, PyObject args[]) { + return __call__(args); + } /** * A variant of the __call__ method with no arguments. The default @@ -360,6 +369,10 @@ public PyObject __call__() { return __call__(Py.EmptyObjects, Py.NoKeywords); } + + public PyObject __call__(ThreadState state) { + return __call__(); + } /** * A variant of the __call__ method with one argument. The default @@ -372,6 +385,10 @@ public PyObject __call__(PyObject arg0) { return __call__(new PyObject[] { arg0 }, Py.NoKeywords); } + + public PyObject __call__(ThreadState state, PyObject arg0) { + return __call__(arg0); + } /** * A variant of the __call__ method with two arguments. The default @@ -386,6 +403,10 @@ return __call__(new PyObject[] { arg0, arg1 }, Py.NoKeywords); } + public PyObject __call__(ThreadState state, PyObject arg0, PyObject arg1) { + return __call__(arg0, arg1); + } + /** * A variant of the __call__ method with three arguments. The default * behavior is to invoke <code>__call__(args, keywords)</code> with the @@ -399,6 +420,10 @@ public PyObject __call__(PyObject arg0, PyObject arg1, PyObject arg2) { return __call__(new PyObject[] { arg0, arg1, arg2 }, Py.NoKeywords); } + + public PyObject __call__(ThreadState state, PyObject arg0, PyObject arg1, PyObject arg2) { + return __call__(arg0, arg1, arg2); + } /** * A variant of the __call__ method with four arguments. The default @@ -411,15 +436,15 @@ * @param arg2 the third argument to the function. * @param arg3 the fourth argument to the function. **/ - public PyObject __call__( - PyObject arg0, - PyObject arg1, - PyObject arg2, - PyObject arg3) { + public PyObject __call__(PyObject arg0, PyObject arg1, PyObject arg2, PyObject arg3) { return __call__( new PyObject[] { arg0, arg1, arg2, arg3 }, Py.NoKeywords); } + + public PyObject __call__(ThreadState state, PyObject arg0, PyObject arg1, PyObject arg2, PyObject arg3) { + return __call__(arg0, arg1, arg2, arg3); + } /** @deprecated **/ public PyObject _callextra(PyObject[] args, Modified: trunk/jython/src/org/python/core/PyReflectedFunction.java =================================================================== --- trunk/jython/src/org/python/core/PyReflectedFunction.java 2009-03-31 14:56:30 UTC (rev 6134) +++ trunk/jython/src/org/python/core/PyReflectedFunction.java 2009-03-31 15:01:43 UTC (rev 6135) @@ -180,7 +180,14 @@ } public PyObject __call__(PyObject[] args, String[] keywords) { - return __call__(null, args, keywords); + PyObject self = null; + /* + PyObject[] new_args = new PyObject[args.length - 1]; + System.arraycopy(args, 1, new_args, 0, new_args.length); + self = args[0]; + args = new_args; + */ + return __call__(self, args, keywords); } // A bunch of code to make error handling prettier Modified: trunk/jython/src/org/python/core/PyTableCode.java =================================================================== --- trunk/jython/src/org/python/core/PyTableCode.java 2009-03-31 14:56:30 UTC (rev 6134) +++ trunk/jython/src/org/python/core/PyTableCode.java 2009-03-31 15:01:43 UTC (rev 6135) @@ -122,9 +122,8 @@ } @Override - public PyObject call(PyFrame frame, PyObject closure) { + public PyObject call(ThreadState ts, PyFrame frame, PyObject closure) { // System.err.println("tablecode call: "+co_name); - ThreadState ts = Py.getThreadState(); if (ts.systemState == null) { ts.systemState = Py.defaultSystemState; } @@ -163,7 +162,7 @@ PyObject ret; try { - ret = funcs.call_function(func_id, frame); + ret = funcs.call_function(func_id, frame, ts); } catch (Throwable t) { // Convert exceptions that occured in Java code to PyExceptions PyException pye = Py.JavaError(t); Modified: trunk/jython/src/org/python/core/ReflectedArgs.java =================================================================== --- trunk/jython/src/org/python/core/ReflectedArgs.java 2009-03-31 14:56:30 UTC (rev 6134) +++ trunk/jython/src/org/python/core/ReflectedArgs.java 2009-03-31 15:01:43 UTC (rev 6135) @@ -52,10 +52,11 @@ if (this.isStatic) { if (self != null) { /* - * PyObject[] newArgs = new PyObject[pyArgs.length+1]; - * System.arraycopy(pyArgs, 0, newArgs, 1, pyArgs.length); - * newArgs[0] = self; pyArgs = newArgs; - */ + PyObject[] newArgs = new PyObject[pyArgs.length+1]; + System.arraycopy(pyArgs, 0, newArgs, 1, pyArgs.length); + newArgs[0] = self; + pyArgs = newArgs; + //*/ self = null; } } else { Modified: trunk/jython/src/org/python/core/imp.java =================================================================== --- trunk/jython/src/org/python/core/imp.java 2009-03-31 14:56:30 UTC (rev 6134) +++ trunk/jython/src/org/python/core/imp.java 2009-03-31 15:01:43 UTC (rev 6135) @@ -313,7 +313,7 @@ try { PyFrame f = new PyFrame(code, module.__dict__, module.__dict__, null); - code.call(f); + code.call(Py.getThreadState(), f); } catch (RuntimeException t) { removeModule(name); throw t; This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <pj...@us...> - 2009-04-10 05:01:35
|
Revision: 6204 http://jython.svn.sourceforge.net/jython/?rev=6204&view=rev Author: pjenvey Date: 2009-04-10 05:01:22 +0000 (Fri, 10 Apr 2009) Log Message: ----------- fix a new GlobalRef being tracked (reaped) for every getweakrefcount/getweakrefs query Modified Paths: -------------- trunk/jython/src/org/python/core/PyType.java trunk/jython/src/org/python/modules/_weakref/GlobalRef.java trunk/jython/src/org/python/modules/_weakref/WeakrefModule.java Modified: trunk/jython/src/org/python/core/PyType.java =================================================================== --- trunk/jython/src/org/python/core/PyType.java 2009-04-10 04:27:38 UTC (rev 6203) +++ trunk/jython/src/org/python/core/PyType.java 2009-04-10 05:01:22 UTC (rev 6204) @@ -18,7 +18,7 @@ import org.python.expose.ExposedSet; import org.python.expose.ExposedType; import org.python.expose.TypeBuilder; -import org.python.modules._weakref.GlobalRef; +import org.python.modules._weakref.WeakrefModule; import org.python.util.Generic; /** @@ -325,7 +325,7 @@ @Override public Object invokeGet(PyObject obj) { - PyList weakrefs = GlobalRef.newInstance(obj).refs(); + PyList weakrefs = WeakrefModule.getweakrefs(obj); switch (weakrefs.size()) { case 0: return Py.None; Modified: trunk/jython/src/org/python/modules/_weakref/GlobalRef.java =================================================================== --- trunk/jython/src/org/python/modules/_weakref/GlobalRef.java 2009-04-10 04:27:38 UTC (rev 6203) +++ trunk/jython/src/org/python/modules/_weakref/GlobalRef.java 2009-04-10 05:01:22 UTC (rev 6204) @@ -110,6 +110,12 @@ return new PyList(list); } + /** + * Create a new tracked GlobalRef. + * + * @param object a PyObject to reference + * @return a new tracked GlobalRef + */ public static GlobalRef newInstance(PyObject object) { GlobalRef ref = objects.get(new GlobalRef(object)); if (ref == null) { @@ -120,6 +126,28 @@ } /** + * Return the number of references to the specified PyObject. + * + * @param object a PyObject + * @return an int reference count + */ + public static int getCount(PyObject object) { + GlobalRef ref = objects.get(new GlobalRef(object)); + return ref == null ? 0 : ref.count(); + } + + /** + * Return a list of references to the specified PyObject. + * + * @param object a PyObject + * @return a PyList of references. may be empty + */ + public static PyList getRefs(PyObject object) { + GlobalRef ref = objects.get(new GlobalRef(object)); + return ref == null ? new PyList() : ref.refs(); + } + + /** * Allow GlobalRef's to be used as hashtable keys. */ public boolean equals(Object o) { Modified: trunk/jython/src/org/python/modules/_weakref/WeakrefModule.java =================================================================== --- trunk/jython/src/org/python/modules/_weakref/WeakrefModule.java 2009-04-10 04:27:38 UTC (rev 6203) +++ trunk/jython/src/org/python/modules/_weakref/WeakrefModule.java 2009-04-10 05:01:22 UTC (rev 6204) @@ -55,20 +55,12 @@ } } - public static int getweakrefcount(PyObject o) { - GlobalRef ref = GlobalRef.newInstance(o); - if (ref == null) { - return 0; - } - return ref.count(); + public static int getweakrefcount(PyObject object) { + return GlobalRef.getCount(object); } - public static PyList getweakrefs(PyObject o) { - GlobalRef ref = GlobalRef.newInstance(o); - if (ref == null) { - return new PyList(); - } - return ref.refs(); + public static PyList getweakrefs(PyObject object) { + return GlobalRef.getRefs(object); } } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <fwi...@us...> - 2009-04-22 01:47:24
|
Revision: 6250 http://jython.svn.sourceforge.net/jython/?rev=6250&view=rev Author: fwierzbicki Date: 2009-04-22 01:47:20 +0000 (Wed, 22 Apr 2009) Log Message: ----------- Factored out calls like: imp.load("os").__getattr__("isatty").__call__(Py.java2py(fd)).__nonzero__(); into FileUtil#isatty and added a fallback to do a simple isatty check modeled after jna-posix JavaPOSIX#isatty. This allows jython to run without Lib/ which was broken. Modified Paths: -------------- trunk/jython/src/org/python/core/io/FileIO.java trunk/jython/src/org/python/core/io/StreamIO.java trunk/jython/src/org/python/core/util/FileUtil.java trunk/jython/src/org/python/util/jython.java Modified: trunk/jython/src/org/python/core/io/FileIO.java =================================================================== --- trunk/jython/src/org/python/core/io/FileIO.java 2009-04-21 03:13:55 UTC (rev 6249) +++ trunk/jython/src/org/python/core/io/FileIO.java 2009-04-22 01:47:20 UTC (rev 6250) @@ -15,6 +15,7 @@ import com.kenai.constantine.platform.Errno; import org.python.core.imp; import org.python.core.Py; +import org.python.core.util.FileUtil; import org.python.core.util.RelativeFile; /** @@ -181,7 +182,7 @@ return false; } try { - return imp.load("os").invoke("isatty", Py.java2py(file.getFD())).__nonzero__(); + return FileUtil.isatty(file.getFD()); } catch (IOException e) { return false; } Modified: trunk/jython/src/org/python/core/io/StreamIO.java =================================================================== --- trunk/jython/src/org/python/core/io/StreamIO.java 2009-04-21 03:13:55 UTC (rev 6249) +++ trunk/jython/src/org/python/core/io/StreamIO.java 2009-04-22 01:47:20 UTC (rev 6250) @@ -18,6 +18,7 @@ import org.python.core.Py; import org.python.core.imp; +import org.python.core.util.FileUtil; /** * Raw I/O implementation for simple streams. @@ -217,7 +218,7 @@ return false; } - return imp.load("os").__getattr__("isatty").__call__(Py.java2py(fd)).__nonzero__(); + return FileUtil.isatty(fd); } /** {@inheritDoc} */ Modified: trunk/jython/src/org/python/core/util/FileUtil.java =================================================================== --- trunk/jython/src/org/python/core/util/FileUtil.java 2009-04-21 03:13:55 UTC (rev 6249) +++ trunk/jython/src/org/python/core/util/FileUtil.java 2009-04-22 01:47:20 UTC (rev 6250) @@ -2,10 +2,14 @@ package org.python.core.util; import java.io.ByteArrayOutputStream; +import java.io.FileDescriptor; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; +import org.python.core.imp; +import org.python.core.Py; +import org.python.core.PyException; import org.python.core.PyFile; /** @@ -60,4 +64,18 @@ } return out.toByteArray(); } + + public static boolean isatty(FileDescriptor fd) { + boolean atty = false; + try { + atty = imp.load("os").__getattr__("isatty").__call__(Py.java2py(fd)).__nonzero__(); + } catch (PyException e) { + //Weak isatty check copied from jna-posix JavaPOSIX class + return (fd == FileDescriptor.in + || fd == FileDescriptor.out + || fd == FileDescriptor.err); + } + return atty; + } + } Modified: trunk/jython/src/org/python/util/jython.java =================================================================== --- trunk/jython/src/org/python/util/jython.java 2009-04-21 03:13:55 UTC (rev 6249) +++ trunk/jython/src/org/python/util/jython.java 2009-04-22 01:47:20 UTC (rev 6250) @@ -24,6 +24,7 @@ import org.python.core.PyStringMap; import org.python.core.PySystemState; import org.python.core.imp; +import org.python.core.util.FileUtil; import org.python.core.util.RelativeFile; import org.python.modules._systemrestart; import org.python.modules.thread.thread; @@ -220,7 +221,7 @@ } catch (java.io.FileNotFoundException e) { throw Py.IOError(e); } - if (imp.load("os").__getattr__("isatty").__call__(Py.java2py(file.getFD())).__nonzero__()) { + if (FileUtil.isatty(file.getFD())) { opts.interactive = true; interp.interact(null, new PyFile(file)); System.exit(0); This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <otm...@us...> - 2009-04-24 08:35:55
|
Revision: 6260 http://jython.svn.sourceforge.net/jython/?rev=6260&view=rev Author: otmarhumbel Date: 2009-04-24 08:35:48 +0000 (Fri, 24 Apr 2009) Log Message: ----------- enable overriding registry file entries with system properties (makes test_java_visibility pass again) Modified Paths: -------------- trunk/jython/src/org/python/core/PySystemState.java trunk/jython/src/org/python/util/PythonInterpreter.java Modified: trunk/jython/src/org/python/core/PySystemState.java =================================================================== --- trunk/jython/src/org/python/core/PySystemState.java 2009-04-24 05:16:57 UTC (rev 6259) +++ trunk/jython/src/org/python/core/PySystemState.java 2009-04-24 08:35:48 UTC (rev 6260) @@ -12,6 +12,7 @@ import java.nio.charset.Charset; import java.nio.charset.UnsupportedCharsetException; import java.security.AccessControlException; +import java.util.Iterator; import java.util.Map; import java.util.Properties; import java.util.StringTokenizer; @@ -618,11 +619,20 @@ private static void addRegistryFile(File file) { if (file.exists()) { if (!file.isDirectory()) { - registry = new Properties(registry); + // pre (e.g. system) properties should override the registry, + // therefore only add missing properties from this registry file + Properties fileProperties = new Properties(); try { FileInputStream fp = new FileInputStream(file); try { - registry.load(fp); + fileProperties.load(fp); + Iterator<Object> iterator = fileProperties.keySet().iterator(); + while (iterator.hasNext()) { + Object key = iterator.next(); + if (!registry.containsKey(key)) { + registry.put(key, fileProperties.get(key)); + } + } } finally { fp.close(); } Modified: trunk/jython/src/org/python/util/PythonInterpreter.java =================================================================== --- trunk/jython/src/org/python/util/PythonInterpreter.java 2009-04-24 05:16:57 UTC (rev 6259) +++ trunk/jython/src/org/python/util/PythonInterpreter.java 2009-04-24 08:35:48 UTC (rev 6260) @@ -36,6 +36,7 @@ * * @param preProperties * A set of properties. Typically System.getProperties() is used. + * PreProperties override properties from the registry file. * @param postProperties * An other set of properties. Values like python.home, python.path and all other * values from the registry files can be added to this property set. PostProperties This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <pj...@us...> - 2009-05-10 02:14:28
|
Revision: 6322 http://jython.svn.sourceforge.net/jython/?rev=6322&view=rev Author: pjenvey Date: 2009-05-10 01:34:53 +0000 (Sun, 10 May 2009) Log Message: ----------- drive encoding from python.console.encoding falling back to file.encoding Modified Paths: -------------- trunk/jython/src/org/python/core/PySystemState.java trunk/jython/src/org/python/util/jython.java Modified: trunk/jython/src/org/python/core/PySystemState.java =================================================================== --- trunk/jython/src/org/python/core/PySystemState.java 2009-05-10 00:00:52 UTC (rev 6321) +++ trunk/jython/src/org/python/core/PySystemState.java 2009-05-10 01:34:53 UTC (rev 6322) @@ -36,6 +36,7 @@ { public static final String PYTHON_CACHEDIR = "python.cachedir"; public static final String PYTHON_CACHEDIR_SKIP = "python.cachedir.skip"; + public static final String PYTHON_CONSOLE_ENCODING = "python.console.encoding"; protected static final String CACHEDIR_DEFAULT_NAME = "cachedir"; public static final String JYTHON_JAR = "jython.jar"; @@ -216,12 +217,7 @@ } private void initEncoding() { - String encoding; - try { - encoding = System.getProperty("file.encoding"); - } catch (SecurityException se) { - encoding = null; - } + String encoding = registry.getProperty("python.console.encoding"); if (encoding == null) { return; } @@ -631,6 +627,15 @@ registry.put(PYTHON_CACHEDIR_SKIP, "true"); } } + if (!registry.containsKey(PYTHON_CONSOLE_ENCODING)) { + String encoding; + try { + encoding = System.getProperty("file.encoding"); + } catch (SecurityException se) { + encoding = null; + } + registry.put(PYTHON_CONSOLE_ENCODING, encoding); + } // Set up options from registry Options.setFromRegistry(); } Modified: trunk/jython/src/org/python/util/jython.java =================================================================== --- trunk/jython/src/org/python/util/jython.java 2009-05-10 00:00:52 UTC (rev 6321) +++ trunk/jython/src/org/python/util/jython.java 2009-05-10 01:34:53 UTC (rev 6322) @@ -280,8 +280,7 @@ if (opts.fixInteractive || (opts.filename == null && opts.command == null)) { if (opts.encoding == null) { - opts.encoding = PySystemState.registry.getProperty( - "python.console.encoding", null); + opts.encoding = PySystemState.registry.getProperty("python.console.encoding"); } if (opts.encoding != null) { if (!Charset.isSupported(opts.encoding)) { @@ -422,6 +421,7 @@ warnoptions.add(args[++index]); } else if (arg.equals("-C")) { encoding = args[++index]; + setProperty("python.console.encoding", encoding); } else if (arg.equals("-E")) { // XXX: accept -E (ignore environment variables) to be compatiable with // CPython. do nothing for now (we could ignore the registry) This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <pj...@us...> - 2009-05-11 00:49:39
|
Revision: 6334 http://jython.svn.sourceforge.net/jython/?rev=6334&view=rev Author: pjenvey Date: 2009-05-11 00:49:23 +0000 (Mon, 11 May 2009) Log Message: ----------- quiet some warnings Modified Paths: -------------- trunk/jython/src/org/python/core/PyString.java trunk/jython/src/org/python/core/exceptions.java trunk/jython/src/org/python/modules/itertools.java trunk/jython/src/org/python/modules/random/PyRandom.java trunk/jython/src/org/python/modules/sre/PatternObject.java trunk/jython/src/org/python/modules/sre/SRE_STATE.java Modified: trunk/jython/src/org/python/core/PyString.java =================================================================== --- trunk/jython/src/org/python/core/PyString.java 2009-05-11 00:48:39 UTC (rev 6333) +++ trunk/jython/src/org/python/core/PyString.java 2009-05-11 00:49:23 UTC (rev 6334) @@ -590,7 +590,7 @@ return StringUtil.toBytes(string); } - public Object __tojava__(Class c) { + public Object __tojava__(Class<?> c) { if (c.isAssignableFrom(String.class)) { return string; } Modified: trunk/jython/src/org/python/core/exceptions.java =================================================================== --- trunk/jython/src/org/python/core/exceptions.java 2009-05-11 00:48:39 UTC (rev 6333) +++ trunk/jython/src/org/python/core/exceptions.java 2009-05-11 00:49:23 UTC (rev 6334) @@ -634,11 +634,12 @@ return bindStaticJavaMethod(name, exceptions.class, methodName); } - public static PyObject bindStaticJavaMethod(String name, Class cls, String methodName) { + public static PyObject bindStaticJavaMethod(String name, Class<?> cls, String methodName) { Method javaMethod; try { - javaMethod = cls.getMethod(methodName, new Class[] {PyObject.class, PyObject[].class, - String[].class}); + javaMethod = cls.getMethod(methodName, + new Class<?>[] {PyObject.class, PyObject[].class, + String[].class}); } catch (Exception e) { throw Py.JavaError(e); } Modified: trunk/jython/src/org/python/modules/itertools.java =================================================================== --- trunk/jython/src/org/python/modules/itertools.java 2009-05-11 00:48:39 UTC (rev 6333) +++ trunk/jython/src/org/python/modules/itertools.java 2009-05-11 00:49:23 UTC (rev 6334) @@ -109,15 +109,14 @@ */ public static PyIterator cycle(final PyObject sequence) { return new ItertoolsIterator() { - List saved = new ArrayList(); + List<PyObject> saved = new ArrayList<PyObject>(); int counter = 0; PyObject iter = sequence.__iter__(); boolean save = true; public PyObject __iternext__() { - - if(save) { + if (save) { PyObject obj = nextElement(iter); if (obj != null) { saved.add(obj); @@ -126,16 +125,16 @@ save = false; } } - if(saved.size() == 0) { + if (saved.size() == 0) { return null; } // pick element from saved List - if(counter >= saved.size()) { + if (counter >= saved.size()) { // start over again counter = 0; } - return (PyObject) saved.get(counter++); + return (PyObject)saved.get(counter++); } }; Modified: trunk/jython/src/org/python/modules/random/PyRandom.java =================================================================== --- trunk/jython/src/org/python/modules/random/PyRandom.java 2009-05-11 00:48:39 UTC (rev 6333) +++ trunk/jython/src/org/python/modules/random/PyRandom.java 2009-05-11 00:49:23 UTC (rev 6334) @@ -48,7 +48,7 @@ if (seed instanceof PyLong) { PyLong max = new PyLong(Long.MAX_VALUE); PyLong seed_modulus = (PyLong)(seed.__mod__(max)); - this.javaRandom.setSeed(((PyLong)seed_modulus).asLong(0)); + this.javaRandom.setSeed(seed_modulus.asLong(0)); } else if (seed instanceof PyInteger) { this.javaRandom.setSeed(((PyInteger)seed).getValue()); } else { Modified: trunk/jython/src/org/python/modules/sre/PatternObject.java =================================================================== --- trunk/jython/src/org/python/modules/sre/PatternObject.java 2009-05-11 00:48:39 UTC (rev 6333) +++ trunk/jython/src/org/python/modules/sre/PatternObject.java 2009-05-11 00:49:23 UTC (rev 6334) @@ -246,7 +246,7 @@ SRE_STATE state = new SRE_STATE(string, start, end, flags); - final List list = new ArrayList(); + final List<PyObject> list = new ArrayList<PyObject>(); while (state.start <= state.end) { state.state_reset(); Modified: trunk/jython/src/org/python/modules/sre/SRE_STATE.java =================================================================== --- trunk/jython/src/org/python/modules/sre/SRE_STATE.java 2009-05-11 00:48:39 UTC (rev 6333) +++ trunk/jython/src/org/python/modules/sre/SRE_STATE.java 2009-05-11 00:49:23 UTC (rev 6334) @@ -365,14 +365,14 @@ boolean ok = true; for (;;) { - switch ((int)set[setidx++]) { + switch (set[setidx++]) { case SRE_OP_FAILURE: TRACE(setidx, ch, "CHARSET FAILURE"); return !ok; case SRE_OP_LITERAL: - TRACE(setidx, ch, "CHARSET LITERAL " + (int) set[setidx]); + TRACE(setidx, ch, "CHARSET LITERAL " + set[setidx]); /* <LITERAL> <code> */ if (ch == set[setidx]) return ok; @@ -381,8 +381,8 @@ case SRE_OP_CATEGORY: /* <CATEGORY> <code> */ - TRACE(setidx, ch, "CHARSET CHARSET " + (int) set[setidx]); - if (sre_category((int)set[setidx], ch)) + TRACE(setidx, ch, "CHARSET CHARSET " + set[setidx]); + if (sre_category(set[setidx], ch)) return ok; setidx++; break; @@ -403,7 +403,7 @@ case SRE_OP_RANGE: /* <RANGE> <lower> <upper> */ - TRACE(setidx, ch, "CHARSET RANGE " + (int) set[setidx] + " " + (int) set[setidx+1]); + TRACE(setidx, ch, "CHARSET RANGE " + set[setidx] + " " + set[setidx+1]); if (set[setidx] <= ch && ch <= set[setidx+1]) return ok; setidx += 2; @@ -494,7 +494,7 @@ case SRE_OP_LITERAL_IGNORE: /* repeated literal */ chr = pattern[pidx+1]; - TRACE(pidx, ptr, "COUNT LITERAL_IGNORE " + (int) chr); + TRACE(pidx, ptr, "COUNT LITERAL_IGNORE " + chr); while (ptr < end && lower(str[ptr]) == chr) ptr++; break; @@ -502,7 +502,7 @@ case SRE_OP_NOT_LITERAL: /* repeated non-literal */ chr = pattern[pidx+1]; - TRACE(pidx, ptr, "COUNT NOT_LITERAL " + (int) chr); + TRACE(pidx, ptr, "COUNT NOT_LITERAL " + chr); while (ptr < end && str[ptr] != chr) ptr++; break; @@ -510,7 +510,7 @@ case SRE_OP_NOT_LITERAL_IGNORE: /* repeated non-literal */ chr = pattern[pidx+1]; - TRACE(pidx, ptr, "COUNT NOT_LITERAL_IGNORE " + (int) chr); + TRACE(pidx, ptr, "COUNT NOT_LITERAL_IGNORE " + chr); while (ptr < end && lower(str[ptr]) != chr) ptr++; break; @@ -564,8 +564,8 @@ case SRE_OP_MARK: /* set mark */ /* <MARK> <gid> */ - TRACE(pidx, ptr, "MARK " + (int) pattern[pidx]); - i = (int)pattern[pidx]; + TRACE(pidx, ptr, "MARK " + pattern[pidx]); + i = pattern[pidx]; if ((i & 1) != 0) this.lastindex = i / 2 + 1; if (i > this.lastmark) @@ -577,7 +577,7 @@ case SRE_OP_LITERAL: /* match literal character */ /* <LITERAL> <code> */ - TRACE(pidx, ptr, "LITERAL " + (int) pattern[pidx]); + TRACE(pidx, ptr, "LITERAL " + pattern[pidx]); if (ptr >= end || str[ptr] != pattern[pidx]) return 0; @@ -588,7 +588,7 @@ case SRE_OP_NOT_LITERAL: /* match anything that is not literal character */ /* args: <code> */ - TRACE(pidx, ptr, "NOT_LITERAL " + (int) pattern[pidx]); + TRACE(pidx, ptr, "NOT_LITERAL " + pattern[pidx]); if (ptr >= end || str[ptr] == pattern[pidx]) return 0; pidx++; @@ -604,8 +604,8 @@ case SRE_OP_AT: /* match at given position */ /* <AT> <code> */ - TRACE(pidx, ptr, "AT " + (int) pattern[pidx]); - if (!SRE_AT(ptr, (int)pattern[pidx])) + TRACE(pidx, ptr, "AT " + pattern[pidx]); + if (!SRE_AT(ptr, pattern[pidx])) return 0; pidx++; break; @@ -613,9 +613,9 @@ case SRE_OP_CATEGORY: /* match at given category */ /* <CATEGORY> <code> */ - TRACE(pidx, ptr, "CATEGORY " + (int)pattern[pidx]); + TRACE(pidx, ptr, "CATEGORY " + pattern[pidx]); - if (ptr >= end || !sre_category((int)pattern[pidx], str[ptr])) + if (ptr >= end || !sre_category(pattern[pidx], str[ptr])) return 0; pidx++; @@ -650,7 +650,7 @@ break; case SRE_OP_LITERAL_IGNORE: - TRACE(pidx, ptr, "LITERAL_IGNORE " + (int) pattern[pidx]); + TRACE(pidx, ptr, "LITERAL_IGNORE " + pattern[pidx]); if (ptr >= end || lower(str[ptr]) != lower(pattern[pidx])) return 0; pidx++; @@ -658,7 +658,7 @@ break; case SRE_OP_NOT_LITERAL_IGNORE: - TRACE(pidx, ptr, "NOT_LITERAL_IGNORE " + (int) pattern[pidx]); + TRACE(pidx, ptr, "NOT_LITERAL_IGNORE " + pattern[pidx]); if (ptr >= end || lower(str[ptr]) == lower(pattern[pidx])) return 0; pidx++; @@ -679,7 +679,7 @@ case SRE_OP_INFO: /* jump forward */ /* <JUMP> <offset> */ - TRACE(pidx, ptr, "JUMP " + (int) pattern[pidx]); + TRACE(pidx, ptr, "JUMP " + pattern[pidx]); pidx += pattern[pidx]; break; @@ -724,7 +724,7 @@ int mincount = pattern[pidx+1]; - TRACE(pidx, ptr, "REPEAT_ONE " + mincount + " " + (int)pattern[pidx+2]); + TRACE(pidx, ptr, "REPEAT_ONE " + mincount + " " + pattern[pidx+2]); if (ptr + mincount > end) return 0; /* cannot match */ @@ -860,7 +860,7 @@ by the UNTIL operator (MAX_UNTIL, MIN_UNTIL) */ /* <REPEAT> <skip> <1=min> <2=max> item <UNTIL> tail */ - TRACE(pidx, ptr, "REPEAT " + (int)pattern[pidx+1] + " " + (int)pattern[pidx+2]); + TRACE(pidx, ptr, "REPEAT " + pattern[pidx+1] + " " + pattern[pidx+2]); SRE_REPEAT rep = new SRE_REPEAT(repeat); rep.count = -1; @@ -1033,7 +1033,7 @@ case SRE_OP_ASSERT: /* assert subpattern */ /* args: <skip> <back> <pattern> */ - TRACE(pidx, ptr, "ASSERT " + (int) pattern[pidx+1]); + TRACE(pidx, ptr, "ASSERT " + pattern[pidx+1]); this.ptr = ptr - pattern[pidx + 1]; if (this.ptr < this.beginning) @@ -1047,7 +1047,7 @@ case SRE_OP_ASSERT_NOT: /* assert not subpattern */ /* args: <skip> <pattern> */ - TRACE(pidx, ptr, "ASSERT_NOT " + (int) pattern[pidx]); + TRACE(pidx, ptr, "ASSERT_NOT " + pattern[pidx]); this.ptr = ptr - pattern[pidx + 1]; if (this.ptr >= this.beginning) { i = SRE_MATCH(pattern, pidx + 2, level + 1); @@ -1065,7 +1065,7 @@ return 0; default: - TRACE(pidx, ptr, "UNKNOWN " + (int) pattern[pidx-1]); + TRACE(pidx, ptr, "UNKNOWN " + pattern[pidx-1]); return SRE_ERROR_ILLEGAL; } } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <zy...@us...> - 2009-05-11 02:39:20
|
Revision: 6335 http://jython.svn.sourceforge.net/jython/?rev=6335&view=rev Author: zyasoft Date: 2009-05-11 02:39:06 +0000 (Mon, 11 May 2009) Log Message: ----------- Applied fixes to problems found by findbugs. Modified Paths: -------------- trunk/jython/src/org/python/core/Py.java trunk/jython/src/org/python/core/PyBytecode.java trunk/jython/src/org/python/core/PyInstance.java trunk/jython/src/org/python/core/PyJavaType.java trunk/jython/src/org/python/core/PySystemState.java trunk/jython/src/org/python/core/PyUnicode.java trunk/jython/src/org/python/core/packagecache/CachedJarsPackageManager.java trunk/jython/src/org/python/core/packagecache/PathPackageManager.java trunk/jython/src/org/python/modules/cStringIO.java trunk/jython/src/org/python/modules/time/Time.java trunk/jython/src/org/python/util/jython.java Modified: trunk/jython/src/org/python/core/Py.java =================================================================== --- trunk/jython/src/org/python/core/Py.java 2009-05-11 00:49:23 UTC (rev 6334) +++ trunk/jython/src/org/python/core/Py.java 2009-05-11 02:39:06 UTC (rev 6335) @@ -490,15 +490,15 @@ /* Helper functions for PyProxy's */ /* Convenience methods to create new constants without using "new" */ - private static PyInteger[] integerCache = null; + private final static PyInteger[] integerCache = new PyInteger[1000]; + static { + for (int j = -100; j < 900; j++) { + integerCache[j + 100] = new PyInteger(j); + } + } + public static final PyInteger newInteger(int i) { - if (integerCache == null) { - integerCache = new PyInteger[1000]; - for (int j = -100; j < 900; j++) { - integerCache[j + 100] = new PyInteger(j); - } - } if (i >= -100 && i < 900) { return integerCache[i + 100]; } else { @@ -1442,8 +1442,15 @@ throw Py.TypeError("None required for void return"); } } - private static PyString[] letters = null; + + private final static PyString[] letters = new PyString[256]; + static { + for (char j = 0; j < 256; j++) { + letters[j] = new PyString(new Character(j).toString()); + } + } + public static final PyString makeCharacter(Character o) { return makeCharacter(o.charValue()); } @@ -1461,13 +1468,6 @@ } else if (codepoint > 256) { return new PyString((char)codepoint); } - - if (letters == null) { - letters = new PyString[256]; - for (char j = 0; j < 256; j++) { - letters[j] = new PyString(new Character(j).toString()); - } - } return letters[codepoint]; } Modified: trunk/jython/src/org/python/core/PyBytecode.java =================================================================== --- trunk/jython/src/org/python/core/PyBytecode.java 2009-05-11 00:49:23 UTC (rev 6334) +++ trunk/jython/src/org/python/core/PyBytecode.java 2009-05-11 02:39:06 UTC (rev 6335) @@ -175,7 +175,7 @@ }; // to enable why's to be stored on a PyStack - private class PyStackWhy extends PyObject { + private static class PyStackWhy extends PyObject { Why why; @@ -189,7 +189,7 @@ } } - private class PyStackException extends PyObject { + private static class PyStackException extends PyObject { PyException exception; @@ -1361,7 +1361,7 @@ // XXX - perhaps add support for max stack size (presumably from co_stacksize) // and capacity hints - private class PyStack { + private static class PyStack { final List<PyObject> stack; @@ -1479,7 +1479,7 @@ } } - private class PyTryBlock extends PyObject { // purely to sit on top of the existing PyFrame in f_exits!!! + private static class PyTryBlock extends PyObject { // purely to sit on top of the existing PyFrame in f_exits!!! int b_type; /* what kind of block this is */ Modified: trunk/jython/src/org/python/core/PyInstance.java =================================================================== --- trunk/jython/src/org/python/core/PyInstance.java 2009-05-11 00:49:23 UTC (rev 6334) +++ trunk/jython/src/org/python/core/PyInstance.java 2009-05-11 02:39:06 UTC (rev 6335) @@ -123,7 +123,7 @@ if (args.length != 0) { init = instclass.lookup("__init__"); if (init != null) { - ret = init.__call__(this, args, keywords); + init.__call__(this, args, keywords); } else { throw Py.TypeError("this constructor takes no arguments"); } Modified: trunk/jython/src/org/python/core/PyJavaType.java =================================================================== --- trunk/jython/src/org/python/core/PyJavaType.java 2009-05-11 00:49:23 UTC (rev 6334) +++ trunk/jython/src/org/python/core/PyJavaType.java 2009-05-11 02:39:06 UTC (rev 6335) @@ -890,9 +890,6 @@ @Override public void setSlice(int start, int stop, int step, PyObject value) { - if (stop < start) { - stop = start; - } if (step == 0) { return; } Modified: trunk/jython/src/org/python/core/PySystemState.java =================================================================== --- trunk/jython/src/org/python/core/PySystemState.java 2009-05-11 00:49:23 UTC (rev 6334) +++ trunk/jython/src/org/python/core/PySystemState.java 2009-05-11 02:39:06 UTC (rev 6335) @@ -13,6 +13,7 @@ import java.nio.charset.UnsupportedCharsetException; import java.security.AccessControlException; import java.util.Map; +import java.util.Map.Entry; import java.util.Properties; import java.util.StringTokenizer; import java.util.jar.JarEntry; @@ -650,9 +651,10 @@ FileInputStream fp = new FileInputStream(file); try { fileProperties.load(fp); - for (Object key : fileProperties.keySet()) { + for (Entry kv : fileProperties.entrySet()) { + Object key = kv.getKey(); if (!registry.containsKey(key)) { - registry.put(key, fileProperties.get(key)); + registry.put(key, kv.getValue()); } } } finally { Modified: trunk/jython/src/org/python/core/PyUnicode.java =================================================================== --- trunk/jython/src/org/python/core/PyUnicode.java 2009-05-11 00:49:23 UTC (rev 6334) +++ trunk/jython/src/org/python/core/PyUnicode.java 2009-05-11 02:39:06 UTC (rev 6335) @@ -365,7 +365,7 @@ } } - private class SteppedIterator<T> implements Iterator { + private static class SteppedIterator<T> implements Iterator { private final Iterator<T> iter; private final int step; @@ -526,7 +526,7 @@ return new PyUnicode(buffer); } - private class StripIterator implements Iterator { + private static class StripIterator implements Iterator { private final Iterator<Integer> iter; private int lookahead = -1; @@ -715,7 +715,7 @@ } } - private class PeekIterator<T> implements Iterator { + private static class PeekIterator<T> implements Iterator { private T lookahead = null; private final Iterator<T> iter; @@ -744,7 +744,7 @@ } } - private class ReversedIterator<T> implements Iterator { + private static class ReversedIterator<T> implements Iterator { private final List<T> reversed = Generic.list(); private final Iterator<T> iter; Modified: trunk/jython/src/org/python/core/packagecache/CachedJarsPackageManager.java =================================================================== --- trunk/jython/src/org/python/core/packagecache/CachedJarsPackageManager.java 2009-05-11 00:49:23 UTC (rev 6334) +++ trunk/jython/src/org/python/core/packagecache/CachedJarsPackageManager.java 2009-05-11 02:39:06 UTC (rev 6335) @@ -167,13 +167,13 @@ // Turn each vector into a comma-separated String Map<String, String> transformed = Generic.map(); - for (String key : zipPackages.keySet()) { - List<String>[] vec = zipPackages.get(key); + for (Entry<String,List<String>[]> kv : zipPackages.entrySet()) { + List<String>[] vec = kv.getValue(); String classes = listToString(vec[0]); if (vec[1].size() > 0) { classes += '@' + listToString(vec[1]); } - transformed.put(key, classes); + transformed.put(kv.getKey(), classes); } return transformed; @@ -344,6 +344,7 @@ // Read in cache file storing package info for a single .jar // Return null and delete this cachefile if it is invalid + @SuppressWarnings("empty-statement") private Map<String, String> readCacheFile(JarXEntry entry, String jarcanon) { String cachefile = entry.cachefile; long mtime = entry.mtime; @@ -388,9 +389,9 @@ ostream.writeLong(entry.mtime); comment("rewriting cachefile for '" + jarcanon + "'"); - for (String packageName : zipPackages.keySet()) { - String classes = zipPackages.get(packageName); - ostream.writeUTF(packageName); + for (Entry<String,String> kv : zipPackages.entrySet()) { + String classes = kv.getValue(); + ostream.writeUTF(kv.getKey()); ostream.writeUTF(classes); } ostream.close(); Modified: trunk/jython/src/org/python/core/packagecache/PathPackageManager.java =================================================================== --- trunk/jython/src/org/python/core/packagecache/PathPackageManager.java 2009-05-11 00:49:23 UTC (rev 6334) +++ trunk/jython/src/org/python/core/packagecache/PathPackageManager.java 2009-05-11 02:39:06 UTC (rev 6335) @@ -64,7 +64,7 @@ return false; } - class PackageExistsFileFilter implements FilenameFilter { + private static class PackageExistsFileFilter implements FilenameFilter { private boolean java; private boolean python; Modified: trunk/jython/src/org/python/modules/cStringIO.java =================================================================== --- trunk/jython/src/org/python/modules/cStringIO.java 2009-05-11 00:49:23 UTC (rev 6334) +++ trunk/jython/src/org/python/modules/cStringIO.java 2009-05-11 02:39:06 UTC (rev 6335) @@ -33,7 +33,7 @@ // would be nicer if we directly imported from os, but crazy to do so // since in python code itself - private class os { + private static class os { public static final int SEEK_SET = 0; public static final int SEEK_CUR = 1; public static final int SEEK_END = 2; Modified: trunk/jython/src/org/python/modules/time/Time.java =================================================================== --- trunk/jython/src/org/python/modules/time/Time.java 2009-05-11 00:49:23 UTC (rev 6334) +++ trunk/jython/src/org/python/modules/time/Time.java 2009-05-11 02:39:06 UTC (rev 6335) @@ -344,40 +344,40 @@ "Nov", "Dec"}; - private static String _shortday(int dow) { + private synchronized static String _shortday(int dow) { // we need to hand craft shortdays[] because Java and Python have // different specifications. Java (undocumented) appears to be // first element "", followed by 0=Sun. Python says 0=Mon - try { - if (shortdays == null) { - shortdays = new String[7]; - String[] names = datesyms.getShortWeekdays(); - for (int i=0; i<6; i++) - shortdays[i] = names[i+2]; - shortdays[6] = names[1]; + if (shortdays == null) { + shortdays = new String[7]; + String[] names = datesyms.getShortWeekdays(); + for (int i = 0; i < 6; i++) { + shortdays[i] = names[i + 2]; } + shortdays[6] = names[1]; } - catch (ArrayIndexOutOfBoundsException e) { - throwValueError("day of week out of range (0-6)"); + try { + return shortdays[dow]; + } catch (ArrayIndexOutOfBoundsException e) { + throw new PyException(Py.ValueError, new PyString("day of week out of range (0-6)")); } - return shortdays[dow]; } - private static String _shortmonth(int month0to11) { + private synchronized static String _shortmonth(int month0to11) { // getShortWeekdays() returns a 13 element array with the last item // being the empty string. This is also undocumented ;-/ - try { - if (shortmonths == null) { - shortmonths = new String[12]; - String[] names = datesyms.getShortMonths(); - for (int i=0; i<12; i++) - shortmonths[i] = names[i]; + if (shortmonths == null) { + shortmonths = new String[12]; + String[] names = datesyms.getShortMonths(); + for (int i = 0; i < 12; i++) { + shortmonths[i] = names[i]; } } - catch (ArrayIndexOutOfBoundsException e) { - throwValueError("month out of range (1-12)"); + try { + return shortmonths[month0to11]; + } catch (ArrayIndexOutOfBoundsException e) { + throw new PyException(Py.ValueError, new PyString("month out of range (1-12)")); } - return shortmonths[month0to11]; } private static String _padint(int i, int target) { Modified: trunk/jython/src/org/python/util/jython.java =================================================================== --- trunk/jython/src/org/python/util/jython.java 2009-05-11 00:49:23 UTC (rev 6334) +++ trunk/jython/src/org/python/util/jython.java 2009-05-11 02:39:06 UTC (rev 6335) @@ -220,12 +220,16 @@ } catch (FileNotFoundException e) { throw Py.IOError(e); } - if (FileUtil.isatty(file.getFD())) { - opts.interactive = true; - interp.interact(null, new PyFile(file)); - System.exit(0); - } else { - interp.execfile(file, opts.filename); + try { + if (FileUtil.isatty(file.getFD())) { + opts.interactive = true; + interp.interact(null, new PyFile(file)); + System.exit(0); + } else { + interp.execfile(file, opts.filename); + } + } finally { + file.close(); } } catch (Throwable t) { if (t instanceof PyException This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |