From: <pj...@us...> - 2008-11-16 22:53:00
|
Revision: 5582 http://jython.svn.sourceforge.net/jython/?rev=5582&view=rev Author: pjenvey Date: 2008-11-16 22:52:56 +0000 (Sun, 16 Nov 2008) Log Message: ----------- fix another binop corner case -- trigger the binop 'flip' when left_type < right_type (in terms of the reversed mro) instead of left_type != right_type Modified Paths: -------------- trunk/jython/Lib/test/test_descr_jy.py trunk/jython/src/org/python/core/PyObject.java trunk/jython/src/org/python/core/PyType.java Modified: trunk/jython/Lib/test/test_descr_jy.py =================================================================== --- trunk/jython/Lib/test/test_descr_jy.py 2008-11-14 22:54:53 UTC (rev 5581) +++ trunk/jython/Lib/test/test_descr_jy.py 2008-11-16 22:52:56 UTC (rev 5582) @@ -208,7 +208,22 @@ raises(bexc, bexc_msg, lambda : func(B())) self.assertEqual(func(C()), cresult) + def test_overriding_base_binop(self): + class MulBase(object): + def __init__(self, value): + self.value = value + def __mul__(self, other): + return self.value * other.value + def __rmul__(self, other): + return other.value * self.value + class DoublerBase(MulBase): + def __mul__(self, other): + return 2 * (self.value * other.value) + class AnotherDoubler(DoublerBase): + pass + self.assertEquals(DoublerBase(2) * AnotherDoubler(3), 12) + class InPlaceTestCase(unittest.TestCase): def test_iadd(self): Modified: trunk/jython/src/org/python/core/PyObject.java =================================================================== --- trunk/jython/src/org/python/core/PyObject.java 2008-11-14 22:54:53 UTC (rev 5581) +++ trunk/jython/src/org/python/core/PyObject.java 2008-11-16 22:52:56 UTC (rev 5582) @@ -1771,14 +1771,14 @@ * test_descr.subclass_right_op. */ PyObject o1 = this; - PyObject[] where = new PyObject[1]; - PyObject where1 = null, where2 = null; - PyObject impl1 = t1.lookup_where(left, where); + int[] where = new int[1]; + int where1, where2; + PyObject impl1 = t1.lookup_where_index(left, where); where1 = where[0]; - PyObject impl2 = t2.lookup_where(right, where); + PyObject impl2 = t2.lookup_where_index(right, where); where2 = where[0]; - if (impl2 != null && where1 != where2 && (t2.isSubType(t1) || - isStrUnicodeSpecialCase(t1, t2, op))) { + if (impl2 != null && where1 < where2 && (t2.isSubType(t1) || + isStrUnicodeSpecialCase(t1, t2, op))) { PyObject tmp = o1; o1 = o2; o2 = tmp; Modified: trunk/jython/src/org/python/core/PyType.java =================================================================== --- trunk/jython/src/org/python/core/PyType.java 2008-11-14 22:54:53 UTC (rev 5581) +++ trunk/jython/src/org/python/core/PyType.java 2008-11-16 22:52:56 UTC (rev 5582) @@ -825,6 +825,34 @@ return null; } + /** + * Like lookup but also provides (in where[0]) the index of the type in the reversed + * mro -- that is, how many subtypes away from the base object the type is. + * + * @param name attribute name (must be interned) + * @param where an int[] with a length of at least 1 + * @return found PyObject or null + */ + public PyObject lookup_where_index(String name, int[] where) { + PyObject[] mro = this.mro; + if (mro == null) { + return null; + } + int i = mro.length; + for (PyObject t : mro) { + i--; + PyObject dict = t.fastGetDict(); + if (dict != null) { + PyObject obj = dict.__finditem__(name); + if (obj != null) { + where[0] = i; + return obj; + } + } + } + return null; + } + public PyObject super_lookup(PyType ref, String name) { PyObject[] mro = this.mro; if (mro == null) { This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <pj...@us...> - 2008-11-22 23:23:56
|
Revision: 5601 http://jython.svn.sourceforge.net/jython/?rev=5601&view=rev Author: pjenvey Date: 2008-11-22 23:23:48 +0000 (Sat, 22 Nov 2008) Log Message: ----------- use the compiled filename for __file__ when appropriate. make imp responsible for setting __file__ instead of the compiler being involved fixes #1138 Modified Paths: -------------- trunk/jython/Lib/inspect.py trunk/jython/Lib/test/test_chdir.py trunk/jython/Lib/test/test_import_jy.py trunk/jython/Lib/test/test_inspect.py trunk/jython/Lib/warnings.py 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/imp.java trunk/jython/src/org/python/modules/imp.java Modified: trunk/jython/Lib/inspect.py =================================================================== --- trunk/jython/Lib/inspect.py 2008-11-22 22:37:49 UTC (rev 5600) +++ trunk/jython/Lib/inspect.py 2008-11-22 23:23:48 UTC (rev 5601) @@ -383,6 +383,8 @@ filename = getfile(object) if string.lower(filename[-4:]) in ('.pyc', '.pyo'): filename = filename[:-4] + '.py' + elif filename.endswith('$py.class'): + filename = filename[:-9] + '.py' for suffix, mode, kind in imp.get_suffixes(): if 'b' in mode and string.lower(filename[-len(suffix):]) == suffix: # Looks like a binary file. We want to only return a text file. Modified: trunk/jython/Lib/test/test_chdir.py =================================================================== --- trunk/jython/Lib/test/test_chdir.py 2008-11-22 22:37:49 UTC (rev 5600) +++ trunk/jython/Lib/test/test_chdir.py 2008-11-22 23:23:48 UTC (rev 5601) @@ -361,14 +361,8 @@ __import__(self.mod_name) self.assert_(self.mod_name in sys.modules) mod = sys.modules[self.mod_name] + self.assertEqual(mod.__file__, self.mod_name + COMPILED_SUFFIX) - # XXX: Jython's import has a bug where it doesn't use the - # $py.class filename when it exists along with the .py file - if sys.platform.startswith('java'): - self.assertEqual(mod.__file__, self.mod_name + '.py') - else: - self.assertEqual(mod.__file__, self.mod_name + COMPILED_SUFFIX) - def test_compile_dest(self): py_compile.compile(self.basename1, self.basename1[:-3] + Modified: trunk/jython/Lib/test/test_import_jy.py =================================================================== --- trunk/jython/Lib/test/test_import_jy.py 2008-11-22 22:37:49 UTC (rev 5600) +++ trunk/jython/Lib/test/test_import_jy.py 2008-11-22 23:23:48 UTC (rev 5601) @@ -73,14 +73,8 @@ fp.close() module_obj = __import__('foo.test') self.assertEquals(module_obj.test.baz, 'testtest') - # XXX: Jython's import has a bug where it doesn't use the - # $py.class filename when it exists along with the .py file - if sys.platform.startswith('java'): - self.assertEqual(module_obj.test.init_file, - os.path.join('foo', '__init__.py')) - else: - self.assertEqual(module_obj.test.init_file, - os.path.join('foo', '__init__' + COMPILED_SUFFIX)) + self.assertEqual(module_obj.test.init_file, + os.path.join('foo', '__init__' + COMPILED_SUFFIX)) # Ensure a recompile of __init__$py.class wasn't triggered to # satisfy the abnormal import Modified: trunk/jython/Lib/test/test_inspect.py =================================================================== --- trunk/jython/Lib/test/test_inspect.py 2008-11-22 22:37:49 UTC (rev 5600) +++ trunk/jython/Lib/test/test_inspect.py 2008-11-22 23:23:48 UTC (rev 5601) @@ -20,6 +20,8 @@ modfile = mod.__file__ if modfile.endswith(('c', 'o')): modfile = modfile[:-1] +elif modfile.endswith('$py.class'): + modfile = modfile[:-9] + '.py' import __builtin__ Modified: trunk/jython/Lib/warnings.py =================================================================== --- trunk/jython/Lib/warnings.py 2008-11-22 22:37:49 UTC (rev 5600) +++ trunk/jython/Lib/warnings.py 2008-11-22 23:23:48 UTC (rev 5601) @@ -48,6 +48,8 @@ fnl = filename.lower() if fnl.endswith((".pyc", ".pyo")): filename = filename[:-1] + elif fnl.endswith("$py.class"): + filename = filename[:-9] + '.py' else: if module == "__main__": try: Modified: trunk/jython/src/org/python/compiler/CodeCompiler.java =================================================================== --- trunk/jython/src/org/python/compiler/CodeCompiler.java 2008-11-22 22:37:49 UTC (rev 5600) +++ trunk/jython/src/org/python/compiler/CodeCompiler.java 2008-11-22 23:23:48 UTC (rev 5601) @@ -303,12 +303,6 @@ visit(((Expr) suite.body[0]).value); code.invokevirtual("org/python/core/PyFrame", "setglobal", "(" +$str + $pyObj + ")V"); } - if (module.setFile) { - loadFrame(); - code.ldc("__file__"); - module.filename.get(code); - code.invokevirtual("org/python/core/PyFrame", "setglobal", "(" +$str + $pyObj + ")V"); - } traverse(suite); return null; } Modified: trunk/jython/src/org/python/compiler/Module.java =================================================================== --- trunk/jython/src/org/python/compiler/Module.java 2008-11-22 22:37:49 UTC (rev 5600) +++ trunk/jython/src/org/python/compiler/Module.java 2008-11-22 23:23:48 UTC (rev 5601) @@ -293,7 +293,6 @@ String sfilename; public Constant mainCode; public boolean linenumbers; - public boolean setFile=true; Future futures; Hashtable scopes; @@ -636,12 +635,10 @@ public static void compile(modType node, OutputStream ostream, String name, String filename, boolean linenumbers, boolean printResults, - boolean setFile, org.python.core.CompilerFlags cflags) throws Exception { Module module = new Module(name, filename, linenumbers); - module.setFile = setFile; if (cflags == null) { cflags = new CompilerFlags(); } @@ -649,7 +646,6 @@ new ScopesCompiler(module, module.scopes).parse(node); //Add __doc__ if it exists - //Add __file__ for filename (if it exists?) Constant main = module.PyCode(node, "<module>", false, null, false, printResults, 0, Modified: trunk/jython/src/org/python/core/Py.java =================================================================== --- trunk/jython/src/org/python/core/Py.java 2008-11-22 22:37:49 UTC (rev 5600) +++ trunk/jython/src/org/python/core/Py.java 2008-11-22 23:23:48 UTC (rev 5601) @@ -1708,8 +1708,7 @@ return Py.java2py(node); } ByteArrayOutputStream ostream = new ByteArrayOutputStream(); - Module.compile(node, ostream, name, filename, linenumbers, - printResults, false, cflags); + Module.compile(node, ostream, name, filename, linenumbers, printResults, cflags); saveClassFile(name, ostream); Modified: trunk/jython/src/org/python/core/imp.java =================================================================== --- trunk/jython/src/org/python/core/imp.java 2008-11-22 22:37:49 UTC (rev 5600) +++ trunk/jython/src/org/python/core/imp.java 2008-11-22 23:23:48 UTC (rev 5601) @@ -7,9 +7,6 @@ import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; import java.util.concurrent.locks.ReentrantLock; import org.python.core.util.FileUtil; @@ -22,9 +19,9 @@ private static final String UNKNOWN_SOURCEFILE = "<unknown>"; - public static final int APIVersion = 16; + public static final int APIVersion = 17; - //This should change to 0 for Python 2.7 and 3.0 see PEP 328 + // 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. */ @@ -88,15 +85,15 @@ } } - static PyObject createFromPyClass(String name, InputStream fp, - boolean testing, String fileName) { + static PyObject createFromPyClass(String name, InputStream fp, boolean testing, + String sourceName, String compiledName) { byte[] data = readCode(name, fp, testing); if (testing && data == null) { return null; } PyCode code; try { - code = BytecodeLoader.makeCode(name + "$py", data, fileName); + code = BytecodeLoader.makeCode(name + "$py", data, sourceName); } catch (Throwable t) { if (testing) { return null; @@ -105,14 +102,14 @@ } } - Py.writeComment(IMPORT_LOG, "'" + name + "' as " + fileName); + Py.writeComment(IMPORT_LOG, String.format("import %s # precompiled from %s", name, + compiledName)); - return createFromCode(name, code, fileName); + return createFromCode(name, code, compiledName); } public static byte[] readCode(String name, InputStream fp, boolean testing) { byte[] data = readBytes(fp); - int n = data.length; int api; try { @@ -209,7 +206,6 @@ filename, true, false, - true, null); return ofp.toByteArray(); } catch(Throwable t) { @@ -256,6 +252,15 @@ if (c instanceof PyTableCode) { code = (PyTableCode) c; } + + if (moduleLocation != null) { + module.__setattr__("__file__", new PyString(moduleLocation)); + } else if (module.__findattr__("__file__") == null) { + // Should probably never happen (but maybe with an odd custom builtins, or + // Java Integration) + Py.writeDebug(IMPORT_LOG, String.format("Warning: %s __file__ is unknown", name)); + } + try { PyFrame f = new PyFrame(code, module.__dict__, module.__dict__, null); code.call(f); @@ -263,12 +268,6 @@ Py.getSystemState().modules.__delitem__(name.intern()); throw t; } - if(moduleLocation != null) { - module.__setattr__("__file__", - new PyString(moduleLocation)); - }else{ - Py.writeDebug(IMPORT_LOG, "No fileName known to set __file__ for " + name + "."); - } return module; } @@ -419,23 +418,25 @@ return load_module.__call__(new PyObject[] { new PyString(name) }); } - public static PyObject loadFromCompiled(String name, InputStream stream, - String filename) { - return createFromPyClass(name, stream, false, filename); + public static PyObject loadFromCompiled(String name, InputStream stream, String sourceName, + String compiledName) { + return createFromPyClass(name, stream, false, sourceName, compiledName); } static PyObject loadFromSource(PySystemState sys, String name, String modName, String entry) { - + String dirName = sys.getPath(entry); String sourceName = "__init__.py"; String compiledName = "__init__$py.class"; - String directoryName = sys.getPath(entry); - // displayDirName is for identification purposes (e.g. - // __file__): when null it forces java.io.File to be a - // relative path (e.g. foo/bar.py instead of /tmp/foo/bar.py) + // display names are for identification purposes (e.g. __file__): when entry is + // null it forces java.io.File to be a relative path (e.g. foo/bar.py instead of + // /tmp/foo/bar.py) String displayDirName = entry.equals("") ? null : entry.toString(); + String displaySourceName = new File(new File(displayDirName, name), sourceName).getPath(); + String displayCompiledName = new File(new File(displayDirName, name), + compiledName).getPath(); // First check for packages - File dir = new File(directoryName, name); + File dir = new File(dirName, name); File sourceFile = new File(dir, sourceName); File compiledFile = new File(dir, compiledName); @@ -445,48 +446,38 @@ Py.writeDebug(IMPORT_LOG, "trying source " + dir.getPath()); sourceName = name + ".py"; compiledName = name + "$py.class"; - sourceFile = new File(directoryName, sourceName); - compiledFile = new File(directoryName, compiledName); + displaySourceName = new File(displayDirName, sourceName).getPath(); + displayCompiledName = new File(displayDirName, compiledName).getPath(); + sourceFile = new File(dirName, sourceName); + compiledFile = new File(dirName, compiledName); } else { PyModule m = addModule(modName); PyObject filename = new PyString(new File(displayDirName, name).getPath()); - m.__dict__.__setitem__("__path__", new PyList( - new PyObject[] { filename })); - m.__dict__.__setitem__("__file__", filename); + m.__dict__.__setitem__("__path__", new PyList(new PyObject[] {filename})); } if (sourceFile.isFile() && caseok(sourceFile, sourceName)) { - String filename; - if (pkg) { - filename = new File(new File(displayDirName, name), sourceName).getPath(); - } else { - filename = new File(displayDirName, sourceName).getPath(); - } - if(compiledFile.isFile() && caseok(compiledFile, compiledName)) { - Py.writeDebug(IMPORT_LOG, "trying precompiled " - + compiledFile.getPath()); + if (compiledFile.isFile() && caseok(compiledFile, compiledName)) { + Py.writeDebug(IMPORT_LOG, "trying precompiled " + compiledFile.getPath()); long pyTime = sourceFile.lastModified(); long classTime = compiledFile.lastModified(); - if(classTime >= pyTime) { - // XXX: filename should use compiledName here (not - // sourceName), but this currently breaks source - // code printed out in tracebacks - PyObject ret = createFromPyClass(modName, makeStream(compiledFile), - true, filename); - if(ret != null) { + if (classTime >= pyTime) { + PyObject ret = createFromPyClass(modName, makeStream(compiledFile), true, + displaySourceName, displayCompiledName); + if (ret != null) { return ret; } } } - return createFromSource(modName, makeStream(sourceFile), filename, + return createFromSource(modName, makeStream(sourceFile), displaySourceName, compiledFile.getPath()); } + // If no source, try loading precompiled - Py.writeDebug(IMPORT_LOG, "trying precompiled with no source " - + compiledFile.getPath()); - if(compiledFile.isFile() && caseok(compiledFile, compiledName)) { - String filename = new File(displayDirName, compiledName).getPath(); - return createFromPyClass(modName, makeStream(compiledFile), true, filename); + Py.writeDebug(IMPORT_LOG, "trying precompiled with no source " + compiledFile.getPath()); + if (compiledFile.isFile() && caseok(compiledFile, compiledName)) { + return createFromPyClass(modName, makeStream(compiledFile), true, displaySourceName, + displayCompiledName); } return null; } Modified: trunk/jython/src/org/python/modules/imp.java =================================================================== --- trunk/jython/src/org/python/modules/imp.java 2008-11-22 22:37:49 UTC (rev 5600) +++ trunk/jython/src/org/python/modules/imp.java 2008-11-22 23:23:48 UTC (rev 5601) @@ -186,13 +186,13 @@ if (o == Py.NoConversion) { throw Py.TypeError("must be a file-like object"); } + String compiledName; switch (type) { case PY_SOURCE: // XXX: This should load the accompanying byte // code file instead, if it exists String resolvedFilename = sys.getPath(filename.toString()); - String compiledName = - org.python.core.imp.makeCompiledFilename(resolvedFilename); + compiledName = org.python.core.imp.makeCompiledFilename(resolvedFilename); if (name.endsWith(".__init__")) { name = name.substring(0, name.length() - ".__init__".length()); } else if (name.equals("__init__")) { @@ -204,8 +204,15 @@ compiledName); break; case PY_COMPILED: + compiledName = filename.toString(); + // XXX: Ideally we wouldn't care about sourceName here (see + // http://bugs.jython.org/issue1605847 msg3805) + String sourceName = compiledName; + if (compiledName.endsWith("$py.class")) { + sourceName = compiledName.substring(0, compiledName.length() - 9) + ".py"; + } mod = org.python.core.imp.loadFromCompiled( - name.intern(), (InputStream)o, filename.toString()); + name.intern(), (InputStream)o, sourceName, filename.toString()); break; case PKG_DIRECTORY: PyModule m = org.python.core.imp.addModule(name); This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <pj...@us...> - 2008-11-23 06:28:46
|
Revision: 5611 http://jython.svn.sourceforge.net/jython/?rev=5611&view=rev Author: pjenvey Date: 2008-11-23 06:28:45 +0000 (Sun, 23 Nov 2008) Log Message: ----------- fix the Carlo Verre hack because open builtin classes are only cool in Ruby and JavaScript, or something like that fixes #1058 and test_descr.carloverre Modified Paths: -------------- trunk/jython/Lib/test/test_descr.py trunk/jython/src/org/python/core/PyObject.java Modified: trunk/jython/Lib/test/test_descr.py =================================================================== --- trunk/jython/Lib/test/test_descr.py 2008-11-23 04:35:59 UTC (rev 5610) +++ trunk/jython/Lib/test/test_descr.py 2008-11-23 06:28:45 UTC (rev 5611) @@ -4424,9 +4424,6 @@ # Lack __basicsize__: http://bugs.jython.org/issue1017 slotmultipleinheritance, - # Carlo hacked us: http://bugs.jython.org/issue1058 - carloverre, - # Jython lacks CPython method-wrappers (though maybe this # should pass anyway?) methodwrapper, Modified: trunk/jython/src/org/python/core/PyObject.java =================================================================== --- trunk/jython/src/org/python/core/PyObject.java 2008-11-23 04:35:59 UTC (rev 5610) +++ trunk/jython/src/org/python/core/PyObject.java 2008-11-23 06:28:45 UTC (rev 5611) @@ -3591,6 +3591,7 @@ @ExposedMethod final void object___setattr__(PyObject name, PyObject value) { + hackCheck("__setattr__"); object___setattr__(asName(name), value); } @@ -3626,6 +3627,7 @@ @ExposedMethod final void object___delattr__(PyObject name) { + hackCheck("__delattr__"); object___delattr__(asName(name)); } @@ -3675,6 +3677,19 @@ } /** + * Helper to check for object.__setattr__ or __delattr__ applied to a type (The Carlo + * Verre hack). + * + * @param what String method name to check for + */ + private void hackCheck(String what) { + if (this instanceof PyType && ((PyType)this).builtin) { + throw Py.TypeError(String.format("can't apply this %s to %s object", what, + objtype.fastGetName())); + } + } + + /** * Used for pickling. Default implementation calls object___reduce__. * * @return a tuple of (class, tuple) This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <pj...@us...> - 2008-11-23 20:58:26
|
Revision: 5619 http://jython.svn.sourceforge.net/jython/?rev=5619&view=rev Author: pjenvey Date: 2008-11-23 20:58:25 +0000 (Sun, 23 Nov 2008) Log Message: ----------- fix bit rot in the Expose javatests: ensure we setType new descriptors, init sys when needed, fix null method docs (use "" instead) Modified Paths: -------------- trunk/jython/src/org/python/expose/generate/InstanceMethodExposer.java trunk/jython/tests/java/org/python/expose/generate/DescriptorExposerTest.java trunk/jython/tests/java/org/python/expose/generate/ExposedTypeProcessorTest.java Modified: trunk/jython/src/org/python/expose/generate/InstanceMethodExposer.java =================================================================== --- trunk/jython/src/org/python/expose/generate/InstanceMethodExposer.java 2008-11-23 19:35:19 UTC (rev 5618) +++ trunk/jython/src/org/python/expose/generate/InstanceMethodExposer.java 2008-11-23 20:58:25 UTC (rev 5619) @@ -28,7 +28,7 @@ new String[0], new String[0], MethodType.DEFAULT, - null); + ""); } public InstanceMethodExposer(Type onType, Modified: trunk/jython/tests/java/org/python/expose/generate/DescriptorExposerTest.java =================================================================== --- trunk/jython/tests/java/org/python/expose/generate/DescriptorExposerTest.java 2008-11-23 19:35:19 UTC (rev 5618) +++ trunk/jython/tests/java/org/python/expose/generate/DescriptorExposerTest.java 2008-11-23 20:58:25 UTC (rev 5619) @@ -33,7 +33,9 @@ DescriptorExposer de = new DescriptorExposer(ASM_TYPE, name); setup.setup(de); Class descriptor = de.load(new BytecodeLoader.Loader()); - return (PyDataDescr)descriptor.newInstance(); + PyDataDescr descr = (PyDataDescr)descriptor.newInstance(); + descr.setType(PY_TYPE); + return descr; } public PyDataDescr makeDescriptor(DescSetup setup) throws Exception { Modified: trunk/jython/tests/java/org/python/expose/generate/ExposedTypeProcessorTest.java =================================================================== --- trunk/jython/tests/java/org/python/expose/generate/ExposedTypeProcessorTest.java 2008-11-23 19:35:19 UTC (rev 5618) +++ trunk/jython/tests/java/org/python/expose/generate/ExposedTypeProcessorTest.java 2008-11-23 20:58:25 UTC (rev 5619) @@ -11,7 +11,7 @@ import org.python.core.PyObject; import org.python.core.PyType; -public class ExposedTypeProcessorTest extends TestCase { +public class ExposedTypeProcessorTest extends InterpTestCase { public void testDetectType() throws Exception { InputStream in = getClass().getClassLoader() @@ -41,6 +41,7 @@ PyBuiltinCallable bound = func.bind(simp); bound.__call__(); PyDataDescr desc = (PyDataDescr)tostringDesc.newInstance(); + desc.setType(simp.getType()); assertEquals(doctoredSimple.getField("toStringVal").get(simp), desc.__get__(simp, PyType.fromClass(doctoredSimple)).toString()); } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <pj...@us...> - 2008-11-24 02:02:51
|
Revision: 5626 http://jython.svn.sourceforge.net/jython/?rev=5626&view=rev Author: pjenvey Date: 2008-11-24 02:02:47 +0000 (Mon, 24 Nov 2008) Log Message: ----------- add an isBaseType flag to @ExposedType for toggling whether types are subclassable. disallow subclassing of builtin_function_or_method (fixes test_descr.errors). note that this requires an ant clean refs #1758319 Modified Paths: -------------- trunk/jython/Lib/test/test_descr.py trunk/jython/src/org/python/core/Py.java trunk/jython/src/org/python/core/PyBuiltinCallable.java trunk/jython/src/org/python/core/PySystemState.java trunk/jython/src/org/python/core/PyType.java trunk/jython/src/org/python/expose/BaseTypeBuilder.java trunk/jython/src/org/python/expose/ExposedType.java trunk/jython/src/org/python/expose/TypeBuilder.java trunk/jython/src/org/python/expose/generate/ExposedTypeProcessor.java trunk/jython/src/org/python/expose/generate/ExposedTypeVisitor.java trunk/jython/src/org/python/expose/generate/TypeExposer.java trunk/jython/tests/java/org/python/expose/generate/ExposedTypeVisitorTest.java trunk/jython/tests/java/org/python/expose/generate/SimpleExposed.java trunk/jython/tests/java/org/python/expose/generate/TypeExposerTest.java Modified: trunk/jython/Lib/test/test_descr.py =================================================================== --- trunk/jython/Lib/test/test_descr.py 2008-11-24 01:57:05 UTC (rev 5625) +++ trunk/jython/Lib/test/test_descr.py 2008-11-24 02:02:47 UTC (rev 5626) @@ -4404,11 +4404,6 @@ classmethods_in_c, staticmethods_in_c, - # Jython allows subclassing of classes it shouldn't (like - # builtin_function_or_method): - # http://bugs.jython.org/issue1758319 - errors, - # CPython's unicode.__cmp__ is derived from type (and only # takes 1 arg) specials, Modified: trunk/jython/src/org/python/core/Py.java =================================================================== --- trunk/jython/src/org/python/core/Py.java 2008-11-24 01:57:05 UTC (rev 5625) +++ trunk/jython/src/org/python/core/Py.java 2008-11-24 02:02:47 UTC (rev 5626) @@ -82,7 +82,9 @@ /** A Python string containing ' ' **/ public static PyString Space; /** Set if the type object is dynamically allocated */ - public static long TPFLAGS_HEAPTYPE; + public static long TPFLAGS_HEAPTYPE = 1L << 9; + /** Set if the type allows subclassing */ + public static long TPFLAGS_BASETYPE = 1L << 10; /** Builtin types that are used to setup PyObject. */ static final Set<Class> BOOTSTRAP_TYPES = new HashSet<Class>(4); Modified: trunk/jython/src/org/python/core/PyBuiltinCallable.java =================================================================== --- trunk/jython/src/org/python/core/PyBuiltinCallable.java 2008-11-24 01:57:05 UTC (rev 5625) +++ trunk/jython/src/org/python/core/PyBuiltinCallable.java 2008-11-24 02:02:47 UTC (rev 5626) @@ -3,8 +3,7 @@ import org.python.expose.ExposedGet; import org.python.expose.ExposedType; -// XXX: not subclassable -@ExposedType(name = "builtin_function_or_method") +@ExposedType(name = "builtin_function_or_method", isBaseType = false) public abstract class PyBuiltinCallable extends PyObject { protected Info info; Modified: trunk/jython/src/org/python/core/PySystemState.java =================================================================== --- trunk/jython/src/org/python/core/PySystemState.java 2008-11-24 01:57:05 UTC (rev 5625) +++ trunk/jython/src/org/python/core/PySystemState.java 2008-11-24 02:02:47 UTC (rev 5626) @@ -589,8 +589,6 @@ Py.Newline = new PyString("\n"); Py.Space = new PyString(" "); - Py.TPFLAGS_HEAPTYPE = (1L<<9); - // Setup standard wrappers for stdout and stderr... Py.stderr = new StderrWrapper(); Py.stdout = new StdoutWrapper(); Modified: trunk/jython/src/org/python/core/PyType.java =================================================================== --- trunk/jython/src/org/python/core/PyType.java 2008-11-24 01:57:05 UTC (rev 5625) +++ trunk/jython/src/org/python/core/PyType.java 2008-11-24 02:02:47 UTC (rev 5626) @@ -58,6 +58,9 @@ boolean has_set; boolean has_delete; + /** Whether this type allows subclassing. */ + private boolean isBaseType = true; + /** Whether finalization is required for this type's instances (implements __del__). */ private boolean needs_finalizer; @@ -134,7 +137,6 @@ bases_list = new PyObject[] {object_type}; } - // XXX can be subclassed ? if (dict.__finditem__("__module__") == null) { PyFrame frame = Py.getFrame(); if (frame != null) { @@ -164,6 +166,11 @@ newtype.numSlots = newtype.base.numSlots; newtype.bases = bases_list; + if (!newtype.base.isBaseType) { + throw Py.TypeError(String.format("type '%.100s' is not an acceptable base type", + newtype.base.name)); + } + PyObject slots = dict.__finditem__("__slots__"); boolean needsDictDescr = false; if (slots == null) { @@ -209,7 +216,7 @@ } } - newtype.tp_flags = Py.TPFLAGS_HEAPTYPE; + newtype.tp_flags = Py.TPFLAGS_HEAPTYPE | Py.TPFLAGS_BASETYPE; // special case __new__, if function => static method PyObject tmp = dict.__finditem__("__new__"); @@ -420,6 +427,11 @@ } + private void setIsBaseType(boolean isBaseType) { + this.isBaseType = isBaseType; + tp_flags = isBaseType ? tp_flags | Py.TPFLAGS_BASETYPE : tp_flags & ~Py.TPFLAGS_BASETYPE; + } + private void mro_internal() { if (getType() == TYPE) { mro = compute_mro(); @@ -891,6 +903,7 @@ PyType objType = fromClass(builder.getTypeClass()); objType.name = builder.getName(); objType.dict = builder.getDict(objType); + objType.setIsBaseType(builder.getIsBaseType()); Class<?> base = builder.getBase(); if (base == Object.class) { base = forClass.getSuperclass(); @@ -907,17 +920,19 @@ return exposedAs; } Class<?> base = null; + boolean isBaseType = true; String name = null; TypeBuilder tb = getBuilder(c); if (tb != null) { name = tb.getName(); + isBaseType = tb.getIsBaseType(); if (!tb.getBase().equals(Object.class)) { base = tb.getBase(); } } PyType type = class_to_type.get(c); if (type == null) { - type = createType(c, base, name); + type = createType(c, base, name, isBaseType); } return type; } @@ -926,7 +941,7 @@ return classToBuilder == null ? null : classToBuilder.get(c); } - private static PyType createType(Class<?> c, Class<?> base, String name) { + private static PyType createType(Class<?> c, Class<?> base, String name, boolean isBaseType) { PyType newtype; if (c == PyType.class) { newtype = new PyType(false); @@ -955,6 +970,7 @@ newtype.name = name; newtype.underlying_class = c; newtype.builtin = true; + newtype.setIsBaseType(isBaseType); fillInMRO(newtype, base); // basic mro, base, bases newtype.fillDict(); return newtype; Modified: trunk/jython/src/org/python/expose/BaseTypeBuilder.java =================================================================== --- trunk/jython/src/org/python/expose/BaseTypeBuilder.java 2008-11-24 01:57:05 UTC (rev 5625) +++ trunk/jython/src/org/python/expose/BaseTypeBuilder.java 2008-11-24 02:02:47 UTC (rev 5626) @@ -22,14 +22,18 @@ private String name; + private boolean isBaseType; + public BaseTypeBuilder(String name, Class typeClass, Class baseClass, + boolean isBaseType, PyBuiltinMethod[] meths, PyDataDescr[] descrs, PyNewWrapper newWrapper) { this.typeClass = typeClass; this.baseClass = baseClass; + this.isBaseType = isBaseType; this.name = name; this.descrs = descrs; this.meths = meths; @@ -64,4 +68,8 @@ public Class getBase() { return baseClass; } -} \ No newline at end of file + + public boolean getIsBaseType() { + return isBaseType; + } +} Modified: trunk/jython/src/org/python/expose/ExposedType.java =================================================================== --- trunk/jython/src/org/python/expose/ExposedType.java 2008-11-24 01:57:05 UTC (rev 5625) +++ trunk/jython/src/org/python/expose/ExposedType.java 2008-11-24 02:02:47 UTC (rev 5626) @@ -26,4 +26,9 @@ * unspecified, the base is set to object, or PyObject.class. */ Class base() default Object.class; + + /** + * @return Whether this type allows subclassing. + */ + boolean isBaseType() default true; } Modified: trunk/jython/src/org/python/expose/TypeBuilder.java =================================================================== --- trunk/jython/src/org/python/expose/TypeBuilder.java 2008-11-24 01:57:05 UTC (rev 5625) +++ trunk/jython/src/org/python/expose/TypeBuilder.java 2008-11-24 02:02:47 UTC (rev 5626) @@ -15,4 +15,6 @@ public Class getTypeClass(); public Class getBase(); + + public boolean getIsBaseType(); } Modified: trunk/jython/src/org/python/expose/generate/ExposedTypeProcessor.java =================================================================== --- trunk/jython/src/org/python/expose/generate/ExposedTypeProcessor.java 2008-11-24 01:57:05 UTC (rev 5625) +++ trunk/jython/src/org/python/expose/generate/ExposedTypeProcessor.java 2008-11-24 02:02:47 UTC (rev 5626) @@ -109,6 +109,8 @@ private Type baseType = OBJECT; + private boolean isBaseType = true; + private boolean generatedStaticBlock; private TypeProcessor(ClassVisitor cv) { @@ -140,6 +142,10 @@ public void handleResult(Type base) { baseType = base; } + + public void handleResult(boolean boolIsBaseType) { + isBaseType = boolIsBaseType; + } }; } return super.visitAnnotation(desc, visible); @@ -158,6 +164,7 @@ } typeExposer = new TypeExposer(onType, baseType, + isBaseType, getName(), methodExposers, descExposers.values(), Modified: trunk/jython/src/org/python/expose/generate/ExposedTypeVisitor.java =================================================================== --- trunk/jython/src/org/python/expose/generate/ExposedTypeVisitor.java 2008-11-24 01:57:05 UTC (rev 5625) +++ trunk/jython/src/org/python/expose/generate/ExposedTypeVisitor.java 2008-11-24 02:02:47 UTC (rev 5626) @@ -13,6 +13,8 @@ private Type base = Type.getType(Object.class); + private boolean isBaseType = true; + public ExposedTypeVisitor(Type onType) { this.onType = onType; } @@ -23,6 +25,8 @@ typeName = (String)value; } else if(name.equals("base")) { base = (Type)value; + } else if(name.equals("isBaseType")) { + isBaseType = (Boolean)value; } else { super.visit(name, value); } @@ -36,10 +40,13 @@ } handleResult(typeName); handleResult(base); + handleResult(isBaseType); } public abstract void handleResult(Type base); + public abstract void handleResult(boolean isBaseType); + /** * @param name - * the name the type should be exposed as from the annotation. Modified: trunk/jython/src/org/python/expose/generate/TypeExposer.java =================================================================== --- trunk/jython/src/org/python/expose/generate/TypeExposer.java 2008-11-24 01:57:05 UTC (rev 5625) +++ trunk/jython/src/org/python/expose/generate/TypeExposer.java 2008-11-24 02:02:47 UTC (rev 5626) @@ -18,6 +18,8 @@ private Type baseType; + private boolean isBaseType; + private Type onType; private String name; @@ -32,12 +34,14 @@ public TypeExposer(Type onType, Type baseType, + boolean isBaseType, String name, Collection<MethodExposer> methods, Collection<DescriptorExposer> descriptors, Exposer ne) { super(BaseTypeBuilder.class, makeGeneratedName(onType)); this.baseType = baseType; + this.isBaseType = isBaseType; this.onType = onType; this.name = name; this.methods = methods; @@ -101,6 +105,7 @@ mv.visitLdcInsn(getName()); mv.visitLdcInsn(onType); mv.visitLdcInsn(baseType); + mv.visitLdcInsn(isBaseType); mv.visitLdcInsn(numNames); mv.visitTypeInsn(ANEWARRAY, BUILTIN_METHOD.getInternalName()); mv.visitVarInsn(ASTORE, 1); @@ -135,7 +140,8 @@ } else { mv.visitInsn(ACONST_NULL); } - superConstructor(STRING, CLASS, CLASS, ABUILTIN_METHOD, ADATA_DESCR, PYNEWWRAPPER); + superConstructor(STRING, CLASS, CLASS, BOOLEAN, ABUILTIN_METHOD, ADATA_DESCR, + PYNEWWRAPPER); endConstructor(); } } Modified: trunk/jython/tests/java/org/python/expose/generate/ExposedTypeVisitorTest.java =================================================================== --- trunk/jython/tests/java/org/python/expose/generate/ExposedTypeVisitorTest.java 2008-11-24 01:57:05 UTC (rev 5625) +++ trunk/jython/tests/java/org/python/expose/generate/ExposedTypeVisitorTest.java 2008-11-24 02:02:47 UTC (rev 5626) @@ -20,6 +20,11 @@ public void handleResult(Type base) { baseResult = base; } + + @Override + public void handleResult(boolean isBaseType) { + isBaseTypeResult = isBaseType; + } }; } @@ -32,9 +37,11 @@ public void testNamedType() { etv.visit("name", "different"); etv.visit("base", Type.getType(PyObject.class)); + etv.visit("isBaseType", false); etv.visitEnd(); assertEquals("different", result); assertEquals(Type.getType(PyObject.class), baseResult); + assertEquals(false, isBaseTypeResult); } ExposedTypeVisitor etv; @@ -42,4 +49,6 @@ private String result; private Type baseResult; + + private boolean isBaseTypeResult; } Modified: trunk/jython/tests/java/org/python/expose/generate/SimpleExposed.java =================================================================== --- trunk/jython/tests/java/org/python/expose/generate/SimpleExposed.java 2008-11-24 01:57:05 UTC (rev 5625) +++ trunk/jython/tests/java/org/python/expose/generate/SimpleExposed.java 2008-11-24 02:02:47 UTC (rev 5626) @@ -15,7 +15,7 @@ import org.python.expose.ExposedType; import org.python.expose.MethodType; -@ExposedType(name = "simpleexposed") +@ExposedType(name = "simpleexposed", isBaseType = false) public class SimpleExposed extends PyObject { public void method() {} @@ -145,4 +145,4 @@ public String toStringVal = TO_STRING_RETURN; public static final String TO_STRING_RETURN = "A simple test class"; -} \ No newline at end of file +} Modified: trunk/jython/tests/java/org/python/expose/generate/TypeExposerTest.java =================================================================== --- trunk/jython/tests/java/org/python/expose/generate/TypeExposerTest.java 2008-11-24 01:57:05 UTC (rev 5625) +++ trunk/jython/tests/java/org/python/expose/generate/TypeExposerTest.java 2008-11-24 02:02:47 UTC (rev 5626) @@ -22,6 +22,7 @@ TypeBuilder t = etp.getTypeExposer().makeBuilder(); assertEquals("simpleexposed", t.getName()); assertEquals(SimpleExposed.class, t.getTypeClass()); + assertEquals(false, t.getIsBaseType()); PyType type = PyType.fromClass(SimpleExposed.class); PyObject dict = t.getDict(type); assertNotNull(dict.__finditem__("simple_method")); @@ -36,6 +37,7 @@ ExposedTypeProcessor etp = new ExposedTypeProcessor(getClass().getClassLoader() .getResourceAsStream("org/python/expose/generate/TypeExposerTest$SimplestNew.class")); TypeBuilder te = etp.getTypeExposer().makeBuilder(); + assertEquals(true, te.getIsBaseType()); PyObject new_ = te.getDict(PyType.fromClass(SimplestNew.class)).__finditem__("__new__"); assertEquals(Py.One, new_.__call__(PyType.fromClass(SimplestNew.class))); } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: Philip J. <pj...@un...> - 2008-11-24 02:05:26
|
Begin forwarded message: > Revision: 5626 > http://jython.svn.sourceforge.net/jython/?rev=5626&view=rev > Author: pjenvey > Date: 2008-11-24 02:02:47 +0000 (Mon, 24 Nov 2008) > > Log Message: > ----------- > add an isBaseType flag to @ExposedType for toggling whether types are > subclassable. disallow subclassing of builtin_function_or_method > (fixes > test_descr.errors). note that this requires an ant clean > refs #1758319 Heads up: You'll need to run an ant clean after updating to this revision. -- Philip Jenvey |
From: <pj...@us...> - 2008-11-24 02:48:39
|
Revision: 5627 http://jython.svn.sourceforge.net/jython/?rev=5627&view=rev Author: pjenvey Date: 2008-11-24 02:48:33 +0000 (Mon, 24 Nov 2008) Log Message: ----------- disallow sublcassing a number of types fixes #1758319 Modified Paths: -------------- trunk/jython/Lib/test/test_bool.py trunk/jython/src/org/python/core/PyBoolean.java trunk/jython/src/org/python/core/PyCell.java trunk/jython/src/org/python/core/PyClassMethodDescr.java trunk/jython/src/org/python/core/PyDataDescr.java trunk/jython/src/org/python/core/PyDictProxy.java trunk/jython/src/org/python/core/PyEllipsis.java trunk/jython/src/org/python/core/PyFunction.java trunk/jython/src/org/python/core/PyGenerator.java trunk/jython/src/org/python/core/PyMethod.java trunk/jython/src/org/python/core/PyMethodDescr.java trunk/jython/src/org/python/core/PyNone.java trunk/jython/src/org/python/core/PyNotImplemented.java trunk/jython/src/org/python/core/PySlice.java trunk/jython/src/org/python/core/PySlot.java trunk/jython/src/org/python/core/PyTraceback.java trunk/jython/src/org/python/core/PyXRange.java trunk/jython/src/org/python/modules/PyTeeIterator.java trunk/jython/src/org/python/modules/_codecs.java trunk/jython/src/org/python/modules/_weakref/CallableProxyType.java trunk/jython/src/org/python/modules/_weakref/ProxyType.java trunk/jython/src/org/python/modules/operator.java trunk/jython/src/org/python/modules/time/PyTimeTuple.java Modified: trunk/jython/Lib/test/test_bool.py =================================================================== --- trunk/jython/Lib/test/test_bool.py 2008-11-24 02:02:47 UTC (rev 5626) +++ trunk/jython/Lib/test/test_bool.py 2008-11-24 02:48:33 UTC (rev 5627) @@ -343,9 +343,6 @@ # StackOverflow if __nonzero__ returns self # http://jython.org/bugs/1758318 del BoolTest.test_convert_to_bool -# bool should not be subclassable -# http://jython.org/bugs/1758319 -del BoolTest.test_subclass def test_main(): test_support.run_unittest(BoolTest) Modified: trunk/jython/src/org/python/core/PyBoolean.java =================================================================== --- trunk/jython/src/org/python/core/PyBoolean.java 2008-11-24 02:02:47 UTC (rev 5626) +++ trunk/jython/src/org/python/core/PyBoolean.java 2008-11-24 02:48:33 UTC (rev 5627) @@ -1,7 +1,5 @@ package org.python.core; -import java.io.Serializable; - import org.python.expose.ExposedMethod; import org.python.expose.ExposedNew; import org.python.expose.ExposedType; @@ -10,7 +8,7 @@ /** * A builtin python bool. */ -@ExposedType(name = "bool") +@ExposedType(name = "bool", isBaseType = false) public class PyBoolean extends PyInteger { public static final PyType TYPE = PyType.fromClass(PyBoolean.class); Modified: trunk/jython/src/org/python/core/PyCell.java =================================================================== --- trunk/jython/src/org/python/core/PyCell.java 2008-11-24 02:02:47 UTC (rev 5626) +++ trunk/jython/src/org/python/core/PyCell.java 2008-11-24 02:48:33 UTC (rev 5627) @@ -10,7 +10,7 @@ * Cells are used to implement variables referenced by multiple * scopes. */ -@ExposedType(name = "cell") +@ExposedType(name = "cell", isBaseType = false) public class PyCell extends PyObject { /** The underlying content of the cell, or null. */ Modified: trunk/jython/src/org/python/core/PyClassMethodDescr.java =================================================================== --- trunk/jython/src/org/python/core/PyClassMethodDescr.java 2008-11-24 02:02:47 UTC (rev 5626) +++ trunk/jython/src/org/python/core/PyClassMethodDescr.java 2008-11-24 02:48:33 UTC (rev 5627) @@ -3,7 +3,7 @@ import org.python.expose.ExposedMethod; import org.python.expose.ExposedType; -@ExposedType(name = "classmethod_descriptor") +@ExposedType(name = "classmethod_descriptor", isBaseType = false) public class PyClassMethodDescr extends PyMethodDescr { public static final PyType TYPE = PyType.fromClass(PyClassMethodDescr.class); Modified: trunk/jython/src/org/python/core/PyDataDescr.java =================================================================== --- trunk/jython/src/org/python/core/PyDataDescr.java 2008-11-24 02:02:47 UTC (rev 5626) +++ trunk/jython/src/org/python/core/PyDataDescr.java 2008-11-24 02:48:33 UTC (rev 5627) @@ -12,7 +12,7 @@ * those methods, their respective implementsDescr* methods should be overriden * as well. */ -@ExposedType(name = "getset_descriptor", base = PyObject.class) +@ExposedType(name = "getset_descriptor", base = PyObject.class, isBaseType = false) public abstract class PyDataDescr extends PyDescriptor { protected Class ofType; Modified: trunk/jython/src/org/python/core/PyDictProxy.java =================================================================== --- trunk/jython/src/org/python/core/PyDictProxy.java 2008-11-24 02:02:47 UTC (rev 5626) +++ trunk/jython/src/org/python/core/PyDictProxy.java 2008-11-24 02:48:33 UTC (rev 5627) @@ -9,7 +9,7 @@ * Readonly proxy for dictionaries (actually any mapping). * */ -@ExposedType(name = "dictproxy") +@ExposedType(name = "dictproxy", isBaseType = false) public class PyDictProxy extends PyObject { /** The dict proxied to. */ Modified: trunk/jython/src/org/python/core/PyEllipsis.java =================================================================== --- trunk/jython/src/org/python/core/PyEllipsis.java 2008-11-24 02:02:47 UTC (rev 5626) +++ trunk/jython/src/org/python/core/PyEllipsis.java 2008-11-24 02:48:33 UTC (rev 5627) @@ -8,8 +8,7 @@ /** * A class representing the singleton Ellipsis <code>...</code> object. */ -// XXX: not subclassable -@ExposedType(name = "ellipsis", base = PyObject.class) +@ExposedType(name = "ellipsis", base = PyObject.class, isBaseType = false) public class PyEllipsis extends PySingleton implements Serializable { public static final PyType TYPE = PyType.fromClass(PyEllipsis.class); Modified: trunk/jython/src/org/python/core/PyFunction.java =================================================================== --- trunk/jython/src/org/python/core/PyFunction.java 2008-11-24 02:02:47 UTC (rev 5626) +++ trunk/jython/src/org/python/core/PyFunction.java 2008-11-24 02:48:33 UTC (rev 5627) @@ -11,7 +11,7 @@ /** * A Python function. */ -@ExposedType(name = "function") +@ExposedType(name = "function", isBaseType = false) public class PyFunction extends PyObject { public static final PyType TYPE = PyType.fromClass(PyFunction.class); Modified: trunk/jython/src/org/python/core/PyGenerator.java =================================================================== --- trunk/jython/src/org/python/core/PyGenerator.java 2008-11-24 02:02:47 UTC (rev 5626) +++ trunk/jython/src/org/python/core/PyGenerator.java 2008-11-24 02:48:33 UTC (rev 5627) @@ -4,7 +4,7 @@ import org.python.expose.ExposedMethod; import org.python.expose.ExposedType; -@ExposedType(name="generator", base=PyObject.class) +@ExposedType(name = "generator", base = PyObject.class, isBaseType = false) public class PyGenerator extends PyIterator { @ExposedGet Modified: trunk/jython/src/org/python/core/PyMethod.java =================================================================== --- trunk/jython/src/org/python/core/PyMethod.java 2008-11-24 02:02:47 UTC (rev 5626) +++ trunk/jython/src/org/python/core/PyMethod.java 2008-11-24 02:48:33 UTC (rev 5627) @@ -10,7 +10,7 @@ /** * A Python method. */ -@ExposedType(name = "instancemethod") +@ExposedType(name = "instancemethod", isBaseType = false) public class PyMethod extends PyObject { public static final PyType TYPE = PyType.fromClass(PyMethod.class); Modified: trunk/jython/src/org/python/core/PyMethodDescr.java =================================================================== --- trunk/jython/src/org/python/core/PyMethodDescr.java 2008-11-24 02:02:47 UTC (rev 5626) +++ trunk/jython/src/org/python/core/PyMethodDescr.java 2008-11-24 02:48:33 UTC (rev 5627) @@ -4,7 +4,7 @@ import org.python.expose.ExposedMethod; import org.python.expose.ExposedType; -@ExposedType(name = "method_descriptor", base = PyObject.class) +@ExposedType(name = "method_descriptor", base = PyObject.class, isBaseType = false) public class PyMethodDescr extends PyDescriptor implements PyBuiltinCallable.Info { protected int minargs, maxargs; Modified: trunk/jython/src/org/python/core/PyNone.java =================================================================== --- trunk/jython/src/org/python/core/PyNone.java 2008-11-24 02:02:47 UTC (rev 5626) +++ trunk/jython/src/org/python/core/PyNone.java 2008-11-24 02:48:33 UTC (rev 5627) @@ -9,8 +9,7 @@ /** * A class representing the singleton None object, */ -// XXX: not subclassable -@ExposedType(name = "NoneType") +@ExposedType(name = "NoneType", isBaseType = false) public class PyNone extends PyObject implements Serializable { Modified: trunk/jython/src/org/python/core/PyNotImplemented.java =================================================================== --- trunk/jython/src/org/python/core/PyNotImplemented.java 2008-11-24 02:02:47 UTC (rev 5626) +++ trunk/jython/src/org/python/core/PyNotImplemented.java 2008-11-24 02:48:33 UTC (rev 5627) @@ -2,6 +2,7 @@ import java.io.Serializable; +// XXX: isBaseType = false public class PyNotImplemented extends PySingleton implements Serializable { PyNotImplemented() { Modified: trunk/jython/src/org/python/core/PySlice.java =================================================================== --- trunk/jython/src/org/python/core/PySlice.java 2008-11-24 02:02:47 UTC (rev 5626) +++ trunk/jython/src/org/python/core/PySlice.java 2008-11-24 02:48:33 UTC (rev 5627) @@ -9,7 +9,7 @@ /** * The Python slice object. */ -@ExposedType(name = "slice") +@ExposedType(name = "slice", isBaseType = false) public class PySlice extends PyObject { public static final PyType TYPE = PyType.fromClass(PySlice.class); Modified: trunk/jython/src/org/python/core/PySlot.java =================================================================== --- trunk/jython/src/org/python/core/PySlot.java 2008-11-24 02:02:47 UTC (rev 5626) +++ trunk/jython/src/org/python/core/PySlot.java 2008-11-24 02:48:33 UTC (rev 5627) @@ -4,7 +4,7 @@ import org.python.expose.ExposedMethod; import org.python.expose.ExposedType; -@ExposedType(name = "member_descriptor", base = PyObject.class) +@ExposedType(name = "member_descriptor", base = PyObject.class, isBaseType = false) public class PySlot extends PyDescriptor { private int index; Modified: trunk/jython/src/org/python/core/PyTraceback.java =================================================================== --- trunk/jython/src/org/python/core/PyTraceback.java 2008-11-24 02:02:47 UTC (rev 5626) +++ trunk/jython/src/org/python/core/PyTraceback.java 2008-11-24 02:48:33 UTC (rev 5627) @@ -6,6 +6,7 @@ /** * A python traceback object. */ +// XXX: isBaseType = false public class PyTraceback extends PyObject { public PyObject tb_next; Modified: trunk/jython/src/org/python/core/PyXRange.java =================================================================== --- trunk/jython/src/org/python/core/PyXRange.java 2008-11-24 02:02:47 UTC (rev 5626) +++ trunk/jython/src/org/python/core/PyXRange.java 2008-11-24 02:48:33 UTC (rev 5627) @@ -8,8 +8,7 @@ /** * The builtin xrange type. */ -// XXX: Not subclassable -@ExposedType(name = "xrange", base = PyObject.class) +@ExposedType(name = "xrange", base = PyObject.class, isBaseType = false) public class PyXRange extends PySequence { public static final PyType TYPE = PyType.fromClass(PyXRange.class); Modified: trunk/jython/src/org/python/modules/PyTeeIterator.java =================================================================== --- trunk/jython/src/org/python/modules/PyTeeIterator.java 2008-11-24 02:02:47 UTC (rev 5626) +++ trunk/jython/src/org/python/modules/PyTeeIterator.java 2008-11-24 02:48:33 UTC (rev 5627) @@ -13,7 +13,7 @@ import org.python.expose.ExposedNew; import org.python.expose.ExposedType; -@ExposedType(name = "itertools.tee", base = PyObject.class) +@ExposedType(name = "itertools.tee", base = PyObject.class, isBaseType = false) public class PyTeeIterator extends PyIterator { private final int position; Modified: trunk/jython/src/org/python/modules/_codecs.java =================================================================== --- trunk/jython/src/org/python/modules/_codecs.java 2008-11-24 02:02:47 UTC (rev 5626) +++ trunk/jython/src/org/python/modules/_codecs.java 2008-11-24 02:48:33 UTC (rev 5627) @@ -650,7 +650,7 @@ * creating integer objects in the process. The trie is created by inverting the * encoding map. */ - @ExposedType(name = "EncodingMap") + @ExposedType(name = "EncodingMap", isBaseType = false) public static class EncodingMap extends PyObject { char[] level1; Modified: trunk/jython/src/org/python/modules/_weakref/CallableProxyType.java =================================================================== --- trunk/jython/src/org/python/modules/_weakref/CallableProxyType.java 2008-11-24 02:02:47 UTC (rev 5626) +++ trunk/jython/src/org/python/modules/_weakref/CallableProxyType.java 2008-11-24 02:48:33 UTC (rev 5627) @@ -9,8 +9,7 @@ /** * ProxyType with __call__. */ -// XXX: not subclassable -@ExposedType(name = "weakcallableproxy") +@ExposedType(name = "weakcallableproxy", isBaseType = false) public class CallableProxyType extends ProxyType { public static final PyType TYPE = PyType.fromClass(CallableProxyType.class); Modified: trunk/jython/src/org/python/modules/_weakref/ProxyType.java =================================================================== --- trunk/jython/src/org/python/modules/_weakref/ProxyType.java 2008-11-24 02:02:47 UTC (rev 5626) +++ trunk/jython/src/org/python/modules/_weakref/ProxyType.java 2008-11-24 02:48:33 UTC (rev 5627) @@ -1,10 +1,8 @@ /* Copyright (c) Jython Developers */ package org.python.modules._weakref; -import org.python.core.Py; import org.python.core.PyComplex; import org.python.core.PyFloat; -import org.python.core.PyLong; import org.python.core.PyObject; import org.python.core.PyString; import org.python.core.PyType; @@ -13,8 +11,7 @@ /** * A weak reference proxy object. */ -// XXX: not subclassable -@ExposedType(name = "weakproxy") +@ExposedType(name = "weakproxy", isBaseType = false) public class ProxyType extends AbstractReference { public static final PyType TYPE = PyType.fromClass(ProxyType.class); Modified: trunk/jython/src/org/python/modules/operator.java =================================================================== --- trunk/jython/src/org/python/modules/operator.java 2008-11-24 02:02:47 UTC (rev 5626) +++ trunk/jython/src/org/python/modules/operator.java 2008-11-24 02:48:33 UTC (rev 5627) @@ -286,8 +286,7 @@ /** * The attrgetter type. */ - // XXX: not subclassable - @ExposedType(name = "operator.attrgetter") + @ExposedType(name = "operator.attrgetter", isBaseType = false) static class PyAttrGetter extends PyObject { public static final PyType TYPE = PyType.fromClass(PyAttrGetter.class); @@ -350,8 +349,7 @@ /** * The itemgetter type. */ - // XXX: not subclassable - @ExposedType(name = "operator.itemgetter") + @ExposedType(name = "operator.itemgetter", isBaseType = false) static class PyItemGetter extends PyObject { public static final PyType TYPE = PyType.fromClass(PyItemGetter.class); Modified: trunk/jython/src/org/python/modules/time/PyTimeTuple.java =================================================================== --- trunk/jython/src/org/python/modules/time/PyTimeTuple.java 2008-11-24 02:02:47 UTC (rev 5626) +++ trunk/jython/src/org/python/modules/time/PyTimeTuple.java 2008-11-24 02:48:33 UTC (rev 5627) @@ -3,11 +3,9 @@ import org.python.core.ArgParser; import org.python.core.Py; -import org.python.core.PyInteger; import org.python.core.PyList; import org.python.core.PyNewWrapper; import org.python.core.PyObject; -import org.python.core.PySequence; import org.python.core.PyTuple; import org.python.core.PyType; import org.python.expose.ExposedGet; @@ -20,7 +18,7 @@ * struct_time of the time module. * */ -@ExposedType(name = "time.struct_time") +@ExposedType(name = "time.struct_time", isBaseType = false) public class PyTimeTuple extends PyTuple { @ExposedGet This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <pj...@us...> - 2008-11-27 04:52:48
|
Revision: 5646 http://jython.svn.sourceforge.net/jython/?rev=5646&view=rev Author: pjenvey Date: 2008-11-27 04:52:37 +0000 (Thu, 27 Nov 2008) Log Message: ----------- temporarily store genexps in Java's frame instead of PyFrame. the latter could modify f_locals when cleaning up the temp slot, which causes an obscure bug if the genexp is iterating over that same f_locals (dict changed size during iteration). e.g., in a module's top level: __all__ = tuple(x for x in locals() if x.isupper()) Modified Paths: -------------- trunk/jython/src/org/python/compiler/CodeCompiler.java Added Paths: ----------- trunk/jython/Lib/test/test_genexps_jy.py Added: trunk/jython/Lib/test/test_genexps_jy.py =================================================================== --- trunk/jython/Lib/test/test_genexps_jy.py (rev 0) +++ trunk/jython/Lib/test/test_genexps_jy.py 2008-11-27 04:52:37 UTC (rev 5646) @@ -0,0 +1,23 @@ +"""Misc generator expression tests + +Made for Jython. +""" +import unittest +from test import test_support + +locals_test = list(local for local in locals() if not local.startswith('_')) + +class GeneratorExpressionsTestCase(unittest.TestCase): + + def test_module_level_locals(self): + # NOTE: The locals_test genexp used to cause a 'dictionary + # changed size during iteration' RuntimeError. If we've gotten + # this far we've already passed + self.assert_(sorted(locals_test) == ['test_support', 'unittest']) + + +def test_main(): + test_support.run_unittest(GeneratorExpressionsTestCase) + +if __name__ == '__main__': + test_main() Modified: trunk/jython/src/org/python/compiler/CodeCompiler.java =================================================================== --- trunk/jython/src/org/python/compiler/CodeCompiler.java 2008-11-27 04:01:27 UTC (rev 5645) +++ trunk/jython/src/org/python/compiler/CodeCompiler.java 2008-11-27 04:52:37 UTC (rev 5646) @@ -2155,7 +2155,6 @@ @Override public Object visitGeneratorExp(GeneratorExp node) throws Exception { String bound_exp = "_(x)"; - String tmp_append ="_(" + node.getLine() + "_" + node.getCharPositionInLine() + ")"; setline(node); @@ -2189,7 +2188,7 @@ } } - module.PyCode(new Suite(node, new stmtType[]{n}), tmp_append, true, + module.PyCode(new Suite(node, new stmtType[]{n}), "<genexpr>", true, className, false, false, node.getLine(), scope, cflags).get(code); @@ -2199,17 +2198,15 @@ } else { code.invokespecial( "org/python/core/PyFunction", "<init>", "(" + $pyObj + $pyObjArr + $pyCode + $pyObj + $pyObjArr + ")V"); } + int genExp = storeTop(); - set(new Name(node, tmp_append, expr_contextType.Store)); - visit(iter); - visit(new Name(node, tmp_append, expr_contextType.Load)); + code.aload(genExp); + 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); - visit(new Delete(n, new exprType[] { new Name(n, tmp_append, expr_contextType.Del) })); - return null; } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <pj...@us...> - 2008-11-28 21:10:45
|
Revision: 5655 http://jython.svn.sourceforge.net/jython/?rev=5655&view=rev Author: pjenvey Date: 2008-11-28 21:10:39 +0000 (Fri, 28 Nov 2008) Log Message: ----------- have exposed methods and fields convert null Strings results to Py.None Modified Paths: -------------- trunk/jython/src/org/python/expose/generate/Exposer.java trunk/jython/tests/java/org/python/expose/generate/DescriptorExposerTest.java trunk/jython/tests/java/org/python/expose/generate/ExposedTypeProcessorTest.java trunk/jython/tests/java/org/python/expose/generate/MethodExposerTest.java trunk/jython/tests/java/org/python/expose/generate/SimpleExposed.java Modified: trunk/jython/src/org/python/expose/generate/Exposer.java =================================================================== --- trunk/jython/src/org/python/expose/generate/Exposer.java 2008-11-28 10:06:54 UTC (rev 5654) +++ trunk/jython/src/org/python/expose/generate/Exposer.java 2008-11-28 21:10:39 UTC (rev 5655) @@ -5,6 +5,7 @@ import org.python.objectweb.asm.ClassVisitor; import org.python.objectweb.asm.ClassWriter; +import org.python.objectweb.asm.Label; import org.python.objectweb.asm.MethodVisitor; import org.python.objectweb.asm.Opcodes; import org.python.objectweb.asm.Type; @@ -228,7 +229,16 @@ if(inputType.equals(VOID)) { getStatic(PY, "None", PYOBJ); } else if(inputType.equals(STRING)) { + Label newString = new Label(); + Label end = new Label(); + mv.visitInsn(DUP); + mv.visitJumpInsn(IFNONNULL, newString); + mv.visitInsn(POP); + getStatic(PY, "None", PYOBJ); + mv.visitJumpInsn(GOTO, end); + mv.visitLabel(newString); callStatic(PY, "newString", PYSTR, STRING); + mv.visitLabel(end); } else if(inputType.equals(BOOLEAN)) { callStatic(PY, "newBoolean", PYBOOLEAN, BOOLEAN); } else if(inputType.equals(INT) || inputType.equals(BYTE) || inputType.equals(SHORT)) { Modified: trunk/jython/tests/java/org/python/expose/generate/DescriptorExposerTest.java =================================================================== --- trunk/jython/tests/java/org/python/expose/generate/DescriptorExposerTest.java 2008-11-28 10:06:54 UTC (rev 5654) +++ trunk/jython/tests/java/org/python/expose/generate/DescriptorExposerTest.java 2008-11-28 21:10:39 UTC (rev 5655) @@ -76,7 +76,17 @@ assertFalse(instance.implementsDescrSet()); assertFalse(instance.implementsDescrDelete()); } + + public void testNullReturns() throws Exception { + PyDataDescr instance = makeDescriptor(new DescSetup() { + public void setup(DescriptorExposer de) { + de.addFieldGetter("nullString", STRING); + } + }); + assertEquals(Py.None, instance.__get__(se, PY_TYPE)); + } + public void testMethodSetter() throws Exception { PyDataDescr instance = makeDescriptor(new DescSetup() { @@ -224,5 +234,7 @@ public boolean bool; public String toStringVal = SimpleExposed.TO_STRING_RETURN; + + public String nullString = null; } } Modified: trunk/jython/tests/java/org/python/expose/generate/ExposedTypeProcessorTest.java =================================================================== --- trunk/jython/tests/java/org/python/expose/generate/ExposedTypeProcessorTest.java 2008-11-28 10:06:54 UTC (rev 5654) +++ trunk/jython/tests/java/org/python/expose/generate/ExposedTypeProcessorTest.java 2008-11-28 21:10:39 UTC (rev 5655) @@ -18,7 +18,7 @@ .getResourceAsStream("org/python/expose/generate/SimpleExposed.class"); ExposedTypeProcessor ice = new ExposedTypeProcessor(in); assertEquals("simpleexposed", ice.getName()); - assertEquals(18, ice.getMethodExposers().size()); + assertEquals(19, ice.getMethodExposers().size()); assertNotNull(ice.getNewExposer()); assertEquals(1, ice.getDescriptorExposers().size()); assertEquals("simpleexposed", ice.getTypeExposer().getName()); Modified: trunk/jython/tests/java/org/python/expose/generate/MethodExposerTest.java =================================================================== --- trunk/jython/tests/java/org/python/expose/generate/MethodExposerTest.java 2008-11-28 10:06:54 UTC (rev 5654) +++ trunk/jython/tests/java/org/python/expose/generate/MethodExposerTest.java 2008-11-28 21:10:39 UTC (rev 5655) @@ -189,6 +189,10 @@ assertEquals("a", createBound("charReturn", CHAR).__call__().toString()); } + public void testNullReturns() throws Exception { + assertEquals(Py.None, createBound("stringReturnNull", STRING).__call__()); + } + public void testClassMethod() throws Exception { ClassMethodExposer exp = new ClassMethodExposer(Type.getType(SimpleExposed.class), Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC, Modified: trunk/jython/tests/java/org/python/expose/generate/SimpleExposed.java =================================================================== --- trunk/jython/tests/java/org/python/expose/generate/SimpleExposed.java 2008-11-28 10:06:54 UTC (rev 5654) +++ trunk/jython/tests/java/org/python/expose/generate/SimpleExposed.java 2008-11-28 21:10:39 UTC (rev 5655) @@ -123,6 +123,11 @@ return 'a'; } + @ExposedMethod + public String stringReturnNull() { + return null; + } + @ExposedClassMethod public static char classmethod(PyType onType) { return 'a'; This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <pj...@us...> - 2008-11-29 07:44:06
|
Revision: 5661 http://jython.svn.sourceforge.net/jython/?rev=5661&view=rev Author: pjenvey Date: 2008-11-29 07:43:57 +0000 (Sat, 29 Nov 2008) Log Message: ----------- constantine-0.4 release Modified Paths: -------------- trunk/jython/build.xml Added Paths: ----------- trunk/jython/extlibs/constantine-0.4.jar Removed Paths: ------------- trunk/jython/extlibs/constantine.jar Modified: trunk/jython/build.xml =================================================================== --- trunk/jython/build.xml 2008-11-29 04:59:20 UTC (rev 5660) +++ trunk/jython/build.xml 2008-11-29 07:43:57 UTC (rev 5661) @@ -526,7 +526,7 @@ <zipfileset src="extlibs/jna-posix.jar"/> <!-- <rule pattern="com.sun.jna.**" result="org.python.jna.@1"/> --> <rule pattern="org.jruby.ext.posix.**" result="org.python.posix.@1"/> - <zipfileset src="extlibs/constantine.jar"/> + <zipfileset src="extlibs/constantine-0.4.jar"/> <rule pattern="com.kenai.constantine.**" result="org.python.constantine.@1"/> </jarjar> <unjar src="${output.dir}/jarjar.jar" dest="${jarjar.dir}"> Added: trunk/jython/extlibs/constantine-0.4.jar =================================================================== (Binary files differ) Property changes on: trunk/jython/extlibs/constantine-0.4.jar ___________________________________________________________________ Added: svn:mime-type + application/octet-stream Deleted: trunk/jython/extlibs/constantine.jar =================================================================== (Binary files differ) This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <nr...@us...> - 2008-12-01 18:33:05
|
Revision: 5670 http://jython.svn.sourceforge.net/jython/?rev=5670&view=rev Author: nriley Date: 2008-12-01 18:33:00 +0000 (Mon, 01 Dec 2008) Log Message: ----------- PyStringMap should not be hashable, just as PyDictionary isn't. Modified Paths: -------------- trunk/jython/Lib/test/test_stringmap.py trunk/jython/src/org/python/core/PyStringMap.java Modified: trunk/jython/Lib/test/test_stringmap.py =================================================================== --- trunk/jython/Lib/test/test_stringmap.py 2008-12-01 01:14:21 UTC (rev 5669) +++ trunk/jython/Lib/test/test_stringmap.py 2008-12-01 18:33:00 UTC (rev 5670) @@ -62,7 +62,10 @@ for i in r.keys(): self.assert_(d.has_key(i)) self.assert_(i in d) - + + # Test unhashability + self.assertRaises(TypeError, hash, d) + def test_stringmap_in_mapping(self): class A: def __init__(self): Modified: trunk/jython/src/org/python/core/PyStringMap.java =================================================================== --- trunk/jython/src/org/python/core/PyStringMap.java 2008-12-01 01:14:21 UTC (rev 5669) +++ trunk/jython/src/org/python/core/PyStringMap.java 2008-12-01 18:33:00 UTC (rev 5670) @@ -500,4 +500,8 @@ return pyKey; } } + + public int hashCode() { + throw Py.TypeError(String.format("unhashable type: '%.200s'", getType().fastGetName())); + } } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <fwi...@us...> - 2008-12-05 01:11:01
|
Revision: 5695 http://jython.svn.sourceforge.net/jython/?rev=5695&view=rev Author: fwierzbicki Date: 2008-12-05 01:10:49 +0000 (Fri, 05 Dec 2008) Log Message: ----------- Merging the astwrite branch into trunk. While I was testing, I noticed some problems stemming from the package names and the "Type" at the end of some of the asdl_antlr.py generated code -- so I fixed that up as well. This checkin changes all of the access on ast nodes to be getters and setters with Lists instead of arrays. The ast nodes also now descend from PyObject instead of Antlr's CommonTree. There are new adapter classes that handle the back and forth of ast nodes from Java to Python. Merged revisions 5586-5592,5594-5595,5597,5612,5628,5633-5634,5636-5637,5641-5643,5660,5672,5677-5679,5683,5685-5686 via svnmerge from https://jython.svn.sourceforge.net/svnroot/jython/branches/astwrite Modified Paths: -------------- trunk/jython/CoreExposed.includes trunk/jython/Lib/ast.py trunk/jython/Lib/inspect.py trunk/jython/Lib/test/test_ast.py trunk/jython/ast/Python.asdl trunk/jython/ast/asdl_antlr.py trunk/jython/grammar/Python.g trunk/jython/src/org/python/antlr/AST.java trunk/jython/src/org/python/antlr/ErrorHandler.java trunk/jython/src/org/python/antlr/ExpressionParser.java trunk/jython/src/org/python/antlr/FailFastHandler.java trunk/jython/src/org/python/antlr/GrammarActions.java trunk/jython/src/org/python/antlr/InteractiveParser.java trunk/jython/src/org/python/antlr/ListErrorHandler.java trunk/jython/src/org/python/antlr/ModuleParser.java trunk/jython/src/org/python/antlr/PythonTree.java trunk/jython/src/org/python/antlr/ast/Assert.java trunk/jython/src/org/python/antlr/ast/Assign.java trunk/jython/src/org/python/antlr/ast/Attribute.java trunk/jython/src/org/python/antlr/ast/AugAssign.java trunk/jython/src/org/python/antlr/ast/BinOp.java trunk/jython/src/org/python/antlr/ast/BoolOp.java trunk/jython/src/org/python/antlr/ast/Break.java trunk/jython/src/org/python/antlr/ast/Call.java trunk/jython/src/org/python/antlr/ast/ClassDef.java trunk/jython/src/org/python/antlr/ast/Compare.java trunk/jython/src/org/python/antlr/ast/Continue.java trunk/jython/src/org/python/antlr/ast/Delete.java trunk/jython/src/org/python/antlr/ast/Dict.java trunk/jython/src/org/python/antlr/ast/Ellipsis.java trunk/jython/src/org/python/antlr/ast/ErrorExpr.java trunk/jython/src/org/python/antlr/ast/ErrorMod.java trunk/jython/src/org/python/antlr/ast/ErrorSlice.java trunk/jython/src/org/python/antlr/ast/ErrorStmt.java trunk/jython/src/org/python/antlr/ast/Exec.java trunk/jython/src/org/python/antlr/ast/Expr.java trunk/jython/src/org/python/antlr/ast/Expression.java trunk/jython/src/org/python/antlr/ast/ExtSlice.java trunk/jython/src/org/python/antlr/ast/For.java trunk/jython/src/org/python/antlr/ast/FunctionDef.java trunk/jython/src/org/python/antlr/ast/GeneratorExp.java trunk/jython/src/org/python/antlr/ast/Global.java trunk/jython/src/org/python/antlr/ast/If.java trunk/jython/src/org/python/antlr/ast/IfExp.java trunk/jython/src/org/python/antlr/ast/Import.java trunk/jython/src/org/python/antlr/ast/ImportFrom.java trunk/jython/src/org/python/antlr/ast/Index.java trunk/jython/src/org/python/antlr/ast/Interactive.java trunk/jython/src/org/python/antlr/ast/Lambda.java trunk/jython/src/org/python/antlr/ast/List.java trunk/jython/src/org/python/antlr/ast/ListComp.java trunk/jython/src/org/python/antlr/ast/Module.java trunk/jython/src/org/python/antlr/ast/Name.java trunk/jython/src/org/python/antlr/ast/Num.java trunk/jython/src/org/python/antlr/ast/Pass.java trunk/jython/src/org/python/antlr/ast/Print.java trunk/jython/src/org/python/antlr/ast/Raise.java trunk/jython/src/org/python/antlr/ast/Repr.java trunk/jython/src/org/python/antlr/ast/Return.java trunk/jython/src/org/python/antlr/ast/Slice.java trunk/jython/src/org/python/antlr/ast/Str.java trunk/jython/src/org/python/antlr/ast/Subscript.java trunk/jython/src/org/python/antlr/ast/Suite.java trunk/jython/src/org/python/antlr/ast/TryExcept.java trunk/jython/src/org/python/antlr/ast/TryFinally.java trunk/jython/src/org/python/antlr/ast/Tuple.java trunk/jython/src/org/python/antlr/ast/UnaryOp.java trunk/jython/src/org/python/antlr/ast/VisitorBase.java trunk/jython/src/org/python/antlr/ast/VisitorIF.java trunk/jython/src/org/python/antlr/ast/While.java trunk/jython/src/org/python/antlr/ast/With.java trunk/jython/src/org/python/antlr/ast/Yield.java trunk/jython/src/org/python/antlr/ast/boolopType.java trunk/jython/src/org/python/antlr/ast/cmpopType.java trunk/jython/src/org/python/antlr/ast/expr_contextType.java trunk/jython/src/org/python/antlr/ast/operatorType.java trunk/jython/src/org/python/antlr/ast/unaryopType.java trunk/jython/src/org/python/compiler/ArgListCompiler.java trunk/jython/src/org/python/compiler/CodeCompiler.java trunk/jython/src/org/python/compiler/Future.java trunk/jython/src/org/python/compiler/Module.java trunk/jython/src/org/python/compiler/ProxyMaker.java trunk/jython/src/org/python/compiler/ScopeInfo.java trunk/jython/src/org/python/compiler/ScopesCompiler.java trunk/jython/src/org/python/core/AbstractArray.java trunk/jython/src/org/python/core/CollectionProxy.java trunk/jython/src/org/python/core/ParserFacade.java trunk/jython/src/org/python/core/Py.java trunk/jython/src/org/python/core/PyInstance.java trunk/jython/src/org/python/core/PyList.java trunk/jython/src/org/python/core/__builtin__.java trunk/jython/src/org/python/core/imp.java trunk/jython/src/org/python/modules/Setup.java Added Paths: ----------- trunk/jython/src/org/python/antlr/adapter/ trunk/jython/src/org/python/antlr/adapter/AliasAdapter.java trunk/jython/src/org/python/antlr/adapter/AstAdapter.java trunk/jython/src/org/python/antlr/adapter/AstAdapters.java trunk/jython/src/org/python/antlr/adapter/CmpopAdapter.java trunk/jython/src/org/python/antlr/adapter/ComprehensionAdapter.java trunk/jython/src/org/python/antlr/adapter/ExcepthandlerAdapter.java trunk/jython/src/org/python/antlr/adapter/ExprAdapter.java trunk/jython/src/org/python/antlr/adapter/IdentifierAdapter.java trunk/jython/src/org/python/antlr/adapter/KeywordAdapter.java trunk/jython/src/org/python/antlr/adapter/SliceAdapter.java trunk/jython/src/org/python/antlr/adapter/StmtAdapter.java trunk/jython/src/org/python/antlr/ast/AstModule.java trunk/jython/src/org/python/antlr/ast/ExceptHandler.java trunk/jython/src/org/python/antlr/base/ trunk/jython/src/org/python/antlr/base/excepthandler.java trunk/jython/src/org/python/antlr/base/expr.java trunk/jython/src/org/python/antlr/base/mod.java trunk/jython/src/org/python/antlr/base/slice.java trunk/jython/src/org/python/antlr/base/stmt.java trunk/jython/src/org/python/antlr/op/ trunk/jython/src/org/python/antlr/op/Add.java trunk/jython/src/org/python/antlr/op/And.java trunk/jython/src/org/python/antlr/op/AugLoad.java trunk/jython/src/org/python/antlr/op/AugStore.java trunk/jython/src/org/python/antlr/op/BitAnd.java trunk/jython/src/org/python/antlr/op/BitOr.java trunk/jython/src/org/python/antlr/op/BitXor.java trunk/jython/src/org/python/antlr/op/Del.java trunk/jython/src/org/python/antlr/op/Div.java trunk/jython/src/org/python/antlr/op/Eq.java trunk/jython/src/org/python/antlr/op/FloorDiv.java trunk/jython/src/org/python/antlr/op/Gt.java trunk/jython/src/org/python/antlr/op/GtE.java trunk/jython/src/org/python/antlr/op/In.java trunk/jython/src/org/python/antlr/op/Invert.java trunk/jython/src/org/python/antlr/op/Is.java trunk/jython/src/org/python/antlr/op/IsNot.java trunk/jython/src/org/python/antlr/op/LShift.java trunk/jython/src/org/python/antlr/op/Load.java trunk/jython/src/org/python/antlr/op/Lt.java trunk/jython/src/org/python/antlr/op/LtE.java trunk/jython/src/org/python/antlr/op/Mod.java trunk/jython/src/org/python/antlr/op/Mult.java trunk/jython/src/org/python/antlr/op/Not.java trunk/jython/src/org/python/antlr/op/NotEq.java trunk/jython/src/org/python/antlr/op/NotIn.java trunk/jython/src/org/python/antlr/op/Or.java trunk/jython/src/org/python/antlr/op/Param.java trunk/jython/src/org/python/antlr/op/Pow.java trunk/jython/src/org/python/antlr/op/RShift.java trunk/jython/src/org/python/antlr/op/Store.java trunk/jython/src/org/python/antlr/op/Sub.java trunk/jython/src/org/python/antlr/op/UAdd.java trunk/jython/src/org/python/antlr/op/USub.java trunk/jython/src/org/python/core/AstList.java Removed Paths: ------------- trunk/jython/Lib/_ast.py trunk/jython/src/org/python/antlr/adapter/AliasAdapter.java trunk/jython/src/org/python/antlr/adapter/AstAdapter.java trunk/jython/src/org/python/antlr/adapter/AstAdapters.java trunk/jython/src/org/python/antlr/adapter/CmpopAdapter.java trunk/jython/src/org/python/antlr/adapter/ComprehensionAdapter.java trunk/jython/src/org/python/antlr/adapter/ExcepthandlerAdapter.java trunk/jython/src/org/python/antlr/adapter/ExprAdapter.java trunk/jython/src/org/python/antlr/adapter/IdentifierAdapter.java trunk/jython/src/org/python/antlr/adapter/KeywordAdapter.java trunk/jython/src/org/python/antlr/adapter/SliceAdapter.java trunk/jython/src/org/python/antlr/adapter/StmtAdapter.java trunk/jython/src/org/python/antlr/ast/aliasType.java trunk/jython/src/org/python/antlr/ast/argumentsType.java trunk/jython/src/org/python/antlr/ast/comprehensionType.java trunk/jython/src/org/python/antlr/ast/excepthandlerType.java trunk/jython/src/org/python/antlr/ast/exprType.java trunk/jython/src/org/python/antlr/ast/keywordType.java trunk/jython/src/org/python/antlr/ast/modType.java trunk/jython/src/org/python/antlr/ast/sliceType.java trunk/jython/src/org/python/antlr/ast/stmtType.java Property Changed: ---------------- trunk/jython/ trunk/jython/ast/ trunk/jython/src/org/python/antlr/ trunk/jython/src/org/python/antlr/ast/ trunk/jython/src/org/python/compiler/ Property changes on: trunk/jython ___________________________________________________________________ Modified: svnmerge-integrated - /branches/astwrite:1-5585 + /branches/astwrite:1-5692 Modified: trunk/jython/CoreExposed.includes =================================================================== --- trunk/jython/CoreExposed.includes 2008-12-05 00:26:54 UTC (rev 5694) +++ trunk/jython/CoreExposed.includes 2008-12-05 01:10:49 UTC (rev 5695) @@ -55,3 +55,64 @@ org/python/modules/zipimport/zipimporter.class org/python/modules/PyStruct.class org/python/modules/PyTeeIterator.class +org/python/antlr/AST.class +org/python/antlr/ast/AsmModule.class +org/python/antlr/ast/And.class +org/python/antlr/ast/BitXor.class +org/python/antlr/ast/Gt.class +org/python/antlr/ast/AugLoad.class +org/python/antlr/ast/Mult.class +org/python/antlr/ast/NotEq.class +org/python/antlr/ast/LShift.class +org/python/antlr/ast/IsNot.class +org/python/antlr/ast/RShift.class +org/python/antlr/ast/Eq.class +org/python/antlr/ast/BitOr.class +org/python/antlr/ast/Div.class +org/python/antlr/ast/LtE.class +org/python/antlr/ast/Store.class +org/python/antlr/ast/Not.class +org/python/antlr/ast/BitAnd.class +org/python/antlr/ast/In.class +org/python/antlr/ast/UAdd.class +org/python/antlr/ast/GtE.class +org/python/antlr/ast/Lt.class +org/python/antlr/ast/Mod.class +org/python/antlr/ast/Sub.class +org/python/antlr/ast/Del.class +org/python/antlr/ast/Pow.class +org/python/antlr/ast/Invert.class +org/python/antlr/ast/Is.class +org/python/antlr/ast/Load.class +org/python/antlr/ast/Add.class +org/python/antlr/ast/AugStore.class +org/python/antlr/ast/Delete.class +org/python/antlr/ast/GeneratorExp.class +org/python/antlr/ast/Import.class +org/python/antlr/ast/comprehensionType.class +org/python/antlr/ast/With.class +org/python/antlr/ast/Module.class +org/python/antlr/ast/Global.class +org/python/antlr/ast/Dict.class +org/python/antlr/ast/ClassDef.class +org/python/antlr/ast/ExceptHandler.class +org/python/antlr/ast/TryExcept.class +org/python/antlr/ast/Tuple.class +org/python/antlr/ast/ListComp.class +org/python/antlr/ast/TryFinally.class +org/python/antlr/ast/If.class +org/python/antlr/ast/ImportFrom.class +org/python/antlr/ast/FunctionDef.class +org/python/antlr/ast/argumentsType.class +org/python/antlr/ast/List.class +org/python/antlr/ast/Interactive.class +org/python/antlr/ast/ExtSlice.class +org/python/antlr/ast/Compare.class +org/python/antlr/ast/While.class +org/python/antlr/ast/Call.class +org/python/antlr/ast/Assign.class +org/python/antlr/ast/For.class +org/python/antlr/ast/Suite.class +org/python/antlr/ast/BoolOp.class +org/python/antlr/ast/Print.class + Deleted: trunk/jython/Lib/_ast.py =================================================================== --- trunk/jython/Lib/_ast.py 2008-12-05 00:26:54 UTC (rev 5694) +++ trunk/jython/Lib/_ast.py 2008-12-05 01:10:49 UTC (rev 5695) @@ -1,79 +0,0 @@ -from org.python.antlr.ast.boolopType import And,Or -from org.python.antlr.ast.operatorType import Add,Sub,Mult,Div,FloorDiv,Mod,LShift,RShift,BitOr,BitAnd,BitXor,Pow -from org.python.antlr.ast.cmpopType import Eq,Gt,GtE,In,Is,IsNot,Lt,LtE,NotEq,NotIn -from org.python.antlr.ast.unaryopType import Invert,Not,UAdd,USub -from org.python.core.PyTableCode import PyCF_ONLY_AST -from org.python.antlr.ast.expr_contextType import Load, Store, Del, AugLoad, AugStore, Param - -from org.python.antlr import AST - -from org.python.antlr.ast import Assert -from org.python.antlr.ast import Assign -from org.python.antlr.ast import Attribute -from org.python.antlr.ast import AugAssign -from org.python.antlr.ast import BinOp -from org.python.antlr.ast import BoolOp -from org.python.antlr.ast import Break -from org.python.antlr.ast import Call -from org.python.antlr.ast import ClassDef -from org.python.antlr.ast import Compare -from org.python.antlr.ast import Continue -from org.python.antlr.ast import Delete -from org.python.antlr.ast import Dict -from org.python.antlr.ast import Ellipsis -from org.python.antlr.ast import Exec -from org.python.antlr.ast import Expr -from org.python.antlr.ast import Expression -from org.python.antlr.ast import ExtSlice -from org.python.antlr.ast import For -from org.python.antlr.ast import FunctionDef -from org.python.antlr.ast import GeneratorExp -from org.python.antlr.ast import Global -from org.python.antlr.ast import If -from org.python.antlr.ast import IfExp -from org.python.antlr.ast import Import -from org.python.antlr.ast import ImportFrom -from org.python.antlr.ast import Index -from org.python.antlr.ast import Interactive -from org.python.antlr.ast import Lambda -from org.python.antlr.ast import List -from org.python.antlr.ast import ListComp -from org.python.antlr.ast import Module -from org.python.antlr.ast import Name -from org.python.antlr.ast import Num -from org.python.antlr.ast import Pass -from org.python.antlr.ast import Print -from org.python.antlr.ast import Raise -from org.python.antlr.ast import Repr -from org.python.antlr.ast import Return -from org.python.antlr.ast import Slice -from org.python.antlr.ast import Str -from org.python.antlr.ast import Subscript -from org.python.antlr.ast import Suite -from org.python.antlr.ast import TryExcept -from org.python.antlr.ast import TryFinally -from org.python.antlr.ast import Tuple -from org.python.antlr.ast import UnaryOp -#from org.python.antlr.ast import Unicode -from org.python.antlr.ast import While -from org.python.antlr.ast import With -from org.python.antlr.ast import Yield - -import org.python.antlr.ast.aliasType as alias -import org.python.antlr.ast.argumentsType as arguments -import org.python.antlr.ast.boolopType as boolop -import org.python.antlr.ast.cmpopType as cmpop -import org.python.antlr.ast.comprehensionType as comprehension -import org.python.antlr.ast.excepthandlerType as excepthandler -import org.python.antlr.ast.exprType as expr -import org.python.antlr.ast.expr_contextType as expr_context -import org.python.antlr.ast.keywordType as keyword -import org.python.antlr.ast.modType as mod -import org.python.antlr.ast.operatorType as operator -import org.python.antlr.ast.sliceType as slice -import org.python.antlr.ast.stmtType as stmt -import org.python.antlr.ast.unaryopType as unaryop - -#Set to the same value as the CPython version we are targetting. -#note that this number comes from the revision number in CPython's repository. -__version__ = 43614 Modified: trunk/jython/Lib/ast.py =================================================================== --- trunk/jython/Lib/ast.py 2008-12-05 00:26:54 UTC (rev 5694) +++ trunk/jython/Lib/ast.py 2008-12-05 01:10:49 UTC (rev 5695) @@ -29,31 +29,6 @@ from _ast import * from _ast import __version__ -if sys.platform.startswith('java'): - import array - - ast_list = array.ArrayType - - def get_class_name(t): - result = t.__class__.__name__ - if result in ("expr_contextType", - "boolopType", - "unaryopType", - "cmpopType", - "operatorType"): - result = str(t) - if result == "AugLoad": - result = "Load" - elif result == "AugStore": - result = "Store" - elif result.endswith("Type"): - result = result[:-4] - return result -else: - ast_list = list - get_class_name = lambda node: node.__class__.__name__ - - def parse(expr, filename='<unknown>', mode='exec'): """ Parse an expression into an AST node. @@ -105,7 +80,7 @@ def _format(node): if isinstance(node, AST): fields = [(a, _format(b)) for a, b in iter_fields(node)] - rv = '%s(%s' % (get_class_name(node), ', '.join( + rv = '%s(%s' % (node.__class__.__name__, ', '.join( ('%s=%s' % field for field in fields) if annotate_fields else (b for a, b in fields) @@ -115,11 +90,11 @@ rv += ', '.join('%s=%s' % (a, _format(getattr(node, a))) for a in node._attributes) return rv + ')' - elif isinstance(node, ast_list): + elif hasattr(node, "__iter__"): return '[%s]' % ', '.join(_format(x) for x in node) return repr(node) if not isinstance(node, AST): - raise TypeError('expected AST, got %r' % get_class_name(node)) + raise TypeError('expected AST, got %r' % node.__class__.__name__) return _format(node) @@ -193,7 +168,7 @@ for name, field in iter_fields(node): if isinstance(field, AST): yield field - elif isinstance(field, ast_list): + elif hasattr(field, "__iter__"): for item in field: if isinstance(item, AST): yield item @@ -206,7 +181,7 @@ will be raised. """ if not isinstance(node, (FunctionDef, ClassDef, Module)): - raise TypeError("%r can't have docstrings" % get_class_name(node)) + raise TypeError("%r can't have docstrings" % node.__class__.__name__) if node.body and isinstance(node.body[0], Expr) and \ isinstance(node.body[0].value, Str): if clean: @@ -251,14 +226,14 @@ def visit(self, node): """Visit a node.""" - method = 'visit_' + get_class_name(node) + method = 'visit_' + node.__class__.__name__ visitor = getattr(self, method, self.generic_visit) return visitor(node) def generic_visit(self, node): """Called if no explicit visitor function exists for a node.""" for field, value in iter_fields(node): - if isinstance(value, ast_list): + if hasattr(value, "__iter__"): for item in value: if isinstance(item, AST): self.visit(item) @@ -305,7 +280,7 @@ def generic_visit(self, node): for field, old_value in iter_fields(node): old_value = getattr(node, field, None) - if isinstance(old_value, ast_list): + if hasattr(old_value, "__iter__"): new_values = [] for value in old_value: if isinstance(value, AST): Modified: trunk/jython/Lib/inspect.py =================================================================== --- trunk/jython/Lib/inspect.py 2008-12-05 00:26:54 UTC (rev 5694) +++ trunk/jython/Lib/inspect.py 2008-12-05 01:10:49 UTC (rev 5695) @@ -315,6 +315,13 @@ return None if not isinstance(doc, types.StringTypes): return None + return cleandoc(doc) + +def cleandoc(doc): + """Clean up indentation from docstrings. + + Any whitespace that can be uniformly removed from the second line + onwards is removed.""" try: lines = string.split(string.expandtabs(doc), '\n') except UnicodeError: Modified: trunk/jython/Lib/test/test_ast.py =================================================================== --- trunk/jython/Lib/test/test_ast.py 2008-12-05 00:26:54 UTC (rev 5694) +++ trunk/jython/Lib/test/test_ast.py 2008-12-05 01:10:49 UTC (rev 5695) @@ -1,36 +1,22 @@ -#Taken and modified from CPython's release25-maint branch, revision 62446. -import sys,os, itertools +import sys, itertools, unittest +from test import test_support import ast -def get_class_name(t): - result = t.__class__.__name__ - if os.name.startswith('java'): - if result in ("expr_contextType", - "boolopType", - "unaryopType", - "cmpopType", - "operatorType"): - result = t.name() - else: - result = result.split(".")[-1] - if result.endswith("Type"): - result = result[:-4] - return result - def to_tuple(t): if t is None or isinstance(t, (basestring, int, long, complex)): return t - elif hasattr(t, '__iter__'): + elif hasattr(t, "__iter__"): return [to_tuple(e) for e in t] - result = [get_class_name(t)] + result = [t.__class__.__name__] if hasattr(t, 'lineno') and hasattr(t, 'col_offset'): result.append((t.lineno, t.col_offset)) - if not hasattr(t, '_fields') or t._fields is None: + if t._fields is None: return tuple(result) for f in t._fields: result.append(to_tuple(getattr(t, f))) return tuple(result) + # These tests are compiled through "exec" # There should be atleast one test per statement exec_tests = [ @@ -134,49 +120,192 @@ # TODO: expr_context, slice, boolop, operator, unaryop, cmpop, comprehension # excepthandler, arguments, keywords, alias -if __name__=='__main__' and sys.argv[1:] == ['-g']: - for statements, kind in ((exec_tests, "exec"), (single_tests, "single"), - (eval_tests, "eval")): - print kind+"_results = [" - for s in statements: - print repr(to_tuple(compile(s, "?", kind, 0x400)))+"," - print "]" - print "run_tests()" - raise SystemExit +class AST_Tests(unittest.TestCase): -def test_order(ast_node, parent_pos): - - if (not isinstance(ast_node, ast.AST) - or not hasattr(ast_node, '_fields') - or ast_node._fields == None): + def _assert_order(self, ast_node, parent_pos): + if not isinstance(ast_node, ast.AST) or ast_node._fields is None: return - if isinstance(ast_node, (ast.expr, ast.stmt, ast.excepthandler)): - node_pos = (ast_node.lineno, ast_node.col_offset) - assert node_pos >= parent_pos, (node_pos, parent_pos) - parent_pos = (ast_node.lineno, ast_node.col_offset) - for name in ast_node._fields: - value = getattr(ast_node, name) - if hasattr(value, '__iter__'): - for child in value: - test_order(child, parent_pos) - elif value != None: - test_order(value, parent_pos) + if isinstance(ast_node, (ast.expr, ast.stmt, ast.excepthandler)): + node_pos = (ast_node.lineno, ast_node.col_offset) + self.assert_(node_pos >= parent_pos) + parent_pos = (ast_node.lineno, ast_node.col_offset) + for name in ast_node._fields: + value = getattr(ast_node, name) + if hasattr(value, "__iter__"): + for child in value: + self._assert_order(child, parent_pos) + elif value is not None: + self._assert_order(value, parent_pos) -def run_tests(): - for input, output, kind in ((exec_tests, exec_results, "exec"), - (single_tests, single_results, "single"), - (eval_tests, eval_results, "eval")): - for i, o in itertools.izip(input, output): - ast_tree = compile(i, "?", kind, 0x400) - assert to_tuple(ast_tree) == o, "expected %s, got %s" % ( - o, to_tuple(ast_tree)) - test_order(ast_tree, (0, 0)) + def test_snippets(self): + for input, output, kind in ((exec_tests, exec_results, "exec"), + (single_tests, single_results, "single"), + (eval_tests, eval_results, "eval")): + for i, o in itertools.izip(input, output): + ast_tree = compile(i, "?", kind, ast.PyCF_ONLY_AST) + self.assertEquals(to_tuple(ast_tree), o) + self._assert_order(ast_tree, (0, 0)) -# XXX: AugStore added for Jython. Short term it is too hard to emit just "Store" as CPython does. + def test_nodeclasses(self): + x = ast.BinOp(1, 2, 3, lineno=0) + self.assertEquals(x.left.n, 1) + self.assertEquals(int(x.op), 2) + self.assertEquals(x.right.n, 3) + self.assertEquals(x.lineno, 0) + + # node raises exception when not given enough arguments + self.assertRaises(TypeError, ast.BinOp, 1, 2) + + # can set attributes through kwargs too + x = ast.BinOp(left=1, op=2, right=3, lineno=0) + self.assertEquals(x.left.n, 1) + self.assertEquals(int(x.op), 2) + self.assertEquals(x.right.n, 3) + self.assertEquals(x.lineno, 0) + + # this used to fail because Sub._fields was None + x = ast.Sub() + + def test_pickling(self): + import pickle + mods = [pickle] + try: + import cPickle + mods.append(cPickle) + except ImportError: + pass + protocols = [0, 1, 2] + for mod in mods: + for protocol in protocols: + for ast in (compile(i, "?", "exec", 0x400) for i in exec_tests): + ast2 = mod.loads(mod.dumps(ast, protocol)) + self.assertEquals(to_tuple(ast2), to_tuple(ast)) + + +class ASTHelpers_Test(unittest.TestCase): + + def test_parse(self): + a = ast.parse('foo(1 + 1)') + b = compile('foo(1 + 1)', '<unknown>', 'exec', ast.PyCF_ONLY_AST) + self.assertEqual(ast.dump(a), ast.dump(b)) + + def test_dump(self): + node = ast.parse('spam(eggs, "and cheese")') + self.assertEqual(ast.dump(node), + "Module(body=[Expr(value=Call(func=Name(id='spam', ctx=Load()), " + "args=[Name(id='eggs', ctx=Load()), Str(s='and cheese')], " + "keywords=[], starargs=None, kwargs=None))])" + ) + self.assertEqual(ast.dump(node, annotate_fields=False), + "Module([Expr(Call(Name('spam', Load()), [Name('eggs', Load()), " + "Str('and cheese')], [], None, None))])" + ) + self.assertEqual(ast.dump(node, include_attributes=True), + "Module(body=[Expr(value=Call(func=Name(id='spam', ctx=Load(), " + "lineno=1, col_offset=0), args=[Name(id='eggs', ctx=Load(), " + "lineno=1, col_offset=5), Str(s='and cheese', lineno=1, " + "col_offset=11)], keywords=[], starargs=None, kwargs=None, " + "lineno=1, col_offset=0), lineno=1, col_offset=0)])" + ) + + def test_copy_location(self): + src = ast.parse('1 + 1', mode='eval') + src.body.right = ast.copy_location(ast.Num(2), src.body.right) + self.assertEqual(ast.dump(src, include_attributes=True), + 'Expression(body=BinOp(left=Num(n=1, lineno=1, col_offset=0), ' + 'op=Add(), right=Num(n=2, lineno=1, col_offset=4), lineno=1, ' + 'col_offset=0))' + ) + + def test_fix_missing_locations(self): + src = ast.parse('write("spam")') + src.body.append(ast.Expr(ast.Call(ast.Name('spam', ast.Load()), + [ast.Str('eggs')], [], None, None))) + self.assertEqual(src, ast.fix_missing_locations(src)) + self.assertEqual(ast.dump(src, include_attributes=True), + "Module(body=[Expr(value=Call(func=Name(id='write', ctx=Load(), " + "lineno=1, col_offset=0), args=[Str(s='spam', lineno=1, " + "col_offset=6)], keywords=[], starargs=None, kwargs=None, " + "lineno=1, col_offset=0), lineno=1, col_offset=0), " + "Expr(value=Call(func=Name(id='spam', ctx=Load(), lineno=1, " + "col_offset=0), args=[Str(s='eggs', lineno=1, col_offset=0)], " + "keywords=[], starargs=None, kwargs=None, lineno=1, " + "col_offset=0), lineno=1, col_offset=0)])" + ) + + def test_increment_lineno(self): + src = ast.parse('1 + 1', mode='eval') + self.assertEqual(ast.increment_lineno(src, n=3), src) + self.assertEqual(ast.dump(src, include_attributes=True), + 'Expression(body=BinOp(left=Num(n=1, lineno=4, col_offset=0), ' + 'op=Add(), right=Num(n=1, lineno=4, col_offset=4), lineno=4, ' + 'col_offset=0))' + ) + + def test_iter_fields(self): + node = ast.parse('foo()', mode='eval') + d = dict(ast.iter_fields(node.body)) + self.assertEqual(d.pop('func').id, 'foo') + + #XXX: tests for equality between astlist and regular lists not + # working, breaking this test up into its components. + #self.assertEqual(d, {'keywords': [], 'kwargs': None, + # 'args': [], 'starargs': None}) + assert len(d) == 4 + assert d['keywords'] is not None + assert len(d['keywords']) == 0 + assert d['args'] is not None + assert len(d['args']) == 0 + assert d['kwargs'] is None + assert d['starargs'] is None + + def test_iter_child_nodes(self): + node = ast.parse("spam(23, 42, eggs='leek')", mode='eval') + self.assertEqual(len(list(ast.iter_child_nodes(node.body))), 4) + iterator = ast.iter_child_nodes(node.body) + self.assertEqual(iterator.next().id, 'spam') + self.assertEqual(iterator.next().n, 23) + self.assertEqual(iterator.next().n, 42) + self.assertEqual(ast.dump(iterator.next()), + "keyword(arg='eggs', value=Str(s='leek'))" + ) + + def test_get_docstring(self): + node = ast.parse('def foo():\n """line one\n line two"""') + self.assertEqual(ast.get_docstring(node.body[0]), + 'line one\nline two') + + def test_literal_eval(self): + self.assertEqual(ast.literal_eval('[1, 2, 3]'), [1, 2, 3]) + self.assertEqual(ast.literal_eval('{"foo": 42}'), {"foo": 42}) + self.assertEqual(ast.literal_eval('(True, False, None)'), (True, False, None)) + self.assertRaises(ValueError, ast.literal_eval, 'foo()') + + +def test_main(): + #XXX: AST pickling is left as a TODO for now. + del AST_Tests.test_pickling + + test_support.run_unittest(AST_Tests, ASTHelpers_Test) + +def main(): + if __name__ != '__main__': + return + if sys.argv[1:] == ['-g']: + for statements, kind in ((exec_tests, "exec"), (single_tests, "single"), + (eval_tests, "eval")): + print kind+"_results = [" + for s in statements: + print repr(to_tuple(compile(s, "?", kind, 0x400)))+"," + print "]" + print "main()" + raise SystemExit + test_main() + #### EVERYTHING BELOW IS GENERATED ##### exec_results = [ ('Module', [('FunctionDef', (1, 0), 'f', ('arguments', [], None, None, []), [('Pass', (1, 9))], [])]), -('Module', [('ClassDef', (1, 0), 'C', [], [('Pass', (1, 8))],[])]), +('Module', [('ClassDef', (1, 0), 'C', [], [('Pass', (1, 8))], [])]), ('Module', [('FunctionDef', (1, 0), 'f', ('arguments', [], None, None, []), [('Return', (1, 8), ('Num', (1, 15), 1))], [])]), ('Module', [('Delete', (1, 0), [('Name', (1, 4), 'v', ('Del',))])]), ('Module', [('Assign', (1, 0), [('Name', (1, 0), 'v', ('Store',))], ('Num', (1, 4), 1))]), @@ -186,7 +315,7 @@ ('Module', [('While', (1, 0), ('Name', (1, 6), 'v', ('Load',)), [('Pass', (1, 8))], [])]), ('Module', [('If', (1, 0), ('Name', (1, 3), 'v', ('Load',)), [('Pass', (1, 5))], [])]), ('Module', [('Raise', (1, 0), ('Name', (1, 6), 'Exception', ('Load',)), ('Str', (1, 17), 'string'), None)]), -('Module', [('TryExcept', (1, 0), [('Pass', (2, 2))], [('excepthandler', (3, 0), ('Name', (3, 7), 'Exception', ('Load',)), None, [('Pass', (4, 2))], 3, 0)], [])]), +('Module', [('TryExcept', (1, 0), [('Pass', (2, 2))], [('ExceptHandler', (3, 0), ('Name', (3, 7), 'Exception', ('Load',)), None, [('Pass', (4, 2))])], [])]), ('Module', [('TryFinally', (1, 0), [('Pass', (2, 2))], [('Pass', (4, 2))])]), ('Module', [('Assert', (1, 0), ('Name', (1, 7), 'v', ('Load',)), None)]), ('Module', [('Import', (1, 0), [('alias', 'sys', None)])]), @@ -221,4 +350,4 @@ ('Expression', ('Tuple', (1, 0), [('Num', (1, 0), 1), ('Num', (1, 2), 2), ('Num', (1, 4), 3)], ('Load',))), ('Expression', ('Call', (1, 0), ('Attribute', (1, 0), ('Attribute', (1, 0), ('Attribute', (1, 0), ('Name', (1, 0), 'a', ('Load',)), 'b', ('Load',)), 'c', ('Load',)), 'd', ('Load',)), [('Subscript', (1, 8), ('Attribute', (1, 8), ('Name', (1, 8), 'a', ('Load',)), 'b', ('Load',)), ('Slice', ('Num', (1, 12), 1), ('Num', (1, 14), 2), None), ('Load',))], [], None, None)), ] -run_tests() +main() Property changes on: trunk/jython/ast ___________________________________________________________________ Added: svn:ignore + .asdl_antlr.py.swp Modified: trunk/jython/ast/Python.asdl =================================================================== --- trunk/jython/ast/Python.asdl 2008-12-05 00:26:54 UTC (rev 5694) +++ trunk/jython/ast/Python.asdl 2008-12-05 01:10:49 UTC (rev 5695) @@ -1,6 +1,6 @@ -- ASDL's five builtin types are identifier, int, string, object, bool -module Python version "$Revision: 53731 $" +module Python version "$Revision: 62047 $" { mod = Module(stmt* body) | Interactive(stmt* body) @@ -10,9 +10,8 @@ | Suite(stmt* body) stmt = FunctionDef(identifier name, arguments args, - stmt* body, expr* decorators) - | ClassDef(identifier name, expr* bases, - stmt* body, expr* decorators) + stmt* body, expr* decorator_list) + | ClassDef(identifier name, expr* bases, stmt* body, expr *decorator_list) | Return(expr? value) | Delete(expr* targets) @@ -29,7 +28,8 @@ | With(expr context_expr, expr? optional_vars, stmt* body) -- 'type' is a bad name - | Raise(expr? type, expr? inst, expr? tback) + -- changed to 'type' to excepttype for Jython + | Raise(expr? excepttype, expr? inst, expr? tback) | TryExcept(stmt* body, excepthandler* handlers, stmt* orelse) | TryFinally(stmt* body, stmt* finalbody) | Assert(expr test, expr? msg) @@ -99,11 +99,9 @@ comprehension = (expr target, expr iter, expr* ifs) -- not sure what to call the first argument for raise and except - -- TODO(jhylton): Figure out if there is a better way to handle - -- lineno and col_offset fields, particularly when - -- ast is exposed to Python. - excepthandler = (expr? type, expr? name, stmt* body, int lineno, - int col_offset) + -- changed to 'type' to excepttype for Jython + excepthandler = ExceptHandler(expr? excepttype, expr? name, stmt* body) + attributes (int lineno, int col_offset) arguments = (expr* args, identifier? vararg, identifier? kwarg, expr* defaults) Modified: trunk/jython/ast/asdl_antlr.py =================================================================== --- trunk/jython/ast/asdl_antlr.py 2008-12-05 00:26:54 UTC (rev 5694) +++ trunk/jython/ast/asdl_antlr.py 2008-12-05 01:10:49 UTC (rev 5695) @@ -9,7 +9,7 @@ import asdl TABSIZE = 4 -MAX_COL = 80 +MAX_COL = 100 def reflow_lines(s, depth): """Reflow the line s indented depth tabs. @@ -51,17 +51,39 @@ self.dir = dir super(EmitVisitor, self).__init__() - def open(self, name, refersToPythonTree=1, useDataOutput=0): - self.file = open(os.path.join(self.dir, "%s.java" % name), "w") + def open(self, package, name, refersToPythonTree=1, useDataOutput=0): + path = os.path.join(self.dir, package, "%s.java" % name) + open(path, "w") + self.file = open(os.path.join(self.dir, package, "%s.java" % name), "w") print >> self.file, "// Autogenerated AST node" - print >> self.file, 'package org.python.antlr.ast;' + print >> self.file, 'package org.python.antlr.%s;' % package if refersToPythonTree: - print >> self.file, 'import org.python.antlr.PythonTree;' print >> self.file, 'import org.antlr.runtime.CommonToken;' print >> self.file, 'import org.antlr.runtime.Token;' + print >> self.file, 'import org.python.antlr.AST;' + print >> self.file, 'import org.python.antlr.PythonTree;' + print >> self.file, 'import org.python.antlr.adapter.AstAdapters;' + print >> self.file, 'import org.python.antlr.base.excepthandler;' + print >> self.file, 'import org.python.antlr.base.expr;' + print >> self.file, 'import org.python.antlr.base.mod;' + print >> self.file, 'import org.python.antlr.base.slice;' + print >> self.file, 'import org.python.antlr.base.stmt;' + print >> self.file, 'import org.python.core.ArgParser;' + print >> self.file, 'import org.python.core.AstList;' + print >> self.file, 'import org.python.core.Py;' + print >> self.file, 'import org.python.core.PyObject;' + print >> self.file, 'import org.python.core.PyString;' + print >> self.file, 'import org.python.core.PyType;' + print >> self.file, 'import org.python.expose.ExposedGet;' + print >> self.file, 'import org.python.expose.ExposedMethod;' + print >> self.file, 'import org.python.expose.ExposedNew;' + print >> self.file, 'import org.python.expose.ExposedSet;' + print >> self.file, 'import org.python.expose.ExposedType;' + if useDataOutput: print >> self.file, 'import java.io.DataOutputStream;' print >> self.file, 'import java.io.IOException;' + print >> self.file, 'import java.util.ArrayList;' print >> self.file def close(self): @@ -131,80 +153,140 @@ self.visit(type.value, type.name, depth) def visitSum(self, sum, name, depth): - if sum.simple: + if sum.simple and not name == "excepthandler": self.simple_sum(sum, name, depth) + self.simple_sum_wrappers(sum, name, depth) else: self.sum_with_constructor(sum, name, depth) def simple_sum(self, sum, name, depth): - self.open("%sType" % name, refersToPythonTree=0) + self.open("ast", "%sType" % name, refersToPythonTree=0) self.emit('import org.python.antlr.AST;', depth) self.emit('', 0) - self.emit("public enum %(name)sType implements AST {" % locals(), depth) + + self.emit("public enum %(name)sType {" % locals(), depth) self.emit("UNDEFINED,", depth + 1) for i in range(len(sum.types) - 1): type = sum.types[i] self.emit("%s," % type.name, depth + 1) self.emit("%s;" % sum.types[len(sum.types) - 1].name, depth + 1) - self.attributes(sum, depth, True); - self.emit("}", depth) self.close() - def attributes(self, obj, depth, always_emit=False): + def simple_sum_wrappers(self, sum, name, depth): + for i in range(len(sum.types)): + type = sum.types[i] + self.open("op", type.name, refersToPythonTree=0) + self.emit('import org.python.antlr.AST;', depth) + self.emit('import org.python.antlr.PythonTree;', depth) + self.emit('import org.python.core.Py;', depth) + self.emit('import org.python.core.PyObject;', depth) + self.emit('import org.python.core.PyString;', depth) + self.emit('import org.python.core.PyType;', depth) + self.emit('import org.python.expose.ExposedGet;', depth) + self.emit('import org.python.expose.ExposedMethod;', depth) + self.emit('import org.python.expose.ExposedNew;', depth) + self.emit('import org.python.expose.ExposedSet;', depth) + self.emit('import org.python.expose.ExposedType;', depth) + self.emit('', 0) + + self.emit('@ExposedType(name = "_ast.%s", base = AST.class)' % type.name, depth) + self.emit("public class %s extends PythonTree {" % type.name, depth) + self.emit('public static final PyType TYPE = PyType.fromClass(%s.class);' % type.name, depth + 1) + self.emit('', 0) + + self.emit("public %s() {" % (type.name), depth) + self.emit("}", depth) + self.emit('', 0) + + self.emit("public %s(PyType subType) {" % (type.name), depth) + self.emit("super(subType);", depth + 1) + self.emit("}", depth) + self.emit('', 0) + + self.emit("@ExposedNew", depth) + self.emit("@ExposedMethod", depth) + self.emit("public void %s___init__(PyObject[] args, String[] keywords) {}" % type.name, depth) + self.emit('', 0) + + self.attributes(type, name, depth); + + self.emit('@ExposedMethod', depth + 1) + self.emit('public PyObject __int__() {', depth + 1) + self.emit("return %s___int__();" % type.name, depth + 2) + self.emit("}", depth + 1) + self.emit('', 0) + + self.emit("final PyObject %s___int__() {" % type.name, depth + 1) + self.emit('return Py.newInteger(%s);' % str(i + 1), depth + 2) + self.emit("}", depth + 1) + self.emit('', 0) + + self.emit("}", depth) + self.close() + + + def attributes(self, obj, name, depth): field_list = [] if hasattr(obj, "fields"): for f in obj.fields: - field_list.append('"%s"' % f.name) + field_list.append('new PyString("%s")' % f.name) if len(field_list) > 0: - self.emit("private final static String[] fields = new String[] {%s};" % - ", ".join(field_list), depth+1) - self.emit("public String[] get_fields() { return fields; }", depth+1) + self.emit("private final static PyString[] fields =", depth + 1) + self.emit("new PyString[] {%s};" % ", ".join(field_list), depth+1) + self.emit('@ExposedGet(name = "_fields")', depth + 1) + self.emit("public PyString[] get_fields() { return fields; }", depth+1) self.emit("", 0) - elif always_emit: - self.emit("private final static String[] fields = new String[0];", depth+1) - self.emit("public String[] get_fields() { return fields; }", depth+1) + else: + self.emit("private final static PyString[] fields = new PyString[0];", depth+1) + self.emit('@ExposedGet(name = "_fields")', depth + 1) + self.emit("public PyString[] get_fields() { return fields; }", depth+1) self.emit("", 0) - att_list = [] - if hasattr(obj, "attributes"): - for a in obj.attributes: - att_list.append('"%s"' % a.name) - if len(att_list) > 0: - self.emit("private final static String[] attributes = new String[] {%s};" % - ", ".join(att_list), depth+1) - self.emit("public String[] get_attributes() { return attributes; }", depth+1) + if str(name) in ('stmt', 'expr', 'excepthandler'): + att_list = ['new PyString("lineno")', 'new PyString("col_offset")'] + self.emit("private final static PyString[] attributes =", depth + 1) + self.emit("new PyString[] {%s};" % ", ".join(att_list), depth + 1) + self.emit('@ExposedGet(name = "_attributes")', depth + 1) + self.emit("public PyString[] get_attributes() { return attributes; }", depth + 1) self.emit("", 0) - elif always_emit: - self.emit("private final static String[] attributes = new String[0];", depth+1) - self.emit("public String[] get_attributes() { return attributes; }", depth+1) + else: + self.emit("private final static PyString[] attributes = new PyString[0];", depth+1) + self.emit('@ExposedGet(name = "_attributes")', depth + 1) + self.emit("public PyString[] get_attributes() { return attributes; }", depth+1) self.emit("", 0) def sum_with_constructor(self, sum, name, depth): - self.open("%sType" % name) + self.open("base", "%s" % name) - self.emit("public abstract class %(name)sType extends PythonTree {" % + self.emit('@ExposedType(name = "_ast.%s", base = AST.class)' % name, depth) + self.emit("public abstract class %(name)s extends PythonTree {" % locals(), depth) self.emit("", 0) + self.emit("public static final PyType TYPE = PyType.fromClass(%s.class);" % name, depth + 1); - self.attributes(sum, depth); + self.attributes(sum, name, depth); - self.emit("public %(name)sType() {" % locals(), depth+1) + self.emit("public %(name)s() {" % locals(), depth+1) self.emit("}", depth+1) self.emit("", 0) - self.emit("public %(name)sType(int ttype, Token token) {" % locals(), depth+1) + self.emit("public %(name)s(PyType subType) {" % locals(), depth+1) + self.emit("}", depth+1) + self.emit("", 0) + + self.emit("public %(name)s(int ttype, Token token) {" % locals(), depth+1) self.emit("super(ttype, token);", depth+2) self.emit("}", depth+1) self.emit("", 0) - self.emit("public %(name)sType(Token token) {" % locals(), depth+1) + self.emit("public %(name)s(Token token) {" % locals(), depth+1) self.emit("super(token);", depth+2) self.emit("}", depth+1) self.emit("", 0) - self.emit("public %(name)sType(PythonTree node) {" % locals(), depth+1) + self.emit("public %(name)s(PythonTree node) {" % locals(), depth+1) self.emit("super(node);", depth+2) self.emit("}", depth+1) self.emit("", 0) @@ -216,22 +298,24 @@ def visitProduct(self, product, name, depth): - self.open("%sType" % name, useDataOutput=1) - self.emit("public class %(name)sType extends PythonTree {" % locals(), depth) + self.open("ast", "%s" % name, useDataOutput=1) + self.emit('@ExposedType(name = "_ast.%s", base = AST.class)' % name, depth) + self.emit("public class %(name)s extends PythonTree {" % locals(), depth) + self.emit("public static final PyType TYPE = PyType.fromClass(%s.class);" % name, depth + 1); for f in product.fields: self.visit(f, depth + 1) self.emit("", depth) - self.attributes(product, depth) + self.attributes(product, name, depth) - self.javaMethods(product, name, "%sType" % name, product.fields, + self.javaMethods(product, name, "%s" % name, product.fields, depth+1) self.emit("}", depth) self.close() def visitConstructor(self, cons, name, depth): - self.open(cons.name, useDataOutput=1) + self.open("ast", cons.name, useDataOutput=1) ifaces = [] for f in cons.fields: if str(f.type) == "expr_context": @@ -240,13 +324,15 @@ s = "implements %s " % ", ".join(ifaces) else: s = "" - self.emit("public class %s extends %sType %s{" % + self.emit('@ExposedType(name = "_ast.%s", base = AST.class)' % cons.name, depth); + self.emit("public class %s extends %s %s{" % (cons.name, name, s), depth) + self.emit("public static final PyType TYPE = PyType.fromClass(%s.class);" % cons.name, depth); for f in cons.fields: self.visit(f, depth + 1) self.emit("", depth) - self.attributes(cons, depth) + self.attributes(cons, name, depth) self.javaMethods(cons, cons.name, cons.name, cons.fields, depth+1) @@ -256,9 +342,10 @@ self.emit("}", depth + 1) self.emit("", 0) - if str(name) in ('stmt', 'expr'): + if str(name) in ('stmt', 'expr', 'excepthandler'): # The lineno property self.emit("private int lineno = -1;", depth + 1) + self.emit('@ExposedGet(name = "lineno")', depth + 1) self.emit("public int getLineno() {", depth + 1) self.emit("if (lineno != -1) {", depth + 2); self.emit("return lineno;", depth + 3); @@ -266,6 +353,7 @@ self.emit('return getLine();', depth + 2) self.emit("}", depth + 1) self.emit("", 0) + self.emit('@ExposedSet(name = "lineno")', depth + 1) self.emit("public void setLineno(int num) {", depth + 1) self.emit("lineno = num;", depth + 2); self.emit("}", depth + 1) @@ -273,6 +361,7 @@ # The col_offset property self.emit("private int col_offset = -1;", depth + 1) + self.emit('@ExposedGet(name = "col_offset")', depth + 1) self.emit("public int getCol_offset() {", depth + 1) self.emit("if (col_offset != -1) {", depth + 2); self.emit("return col_offset;", depth + 3); @@ -280,75 +369,49 @@ self.emit('return getCharPositionInLine();', depth + 2) self.emit("}", depth + 1) self.emit("", 0) + self.emit('@ExposedSet(name = "col_offset")', depth + 1) self.emit("public void setCol_offset(int num) {", depth + 1) self.emit("col_offset = num;", depth + 2); self.emit("}", depth + 1) self.emit("", 0) + self.emit("}", depth) self.close() def javaConstructorHelper(self, fields, depth): for f in fields: + #if f.seq: + # self.emit("this.%s = new %s(%s);" % (f.name, + # self.javaType(f), f.name), depth+1) + #else: self.emit("this.%s = %s;" % (f.name, f.name), depth+1) + fparg = self.fieldDef(f) - #if field.typedef and field.typedef.simple: + not_simple = True if f.typedef is not None and f.typedef.simple: not_simple = False #For now ignoring String -- will want to revisit - if not_simple and not fparg.startswith("String"): + if not_simple and fparg.find("String") == -1: if f.seq: - self.emit("if (%s != null) {" % f.name, depth+1); - self.emit("for(int i%(name)s=0;i%(name)s<%(name)s.length;i%(name)s++) {" % {"name":f.name}, depth+2) - self.emit("addChild(%s[i%s]);" % (f.name, f.name), depth+3) - self.emit("}", depth+2) + self.emit("if (%s == null) {" % f.name, depth+1); + self.emit("this.%s = new ArrayList<%s>();" % (f.name, self.javaType(f, False)), depth+2) self.emit("}", depth+1) + self.emit("for(PythonTree t : this.%(name)s) {" % {"name":f.name}, depth+1) + self.emit("addChild(t);", depth+2) + self.emit("}", depth+1) elif str(f.type) == "expr": self.emit("addChild(%s);" % (f.name), depth+1) #XXX: this method used to emit a pickle(DataOutputStream ostream) for cPickle support. # If we want to re-add it, see Jython 2.2's pickle method in its ast nodes. def javaMethods(self, type, clsname, ctorname, fields, depth): - # The java ctors - fpargs = ", ".join([self.fieldDef(f) for f in fields]) - self.emit("public %s(%s) {" % (ctorname, fpargs), depth) - self.javaConstructorHelper(fields, depth) - self.emit("}", depth) - self.emit("", 0) + self.javaConstructors(type, clsname, ctorname, fields, depth) - token = asdl.Field('Token', 'token') - token.typedef = False - fpargs = ", ".join([self.fieldDef(f) for f in [token] + fields]) - self.emit("public %s(%s) {" % (ctorname, fpargs), depth) - self.emit("super(token);", depth+1) - self.javaConstructorHelper(fields, depth) - self.emit("}", depth) - self.emit("", 0) - - ttype = asdl.Field('int', 'ttype') - ttype.typedef = False - fpargs = ", ".join([self.fieldDef(f) for f in [ttype, token] + fields]) - self.emit("public %s(%s) {" % (ctorname, fpargs), depth) - self.emit("super(ttype, token);", depth+1) - self.javaConstructorHelper(fields, depth) - self.emit("}", depth) - self.emit("", 0) - - tree = asdl.Field('PythonTree', 'tree') - tree.typedef = False - fpargs = ", ".join([self.fieldDef(f) for f in [tree] + fields]) - self.emit("public %s(%s) {" % (ctorname, fpargs), depth) - self.emit("super(tree);", depth+1) - self.javaConstructorHelper(fields, depth) - self.emit("}", depth) - self.emit("", 0) - - if fpargs: - fpargs += ", " - # The toString() method + self.emit('@ExposedGet(name = "repr")', depth) self.emit("public String toString() {", depth) self.emit('return "%s";' % clsname, depth+1) self.emit("}", depth) @@ -386,10 +449,10 @@ continue if f.seq: self.emit('if (%s != null) {' % f.name, depth+1) - self.emit('for (int i = 0; i < %s.length; i++) {' % f.name, + self.emit('for (PythonTree t : %s) {' % f.name, depth+2) - self.emit('if (%s[i] != null)' % f.name, depth+3) - self.emit('%s[i].accept(visitor);' % f.name, depth+4) + self.emit('if (t != null)', depth+3) + self.emit('t.accept(visitor);', depth+4) self.emit('}', depth+2) self.emit('}', depth+1) else: @@ -398,26 +461,131 @@ self.emit('}', depth) self.emit("", 0) + def javaConstructors(self, type, clsname, ctorname, fields, depth): + if len(fields) > 0: + self.emit("public %s() {" % (ctorname), depth) + self.emit("this(TYPE);", depth + 1) + self.emit("}", depth) + + self.emit("public %s(PyType subType) {" % (ctorname), depth) + self.emit("super(subType);", depth + 1) + self.emit("}", depth) + + fpargs = ", ".join(['"%s"' % f.name for f in fields]) + self.emit("@ExposedNew", depth) + self.emit("@ExposedMethod", depth) + self.emit("public void %s___init__(PyObject[] args, String[] keywords) {" % ctorname, depth) + self.emit('ArgParser ap = new ArgParser("%s", args, keywords, new String[]' % ctorname, depth + 1) + self.emit('{%s}, %s);' % (fpargs, len(fields)), depth + 2) + i = 0 + for f in fields: + self.emit("set%s(ap.getPyObject(%s));" % (str(f.name).capitalize(), + str(i)), depth+1) + i += 1 + self.emit("}", depth) + self.emit("", 0) + + fpargs = ", ".join(["PyObject %s" % f.name for f in fields]) + self.emit("public %s(%s) {" % (ctorname, fpargs), depth) + for f in fields: + self.emit("set%s(%s);" % (str(f.name).capitalize(), + f.name), depth+1) + self.emit("}", depth) + self.emit("", 0) + + token = asdl.Field('Token', 'token') + token.typedef = False + fpargs = ", ".join([self.fieldDef(f) for f in [token] + fields]) + self.emit("public %s(%s) {" % (ctorname, fpargs), depth) + self.emit("super(token);", depth+1) + self.javaConstructorHelper(fields, depth) + self.emit("}", depth) + self.emit("", 0) + + ttype = asdl.Field('int', 'ttype') + ttype.typedef = False + fpargs = ", ".join([self.fieldDef(f) for f in [ttype, token] + fields]) + self.emit("public %s(%s) {" % (ctorname, fpargs), depth) + self.emit("super(ttype, token);", depth+1) + self.javaConstructorHelper(fields, depth) + self.emit("}", depth) + self.emit("", 0) + + tree = asdl.Field('PythonTree', 'tree') + tree.typedef = False + fpargs = ", ".join([self.fieldDef(f) for f in [tree] + fields]) + self.emit("public %s(%s) {" % (ctorname, fpargs), depth) + self.emit("super(tree);", depth+1) + self.javaConstructorHelper(fields, depth) + self.emit("}", depth) + self.emit("", 0) + + def visitField(self, field, depth): - self.emit("public %s;" % self.fieldDef(field), depth) + self.emit("private %s;" % self.fieldDef(field), depth) + self.emit("public %s getInternal%s() {" % (self.javaType(field), + str(field.name).capitalize()), depth) + self.emit("return %s;" % field.name, depth+1) + self.emit("}", depth) + self.emit('@ExposedGet(name = "%s")' % field.name, depth) + self.emit("public PyObject get%s() {" % (str(field.name).capitalize()), depth) + if field.seq: + self.emit("return new AstList(%s, AstAdapters.%sAdapter);" % (field.name, field.type), depth+1) + else: + if str(field.type) == 'identifier': + self.emit("if (%s == null) return Py.None;" % field.name, depth+1) + self.emit("return new PyString(%s);" % field.name, depth+1) + elif str(field.type) == 'string' or str(field.type) == 'object': + self.emit("return (PyObject)%s;" % field.name, depth+1) + elif str(field.type) == 'bool': + self.emit("if (%s) return Py.True;" % field.name, depth+1) + self.emit("return Py.False;" % field.name, depth+1) + elif str(field.type) == 'int': + self.emit("return Py.newInteger(%s);" % field.name, depth+1) + elif field.typedef.simple: + self.emit("return AstAdapters.%s2py(%s);" % (str(field.type), field.name), depth+1) + else: + self.emit("return %s;" % field.name, depth+1) + #self.emit("return Py.None;", depth+1) + self.emit("}", depth) + self.emit('@ExposedSet(name = "%s")' % field.name, depth) + self.emit("public void set%s(PyObject %s) {" % (str(field.name).capitalize(), + field.name), depth) + if field.seq: + #self.emit("this.%s = new %s(" % (field.name, self.javaType(field)), depth+1) + self.emit("this.%s = AstAdapters.py2... [truncated message content] |
From: <fwi...@us...> - 2008-12-05 14:26:17
|
Revision: 5702 http://jython.svn.sourceforge.net/jython/?rev=5702&view=rev Author: fwierzbicki Date: 2008-12-05 14:26:10 +0000 (Fri, 05 Dec 2008) Log Message: ----------- Derived classes for org/python/antlr/ast/* Modified Paths: -------------- trunk/jython/ast/asdl_antlr.py trunk/jython/src/org/python/antlr/ast/Assert.java trunk/jython/src/org/python/antlr/ast/Assign.java trunk/jython/src/org/python/antlr/ast/Attribute.java trunk/jython/src/org/python/antlr/ast/AugAssign.java trunk/jython/src/org/python/antlr/ast/BinOp.java trunk/jython/src/org/python/antlr/ast/BoolOp.java trunk/jython/src/org/python/antlr/ast/Break.java trunk/jython/src/org/python/antlr/ast/Call.java trunk/jython/src/org/python/antlr/ast/ClassDef.java trunk/jython/src/org/python/antlr/ast/Compare.java trunk/jython/src/org/python/antlr/ast/Continue.java trunk/jython/src/org/python/antlr/ast/Delete.java trunk/jython/src/org/python/antlr/ast/Dict.java trunk/jython/src/org/python/antlr/ast/Ellipsis.java trunk/jython/src/org/python/antlr/ast/ExceptHandler.java trunk/jython/src/org/python/antlr/ast/Exec.java trunk/jython/src/org/python/antlr/ast/Expr.java trunk/jython/src/org/python/antlr/ast/Expression.java trunk/jython/src/org/python/antlr/ast/ExtSlice.java trunk/jython/src/org/python/antlr/ast/For.java trunk/jython/src/org/python/antlr/ast/FunctionDef.java trunk/jython/src/org/python/antlr/ast/GeneratorExp.java trunk/jython/src/org/python/antlr/ast/Global.java trunk/jython/src/org/python/antlr/ast/If.java trunk/jython/src/org/python/antlr/ast/IfExp.java trunk/jython/src/org/python/antlr/ast/Import.java trunk/jython/src/org/python/antlr/ast/ImportFrom.java trunk/jython/src/org/python/antlr/ast/Index.java trunk/jython/src/org/python/antlr/ast/Interactive.java trunk/jython/src/org/python/antlr/ast/Lambda.java trunk/jython/src/org/python/antlr/ast/List.java trunk/jython/src/org/python/antlr/ast/ListComp.java trunk/jython/src/org/python/antlr/ast/Module.java trunk/jython/src/org/python/antlr/ast/Name.java trunk/jython/src/org/python/antlr/ast/Num.java trunk/jython/src/org/python/antlr/ast/Pass.java trunk/jython/src/org/python/antlr/ast/Print.java trunk/jython/src/org/python/antlr/ast/Raise.java trunk/jython/src/org/python/antlr/ast/Repr.java trunk/jython/src/org/python/antlr/ast/Return.java trunk/jython/src/org/python/antlr/ast/Slice.java trunk/jython/src/org/python/antlr/ast/Str.java trunk/jython/src/org/python/antlr/ast/Subscript.java trunk/jython/src/org/python/antlr/ast/Suite.java trunk/jython/src/org/python/antlr/ast/TryExcept.java trunk/jython/src/org/python/antlr/ast/TryFinally.java trunk/jython/src/org/python/antlr/ast/Tuple.java trunk/jython/src/org/python/antlr/ast/UnaryOp.java trunk/jython/src/org/python/antlr/ast/While.java trunk/jython/src/org/python/antlr/ast/With.java trunk/jython/src/org/python/antlr/ast/Yield.java trunk/jython/src/org/python/antlr/ast/alias.java trunk/jython/src/org/python/antlr/ast/arguments.java trunk/jython/src/org/python/antlr/ast/comprehension.java trunk/jython/src/org/python/antlr/ast/keyword.java trunk/jython/src/templates/mappings Added Paths: ----------- trunk/jython/src/org/python/antlr/ast/AssertDerived.java trunk/jython/src/org/python/antlr/ast/AssignDerived.java trunk/jython/src/org/python/antlr/ast/AttributeDerived.java trunk/jython/src/org/python/antlr/ast/AugAssignDerived.java trunk/jython/src/org/python/antlr/ast/BinOpDerived.java trunk/jython/src/org/python/antlr/ast/BoolOpDerived.java trunk/jython/src/org/python/antlr/ast/BreakDerived.java trunk/jython/src/org/python/antlr/ast/CallDerived.java trunk/jython/src/org/python/antlr/ast/ClassDefDerived.java trunk/jython/src/org/python/antlr/ast/CompareDerived.java trunk/jython/src/org/python/antlr/ast/ContinueDerived.java trunk/jython/src/org/python/antlr/ast/DeleteDerived.java trunk/jython/src/org/python/antlr/ast/DictDerived.java trunk/jython/src/org/python/antlr/ast/EllipsisDerived.java trunk/jython/src/org/python/antlr/ast/ExceptHandlerDerived.java trunk/jython/src/org/python/antlr/ast/ExecDerived.java trunk/jython/src/org/python/antlr/ast/ExprDerived.java trunk/jython/src/org/python/antlr/ast/ExpressionDerived.java trunk/jython/src/org/python/antlr/ast/ExtSliceDerived.java trunk/jython/src/org/python/antlr/ast/ForDerived.java trunk/jython/src/org/python/antlr/ast/FunctionDefDerived.java trunk/jython/src/org/python/antlr/ast/GeneratorExpDerived.java trunk/jython/src/org/python/antlr/ast/GlobalDerived.java trunk/jython/src/org/python/antlr/ast/IfDerived.java trunk/jython/src/org/python/antlr/ast/IfExpDerived.java trunk/jython/src/org/python/antlr/ast/ImportDerived.java trunk/jython/src/org/python/antlr/ast/ImportFromDerived.java trunk/jython/src/org/python/antlr/ast/IndexDerived.java trunk/jython/src/org/python/antlr/ast/InteractiveDerived.java trunk/jython/src/org/python/antlr/ast/LambdaDerived.java trunk/jython/src/org/python/antlr/ast/ListCompDerived.java trunk/jython/src/org/python/antlr/ast/ListDerived.java trunk/jython/src/org/python/antlr/ast/ModuleDerived.java trunk/jython/src/org/python/antlr/ast/NameDerived.java trunk/jython/src/org/python/antlr/ast/NumDerived.java trunk/jython/src/org/python/antlr/ast/PassDerived.java trunk/jython/src/org/python/antlr/ast/PrintDerived.java trunk/jython/src/org/python/antlr/ast/RaiseDerived.java trunk/jython/src/org/python/antlr/ast/ReprDerived.java trunk/jython/src/org/python/antlr/ast/ReturnDerived.java trunk/jython/src/org/python/antlr/ast/SliceDerived.java trunk/jython/src/org/python/antlr/ast/StrDerived.java trunk/jython/src/org/python/antlr/ast/SubscriptDerived.java trunk/jython/src/org/python/antlr/ast/SuiteDerived.java trunk/jython/src/org/python/antlr/ast/TryExceptDerived.java trunk/jython/src/org/python/antlr/ast/TryFinallyDerived.java trunk/jython/src/org/python/antlr/ast/TupleDerived.java trunk/jython/src/org/python/antlr/ast/UnaryOpDerived.java trunk/jython/src/org/python/antlr/ast/WhileDerived.java trunk/jython/src/org/python/antlr/ast/WithDerived.java trunk/jython/src/org/python/antlr/ast/YieldDerived.java trunk/jython/src/org/python/antlr/ast/aliasDerived.java trunk/jython/src/org/python/antlr/ast/argumentsDerived.java trunk/jython/src/org/python/antlr/ast/comprehensionDerived.java trunk/jython/src/org/python/antlr/ast/keywordDerived.java trunk/jython/src/templates/ast_Assert.derived trunk/jython/src/templates/ast_Assign.derived trunk/jython/src/templates/ast_Attribute.derived trunk/jython/src/templates/ast_AugAssign.derived trunk/jython/src/templates/ast_BinOp.derived trunk/jython/src/templates/ast_BoolOp.derived trunk/jython/src/templates/ast_Break.derived trunk/jython/src/templates/ast_Call.derived trunk/jython/src/templates/ast_ClassDef.derived trunk/jython/src/templates/ast_Compare.derived trunk/jython/src/templates/ast_Continue.derived trunk/jython/src/templates/ast_Delete.derived trunk/jython/src/templates/ast_Dict.derived trunk/jython/src/templates/ast_Ellipsis.derived trunk/jython/src/templates/ast_ExceptHandler.derived trunk/jython/src/templates/ast_Exec.derived trunk/jython/src/templates/ast_Expr.derived trunk/jython/src/templates/ast_Expression.derived trunk/jython/src/templates/ast_ExtSlice.derived trunk/jython/src/templates/ast_For.derived trunk/jython/src/templates/ast_FunctionDef.derived trunk/jython/src/templates/ast_GeneratorExp.derived trunk/jython/src/templates/ast_Global.derived trunk/jython/src/templates/ast_If.derived trunk/jython/src/templates/ast_IfExp.derived trunk/jython/src/templates/ast_Import.derived trunk/jython/src/templates/ast_ImportFrom.derived trunk/jython/src/templates/ast_Index.derived trunk/jython/src/templates/ast_Interactive.derived trunk/jython/src/templates/ast_Lambda.derived trunk/jython/src/templates/ast_List.derived trunk/jython/src/templates/ast_ListComp.derived trunk/jython/src/templates/ast_Module.derived trunk/jython/src/templates/ast_Name.derived trunk/jython/src/templates/ast_Num.derived trunk/jython/src/templates/ast_Pass.derived trunk/jython/src/templates/ast_Print.derived trunk/jython/src/templates/ast_Raise.derived trunk/jython/src/templates/ast_Repr.derived trunk/jython/src/templates/ast_Return.derived trunk/jython/src/templates/ast_Slice.derived trunk/jython/src/templates/ast_Str.derived trunk/jython/src/templates/ast_Subscript.derived trunk/jython/src/templates/ast_Suite.derived trunk/jython/src/templates/ast_TryExcept.derived trunk/jython/src/templates/ast_TryFinally.derived trunk/jython/src/templates/ast_Tuple.derived trunk/jython/src/templates/ast_UnaryOp.derived trunk/jython/src/templates/ast_While.derived trunk/jython/src/templates/ast_With.derived trunk/jython/src/templates/ast_Yield.derived trunk/jython/src/templates/ast_alias.derived trunk/jython/src/templates/ast_arguments.derived trunk/jython/src/templates/ast_comprehension.derived trunk/jython/src/templates/ast_keyword.derived Modified: trunk/jython/ast/asdl_antlr.py =================================================================== --- trunk/jython/ast/asdl_antlr.py 2008-12-05 11:38:02 UTC (rev 5701) +++ trunk/jython/ast/asdl_antlr.py 2008-12-05 14:26:10 UTC (rev 5702) @@ -462,16 +462,19 @@ self.emit("", 0) def javaConstructors(self, type, clsname, ctorname, fields, depth): + self.emit("public %s(PyType subType) {" % (ctorname), depth) + self.emit("super(subType);", depth + 1) + self.emit("}", depth) + if len(fields) > 0: self.emit("public %s() {" % (ctorname), depth) self.emit("this(TYPE);", depth + 1) self.emit("}", depth) - self.emit("public %s(PyType subType) {" % (ctorname), depth) - self.emit("super(subType);", depth + 1) - self.emit("}", depth) - - fpargs = ", ".join(['"%s"' % f.name for f in fields]) + fnames = ['"%s"' % f.name for f in fields] + if str(clsname) in ('stmt', 'expr', 'excepthandler'): + fnames.extend(['"lineno"', '"col_offset"']) + fpargs = ", ".join(fnames) self.emit("@ExposedNew", depth) self.emit("@ExposedMethod", depth) self.emit("public void %s___init__(PyObject[] args, String[] keywords) {" % ctorname, depth) @@ -482,6 +485,19 @@ self.emit("set%s(ap.getPyObject(%s));" % (str(f.name).capitalize(), str(i)), depth+1) i += 1 + if str(clsname) in ('stmt', 'expr', 'excepthandler'): + self.emit("PyObject lin = ap.getPyObject(%s, null);" % str(i), depth + 1) + self.emit("if (lin != null) {", depth + 1) + self.emit("setLineno(lin);", depth + 2) + self.emit("}", depth + 1) + self.emit("", 0) + + self.emit("PyObject col = ap.getPyObject(%s, null);" % str(i+1), depth + 1) + self.emit("if (col != null) {", depth + 1) + self.emit("setLineno(col);", depth + 2) + self.emit("}", depth + 1) + self.emit("", 0) + self.emit("}", depth) self.emit("", 0) Modified: trunk/jython/src/org/python/antlr/ast/Assert.java =================================================================== --- trunk/jython/src/org/python/antlr/ast/Assert.java 2008-12-05 11:38:02 UTC (rev 5701) +++ trunk/jython/src/org/python/antlr/ast/Assert.java 2008-12-05 14:26:10 UTC (rev 5702) @@ -65,12 +65,12 @@ @ExposedGet(name = "_attributes") public PyString[] get_attributes() { return attributes; } + public Assert(PyType subType) { + super(subType); + } public Assert() { this(TYPE); } - public Assert(PyType subType) { - super(subType); - } @ExposedNew @ExposedMethod public void Assert___init__(PyObject[] args, String[] keywords) { Added: trunk/jython/src/org/python/antlr/ast/AssertDerived.java =================================================================== --- trunk/jython/src/org/python/antlr/ast/AssertDerived.java (rev 0) +++ trunk/jython/src/org/python/antlr/ast/AssertDerived.java 2008-12-05 14:26:10 UTC (rev 5702) @@ -0,0 +1,1156 @@ +/* Generated file, do not modify. See jython/src/templates/gderived.py. */ +package org.python.antlr.ast; + +import org.python.core.*; + +public class AssertDerived extends Assert implements Slotted { + + public PyObject getSlot(int index) { + return slots[index]; + } + + public void setSlot(int index,PyObject value) { + slots[index]=value; + } + + private PyObject[]slots; + + private PyObject dict; + + public PyObject fastGetDict() { + return dict; + } + + public PyObject getDict() { + return dict; + } + + public void setDict(PyObject newDict) { + if (newDict instanceof PyStringMap||newDict instanceof PyDictionary) { + dict=newDict; + } else { + throw Py.TypeError("__dict__ must be set to a Dictionary "+newDict.getClass().getName()); + } + } + + public void delDict() { + // deleting an object's instance dict makes it grow a new one + dict=new PyStringMap(); + } + + public AssertDerived(PyType subtype) { + super(subtype); + slots=new PyObject[subtype.getNumSlots()]; + dict=subtype.instDict(); + } + + public PyString __str__() { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__str__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(); + if (res instanceof PyString) + return(PyString)res; + throw Py.TypeError("__str__"+" returned non-"+"string"+" (type "+res.getType().fastGetName()+")"); + } + return super.__str__(); + } + + public PyString __repr__() { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__repr__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(); + if (res instanceof PyString) + return(PyString)res; + throw Py.TypeError("__repr__"+" returned non-"+"string"+" (type "+res.getType().fastGetName()+")"); + } + return super.__repr__(); + } + + public PyString __hex__() { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__hex__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(); + if (res instanceof PyString) + return(PyString)res; + throw Py.TypeError("__hex__"+" returned non-"+"string"+" (type "+res.getType().fastGetName()+")"); + } + return super.__hex__(); + } + + public PyString __oct__() { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__oct__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(); + if (res instanceof PyString) + return(PyString)res; + throw Py.TypeError("__oct__"+" returned non-"+"string"+" (type "+res.getType().fastGetName()+")"); + } + return super.__oct__(); + } + + public PyFloat __float__() { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__float__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(); + if (res instanceof PyFloat) + return(PyFloat)res; + throw Py.TypeError("__float__"+" returned non-"+"float"+" (type "+res.getType().fastGetName()+")"); + } + return super.__float__(); + } + + public PyComplex __complex__() { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__complex__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(); + if (res instanceof PyComplex) + return(PyComplex)res; + throw Py.TypeError("__complex__"+" returned non-"+"complex"+" (type "+res.getType().fastGetName()+")"); + } + return super.__complex__(); + } + + public PyObject __pos__() { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__pos__"); + if (impl!=null) + return impl.__get__(this,self_type).__call__(); + return super.__pos__(); + } + + public PyObject __neg__() { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__neg__"); + if (impl!=null) + return impl.__get__(this,self_type).__call__(); + return super.__neg__(); + } + + public PyObject __abs__() { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__abs__"); + if (impl!=null) + return impl.__get__(this,self_type).__call__(); + return super.__abs__(); + } + + public PyObject __invert__() { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__invert__"); + if (impl!=null) + return impl.__get__(this,self_type).__call__(); + return super.__invert__(); + } + + public PyObject __reduce__() { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__reduce__"); + if (impl!=null) + return impl.__get__(this,self_type).__call__(); + return super.__reduce__(); + } + + public PyObject __add__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__add__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res==Py.NotImplemented) + return null; + return res; + } + return super.__add__(other); + } + + public PyObject __radd__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__radd__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res==Py.NotImplemented) + return null; + return res; + } + return super.__radd__(other); + } + + public PyObject __sub__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__sub__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res==Py.NotImplemented) + return null; + return res; + } + return super.__sub__(other); + } + + public PyObject __rsub__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__rsub__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res==Py.NotImplemented) + return null; + return res; + } + return super.__rsub__(other); + } + + public PyObject __mul__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__mul__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res==Py.NotImplemented) + return null; + return res; + } + return super.__mul__(other); + } + + public PyObject __rmul__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__rmul__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res==Py.NotImplemented) + return null; + return res; + } + return super.__rmul__(other); + } + + public PyObject __div__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__div__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res==Py.NotImplemented) + return null; + return res; + } + return super.__div__(other); + } + + public PyObject __rdiv__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__rdiv__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res==Py.NotImplemented) + return null; + return res; + } + return super.__rdiv__(other); + } + + public PyObject __floordiv__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__floordiv__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res==Py.NotImplemented) + return null; + return res; + } + return super.__floordiv__(other); + } + + public PyObject __rfloordiv__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__rfloordiv__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res==Py.NotImplemented) + return null; + return res; + } + return super.__rfloordiv__(other); + } + + public PyObject __truediv__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__truediv__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res==Py.NotImplemented) + return null; + return res; + } + return super.__truediv__(other); + } + + public PyObject __rtruediv__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__rtruediv__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res==Py.NotImplemented) + return null; + return res; + } + return super.__rtruediv__(other); + } + + public PyObject __mod__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__mod__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res==Py.NotImplemented) + return null; + return res; + } + return super.__mod__(other); + } + + public PyObject __rmod__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__rmod__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res==Py.NotImplemented) + return null; + return res; + } + return super.__rmod__(other); + } + + public PyObject __divmod__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__divmod__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res==Py.NotImplemented) + return null; + return res; + } + return super.__divmod__(other); + } + + public PyObject __rdivmod__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__rdivmod__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res==Py.NotImplemented) + return null; + return res; + } + return super.__rdivmod__(other); + } + + public PyObject __rpow__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__rpow__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res==Py.NotImplemented) + return null; + return res; + } + return super.__rpow__(other); + } + + public PyObject __lshift__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__lshift__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res==Py.NotImplemented) + return null; + return res; + } + return super.__lshift__(other); + } + + public PyObject __rlshift__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__rlshift__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res==Py.NotImplemented) + return null; + return res; + } + return super.__rlshift__(other); + } + + public PyObject __rshift__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__rshift__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res==Py.NotImplemented) + return null; + return res; + } + return super.__rshift__(other); + } + + public PyObject __rrshift__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__rrshift__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res==Py.NotImplemented) + return null; + return res; + } + return super.__rrshift__(other); + } + + public PyObject __and__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__and__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res==Py.NotImplemented) + return null; + return res; + } + return super.__and__(other); + } + + public PyObject __rand__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__rand__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res==Py.NotImplemented) + return null; + return res; + } + return super.__rand__(other); + } + + public PyObject __or__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__or__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res==Py.NotImplemented) + return null; + return res; + } + return super.__or__(other); + } + + public PyObject __ror__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__ror__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res==Py.NotImplemented) + return null; + return res; + } + return super.__ror__(other); + } + + public PyObject __xor__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__xor__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res==Py.NotImplemented) + return null; + return res; + } + return super.__xor__(other); + } + + public PyObject __rxor__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__rxor__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res==Py.NotImplemented) + return null; + return res; + } + return super.__rxor__(other); + } + + public PyObject __lt__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__lt__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res==Py.NotImplemented) + return null; + return res; + } + return super.__lt__(other); + } + + public PyObject __le__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__le__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res==Py.NotImplemented) + return null; + return res; + } + return super.__le__(other); + } + + public PyObject __gt__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__gt__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res==Py.NotImplemented) + return null; + return res; + } + return super.__gt__(other); + } + + public PyObject __ge__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__ge__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res==Py.NotImplemented) + return null; + return res; + } + return super.__ge__(other); + } + + public PyObject __eq__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__eq__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res==Py.NotImplemented) + return null; + return res; + } + return super.__eq__(other); + } + + public PyObject __ne__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__ne__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res==Py.NotImplemented) + return null; + return res; + } + return super.__ne__(other); + } + + public PyObject __iadd__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__iadd__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res==Py.NotImplemented) + return null; + return res; + } + return super.__iadd__(other); + } + + public PyObject __isub__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__isub__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res==Py.NotImplemented) + return null; + return res; + } + return super.__isub__(other); + } + + public PyObject __imul__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__imul__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res==Py.NotImplemented) + return null; + return res; + } + return super.__imul__(other); + } + + public PyObject __idiv__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__idiv__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res==Py.NotImplemented) + return null; + return res; + } + return super.__idiv__(other); + } + + public PyObject __ifloordiv__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__ifloordiv__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res==Py.NotImplemented) + return null; + return res; + } + return super.__ifloordiv__(other); + } + + public PyObject __itruediv__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__itruediv__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res==Py.NotImplemented) + return null; + return res; + } + return super.__itruediv__(other); + } + + public PyObject __imod__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__imod__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res==Py.NotImplemented) + return null; + return res; + } + return super.__imod__(other); + } + + public PyObject __ipow__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__ipow__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res==Py.NotImplemented) + return null; + return res; + } + return super.__ipow__(other); + } + + public PyObject __ilshift__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__ilshift__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res==Py.NotImplemented) + return null; + return res; + } + return super.__ilshift__(other); + } + + public PyObject __irshift__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__irshift__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res==Py.NotImplemented) + return null; + return res; + } + return super.__irshift__(other); + } + + public PyObject __iand__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__iand__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res==Py.NotImplemented) + return null; + return res; + } + return super.__iand__(other); + } + + public PyObject __ior__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__ior__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res==Py.NotImplemented) + return null; + return res; + } + return super.__ior__(other); + } + + public PyObject __ixor__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__ixor__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res==Py.NotImplemented) + return null; + return res; + } + return super.__ixor__(other); + } + + public PyObject __int__() { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__int__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(); + if (res instanceof PyInteger||res instanceof PyLong) + return(PyObject)res; + throw Py.TypeError("__int__"+" should return an integer"); + } + return super.__int__(); + } + + public PyObject __long__() { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__long__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(); + if (res instanceof PyLong||res instanceof PyInteger) + return res; + throw Py.TypeError("__long__"+" returned non-"+"long"+" (type "+res.getType().fastGetName()+")"); + } + return super.__long__(); + } + + public int hashCode() { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__hash__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(); + if (res instanceof PyInteger) { + return((PyInteger)res).getValue(); + } else + if (res instanceof PyLong) { + return((PyLong)res).getValue().intValue(); + } + throw Py.TypeError("__hash__ should return a int"); + } + if (self_type.lookup("__eq__")!=null||self_type.lookup("__cmp__")!=null) { + throw Py.TypeError(String.format("unhashable type: '%.200s'",getType().fastGetName())); + } + return super.hashCode(); + } + + public PyUnicode __unicode__() { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__unicode__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(); + if (res instanceof PyUnicode) + return(PyUnicode)res; + if (res instanceof PyString) + return new PyUnicode((PyString)res); + throw Py.TypeError("__unicode__"+" should return a "+"unicode"); + } + return super.__unicode__(); + } + + public int __cmp__(PyObject other) { + PyType self_type=getType(); + PyType[]where_type=new PyType[1]; + PyObject impl=self_type.lookup_where("__cmp__",where_type); + // Full Compatibility with CPython __cmp__: + // If the derived type don't override __cmp__, the + // *internal* super().__cmp__ should be called, not the + // exposed one. The difference is that the exposed __cmp__ + // throws a TypeError if the argument is an instance of the same type. + if (impl==null||where_type[0]==TYPE||Py.isSubClass(TYPE,where_type[0])) { + return super.__cmp__(other); + } + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res==Py.NotImplemented) { + return-2; + } + int c=res.asInt(); + return c<0?-1:c>0?1:0; + } + + public boolean __nonzero__() { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__nonzero__"); + if (impl==null) { + impl=self_type.lookup("__len__"); + if (impl==null) + return super.__nonzero__(); + } + return impl.__get__(this,self_type).__call__().__nonzero__(); + } + + public boolean __contains__(PyObject o) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__contains__"); + if (impl==null) + return super.__contains__(o); + return impl.__get__(this,self_type).__call__(o).__nonzero__(); + } + + public int __len__() { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__len__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(); + if (res instanceof PyInteger) + return((PyInteger)res).getValue(); + throw Py.TypeError("__len__ should return a int"); + } + return super.__len__(); + } + + public PyObject __iter__() { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__iter__"); + if (impl!=null) + return impl.__get__(this,self_type).__call__(); + impl=self_type.lookup("__getitem__"); + if (impl==null) + return super.__iter__(); + return new PySequenceIter(this); + } + + public PyObject __iternext__() { + PyType self_type=getType(); + PyObject impl=self_type.lookup("next"); + if (impl!=null) { + try { + return impl.__get__(this,self_type).__call__(); + } catch (PyException exc) { + if (Py.matchException(exc,Py.StopIteration)) + return null; + throw exc; + } + } + return super.__iternext__(); // ??? + } + + public PyObject __finditem__(PyObject key) { // ??? + PyType self_type=getType(); + PyObject impl=self_type.lookup("__getitem__"); + if (impl!=null) + try { + return impl.__get__(this,self_type).__call__(key); + } catch (PyException exc) { + if (Py.matchException(exc,Py.LookupError)) + return null; + throw exc; + } + return super.__finditem__(key); + } + + public PyObject __finditem__(int key) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__getitem__"); + if (impl!=null) + try { + return impl.__get__(this,self_type).__call__(new PyInteger(key)); + } catch (PyException exc) { + if (Py.matchException(exc,Py.LookupError)) + return null; + throw exc; + } + return super.__finditem__(key); + } + + public PyObject __getitem__(PyObject key) { + // Same as __finditem__, without swallowing LookupErrors. This allows + // __getitem__ implementations written in Python to raise custom + // exceptions (such as subclasses of KeyError). + // + // We are forced to duplicate the code, instead of defining __finditem__ + // in terms of __getitem__. That's because PyObject defines __getitem__ + // in terms of __finditem__. Therefore, we would end with an infinite + // loop when self_type.lookup("__getitem__") returns null: + // + // __getitem__ -> super.__getitem__ -> __finditem__ -> __getitem__ + // + // By duplicating the (short) lookup and call code, we are safe, because + // the call chains will be: + // + // __finditem__ -> super.__finditem__ + // + // __getitem__ -> super.__getitem__ -> __finditem__ -> super.__finditem__ + + PyType self_type=getType(); + PyObject impl=self_type.lookup("__getitem__"); + if (impl!=null) + return impl.__get__(this,self_type).__call__(key); + return super.__getitem__(key); + } + + public void __setitem__(PyObject key,PyObject value) { // ??? + PyType self_type=getType(); + PyObject impl=self_type.lookup("__setitem__"); + if (impl!=null) { + impl.__get__(this,self_type).__call__(key,value); + return; + } + super.__setitem__(key,value); + } + + public PyObject __getslice__(PyObject start,PyObject stop,PyObject step) { // ??? + if (step!=null) { + return __getitem__(new PySlice(start,stop,step)); + } + PyType self_type=getType(); + PyObject impl=self_type.lookup("__getslice__"); + if (impl!=null) { + PyObject[]indices=PySlice.indices2(this,start,stop); + return impl.__get__(this,self_type).__call__(indices[0],indices[1]); + } + return super.__getslice__(start,stop,step); + } + + public void __setslice__(PyObject start,PyObject stop,PyObject step,PyObject value) { + if (step!=null) { + __setitem__(new PySlice(start,stop,step),value); + return; + } + PyType self_type=getType(); + PyObject impl=self_type.lookup("__setslice__"); + if (impl!=null) { + PyObject[]indices=PySlice.indices2(this,start,stop); + impl.__get__(this,self_type).__call__(indices[0],indices[1],value); + return; + } + super.__setslice__(start,stop,step,value); + } + + public void __delslice__(PyObject start,PyObject stop,PyObject step) { + if (step!=null) { + __delitem__(new PySlice(start,stop,step)); + return; + } + PyType self_type=getType(); + PyObject impl=self_type.lookup("__delslice__"); + if (impl!=null) { + PyObject[]indices=PySlice.indices2(this,start,stop); + impl.__get__(this,self_type).__call__(indices[0],indices[1]); + return; + } + super.__delslice__(start,stop,step); + } + + public void __delitem__(PyObject key) { // ??? + PyType self_type=getType(); + PyObject impl=self_type.lookup("__delitem__"); + if (impl!=null) { + impl.__get__(this,self_type).__call__(key); + return; + } + super.__delitem__(key); + } + + public PyObject __call__(PyObject args[],String keywords[]) { + ThreadState ts=Py.getThreadState(); + if (ts.recursion_depth++>ts.systemState.getrecursionlimit()) + throw Py.RuntimeError("maximum __call__ recursion depth exceeded"); + try { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__call__"); + if (impl!=null) + return impl.__get__(this,self_type).__call__(args,keywords); + return super.__call__(args,keywords); + } finally { + --ts.recursion_depth; + } + } + + public PyObject __findattr_ex__(String name) { + PyType self_type=getType(); + // TODO: We should speed this up. As the __getattribute__ slot almost never + // changes, it is a good candidate for caching, as PyClass does with + // __getattr__. See #1102. + PyObject getattribute=self_type.lookup("__getattribute__"); + PyString py_name=null; + PyException firstAttributeError=null; + try { + if (getattribute!=null) { + py_name=PyString.fromInterned(name); + return getattribute.__get__(this,self_type).__call__(py_name); + } else { + Py.Warning(String.format("__getattribute__ not found on type %s",self_type.getName())); + PyObject ret=super.__findattr_ex__(name); + if (ret!=null) { + return ret; + } // else: pass through to __getitem__ invocation + } + } catch (PyException e) { + if (!Py.matchException(e,Py.AttributeError)) { + throw e; + } else { + firstAttributeError=e; // saved to avoid swallowing custom AttributeErrors + // and pass through to __getattr__ invocation. + } + } + PyObject getattr=self_type.lookup("__getattr__"); + if (getattr!=null) { + if (py_name==null) { + py_name=PyString.fromInterned(name); + } + return getattr.__get__(this,self_type).__call__(py_name); + } + if (firstAttributeError!=null) { + throw firstAttributeError; + } + return null; + } + + public void __setattr__(String name,PyObject value) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__setattr__"); + if (impl!=null) { + impl.__get__(this,self_type).__call__(PyString.fromInterned(name),value); + return; + } + super.__setattr__(name,value); + } + + public void __delattr__(String name) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__delattr__"); + if (impl!=null) { + impl.__get__(this,self_type).__call__(PyString.fromInterned(name)); + return; + } + super.__delattr__(name); + } + + public PyObject __get__(PyObject obj,PyObject type) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__get__"); + if (impl!=null) { + if (obj==null) + obj=Py.None; + if (type==null) + type=Py.None; + return impl.__get__(this,self_type).__call__(obj,type); + } + return super.__get__(obj,type); + } + + public void __set__(PyObject obj,PyObject value) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__set__"); + if (impl!=null) { + impl.__get__(this,self_type).__call__(obj,value); + return; + } + super.__set__(obj,value); + } + + public void __delete__(PyObject obj) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__delete__"); + if (impl!=null) { + impl.__get__(this,self_type).__call__(obj); + return; + } + super.__delete__(obj); + } + + public PyObject __pow__(PyObject other,PyObject modulo) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__pow__"); + if (impl!=null) { + PyObject res; + if (modulo==null) { + res=impl.__get__(this,self_type).__call__(other); + } else { + res=impl.__get__(this,self_type).__call__(other,modulo); + } + if (res==Py.NotImplemented) + return null; + return res; + } + return super.__pow__(other,modulo); + } + + public void dispatch__init__(PyType type,PyObject[]args,String[]keywords) { + PyType self_type=getType(); + if (self_type.isSubType(type)) { + PyObject impl=self_type.lookup("__init__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(args,keywords); + if (res!=Py.None) { + throw Py.TypeError(String.format("__init__() should return None, not '%.200s'",res.getType().fastGetName())); + } + } + } + } + + public PyObject __index__() { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__index__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(); + if (res instanceof PyInteger||res instanceof PyLong) { + return res; + } + throw Py.TypeError(String.format("__index__ returned non-(int,long) (type %s)",res.getType().fastGetName())); + } + return super.__index__(); + } + + public Object __tojava__(Class c) { + // If we are not being asked by the "default" conversion to java, then + // we can provide this as the result, as long as it is a instance of the + // specified class. Without this, derived.__tojava__(PyObject.class) + // would broke. (And that's not pure speculation: PyReflectedFunction's + // ReflectedArgs asks for things like that). + if ((c!=Object.class)&&(c.isInstance(this))) { + return this; + } + // Otherwise, we call the derived __tojava__, if it exists: + PyType self_type=getType(); + PyObject impl=self_type.lookup("__tojava__"); + if (impl!=null) + return impl.__get__(this,self_type).__call__(Py.java2py(c)).__tojava__(Object.class); + return super.__tojava__(c); + } + + public Object __coerce_ex__(PyObject o) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__coerce__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(o); + if (res==Py.NotImplemented) + return Py.None; + if (!(res instanceof PyTuple)) + throw Py.TypeError("__coerce__ didn't return a 2-tuple"); + return((PyTuple)res).getArray(); + } + return super.__coerce_ex__(o); + } + + public String toString() { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__repr__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(); + if (!(res instanceof PyString)) + throw Py.TypeError("__repr__ returned non-string (type "+res.getType().fastGetName()+")"); + return((PyString)res).toString(); + } + return super.toString(); + } + +} Modified: trunk/jython/src/org/python/antlr/ast/Assign.java =================================================================== --- trunk/jython/src/org/python/antlr/ast/Assign.java 2008-12-05 11:38:02 UTC (rev 5701) +++ trunk/jython/src/org/python/antlr/ast/Assign.java 2008-12-05 14:26:10 UTC (rev 5702) @@ -65,12 +65,12 @@ @ExposedGet(name = "_attributes") public PyString[] get_attributes() { return attributes; } + public Assign(PyType subType) { + super(subType); + } public Assign() { this(TYPE); } - public Assign(PyType subType) { - super(subType); - } @ExposedNew @ExposedMethod public void Assign___init__(PyObject[] args, String[] keywords) { Added: trunk/jython/src/org/python/antlr/ast/AssignDerived.java =================================================================== --- trunk/jython/src/org/python/antlr/ast/AssignDerived.java (rev 0) +++ trunk/jython/src/org/python/antlr/ast/AssignDerived.java 2008-12-05 14:26:10 UTC (rev 5702) @@ -0,0 +1,1156 @@ +/* Generated file, do not modify. See jython/src/templates/gderived.py. */ +package org.python.antlr.ast; + +import org.python.core.*; + +public class AssignDerived extends Assign implements Slotted { + + public PyObject getSlot(int index) { + return slots[index]; + } + + public void setSlot(int index,PyObject value) { + slots[index]=value; + } + + private PyObject[]slots; + + private PyObject dict; + + public PyObject fastGetDict() { + return dict; + } + + public PyObject getDict() { + return dict; + } + + public void setDict(PyObject newDict) { + if (newDict instanceof PyStringMap||newDict instanceof PyDictionary) { + dict=newDict; + } else { + throw Py.TypeError("__dict__ must be set to a Dictionary "+newDict.getClass().getName()); + } + } + + public void delDict() { + // deleting an object's instance dict makes it grow a new one + dict=new PyStringMap(); + } + + public AssignDerived(PyType subtype) { + super(subtype); + slots=new PyObject[subtype.getNumSlots()]; + dict=subtype.instDict(); + } + + public PyString __str__() { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__str__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(); + if (res instanceof PyString) + return(PyString)res; + throw Py.TypeError("__str__"+" returned non-"+"string"+" (type "+res.getType().fastGetName()+")"); + } + return super.__str__(); + } + + public PyString __repr__() { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__repr__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(); + if (res instanceof PyString) + return(PyString)res; + throw Py.TypeError("__repr__"+" returned non-"+"string"+" (type "+res.getType().fastGetName()+")"); + } + return super.__repr__(); + } + + public PyString __hex__() { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__hex__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(); + if (res instanceof PyString) + return(PyString)res; + throw Py.TypeError("__hex__"+" returned non-"+"string"+" (type "+res.getType().fastGetName()+")"); + } + return super.__hex__(); + } + + public PyString __oct__() { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__oct__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(); + if (res instanceof PyString) + return(PyString)res; + throw Py.TypeError("__oct__"+" returned non-"+"string"+" (type "+res.getType().fastGetName()+")"); + } + return super.__oct__(); + } + + public PyFloat __float__() { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__float__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(); + if (res instanceof PyFloat) + return(PyFloat)res; + throw Py.TypeError("__float__"+" returned non-"+"float"+" (type "+res.getType().fastGetName()+")"); + } + return super.__float__(); + } + + public PyComplex __complex__() { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__complex__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(); + if (res instanceof PyComplex) + return(PyComplex)res; + throw Py.TypeError("__complex__"+" returned non-"+"complex"+" (type "+res.getType().fastGetName()+")"); + } + return super.__complex__(); + } + + public PyObject __pos__() { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__pos__"); + if (impl!=null) + return impl.__get__(this,self_type).__call__(); + return super.__pos__(); + } + + public PyObject __neg__() { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__neg__"); + if (impl!=null) + return impl.__get__(this,self_type).__call__(); + return super.__neg__(); + } + + public PyObject __abs__() { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__abs__"); + if (impl!=null) + return impl.__get__(this,self_type).__call__(); + return super.__abs__(); + } + + public PyObject __invert__() { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__invert__"); + if (impl!=null) + return impl.__get__(this,self_type).__call__(); + return super.__invert__(); + } + + public PyObject __reduce__() { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__reduce__"); + if (impl!=null) + return impl.__get__(this,self_type).__call__(); + return super.__reduce__(); + } + + public PyObject __add__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__add__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res==Py.NotImplemented) + return null; + return res; + } + return super.__add__(other); + } + + public PyObject __radd__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__radd__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res==Py.NotImplemented) + return null; + return res; + } + return super.__radd__(other); + } + + public PyObject __sub__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__sub__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res==Py.NotImplemented) + return null; + return res; + } + return super.__sub__(other); + } + + public PyObject __rsub__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__r... [truncated message content] |
From: <fwi...@us...> - 2008-12-05 16:10:23
|
Revision: 5703 http://jython.svn.sourceforge.net/jython/?rev=5703&view=rev Author: fwierzbicki Date: 2008-12-05 16:10:15 +0000 (Fri, 05 Dec 2008) Log Message: ----------- org/python/antlr/op/* Derived classes, and fixed lineno, col_offset from ast_antlr.py Modified Paths: -------------- trunk/jython/ast/asdl_antlr.py trunk/jython/src/org/python/antlr/ast/Assert.java trunk/jython/src/org/python/antlr/ast/Assign.java trunk/jython/src/org/python/antlr/ast/Attribute.java trunk/jython/src/org/python/antlr/ast/AugAssign.java trunk/jython/src/org/python/antlr/ast/BinOp.java trunk/jython/src/org/python/antlr/ast/BoolOp.java trunk/jython/src/org/python/antlr/ast/Call.java trunk/jython/src/org/python/antlr/ast/ClassDef.java trunk/jython/src/org/python/antlr/ast/Compare.java trunk/jython/src/org/python/antlr/ast/Delete.java trunk/jython/src/org/python/antlr/ast/Dict.java trunk/jython/src/org/python/antlr/ast/ExceptHandler.java trunk/jython/src/org/python/antlr/ast/Exec.java trunk/jython/src/org/python/antlr/ast/Expr.java trunk/jython/src/org/python/antlr/ast/For.java trunk/jython/src/org/python/antlr/ast/FunctionDef.java trunk/jython/src/org/python/antlr/ast/GeneratorExp.java trunk/jython/src/org/python/antlr/ast/Global.java trunk/jython/src/org/python/antlr/ast/If.java trunk/jython/src/org/python/antlr/ast/IfExp.java trunk/jython/src/org/python/antlr/ast/Import.java trunk/jython/src/org/python/antlr/ast/ImportFrom.java trunk/jython/src/org/python/antlr/ast/Lambda.java trunk/jython/src/org/python/antlr/ast/List.java trunk/jython/src/org/python/antlr/ast/ListComp.java trunk/jython/src/org/python/antlr/ast/Name.java trunk/jython/src/org/python/antlr/ast/Num.java trunk/jython/src/org/python/antlr/ast/Print.java trunk/jython/src/org/python/antlr/ast/Raise.java trunk/jython/src/org/python/antlr/ast/Repr.java trunk/jython/src/org/python/antlr/ast/Return.java trunk/jython/src/org/python/antlr/ast/Str.java trunk/jython/src/org/python/antlr/ast/Subscript.java trunk/jython/src/org/python/antlr/ast/TryExcept.java trunk/jython/src/org/python/antlr/ast/TryFinally.java trunk/jython/src/org/python/antlr/ast/Tuple.java trunk/jython/src/org/python/antlr/ast/UnaryOp.java trunk/jython/src/org/python/antlr/ast/While.java trunk/jython/src/org/python/antlr/ast/With.java trunk/jython/src/org/python/antlr/ast/Yield.java trunk/jython/src/templates/mappings Added Paths: ----------- trunk/jython/src/org/python/antlr/op/AddDerived.java trunk/jython/src/org/python/antlr/op/AndDerived.java trunk/jython/src/org/python/antlr/op/AugLoadDerived.java trunk/jython/src/org/python/antlr/op/AugStoreDerived.java trunk/jython/src/org/python/antlr/op/BitAndDerived.java trunk/jython/src/org/python/antlr/op/BitOrDerived.java trunk/jython/src/org/python/antlr/op/BitXorDerived.java trunk/jython/src/org/python/antlr/op/DelDerived.java trunk/jython/src/org/python/antlr/op/DivDerived.java trunk/jython/src/org/python/antlr/op/EqDerived.java trunk/jython/src/org/python/antlr/op/FloorDivDerived.java trunk/jython/src/org/python/antlr/op/GtDerived.java trunk/jython/src/org/python/antlr/op/GtEDerived.java trunk/jython/src/org/python/antlr/op/InDerived.java trunk/jython/src/org/python/antlr/op/InvertDerived.java trunk/jython/src/org/python/antlr/op/IsDerived.java trunk/jython/src/org/python/antlr/op/IsNotDerived.java trunk/jython/src/org/python/antlr/op/LShiftDerived.java trunk/jython/src/org/python/antlr/op/LoadDerived.java trunk/jython/src/org/python/antlr/op/LtDerived.java trunk/jython/src/org/python/antlr/op/LtEDerived.java trunk/jython/src/org/python/antlr/op/ModDerived.java trunk/jython/src/org/python/antlr/op/MultDerived.java trunk/jython/src/org/python/antlr/op/NotDerived.java trunk/jython/src/org/python/antlr/op/NotEqDerived.java trunk/jython/src/org/python/antlr/op/NotInDerived.java trunk/jython/src/org/python/antlr/op/OrDerived.java trunk/jython/src/org/python/antlr/op/ParamDerived.java trunk/jython/src/org/python/antlr/op/PowDerived.java trunk/jython/src/org/python/antlr/op/RShiftDerived.java trunk/jython/src/org/python/antlr/op/StoreDerived.java trunk/jython/src/org/python/antlr/op/SubDerived.java trunk/jython/src/org/python/antlr/op/UAddDerived.java trunk/jython/src/org/python/antlr/op/USubDerived.java trunk/jython/src/templates/op_Add.derived trunk/jython/src/templates/op_And.derived trunk/jython/src/templates/op_AugLoad.derived trunk/jython/src/templates/op_AugStore.derived trunk/jython/src/templates/op_BitAnd.derived trunk/jython/src/templates/op_BitOr.derived trunk/jython/src/templates/op_BitXor.derived trunk/jython/src/templates/op_Del.derived trunk/jython/src/templates/op_Div.derived trunk/jython/src/templates/op_Eq.derived trunk/jython/src/templates/op_FloorDiv.derived trunk/jython/src/templates/op_Gt.derived trunk/jython/src/templates/op_GtE.derived trunk/jython/src/templates/op_In.derived trunk/jython/src/templates/op_Invert.derived trunk/jython/src/templates/op_Is.derived trunk/jython/src/templates/op_IsNot.derived trunk/jython/src/templates/op_LShift.derived trunk/jython/src/templates/op_Load.derived trunk/jython/src/templates/op_Lt.derived trunk/jython/src/templates/op_LtE.derived trunk/jython/src/templates/op_Mod.derived trunk/jython/src/templates/op_Mult.derived trunk/jython/src/templates/op_Not.derived trunk/jython/src/templates/op_NotEq.derived trunk/jython/src/templates/op_NotIn.derived trunk/jython/src/templates/op_Or.derived trunk/jython/src/templates/op_Param.derived trunk/jython/src/templates/op_Pow.derived trunk/jython/src/templates/op_RShift.derived trunk/jython/src/templates/op_Store.derived trunk/jython/src/templates/op_Sub.derived trunk/jython/src/templates/op_UAdd.derived trunk/jython/src/templates/op_USub.derived Modified: trunk/jython/ast/asdl_antlr.py =================================================================== --- trunk/jython/ast/asdl_antlr.py 2008-12-05 14:26:10 UTC (rev 5702) +++ trunk/jython/ast/asdl_antlr.py 2008-12-05 16:10:15 UTC (rev 5703) @@ -308,7 +308,7 @@ self.attributes(product, name, depth) - self.javaMethods(product, name, "%s" % name, product.fields, + self.javaMethods(product, name, name, True, product.fields, depth+1) self.emit("}", depth) @@ -334,7 +334,7 @@ self.attributes(cons, name, depth) - self.javaMethods(cons, cons.name, cons.name, cons.fields, depth+1) + self.javaMethods(cons, name, cons.name, False, cons.fields, depth+1) if "Context" in ifaces: self.emit("public void setContext(expr_contextType c) {", depth + 1) @@ -406,9 +406,9 @@ #XXX: this method used to emit a pickle(DataOutputStream ostream) for cPickle support. # If we want to re-add it, see Jython 2.2's pickle method in its ast nodes. - def javaMethods(self, type, clsname, ctorname, fields, depth): + def javaMethods(self, type, name, clsname, is_product, fields, depth): - self.javaConstructors(type, clsname, ctorname, fields, depth) + self.javaConstructors(type, name, clsname, is_product, fields, depth) # The toString() method self.emit('@ExposedGet(name = "repr")', depth) @@ -432,11 +432,11 @@ # The accept() method self.emit("public <R> R accept(VisitorIF<R> visitor) throws Exception {", depth) - if clsname == ctorname: - self.emit('return visitor.visit%s(this);' % clsname, depth+1) - else: + if is_product: self.emit('traverse(visitor);' % clsname, depth+1) self.emit('return null;' % clsname, depth+1) + else: + self.emit('return visitor.visit%s(this);' % clsname, depth+1) self.emit("}", depth) self.emit("", 0) @@ -461,39 +461,39 @@ self.emit('}', depth) self.emit("", 0) - def javaConstructors(self, type, clsname, ctorname, fields, depth): - self.emit("public %s(PyType subType) {" % (ctorname), depth) + def javaConstructors(self, type, name, clsname, is_product, fields, depth): + self.emit("public %s(PyType subType) {" % (clsname), depth) self.emit("super(subType);", depth + 1) self.emit("}", depth) if len(fields) > 0: - self.emit("public %s() {" % (ctorname), depth) + self.emit("public %s() {" % (clsname), depth) self.emit("this(TYPE);", depth + 1) self.emit("}", depth) fnames = ['"%s"' % f.name for f in fields] - if str(clsname) in ('stmt', 'expr', 'excepthandler'): + if str(name) in ('stmt', 'expr', 'excepthandler'): fnames.extend(['"lineno"', '"col_offset"']) fpargs = ", ".join(fnames) self.emit("@ExposedNew", depth) self.emit("@ExposedMethod", depth) - self.emit("public void %s___init__(PyObject[] args, String[] keywords) {" % ctorname, depth) - self.emit('ArgParser ap = new ArgParser("%s", args, keywords, new String[]' % ctorname, depth + 1) + self.emit("public void %s___init__(PyObject[] args, String[] keywords) {" % clsname, depth) + self.emit('ArgParser ap = new ArgParser("%s", args, keywords, new String[]' % clsname, depth + 1) self.emit('{%s}, %s);' % (fpargs, len(fields)), depth + 2) i = 0 for f in fields: self.emit("set%s(ap.getPyObject(%s));" % (str(f.name).capitalize(), str(i)), depth+1) i += 1 - if str(clsname) in ('stmt', 'expr', 'excepthandler'): - self.emit("PyObject lin = ap.getPyObject(%s, null);" % str(i), depth + 1) - self.emit("if (lin != null) {", depth + 1) + if str(name) in ('stmt', 'expr', 'excepthandler'): + self.emit("int lin = ap.getInt(%s, -1);" % str(i), depth + 1) + self.emit("if (lin != -1) {", depth + 1) self.emit("setLineno(lin);", depth + 2) self.emit("}", depth + 1) self.emit("", 0) - self.emit("PyObject col = ap.getPyObject(%s, null);" % str(i+1), depth + 1) - self.emit("if (col != null) {", depth + 1) + self.emit("int col = ap.getInt(%s, -1);" % str(i+1), depth + 1) + self.emit("if (col != -1) {", depth + 1) self.emit("setLineno(col);", depth + 2) self.emit("}", depth + 1) self.emit("", 0) @@ -502,7 +502,7 @@ self.emit("", 0) fpargs = ", ".join(["PyObject %s" % f.name for f in fields]) - self.emit("public %s(%s) {" % (ctorname, fpargs), depth) + self.emit("public %s(%s) {" % (clsname, fpargs), depth) for f in fields: self.emit("set%s(%s);" % (str(f.name).capitalize(), f.name), depth+1) @@ -512,7 +512,7 @@ token = asdl.Field('Token', 'token') token.typedef = False fpargs = ", ".join([self.fieldDef(f) for f in [token] + fields]) - self.emit("public %s(%s) {" % (ctorname, fpargs), depth) + self.emit("public %s(%s) {" % (clsname, fpargs), depth) self.emit("super(token);", depth+1) self.javaConstructorHelper(fields, depth) self.emit("}", depth) @@ -521,7 +521,7 @@ ttype = asdl.Field('int', 'ttype') ttype.typedef = False fpargs = ", ".join([self.fieldDef(f) for f in [ttype, token] + fields]) - self.emit("public %s(%s) {" % (ctorname, fpargs), depth) + self.emit("public %s(%s) {" % (clsname, fpargs), depth) self.emit("super(ttype, token);", depth+1) self.javaConstructorHelper(fields, depth) self.emit("}", depth) @@ -530,7 +530,7 @@ tree = asdl.Field('PythonTree', 'tree') tree.typedef = False fpargs = ", ".join([self.fieldDef(f) for f in [tree] + fields]) - self.emit("public %s(%s) {" % (ctorname, fpargs), depth) + self.emit("public %s(%s) {" % (clsname, fpargs), depth) self.emit("super(tree);", depth+1) self.javaConstructorHelper(fields, depth) self.emit("}", depth) Modified: trunk/jython/src/org/python/antlr/ast/Assert.java =================================================================== --- trunk/jython/src/org/python/antlr/ast/Assert.java 2008-12-05 14:26:10 UTC (rev 5702) +++ trunk/jython/src/org/python/antlr/ast/Assert.java 2008-12-05 16:10:15 UTC (rev 5703) @@ -75,9 +75,19 @@ @ExposedMethod public void Assert___init__(PyObject[] args, String[] keywords) { ArgParser ap = new ArgParser("Assert", args, keywords, new String[] - {"test", "msg"}, 2); + {"test", "msg", "lineno", "col_offset"}, 2); setTest(ap.getPyObject(0)); setMsg(ap.getPyObject(1)); + int lin = ap.getInt(2, -1); + if (lin != -1) { + setLineno(lin); + } + + int col = ap.getInt(3, -1); + if (col != -1) { + setLineno(col); + } + } public Assert(PyObject test, PyObject msg) { Modified: trunk/jython/src/org/python/antlr/ast/Assign.java =================================================================== --- trunk/jython/src/org/python/antlr/ast/Assign.java 2008-12-05 14:26:10 UTC (rev 5702) +++ trunk/jython/src/org/python/antlr/ast/Assign.java 2008-12-05 16:10:15 UTC (rev 5703) @@ -75,9 +75,19 @@ @ExposedMethod public void Assign___init__(PyObject[] args, String[] keywords) { ArgParser ap = new ArgParser("Assign", args, keywords, new String[] - {"targets", "value"}, 2); + {"targets", "value", "lineno", "col_offset"}, 2); setTargets(ap.getPyObject(0)); setValue(ap.getPyObject(1)); + int lin = ap.getInt(2, -1); + if (lin != -1) { + setLineno(lin); + } + + int col = ap.getInt(3, -1); + if (col != -1) { + setLineno(col); + } + } public Assign(PyObject targets, PyObject value) { Modified: trunk/jython/src/org/python/antlr/ast/Attribute.java =================================================================== --- trunk/jython/src/org/python/antlr/ast/Attribute.java 2008-12-05 14:26:10 UTC (rev 5702) +++ trunk/jython/src/org/python/antlr/ast/Attribute.java 2008-12-05 16:10:15 UTC (rev 5703) @@ -89,10 +89,20 @@ @ExposedMethod public void Attribute___init__(PyObject[] args, String[] keywords) { ArgParser ap = new ArgParser("Attribute", args, keywords, new String[] - {"value", "attr", "ctx"}, 3); + {"value", "attr", "ctx", "lineno", "col_offset"}, 3); setValue(ap.getPyObject(0)); setAttr(ap.getPyObject(1)); setCtx(ap.getPyObject(2)); + int lin = ap.getInt(3, -1); + if (lin != -1) { + setLineno(lin); + } + + int col = ap.getInt(4, -1); + if (col != -1) { + setLineno(col); + } + } public Attribute(PyObject value, PyObject attr, PyObject ctx) { Modified: trunk/jython/src/org/python/antlr/ast/AugAssign.java =================================================================== --- trunk/jython/src/org/python/antlr/ast/AugAssign.java 2008-12-05 14:26:10 UTC (rev 5702) +++ trunk/jython/src/org/python/antlr/ast/AugAssign.java 2008-12-05 16:10:15 UTC (rev 5703) @@ -88,10 +88,20 @@ @ExposedMethod public void AugAssign___init__(PyObject[] args, String[] keywords) { ArgParser ap = new ArgParser("AugAssign", args, keywords, new String[] - {"target", "op", "value"}, 3); + {"target", "op", "value", "lineno", "col_offset"}, 3); setTarget(ap.getPyObject(0)); setOp(ap.getPyObject(1)); setValue(ap.getPyObject(2)); + int lin = ap.getInt(3, -1); + if (lin != -1) { + setLineno(lin); + } + + int col = ap.getInt(4, -1); + if (col != -1) { + setLineno(col); + } + } public AugAssign(PyObject target, PyObject op, PyObject value) { Modified: trunk/jython/src/org/python/antlr/ast/BinOp.java =================================================================== --- trunk/jython/src/org/python/antlr/ast/BinOp.java 2008-12-05 14:26:10 UTC (rev 5702) +++ trunk/jython/src/org/python/antlr/ast/BinOp.java 2008-12-05 16:10:15 UTC (rev 5703) @@ -88,10 +88,20 @@ @ExposedMethod public void BinOp___init__(PyObject[] args, String[] keywords) { ArgParser ap = new ArgParser("BinOp", args, keywords, new String[] - {"left", "op", "right"}, 3); + {"left", "op", "right", "lineno", "col_offset"}, 3); setLeft(ap.getPyObject(0)); setOp(ap.getPyObject(1)); setRight(ap.getPyObject(2)); + int lin = ap.getInt(3, -1); + if (lin != -1) { + setLineno(lin); + } + + int col = ap.getInt(4, -1); + if (col != -1) { + setLineno(col); + } + } public BinOp(PyObject left, PyObject op, PyObject right) { Modified: trunk/jython/src/org/python/antlr/ast/BoolOp.java =================================================================== --- trunk/jython/src/org/python/antlr/ast/BoolOp.java 2008-12-05 14:26:10 UTC (rev 5702) +++ trunk/jython/src/org/python/antlr/ast/BoolOp.java 2008-12-05 16:10:15 UTC (rev 5703) @@ -75,9 +75,19 @@ @ExposedMethod public void BoolOp___init__(PyObject[] args, String[] keywords) { ArgParser ap = new ArgParser("BoolOp", args, keywords, new String[] - {"op", "values"}, 2); + {"op", "values", "lineno", "col_offset"}, 2); setOp(ap.getPyObject(0)); setValues(ap.getPyObject(1)); + int lin = ap.getInt(2, -1); + if (lin != -1) { + setLineno(lin); + } + + int col = ap.getInt(3, -1); + if (col != -1) { + setLineno(col); + } + } public BoolOp(PyObject op, PyObject values) { Modified: trunk/jython/src/org/python/antlr/ast/Call.java =================================================================== --- trunk/jython/src/org/python/antlr/ast/Call.java 2008-12-05 14:26:10 UTC (rev 5702) +++ trunk/jython/src/org/python/antlr/ast/Call.java 2008-12-05 16:10:15 UTC (rev 5703) @@ -115,12 +115,22 @@ @ExposedMethod public void Call___init__(PyObject[] args, String[] keywords) { ArgParser ap = new ArgParser("Call", args, keywords, new String[] - {"func", "args", "keywords", "starargs", "kwargs"}, 5); + {"func", "args", "keywords", "starargs", "kwargs", "lineno", "col_offset"}, 5); setFunc(ap.getPyObject(0)); setArgs(ap.getPyObject(1)); setKeywords(ap.getPyObject(2)); setStarargs(ap.getPyObject(3)); setKwargs(ap.getPyObject(4)); + int lin = ap.getInt(5, -1); + if (lin != -1) { + setLineno(lin); + } + + int col = ap.getInt(6, -1); + if (col != -1) { + setLineno(col); + } + } public Call(PyObject func, PyObject args, PyObject keywords, PyObject starargs, PyObject Modified: trunk/jython/src/org/python/antlr/ast/ClassDef.java =================================================================== --- trunk/jython/src/org/python/antlr/ast/ClassDef.java 2008-12-05 14:26:10 UTC (rev 5702) +++ trunk/jython/src/org/python/antlr/ast/ClassDef.java 2008-12-05 16:10:15 UTC (rev 5703) @@ -103,11 +103,21 @@ @ExposedMethod public void ClassDef___init__(PyObject[] args, String[] keywords) { ArgParser ap = new ArgParser("ClassDef", args, keywords, new String[] - {"name", "bases", "body", "decorator_list"}, 4); + {"name", "bases", "body", "decorator_list", "lineno", "col_offset"}, 4); setName(ap.getPyObject(0)); setBases(ap.getPyObject(1)); setBody(ap.getPyObject(2)); setDecorator_list(ap.getPyObject(3)); + int lin = ap.getInt(4, -1); + if (lin != -1) { + setLineno(lin); + } + + int col = ap.getInt(5, -1); + if (col != -1) { + setLineno(col); + } + } public ClassDef(PyObject name, PyObject bases, PyObject body, PyObject decorator_list) { Modified: trunk/jython/src/org/python/antlr/ast/Compare.java =================================================================== --- trunk/jython/src/org/python/antlr/ast/Compare.java 2008-12-05 14:26:10 UTC (rev 5702) +++ trunk/jython/src/org/python/antlr/ast/Compare.java 2008-12-05 16:10:15 UTC (rev 5703) @@ -88,10 +88,20 @@ @ExposedMethod public void Compare___init__(PyObject[] args, String[] keywords) { ArgParser ap = new ArgParser("Compare", args, keywords, new String[] - {"left", "ops", "comparators"}, 3); + {"left", "ops", "comparators", "lineno", "col_offset"}, 3); setLeft(ap.getPyObject(0)); setOps(ap.getPyObject(1)); setComparators(ap.getPyObject(2)); + int lin = ap.getInt(3, -1); + if (lin != -1) { + setLineno(lin); + } + + int col = ap.getInt(4, -1); + if (col != -1) { + setLineno(col); + } + } public Compare(PyObject left, PyObject ops, PyObject comparators) { Modified: trunk/jython/src/org/python/antlr/ast/Delete.java =================================================================== --- trunk/jython/src/org/python/antlr/ast/Delete.java 2008-12-05 14:26:10 UTC (rev 5702) +++ trunk/jython/src/org/python/antlr/ast/Delete.java 2008-12-05 16:10:15 UTC (rev 5703) @@ -62,8 +62,18 @@ @ExposedMethod public void Delete___init__(PyObject[] args, String[] keywords) { ArgParser ap = new ArgParser("Delete", args, keywords, new String[] - {"targets"}, 1); + {"targets", "lineno", "col_offset"}, 1); setTargets(ap.getPyObject(0)); + int lin = ap.getInt(1, -1); + if (lin != -1) { + setLineno(lin); + } + + int col = ap.getInt(2, -1); + if (col != -1) { + setLineno(col); + } + } public Delete(PyObject targets) { Modified: trunk/jython/src/org/python/antlr/ast/Dict.java =================================================================== --- trunk/jython/src/org/python/antlr/ast/Dict.java 2008-12-05 14:26:10 UTC (rev 5702) +++ trunk/jython/src/org/python/antlr/ast/Dict.java 2008-12-05 16:10:15 UTC (rev 5703) @@ -75,9 +75,19 @@ @ExposedMethod public void Dict___init__(PyObject[] args, String[] keywords) { ArgParser ap = new ArgParser("Dict", args, keywords, new String[] - {"keys", "values"}, 2); + {"keys", "values", "lineno", "col_offset"}, 2); setKeys(ap.getPyObject(0)); setValues(ap.getPyObject(1)); + int lin = ap.getInt(2, -1); + if (lin != -1) { + setLineno(lin); + } + + int col = ap.getInt(3, -1); + if (col != -1) { + setLineno(col); + } + } public Dict(PyObject keys, PyObject values) { Modified: trunk/jython/src/org/python/antlr/ast/ExceptHandler.java =================================================================== --- trunk/jython/src/org/python/antlr/ast/ExceptHandler.java 2008-12-05 14:26:10 UTC (rev 5702) +++ trunk/jython/src/org/python/antlr/ast/ExceptHandler.java 2008-12-05 16:10:15 UTC (rev 5703) @@ -88,10 +88,20 @@ @ExposedMethod public void ExceptHandler___init__(PyObject[] args, String[] keywords) { ArgParser ap = new ArgParser("ExceptHandler", args, keywords, new String[] - {"excepttype", "name", "body"}, 3); + {"excepttype", "name", "body", "lineno", "col_offset"}, 3); setExcepttype(ap.getPyObject(0)); setName(ap.getPyObject(1)); setBody(ap.getPyObject(2)); + int lin = ap.getInt(3, -1); + if (lin != -1) { + setLineno(lin); + } + + int col = ap.getInt(4, -1); + if (col != -1) { + setLineno(col); + } + } public ExceptHandler(PyObject excepttype, PyObject name, PyObject body) { Modified: trunk/jython/src/org/python/antlr/ast/Exec.java =================================================================== --- trunk/jython/src/org/python/antlr/ast/Exec.java 2008-12-05 14:26:10 UTC (rev 5702) +++ trunk/jython/src/org/python/antlr/ast/Exec.java 2008-12-05 16:10:15 UTC (rev 5703) @@ -88,10 +88,20 @@ @ExposedMethod public void Exec___init__(PyObject[] args, String[] keywords) { ArgParser ap = new ArgParser("Exec", args, keywords, new String[] - {"body", "globals", "locals"}, 3); + {"body", "globals", "locals", "lineno", "col_offset"}, 3); setBody(ap.getPyObject(0)); setGlobals(ap.getPyObject(1)); setLocals(ap.getPyObject(2)); + int lin = ap.getInt(3, -1); + if (lin != -1) { + setLineno(lin); + } + + int col = ap.getInt(4, -1); + if (col != -1) { + setLineno(col); + } + } public Exec(PyObject body, PyObject globals, PyObject locals) { Modified: trunk/jython/src/org/python/antlr/ast/Expr.java =================================================================== --- trunk/jython/src/org/python/antlr/ast/Expr.java 2008-12-05 14:26:10 UTC (rev 5702) +++ trunk/jython/src/org/python/antlr/ast/Expr.java 2008-12-05 16:10:15 UTC (rev 5703) @@ -62,8 +62,18 @@ @ExposedMethod public void Expr___init__(PyObject[] args, String[] keywords) { ArgParser ap = new ArgParser("Expr", args, keywords, new String[] - {"value"}, 1); + {"value", "lineno", "col_offset"}, 1); setValue(ap.getPyObject(0)); + int lin = ap.getInt(1, -1); + if (lin != -1) { + setLineno(lin); + } + + int col = ap.getInt(2, -1); + if (col != -1) { + setLineno(col); + } + } public Expr(PyObject value) { Modified: trunk/jython/src/org/python/antlr/ast/For.java =================================================================== --- trunk/jython/src/org/python/antlr/ast/For.java 2008-12-05 14:26:10 UTC (rev 5702) +++ trunk/jython/src/org/python/antlr/ast/For.java 2008-12-05 16:10:15 UTC (rev 5703) @@ -102,11 +102,21 @@ @ExposedMethod public void For___init__(PyObject[] args, String[] keywords) { ArgParser ap = new ArgParser("For", args, keywords, new String[] - {"target", "iter", "body", "orelse"}, 4); + {"target", "iter", "body", "orelse", "lineno", "col_offset"}, 4); setTarget(ap.getPyObject(0)); setIter(ap.getPyObject(1)); setBody(ap.getPyObject(2)); setOrelse(ap.getPyObject(3)); + int lin = ap.getInt(4, -1); + if (lin != -1) { + setLineno(lin); + } + + int col = ap.getInt(5, -1); + if (col != -1) { + setLineno(col); + } + } public For(PyObject target, PyObject iter, PyObject body, PyObject orelse) { Modified: trunk/jython/src/org/python/antlr/ast/FunctionDef.java =================================================================== --- trunk/jython/src/org/python/antlr/ast/FunctionDef.java 2008-12-05 14:26:10 UTC (rev 5702) +++ trunk/jython/src/org/python/antlr/ast/FunctionDef.java 2008-12-05 16:10:15 UTC (rev 5703) @@ -103,11 +103,21 @@ @ExposedMethod public void FunctionDef___init__(PyObject[] args, String[] keywords) { ArgParser ap = new ArgParser("FunctionDef", args, keywords, new String[] - {"name", "args", "body", "decorator_list"}, 4); + {"name", "args", "body", "decorator_list", "lineno", "col_offset"}, 4); setName(ap.getPyObject(0)); setArgs(ap.getPyObject(1)); setBody(ap.getPyObject(2)); setDecorator_list(ap.getPyObject(3)); + int lin = ap.getInt(4, -1); + if (lin != -1) { + setLineno(lin); + } + + int col = ap.getInt(5, -1); + if (col != -1) { + setLineno(col); + } + } public FunctionDef(PyObject name, PyObject args, PyObject body, PyObject decorator_list) { Modified: trunk/jython/src/org/python/antlr/ast/GeneratorExp.java =================================================================== --- trunk/jython/src/org/python/antlr/ast/GeneratorExp.java 2008-12-05 14:26:10 UTC (rev 5702) +++ trunk/jython/src/org/python/antlr/ast/GeneratorExp.java 2008-12-05 16:10:15 UTC (rev 5703) @@ -75,9 +75,19 @@ @ExposedMethod public void GeneratorExp___init__(PyObject[] args, String[] keywords) { ArgParser ap = new ArgParser("GeneratorExp", args, keywords, new String[] - {"elt", "generators"}, 2); + {"elt", "generators", "lineno", "col_offset"}, 2); setElt(ap.getPyObject(0)); setGenerators(ap.getPyObject(1)); + int lin = ap.getInt(2, -1); + if (lin != -1) { + setLineno(lin); + } + + int col = ap.getInt(3, -1); + if (col != -1) { + setLineno(col); + } + } public GeneratorExp(PyObject elt, PyObject generators) { Modified: trunk/jython/src/org/python/antlr/ast/Global.java =================================================================== --- trunk/jython/src/org/python/antlr/ast/Global.java 2008-12-05 14:26:10 UTC (rev 5702) +++ trunk/jython/src/org/python/antlr/ast/Global.java 2008-12-05 16:10:15 UTC (rev 5703) @@ -62,8 +62,18 @@ @ExposedMethod public void Global___init__(PyObject[] args, String[] keywords) { ArgParser ap = new ArgParser("Global", args, keywords, new String[] - {"names"}, 1); + {"names", "lineno", "col_offset"}, 1); setNames(ap.getPyObject(0)); + int lin = ap.getInt(1, -1); + if (lin != -1) { + setLineno(lin); + } + + int col = ap.getInt(2, -1); + if (col != -1) { + setLineno(col); + } + } public Global(PyObject names) { Modified: trunk/jython/src/org/python/antlr/ast/If.java =================================================================== --- trunk/jython/src/org/python/antlr/ast/If.java 2008-12-05 14:26:10 UTC (rev 5702) +++ trunk/jython/src/org/python/antlr/ast/If.java 2008-12-05 16:10:15 UTC (rev 5703) @@ -88,10 +88,20 @@ @ExposedMethod public void If___init__(PyObject[] args, String[] keywords) { ArgParser ap = new ArgParser("If", args, keywords, new String[] - {"test", "body", "orelse"}, 3); + {"test", "body", "orelse", "lineno", "col_offset"}, 3); setTest(ap.getPyObject(0)); setBody(ap.getPyObject(1)); setOrelse(ap.getPyObject(2)); + int lin = ap.getInt(3, -1); + if (lin != -1) { + setLineno(lin); + } + + int col = ap.getInt(4, -1); + if (col != -1) { + setLineno(col); + } + } public If(PyObject test, PyObject body, PyObject orelse) { Modified: trunk/jython/src/org/python/antlr/ast/IfExp.java =================================================================== --- trunk/jython/src/org/python/antlr/ast/IfExp.java 2008-12-05 14:26:10 UTC (rev 5702) +++ trunk/jython/src/org/python/antlr/ast/IfExp.java 2008-12-05 16:10:15 UTC (rev 5703) @@ -88,10 +88,20 @@ @ExposedMethod public void IfExp___init__(PyObject[] args, String[] keywords) { ArgParser ap = new ArgParser("IfExp", args, keywords, new String[] - {"test", "body", "orelse"}, 3); + {"test", "body", "orelse", "lineno", "col_offset"}, 3); setTest(ap.getPyObject(0)); setBody(ap.getPyObject(1)); setOrelse(ap.getPyObject(2)); + int lin = ap.getInt(3, -1); + if (lin != -1) { + setLineno(lin); + } + + int col = ap.getInt(4, -1); + if (col != -1) { + setLineno(col); + } + } public IfExp(PyObject test, PyObject body, PyObject orelse) { Modified: trunk/jython/src/org/python/antlr/ast/Import.java =================================================================== --- trunk/jython/src/org/python/antlr/ast/Import.java 2008-12-05 14:26:10 UTC (rev 5702) +++ trunk/jython/src/org/python/antlr/ast/Import.java 2008-12-05 16:10:15 UTC (rev 5703) @@ -62,8 +62,18 @@ @ExposedMethod public void Import___init__(PyObject[] args, String[] keywords) { ArgParser ap = new ArgParser("Import", args, keywords, new String[] - {"names"}, 1); + {"names", "lineno", "col_offset"}, 1); setNames(ap.getPyObject(0)); + int lin = ap.getInt(1, -1); + if (lin != -1) { + setLineno(lin); + } + + int col = ap.getInt(2, -1); + if (col != -1) { + setLineno(col); + } + } public Import(PyObject names) { Modified: trunk/jython/src/org/python/antlr/ast/ImportFrom.java =================================================================== --- trunk/jython/src/org/python/antlr/ast/ImportFrom.java 2008-12-05 14:26:10 UTC (rev 5702) +++ trunk/jython/src/org/python/antlr/ast/ImportFrom.java 2008-12-05 16:10:15 UTC (rev 5703) @@ -89,10 +89,20 @@ @ExposedMethod public void ImportFrom___init__(PyObject[] args, String[] keywords) { ArgParser ap = new ArgParser("ImportFrom", args, keywords, new String[] - {"module", "names", "level"}, 3); + {"module", "names", "level", "lineno", "col_offset"}, 3); setModule(ap.getPyObject(0)); setNames(ap.getPyObject(1)); setLevel(ap.getPyObject(2)); + int lin = ap.getInt(3, -1); + if (lin != -1) { + setLineno(lin); + } + + int col = ap.getInt(4, -1); + if (col != -1) { + setLineno(col); + } + } public ImportFrom(PyObject module, PyObject names, PyObject level) { Modified: trunk/jython/src/org/python/antlr/ast/Lambda.java =================================================================== --- trunk/jython/src/org/python/antlr/ast/Lambda.java 2008-12-05 14:26:10 UTC (rev 5702) +++ trunk/jython/src/org/python/antlr/ast/Lambda.java 2008-12-05 16:10:15 UTC (rev 5703) @@ -75,9 +75,19 @@ @ExposedMethod public void Lambda___init__(PyObject[] args, String[] keywords) { ArgParser ap = new ArgParser("Lambda", args, keywords, new String[] - {"args", "body"}, 2); + {"args", "body", "lineno", "col_offset"}, 2); setArgs(ap.getPyObject(0)); setBody(ap.getPyObject(1)); + int lin = ap.getInt(2, -1); + if (lin != -1) { + setLineno(lin); + } + + int col = ap.getInt(3, -1); + if (col != -1) { + setLineno(col); + } + } public Lambda(PyObject args, PyObject body) { Modified: trunk/jython/src/org/python/antlr/ast/List.java =================================================================== --- trunk/jython/src/org/python/antlr/ast/List.java 2008-12-05 14:26:10 UTC (rev 5702) +++ trunk/jython/src/org/python/antlr/ast/List.java 2008-12-05 16:10:15 UTC (rev 5703) @@ -75,9 +75,19 @@ @ExposedMethod public void List___init__(PyObject[] args, String[] keywords) { ArgParser ap = new ArgParser("List", args, keywords, new String[] - {"elts", "ctx"}, 2); + {"elts", "ctx", "lineno", "col_offset"}, 2); setElts(ap.getPyObject(0)); setCtx(ap.getPyObject(1)); + int lin = ap.getInt(2, -1); + if (lin != -1) { + setLineno(lin); + } + + int col = ap.getInt(3, -1); + if (col != -1) { + setLineno(col); + } + } public List(PyObject elts, PyObject ctx) { Modified: trunk/jython/src/org/python/antlr/ast/ListComp.java =================================================================== --- trunk/jython/src/org/python/antlr/ast/ListComp.java 2008-12-05 14:26:10 UTC (rev 5702) +++ trunk/jython/src/org/python/antlr/ast/ListComp.java 2008-12-05 16:10:15 UTC (rev 5703) @@ -75,9 +75,19 @@ @ExposedMethod public void ListComp___init__(PyObject[] args, String[] keywords) { ArgParser ap = new ArgParser("ListComp", args, keywords, new String[] - {"elt", "generators"}, 2); + {"elt", "generators", "lineno", "col_offset"}, 2); setElt(ap.getPyObject(0)); setGenerators(ap.getPyObject(1)); + int lin = ap.getInt(2, -1); + if (lin != -1) { + setLineno(lin); + } + + int col = ap.getInt(3, -1); + if (col != -1) { + setLineno(col); + } + } public ListComp(PyObject elt, PyObject generators) { Modified: trunk/jython/src/org/python/antlr/ast/Name.java =================================================================== --- trunk/jython/src/org/python/antlr/ast/Name.java 2008-12-05 14:26:10 UTC (rev 5702) +++ trunk/jython/src/org/python/antlr/ast/Name.java 2008-12-05 16:10:15 UTC (rev 5703) @@ -76,9 +76,19 @@ @ExposedMethod public void Name___init__(PyObject[] args, String[] keywords) { ArgParser ap = new ArgParser("Name", args, keywords, new String[] - {"id", "ctx"}, 2); + {"id", "ctx", "lineno", "col_offset"}, 2); setId(ap.getPyObject(0)); setCtx(ap.getPyObject(1)); + int lin = ap.getInt(2, -1); + if (lin != -1) { + setLineno(lin); + } + + int col = ap.getInt(3, -1); + if (col != -1) { + setLineno(col); + } + } public Name(PyObject id, PyObject ctx) { Modified: trunk/jython/src/org/python/antlr/ast/Num.java =================================================================== --- trunk/jython/src/org/python/antlr/ast/Num.java 2008-12-05 14:26:10 UTC (rev 5702) +++ trunk/jython/src/org/python/antlr/ast/Num.java 2008-12-05 16:10:15 UTC (rev 5703) @@ -62,8 +62,18 @@ @ExposedMethod public void Num___init__(PyObject[] args, String[] keywords) { ArgParser ap = new ArgParser("Num", args, keywords, new String[] - {"n"}, 1); + {"n", "lineno", "col_offset"}, 1); setN(ap.getPyObject(0)); + int lin = ap.getInt(1, -1); + if (lin != -1) { + setLineno(lin); + } + + int col = ap.getInt(2, -1); + if (col != -1) { + setLineno(col); + } + } public Num(PyObject n) { Modified: trunk/jython/src/org/python/antlr/ast/Print.java =================================================================== --- trunk/jython/src/org/python/antlr/ast/Print.java 2008-12-05 14:26:10 UTC (rev 5702) +++ trunk/jython/src/org/python/antlr/ast/Print.java 2008-12-05 16:10:15 UTC (rev 5703) @@ -89,10 +89,20 @@ @ExposedMethod public void Print___init__(PyObject[] args, String[] keywords) { ArgParser ap = new ArgParser("Print", args, keywords, new String[] - {"dest", "values", "nl"}, 3); + {"dest", "values", "nl", "lineno", "col_offset"}, 3); setDest(ap.getPyObject(0)); setValues(ap.getPyObject(1)); setNl(ap.getPyObject(2)); + int lin = ap.getInt(3, -1); + if (lin != -1) { + setLineno(lin); + } + + int col = ap.getInt(4, -1); + if (col != -1) { + setLineno(col); + } + } public Print(PyObject dest, PyObject values, PyObject nl) { Modified: trunk/jython/src/org/python/antlr/ast/Raise.java =================================================================== --- trunk/jython/src/org/python/antlr/ast/Raise.java 2008-12-05 14:26:10 UTC (rev 5702) +++ trunk/jython/src/org/python/antlr/ast/Raise.java 2008-12-05 16:10:15 UTC (rev 5703) @@ -88,10 +88,20 @@ @ExposedMethod public void Raise___init__(PyObject[] args, String[] keywords) { ArgParser ap = new ArgParser("Raise", args, keywords, new String[] - {"excepttype", "inst", "tback"}, 3); + {"excepttype", "inst", "tback", "lineno", "col_offset"}, 3); setExcepttype(ap.getPyObject(0)); setInst(ap.getPyObject(1)); setTback(ap.getPyObject(2)); + int lin = ap.getInt(3, -1); + if (lin != -1) { + setLineno(lin); + } + + int col = ap.getInt(4, -1); + if (col != -1) { + setLineno(col); + } + } public Raise(PyObject excepttype, PyObject inst, PyObject tback) { Modified: trunk/jython/src/org/python/antlr/ast/Repr.java =================================================================== --- trunk/jython/src/org/python/antlr/ast/Repr.java 2008-12-05 14:26:10 UTC (rev 5702) +++ trunk/jython/src/org/python/antlr/ast/Repr.java 2008-12-05 16:10:15 UTC (rev 5703) @@ -62,8 +62,18 @@ @ExposedMethod public void Repr___init__(PyObject[] args, String[] keywords) { ArgParser ap = new ArgParser("Repr", args, keywords, new String[] - {"value"}, 1); + {"value", "lineno", "col_offset"}, 1); setValue(ap.getPyObject(0)); + int lin = ap.getInt(1, -1); + if (lin != -1) { + setLineno(lin); + } + + int col = ap.getInt(2, -1); + if (col != -1) { + setLineno(col); + } + } public Repr(PyObject value) { Modified: trunk/jython/src/org/python/antlr/ast/Return.java =================================================================== --- trunk/jython/src/org/python/antlr/ast/Return.java 2008-12-05 14:26:10 UTC (rev 5702) +++ trunk/jython/src/org/python/antlr/ast/Return.java 2008-12-05 16:10:15 UTC (rev 5703) @@ -62,8 +62,18 @@ @ExposedMethod public void Return___init__(PyObject[] args, String[] keywords) { ArgParser ap = new ArgParser("Return", args, keywords, new String[] - {"value"}, 1); + {"value", "lineno", "col_offset"}, 1); setValue(ap.getPyObject(0)); + int lin = ap.getInt(1, -1); + if (lin != -1) { + setLineno(lin); + } + + int col = ap.getInt(2, -1); + if (col != -1) { + setLineno(col); + } + } public Return(PyObject value) { Modified: trunk/jython/src/org/python/antlr/ast/Str.java =================================================================== --- trunk/jython/src/org/python/antlr/ast/Str.java 2008-12-05 14:26:10 UTC (rev 5702) +++ trunk/jython/src/org/python/antlr/ast/Str.java 2008-12-05 16:10:15 UTC (rev 5703) @@ -62,8 +62,18 @@ @ExposedMethod public void Str___init__(PyObject[] args, String[] keywords) { ArgParser ap = new ArgParser("Str", args, keywords, new String[] - {"s"}, 1); + {"s", "lineno", "col_offset"}, 1); setS(ap.getPyObject(0)); + int lin = ap.getInt(1, -1); + if (lin != -1) { + setLineno(lin); + } + + int col = ap.getInt(2, -1); + if (col != -1) { + setLineno(col); + } + } public Str(PyObject s) { Modified: trunk/jython/src/org/python/antlr/ast/Subscript.java =================================================================== --- trunk/jython/src/org/python/antlr/ast/Subscript.java 2008-12-05 14:26:10 UTC (rev 5702) +++ trunk/jython/src/org/python/antlr/ast/Subscript.java 2008-12-05 16:10:15 UTC (rev 5703) @@ -88,10 +88,20 @@ @ExposedMethod public void Subscript___init__(PyObject[] args, String[] keywords) { ArgParser ap = new ArgParser("Subscript", args, keywords, new String[] - {"value", "slice", "ctx"}, 3); + {"value", "slice", "ctx", "lineno", "col_offset"}, 3); setValue(ap.getPyObject(0)); setSlice(ap.getPyObject(1)); setCtx(ap.getPyObject(2)); + int lin = ap.getInt(3, -1); + if (lin != -1) { + setLineno(lin); + } + + int col = ap.getInt(4, -1); + if (col != -1) { + setLineno(col); + } + } public Subscript(PyObject value, PyObject slice, PyObject ctx) { Modified: trunk/jython/src/org/python/antlr/ast/TryExcept.java =================================================================== --- trunk/jython/src/org/python/antlr/ast/TryExcept.java 2008-12-05 14:26:10 UTC (rev 5702) +++ trunk/jython/src/org/python/antlr/ast/TryExcept.java 2008-12-05 16:10:15 UTC (rev 5703) @@ -88,10 +88,20 @@ @ExposedMethod public void TryExcept___init__(PyObject[] args, String[] keywords) { ArgParser ap = new ArgParser("TryExcept", args, keywords, new String[] - {"body", "handlers", "orelse"}, 3); + {"body", "handlers", "orelse", "lineno", "col_offset"}, 3); setBody(ap.getPyObject(0)); setHandlers(ap.getPyObject(1)); setOrelse(ap.getPyObject(2)); + int lin = ap.getInt(3, -1); + if (lin != -1) { + setLineno(lin); + } + + int col = ap.getInt(4, -1); + if (col != -1) { + setLineno(col); + } + } public TryExcept(PyObject body, PyObject handlers, PyObject orelse) { Modified: trunk/jython/src/org/python/antlr/ast/TryFinally.java =================================================================== --- trunk/jython/src/org/python/antlr/ast/TryFinally.java 2008-12-05 14:26:10 UTC (rev 5702) +++ trunk/jython/src/org/python/antlr/ast/TryFinally.java 2008-12-05 16:10:15 UTC (rev 5703) @@ -75,9 +75,19 @@ @ExposedMethod public void TryFinally___init__(PyObject[] args, String[] keywords) { ArgParser ap = new ArgParser("TryFinally", args, keywords, new String[] - {"body", "finalbody"}, 2); + {"body", "finalbody", "lineno", "col_offset"}, 2); setBody(ap.getPyObject(0)); setFinalbody(ap.getPyObject(1)); + int lin = ap.getInt(2, -1); + if (lin != -1) { + setLineno(lin); + } + + int col = ap.getInt(3, -1); + if (col != -1) { + setLineno(col); + } + } public TryFinally(PyObject body, PyObject finalbody) { Modified: trunk/jython/src/org/python/antlr/ast/Tuple.java =================================================================== --- trunk/jython/src/org/python/antlr/ast/Tuple.java 2008-12-05 14:26:10 UTC (rev 5702) +++ trunk/jython/src/org/python/antlr/ast/Tuple.java 2008-12-05 16:10:15 UTC (rev 5703) @@ -75,9 +75,19 @@ @ExposedMethod public void Tuple___init__(PyObject[] args, String[] keywords) { ArgParser ap = new ArgParser("Tuple", args, keywords, new String[] - {"elts", "ctx"}, 2); + {"elts", "ctx", "lineno", "col_offset"}, 2); setElts(ap.getPyObject(0)); setCtx(ap.getPyObject(1)); + int lin = ap.getInt(2, -1); + if (lin != -1) { + setLineno(lin); + } + + int col = ap.getInt(3, -1); + if (col != -1) { + setLineno(col); + } + } public Tuple(PyObject elts, PyObject ctx) { Modified: trunk/jython/src/org/python/antlr/ast/UnaryOp.java =================================================================== --- trunk/jython/src/org/python/antlr/ast/UnaryOp.java 2008-12-05 14:26:10 UTC (rev 5702) +++ trunk/jython/src/org/python/antlr/ast/UnaryOp.java 2008-12-05 16:10:15 UTC (rev 5703) @@ -75,9 +75,19 @@ @ExposedMethod public void UnaryOp___init__(PyObject[] args, String[] keywords) { ArgParser ap = new ArgParser("UnaryOp", args, keywords, new String[] - {"op", "operand"}, 2); + {"op", "operand", "lineno", "col_offset"}, 2); setOp(ap.getPyObject(0)); setOperand(ap.getPyObject(1)); + int lin = ap.getInt(2, -1); + if (lin != -1) { + setLineno(lin); + } + + int col = ap.getInt(3, -1); + if (col != -1) { + setLineno(col); + } + } public UnaryOp(PyObject op, PyObject operand) { Modified: trunk/jython/src/org/python/antlr/ast/While.java =================================================================== --- trunk/jython/src/org/python/antlr/ast/While.java 2008-12-05 14:26:10 UTC (rev 5702) +++ trunk/jython/src/org/python/antlr/ast/While.java 2008-12-05 16:10:15 UTC (rev 5703) @@ -88,10 +88,20 @@ @ExposedMethod public void While___init__(PyObject[] args, String[] keywords) { ArgParser ap = new ArgParser("While", args, keywords, new String[] - {"test", "body", "orelse"}, 3); + {"test", "body", "orelse", "lineno", "col_offset"}, 3); setTest(ap.getPyObject(0)); setBody(ap.getPyObject(1)); setOrelse(ap.getPyObject(2)); + int lin = ap.getInt(3, -1); + if (lin != -1) { + setLineno(lin); + } + + int col = ap.getInt(4, -1); + if (col != -1) { + setLineno(col); + } + } public While(PyObject test, PyObject body, PyObject orelse) { Modified: trunk/jython/src/org/python/antlr/ast/With.java =================================================================== --- trunk/jython/src/org/python/antlr/ast/With.java 2008-12-05 14:26:10 UTC (rev 5702) +++ trunk/jython/src/org/python/antlr/ast/With.java 2008-12-05 16:10:15 UTC (rev 5703) @@ -89,10 +89,20 @@ @ExposedMethod public void With___init__(PyObject[] args, String[] keywords) { ArgParser ap = new ArgParser("With", args, keywords, new String[] - {"context_expr", "optional_vars", "body"}, 3); + {"context_expr", "optional_vars", "body", "lineno", "col_offset"}, 3); setContext_expr(ap.getPyObject(0)); setOptional_vars(ap.getPyObject(1)); setBody(ap.getPyObject(2)); + int lin = ap.getInt(3, -1); + if (lin != -1) { + setLineno(lin); + } + + int col = ap.getInt(4, -1); + if (col != -1) { + setLineno(col); + } + } public With(PyObject context_expr, PyObject optional_vars, PyObject body) { Modified: trunk/jython/src/org/python/antlr/ast/Yield.java =================================================================== --- trunk/jython/src/org/python/antlr/ast/Yield.java 2008-12-05 14:26:10 UTC (rev 5702) +++ trunk/jython/src/org/python/antlr/ast/Yield.java 2008-12-05 16:10:15 UTC (rev 5703) @@ -62,8 +62,18 @@ @ExposedMethod public void Yield___init__(PyObject[] args, String[] keywords) { ArgParser ap = new ArgParser("Yield", args, keywords, new String[] - {"value"}, 1); + {"value", "lineno", "col_offset"}, 1); setValue(ap.getPyObject(0)); + int lin = ap.getInt(1, -1); + if (lin != -1) { + setLineno(lin); + } + + int col = ap.getInt(2, -1); + if (col != -1) { + setLineno(col); + } + } public Yield(PyObject value) { Added: trunk/jython/src/org/python/antlr/op/AddDerived.java =================================================================== --- trunk/jython/src/org/python/antlr/op/AddDerived.java (rev 0) +++ trunk/jython/src/org/python/antlr/op/AddDerived.java 2008-12-05 16:10:15 UTC (rev 5703) @@ -0,0 +1,1156 @@ +/* Generated file, do not modify. See jython/src/templates/gderived.py. */ +package org.python.antlr.op; + +import org.python.core.*; + +public class AddDerived extends Add implements Slotted { + + public PyObject getSlot(int index) { + return slots[index]; + } + + public void setSlot(int index,PyObject value) { + slots[index]=value; + } + + private PyObject[]slots; + + private PyObject dict; + + public PyObject fastGetDict() { + return dict; + } + + public PyObject getDict() { + return dict; + } + + public void setDict(PyObject newDict) { + if (newDict instanceof PyStringMap||newDict instanceof PyDictionary) { + dict=newDict; + } else { + throw Py.TypeError("__dict__ must be set to a Dictionary "+newDict.getClass().getName()); + } + } + + public void delDict() { + // deleting an object's instance dict makes it grow a new one + dict=new PyStringMap(); + } + + public AddDerived(PyType subtype) { + super(subtype); + slots=new PyObject[subtype.getNumSlots()]; + dict=subtype.instDict(); + } + + public PyString __str__() { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__str__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(); + if (res instanceof PyString) + return(PyString)res; + throw Py.TypeError("__str__"+" returned non-"+"string"+" (type "+res.getType().fastGetName()+")"); + } + return super.__str__(); + } + + public PyString __repr__() { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__repr__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(); + if (res instanceof PyString) + return(PyString)res; + throw Py.TypeError("__repr__"+" returned non-"+"string"+" (type "+res.getType().fastGetName()+")"); + } + return super.__repr__(); + } + + public PyString __hex__() { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__hex__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(); + if (res instanceof PyString) + return(PyString)res; + throw Py.TypeError("__hex__"+" returned non-"+"string"+" (type "+res.getType().fastGetName()+")"); + } + return super.__hex__(); + } + + public PyString __oct__() { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__oct__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(); + if (res instanceof PyString) + return(PyString)res; + throw Py.TypeError("__oct__"+" returned non-"+"string"+" (type "+res.getType().fastGetName()+")"); + } + return super.__oct__(); + } + + public PyFloat __float__() { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__float__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(); + if (res instanceof PyFloat) + return(PyFloat)res; + throw Py.TypeError("__float__"+" returned non-"+"float"+" (type "+res.getType().fastGetName()+")"); + } + return super.__float__(); + } + + public PyComplex __complex__() { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__complex__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(); + if (res instanceof PyComplex) + return(PyComplex)res; + throw Py.TypeError("__complex__"+" returned non-"+"complex"+" (type "+res.getType().fastGetName()+")"); + } + return super.__complex__(); + } + + public PyObject __pos__() { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__pos__"); + if (impl!=null) + return impl.__get__(this,self_type).__call__(); + return super.__pos__(); + } + + public PyObject __neg__() { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__neg__"); + if (impl!=null) + return impl.__get__(this,self_type).__call__(); + return super.__neg__(); + } + + public PyObject __abs__() { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__abs__"); + if (impl!=null) + return impl.__get__(this,self_type).__call__(); + return super.__abs__(); + } + + public PyObject __invert__() { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__invert__"); + if (impl!=null) + return impl.__get__(this,self_type).__call__(); + return super.__invert__(); + } + + public PyObject __reduce__() { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__reduce__"); + if (impl!=null) + return impl.__get__(this,self_type).__call__(); + return super.__reduce__(); + } + + public PyObject __add__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__add__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res==Py.NotImplemented) + return null; + return res; + } + return super.__add__(other); + } + + public PyObject __radd__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__radd__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res==Py.NotImplemented) + return null; + return res; + } + return super.__radd__(other); + } + + public PyObject __sub__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__sub__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res==Py.NotImplemented) + return null; + return res; + } + return super.__sub__(other); + } + + public PyObject __rsub__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__rsub__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res==Py.NotImplemented) + return null; + return res; + } + return super.__rsub__(other); + } + + public PyObject __mul__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__mul__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res==Py.NotImplemented) + return null; + return res; + } + return super.__mul__(other); + } + + public PyObject __rmul__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__rmul__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res==Py.NotImplemented) + return null; + return res; + } + return super.__rmul__(other); + } + + public PyObject __div__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__div__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res==Py.NotImplemented) + return null; + return res; + } + return super.__div__(other); + } + + public PyObject __rdiv__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__rdiv__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res==Py.NotImplemented) + return null; + return res; + } + return super.__rdiv__(other); + } + + public PyObject __floordiv__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__floordiv__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res==Py.NotImplemented) + return null; + return res; + } + return super.__floordiv__(other); + } + + public PyObject __rfloordiv__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__rfloordiv__"); + if (impl!=null) { + Py... [truncated message content] |
From: <fwi...@us...> - 2008-12-06 02:49:56
|
Revision: 5706 http://jython.svn.sourceforge.net/jython/?rev=5706&view=rev Author: fwierzbicki Date: 2008-12-06 02:49:45 +0000 (Sat, 06 Dec 2008) Log Message: ----------- Added better lineno and col_offset support to a couple of ast nodes, also finished slice support in AstList. Modified Paths: -------------- trunk/jython/ast/asdl_antlr.py trunk/jython/src/org/python/antlr/ast/Break.java trunk/jython/src/org/python/antlr/ast/Continue.java trunk/jython/src/org/python/antlr/ast/Ellipsis.java trunk/jython/src/org/python/antlr/ast/Pass.java trunk/jython/src/org/python/core/AstList.java Modified: trunk/jython/ast/asdl_antlr.py =================================================================== --- trunk/jython/ast/asdl_antlr.py 2008-12-06 02:35:31 UTC (rev 5705) +++ trunk/jython/ast/asdl_antlr.py 2008-12-06 02:49:45 UTC (rev 5706) @@ -470,45 +470,47 @@ self.emit("public %s() {" % (clsname), depth) self.emit("this(TYPE);", depth + 1) self.emit("}", depth) - fnames = ['"%s"' % f.name for f in fields] - if str(name) in ('stmt', 'expr', 'excepthandler'): - fnames.extend(['"lineno"', '"col_offset"']) - fpargs = ", ".join(fnames) - self.emit("@ExposedNew", depth) - self.emit("@ExposedMethod", depth) - self.emit("public void %s___init__(PyObject[] args, String[] keywords) {" % clsname, depth) - self.emit('ArgParser ap = new ArgParser("%s", args, keywords, new String[]' % clsname, depth + 1) - self.emit('{%s}, %s);' % (fpargs, len(fields)), depth + 2) - i = 0 - for f in fields: - self.emit("set%s(ap.getPyObject(%s));" % (str(f.name).capitalize(), - str(i)), depth+1) - i += 1 - if str(name) in ('stmt', 'expr', 'excepthandler'): - self.emit("int lin = ap.getInt(%s, -1);" % str(i), depth + 1) - self.emit("if (lin != -1) {", depth + 1) - self.emit("setLineno(lin);", depth + 2) - self.emit("}", depth + 1) - self.emit("", 0) + else: + fnames = [] - self.emit("int col = ap.getInt(%s, -1);" % str(i+1), depth + 1) - self.emit("if (col != -1) {", depth + 1) - self.emit("setLineno(col);", depth + 2) - self.emit("}", depth + 1) - self.emit("", 0) - - self.emit("}", depth) + if str(name) in ('stmt', 'expr', 'excepthandler'): + fnames.extend(['"lineno"', '"col_offset"']) + fpargs = ", ".join(fnames) + self.emit("@ExposedNew", depth) + self.emit("@ExposedMethod", depth) + self.emit("public void %s___init__(PyObject[] args, String[] keywords) {" % clsname, depth) + self.emit('ArgParser ap = new ArgParser("%s", args, keywords, new String[]' % clsname, depth + 1) + self.emit('{%s}, %s);' % (fpargs, len(fields)), depth + 2) + i = 0 + for f in fields: + self.emit("set%s(ap.getPyObject(%s));" % (str(f.name).capitalize(), + str(i)), depth+1) + i += 1 + if str(name) in ('stmt', 'expr', 'excepthandler'): + self.emit("int lin = ap.getInt(%s, -1);" % str(i), depth + 1) + self.emit("if (lin != -1) {", depth + 1) + self.emit("setLineno(lin);", depth + 2) + self.emit("}", depth + 1) self.emit("", 0) - fpargs = ", ".join(["PyObject %s" % f.name for f in fields]) - self.emit("public %s(%s) {" % (clsname, fpargs), depth) - for f in fields: - self.emit("set%s(%s);" % (str(f.name).capitalize(), - f.name), depth+1) - self.emit("}", depth) + self.emit("int col = ap.getInt(%s, -1);" % str(i+1), depth + 1) + self.emit("if (col != -1) {", depth + 1) + self.emit("setLineno(col);", depth + 2) + self.emit("}", depth + 1) self.emit("", 0) + self.emit("}", depth) + self.emit("", 0) + + fpargs = ", ".join(["PyObject %s" % f.name for f in fields]) + self.emit("public %s(%s) {" % (clsname, fpargs), depth) + for f in fields: + self.emit("set%s(%s);" % (str(f.name).capitalize(), + f.name), depth+1) + self.emit("}", depth) + self.emit("", 0) + token = asdl.Field('Token', 'token') token.typedef = False fpargs = ", ".join([self.fieldDef(f) for f in [token] + fields]) Modified: trunk/jython/src/org/python/antlr/ast/Break.java =================================================================== --- trunk/jython/src/org/python/antlr/ast/Break.java 2008-12-06 02:35:31 UTC (rev 5705) +++ trunk/jython/src/org/python/antlr/ast/Break.java 2008-12-06 02:49:45 UTC (rev 5706) @@ -41,6 +41,26 @@ public Break(PyType subType) { super(subType); } + @ExposedNew + @ExposedMethod + public void Break___init__(PyObject[] args, String[] keywords) { + ArgParser ap = new ArgParser("Break", args, keywords, new String[] + {"lineno", "col_offset"}, 0); + int lin = ap.getInt(0, -1); + if (lin != -1) { + setLineno(lin); + } + + int col = ap.getInt(1, -1); + if (col != -1) { + setLineno(col); + } + + } + + public Break() { + } + public Break(Token token) { super(token); } Modified: trunk/jython/src/org/python/antlr/ast/Continue.java =================================================================== --- trunk/jython/src/org/python/antlr/ast/Continue.java 2008-12-06 02:35:31 UTC (rev 5705) +++ trunk/jython/src/org/python/antlr/ast/Continue.java 2008-12-06 02:49:45 UTC (rev 5706) @@ -41,6 +41,26 @@ public Continue(PyType subType) { super(subType); } + @ExposedNew + @ExposedMethod + public void Continue___init__(PyObject[] args, String[] keywords) { + ArgParser ap = new ArgParser("Continue", args, keywords, new String[] + {"lineno", "col_offset"}, 0); + int lin = ap.getInt(0, -1); + if (lin != -1) { + setLineno(lin); + } + + int col = ap.getInt(1, -1); + if (col != -1) { + setLineno(col); + } + + } + + public Continue() { + } + public Continue(Token token) { super(token); } Modified: trunk/jython/src/org/python/antlr/ast/Ellipsis.java =================================================================== --- trunk/jython/src/org/python/antlr/ast/Ellipsis.java 2008-12-06 02:35:31 UTC (rev 5705) +++ trunk/jython/src/org/python/antlr/ast/Ellipsis.java 2008-12-06 02:49:45 UTC (rev 5706) @@ -40,6 +40,16 @@ public Ellipsis(PyType subType) { super(subType); } + @ExposedNew + @ExposedMethod + public void Ellipsis___init__(PyObject[] args, String[] keywords) { + ArgParser ap = new ArgParser("Ellipsis", args, keywords, new String[] + {}, 0); + } + + public Ellipsis() { + } + public Ellipsis(Token token) { super(token); } Modified: trunk/jython/src/org/python/antlr/ast/Pass.java =================================================================== --- trunk/jython/src/org/python/antlr/ast/Pass.java 2008-12-06 02:35:31 UTC (rev 5705) +++ trunk/jython/src/org/python/antlr/ast/Pass.java 2008-12-06 02:49:45 UTC (rev 5706) @@ -41,6 +41,26 @@ public Pass(PyType subType) { super(subType); } + @ExposedNew + @ExposedMethod + public void Pass___init__(PyObject[] args, String[] keywords) { + ArgParser ap = new ArgParser("Pass", args, keywords, new String[] + {"lineno", "col_offset"}, 0); + int lin = ap.getInt(0, -1); + if (lin != -1) { + setLineno(lin); + } + + int col = ap.getInt(1, -1); + if (col != -1) { + setLineno(col); + } + + } + + public Pass() { + } + public Pass(Token token) { super(token); } Modified: trunk/jython/src/org/python/core/AstList.java =================================================================== --- trunk/jython/src/org/python/core/AstList.java 2008-12-06 02:35:31 UTC (rev 5705) +++ trunk/jython/src/org/python/core/AstList.java 2008-12-06 02:49:45 UTC (rev 5706) @@ -455,9 +455,62 @@ } protected void setslice(int start, int stop, int step, PyObject value) { - //FIXME + if(stop < start) { + stop = start; + } + if (value instanceof PySequence) { + PySequence sequence = (PySequence) value; + setslicePySequence(start, stop, step, sequence); + } else if (value instanceof List) { + List list = (List)value.__tojava__(List.class); + if(list != null && list != Py.NoConversion) { + setsliceList(start, stop, step, list); + } + } else { + setsliceIterable(start, stop, step, value); + } } - + + protected void setslicePySequence(int start, int stop, int step, PySequence value) { + if (step != 0) { + if(value == this) { + PyList newseq = new PyList(); + PyObject iter = value.__iter__(); + for(PyObject item = null; (item = iter.__iternext__()) != null;) { + newseq.append(item); + } + value = newseq; + } + int n = value.__len__(); + for (int i = 0, j = start; i < n; i++, j += step) { + pyset(j, value.pyget(i)); + } + } + } + + protected void setsliceList(int start, int stop, int step, List value) { + if(step != 1) { + throw Py.TypeError("setslice with java.util.List and step != 1 not supported yet"); + } + int n = value.size(); + for(int i = 0; i < n; i++) { + data.add(i + start, value.get(i)); + } + } + + protected void setsliceIterable(int start, int stop, int step, PyObject value) { + PyObject[] seq; + try { + seq = Py.make_array(value); + } catch (PyException pye) { + if (Py.matchException(pye, Py.TypeError)) { + throw Py.TypeError("can only assign an iterable"); + } + throw pye; + } + setslicePySequence(start, stop, step, new PyList(seq)); + } + public void add(int index, Object element) { data.add(index, element); } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <pj...@us...> - 2008-12-06 06:52:33
|
Revision: 5712 http://jython.svn.sourceforge.net/jython/?rev=5712&view=rev Author: pjenvey Date: 2008-12-06 06:52:28 +0000 (Sat, 06 Dec 2008) Log Message: ----------- o fix str/unicode add/join to decode when appropriate o fix '%r' % u'' returning unicode o cast fastSequence to a PySequence Modified Paths: -------------- trunk/jython/Lib/test/test_unicode_jy.py trunk/jython/src/org/python/core/PySequence.java trunk/jython/src/org/python/core/PyString.java trunk/jython/src/org/python/core/PyUnicode.java Modified: trunk/jython/Lib/test/test_unicode_jy.py =================================================================== --- trunk/jython/Lib/test/test_unicode_jy.py 2008-12-06 05:18:08 UTC (rev 5711) +++ trunk/jython/Lib/test/test_unicode_jy.py 2008-12-06 06:52:28 UTC (rev 5712) @@ -72,7 +72,18 @@ self.assertEqual(u'%c' % sys.maxunicode, u'\U0010ffff') self.assertRaises(OverflowError, '%c'.__mod__, sys.maxunicode + 1) + def test_repr(self): + self.assert_(isinstance('%r' % u'foo', str)) + def test_concat(self): + self.assertRaises(UnicodeDecodeError, lambda : u'' + '毛泽东') + self.assertRaises(UnicodeDecodeError, lambda : '毛泽东' + u'') + + def test_join(self): + self.assertRaises(UnicodeDecodeError, u''.join, ['foo', '毛泽东']) + self.assertRaises(UnicodeDecodeError, '毛泽东'.join, [u'foo', u'bar']) + + def test_main(): test_support.run_unittest(UnicodeTestCase) Modified: trunk/jython/src/org/python/core/PySequence.java =================================================================== --- trunk/jython/src/org/python/core/PySequence.java 2008-12-06 05:18:08 UTC (rev 5711) +++ trunk/jython/src/org/python/core/PySequence.java 2008-12-06 06:52:28 UTC (rev 5712) @@ -218,9 +218,9 @@ // Return a copy of a sequence where the __len__() method is // telling the truth. - protected static PyObject fastSequence(PyObject seq, String msg) { - if(seq instanceof PySequence) { - return seq; + protected static PySequence fastSequence(PyObject seq, String msg) { + if (seq instanceof PySequence) { + return (PySequence)seq; } PyList list = new PyList(); PyObject iter = Py.iter(seq, msg); Modified: trunk/jython/src/org/python/core/PyString.java =================================================================== --- trunk/jython/src/org/python/core/PyString.java 2008-12-06 05:18:08 UTC (rev 5711) +++ trunk/jython/src/org/python/core/PyString.java 2008-12-06 06:52:28 UTC (rev 5712) @@ -704,21 +704,20 @@ return repeat(o.asIndex(Py.OverflowError)); } - public PyObject __add__(PyObject generic_other) { - return str___add__(generic_other); + public PyObject __add__(PyObject other) { + return str___add__(other); } @ExposedMethod(type = MethodType.BINARY) - final PyObject str___add__(PyObject generic_other) { - if (generic_other instanceof PyString) { - PyString other = (PyString)generic_other; - String result = string.concat(other.string); - if (generic_other instanceof PyUnicode) { - return new PyUnicode(result); - } - return createInstance(result); + final PyObject str___add__(PyObject other) { + if (other instanceof PyUnicode) { + return decode().__add__(other); } - else return null; + if (other instanceof PyString) { + PyString otherStr = (PyString)other; + return new PyString(string.concat(otherStr.string)); + } + return null; } @ExposedMethod @@ -1847,67 +1846,135 @@ } } - return newPiece.str_join(splitfields(oldPiece.string, maxsplit)); + return newPiece.join(splitfields(oldPiece.string, maxsplit)); } - public String join(PyObject seq) { - return str_join(seq).string; + public PyString join(PyObject seq) { + return str_join(seq); } @ExposedMethod final PyString str_join(PyObject obj) { - // Similar to CPython's abstract::PySequence_Fast - PySequence seq; - if (obj instanceof PySequence) { - seq = (PySequence)obj; - } else { - seq = new PyList(obj.__iter__()); + PySequence seq = fastSequence(obj, ""); + int seqLen = seq.__len__(); + if (seqLen == 0) { + return Py.EmptyString; } PyObject item; - int seqlen = seq.__len__(); - if (seqlen == 0) { - return createInstance("", true); - } - if (seqlen == 1) { + if (seqLen == 1) { item = seq.pyget(0); - if (item.getType() == PyUnicode.TYPE || - (item.getType() == PyString.TYPE && getType() == PyString.TYPE)) { + if (item.getType() == PyString.TYPE || item.getType() == PyUnicode.TYPE) { return (PyString)item; } } - boolean needsUnicode = false; - long joinedSize = 0; - StringBuilder buf = new StringBuilder(); - for (int i = 0; i < seqlen; i++) { + // There are at least two things to join, or else we have a subclass of the + // builtin types in the sequence. Do a pre-pass to figure out the total amount of + // space we'll need, see whether any argument is absurd, and defer to the Unicode + // join if appropriate + int i = 0; + long size = 0; + int sepLen = string.length(); + for (; i < seqLen; i++) { item = seq.pyget(i); if (!(item instanceof PyString)) { throw Py.TypeError(String.format("sequence item %d: expected string, %.80s found", i, item.getType().fastGetName())); } if (item instanceof PyUnicode) { - needsUnicode = true; + // Defer to Unicode join. CAUTION: There's no gurantee that the original + // sequence can be iterated over again, so we must pass seq here + return unicodeJoin(seq); } - if (i > 0) { - buf.append(string); - joinedSize += string.length(); + + if (i != 0) { + size += sepLen; } - String itemString = ((PyString)item).string; - buf.append(itemString); - joinedSize += itemString.length(); - if (joinedSize > Integer.MAX_VALUE) { + size += ((PyString)item).string.length(); + if (size > Integer.MAX_VALUE) { throw Py.OverflowError("join() result is too long for a Python string"); } } - if (needsUnicode){ - return new PyUnicode(buf.toString()); + // Catenate everything + StringBuilder buf = new StringBuilder((int)size); + for (i = 0; i < seqLen; i++) { + item = seq.pyget(i); + if (i != 0) { + buf.append(string); + } + buf.append(((PyString)item).string); } - return createInstance(buf.toString(), true); + return new PyString(buf.toString()); } + final PyUnicode unicodeJoin(PyObject obj) { + PySequence seq = fastSequence(obj, ""); + // A codec may be invoked to convert str objects to Unicode, and so it's possible + // to call back into Python code during PyUnicode_FromObject(), and so it's + // possible for a sick codec to change the size of fseq (if seq is a list). + // Therefore we have to keep refetching the size -- can't assume seqlen is + // invariant. + int seqLen = seq.__len__(); + // If empty sequence, return u"" + if (seqLen == 0) { + return new PyUnicode(); + } + // If singleton sequence with an exact Unicode, return that + PyObject item; + if (seqLen == 1) { + item = seq.pyget(0); + if (item.getType() == PyUnicode.TYPE) { + return (PyUnicode)item; + } + } + + String sep = null; + if (seqLen > 1) { + if (this instanceof PyUnicode) { + sep = string; + } else { + sep = ((PyUnicode)decode()).string; + // In case decode()'s codec mutated seq + seqLen = seq.__len__(); + } + } + + // At least two items to join, or one that isn't exact Unicode + long size = 0; + int sepLen = string.length(); + StringBuilder buf = new StringBuilder(); + String itemString; + for (int i = 0; i < seqLen; i++) { + item = seq.pyget(i); + // Convert item to Unicode + if (!(item instanceof PyString)) { + throw Py.TypeError(String.format("sequence item %d: expected string or Unicode," + + " %.80s found", + i, item.getType().fastGetName())); + } + if (!(item instanceof PyUnicode)) { + item = ((PyString)item).decode(); + // In case decode()'s codec mutated seq + seqLen = seq.__len__(); + } + itemString = ((PyUnicode)item).string; + + if (i != 0) { + size += sepLen; + buf.append(sep); + } + size += itemString.length(); + if (size > Integer.MAX_VALUE) { + throw Py.OverflowError("join() result is too long for a Python string"); + } + buf.append(itemString); + } + return new PyUnicode(buf.toString()); + } + public boolean startswith(PyObject prefix) { return str_startswith(prefix, 0, null); } @@ -2826,11 +2893,11 @@ fill = ' '; switch(c) { case 's': - case 'r': - fill = ' '; if (arg instanceof PyUnicode) { needUnicode = true; } + case 'r': + fill = ' '; if (c == 's') if (needUnicode) string = arg.__unicode__().toString(); Modified: trunk/jython/src/org/python/core/PyUnicode.java =================================================================== --- trunk/jython/src/org/python/core/PyUnicode.java 2008-12-06 05:18:08 UTC (rev 5711) +++ trunk/jython/src/org/python/core/PyUnicode.java 2008-12-06 06:52:28 UTC (rev 5712) @@ -455,9 +455,21 @@ return str___rmul__(o); } + public PyObject __add__(PyObject other) { + return unicode___add__(other); + } + @ExposedMethod(type = MethodType.BINARY) - final PyObject unicode___add__(PyObject generic_other) { - return str___add__(generic_other); + final PyObject unicode___add__(PyObject other) { + PyUnicode otherUnicode; + if (other instanceof PyUnicode) { + otherUnicode = (PyUnicode)other; + } else if (other instanceof PyString) { + otherUnicode = (PyUnicode)((PyString)other).decode(); + } else { + return null; + } + return new PyUnicode(string.concat(otherUnicode.string)); } @ExposedMethod @@ -1098,9 +1110,13 @@ } // end utf-16 aware + public PyString join(PyObject seq) { + return unicode_join(seq); + } + @ExposedMethod - final PyString unicode_join(PyObject seq) { - return str_join(seq); + final PyUnicode unicode_join(PyObject seq) { + return unicodeJoin(seq); } @ExposedMethod(defaults = {"0", "null"}) This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <pj...@us...> - 2008-12-09 21:56:55
|
Revision: 5724 http://jython.svn.sourceforge.net/jython/?rev=5724&view=rev Author: pjenvey Date: 2008-12-09 21:56:51 +0000 (Tue, 09 Dec 2008) Log Message: ----------- o allow overriding of ExceptionHandler's inline finally block o fix the with statement's normal finally/exit block so it also happens for non local gotos (e.g. return, continue) o modify test_with instead of adding test_with_jy to test for this case -- the lack of these tests is really a test bug IMO fixes #1194 pointed out by Terrence Cole Modified Paths: -------------- trunk/jython/Lib/test/test_with.py trunk/jython/src/org/python/compiler/CodeCompiler.java Modified: trunk/jython/Lib/test/test_with.py =================================================================== --- trunk/jython/Lib/test/test_with.py 2008-12-09 08:45:33 UTC (rev 5723) +++ trunk/jython/Lib/test/test_with.py 2008-12-09 21:56:51 UTC (rev 5724) @@ -506,59 +506,70 @@ self.assertRaises(GeneratorExit, shouldThrow) -class NonLocalFlowControlTestCase(unittest.TestCase): +class NonLocalFlowControlTestCase(unittest.TestCase, + ContextmanagerAssertionMixin): def testWithBreak(self): + mock = mock_contextmanager_generator() counter = 0 while True: counter += 1 - with mock_contextmanager_generator(): + with mock: counter += 10 break counter += 100 # Not reached self.assertEqual(counter, 11) + self.assertAfterWithManagerInvariantsNoError(mock) def testWithContinue(self): + mock = mock_contextmanager_generator() counter = 0 while True: counter += 1 if counter > 2: break - with mock_contextmanager_generator(): + with mock: counter += 10 continue counter += 100 # Not reached self.assertEqual(counter, 12) + self.assertAfterWithManagerInvariantsNoError(mock) def testWithReturn(self): + mock = mock_contextmanager_generator() def foo(): counter = 0 while True: counter += 1 - with mock_contextmanager_generator(): + with mock: counter += 10 return counter counter += 100 # Not reached self.assertEqual(foo(), 11) + self.assertAfterWithManagerInvariantsNoError(mock) def testWithYield(self): + mock = mock_contextmanager_generator() def gen(): - with mock_contextmanager_generator(): + with mock: yield 12 yield 13 x = list(gen()) self.assertEqual(x, [12, 13]) + self.assertAfterWithManagerInvariantsNoError(mock) def testWithRaise(self): + mock = mock_contextmanager_generator() counter = 0 try: counter += 1 - with mock_contextmanager_generator(): + with mock: counter += 10 raise RuntimeError counter += 100 # Not reached except RuntimeError: self.assertEqual(counter, 11) + self.assertAfterWithManagerInvariants(mock, sys.exc_info()) else: self.fail("Didn't raise RuntimeError") Modified: trunk/jython/src/org/python/compiler/CodeCompiler.java =================================================================== --- trunk/jython/src/org/python/compiler/CodeCompiler.java 2008-12-09 08:45:33 UTC (rev 5723) +++ trunk/jython/src/org/python/compiler/CodeCompiler.java 2008-12-09 21:56:51 UTC (rev 5724) @@ -1225,7 +1225,7 @@ // also exiting the try: portion of this particular finally } if (handler.isFinallyHandler()) { - suite(((TryFinally) handler.node).getInternalFinalbody()); + handler.finalBody(this); } } @@ -2245,15 +2245,14 @@ throw new ParseException("'with' will become a reserved keyword in Python 2.6", node); } - Label label_body_start = new Label(); - Label label_body_end = new Label(); - Label label_catch = new Label(); - Label label_finally = new Label(); - Label label_end = new Label(); + final Label label_body_start = new Label(); + final Label label_body_end = new Label(); + final Label label_catch = new Label(); + final Label label_end = new Label(); - Method getattr = Method.getMethod("org.python.core.PyObject __getattr__ (String)"); - Method call = Method.getMethod("org.python.core.PyObject __call__ ()"); - Method call3 = Method.getMethod("org.python.core.PyObject __call__ (org.python.core.PyObject,org.python.core.PyObject,org.python.core.PyObject)"); + 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)"); // mgr = (EXPR) visit(node.getInternalContext_expr()); @@ -2261,7 +2260,7 @@ code.ldc("__exit__"); code.invokevirtual(Type.getType(PyObject.class).getInternalName(), getattr.getName(), getattr.getDescriptor()); - int __exit__ = code.getLocal("org/python/core/PyObject"); + final int __exit__ = code.getLocal("org/python/core/PyObject"); code.astore(__exit__); // value = mgr.__enter__() @@ -2272,11 +2271,34 @@ code.astore(value_tmp); // exc = True # not necessary, since we don't exec finally if exception + + // FINALLY (preparation) + // ordinarily with a finally, we need to duplicate the code. that's not the case + // here + // # The normal and non-local-goto cases are handled here + // if exc: # implicit + // exit(None, None, None) + ExceptionHandler normalExit = new ExceptionHandler() { + @Override + public boolean isFinallyHandler() { return true; } + + @Override + public void finalBody(CodeCompiler compiler) throws Exception { + compiler.code.aload(__exit__); + compiler.getNone(); + compiler.code.dup(); + compiler.code.dup(); + compiler.code.invokevirtual(Type.getType(PyObject.class).getInternalName(), + call3.getName(), call3.getDescriptor()); + compiler.code.pop(); + } + }; + exceptionHandlers.push(normalExit); + // try-catch block here - //code.trycatch(label_body_start, label_body_end, label_catch, "java/lang/Throwable"); ExceptionHandler handler = new ExceptionHandler(); + exceptionHandlers.push(handler); handler.exceptionStarts.addElement(label_body_start); - exceptionHandlers.push(handler); // VAR = value # Only if "as VAR" is present code.label(label_body_start); @@ -2285,13 +2307,22 @@ } code.freeLocal(value_tmp); - // BLOCK - suite(node.getInternalBody()); + // BLOCK + FINALLY if non-local-goto + Object blockResult = suite(node.getInternalBody()); + normalExit.bodyDone = true; exceptionHandlers.pop(); - code.goto_(label_finally); + exceptionHandlers.pop(); code.label(label_body_end); handler.exceptionEnds.addElement(label_body_end); + // FINALLY if *not* non-local-goto + if (blockResult == NoExit) { + // BLOCK would have generated FINALLY for us if it exited (due to a break, + // continue or return) + inlineFinally(normalExit); + code.goto_(label_end); + } + // CATCH code.label(label_catch); @@ -2322,29 +2353,12 @@ code.invokestatic("org/python/core/Py", "makeException", "()Lorg/python/core/PyException;"); code.checkcast("java/lang/Throwable"); code.athrow(); - code.freeLocal(ts_tmp); - - handler.addExceptionHandlers(label_catch); - // FINALLY - // ordinarily with a finally, we need to duplicate the code. that's not the case here - // # The normal and non-local-goto cases are handled here - // if exc: # implicit - // exit(None, None, None) - - code.label(label_finally); - - code.aload(__exit__); - getNone(); - code.dup(); - code.dup(); - code.invokevirtual(Type.getType(PyObject.class).getInternalName(), call3.getName(), call3.getDescriptor()); - code.pop(); - code.label(label_end); code.freeLocal(__exit__); + handler.addExceptionHandlers(label_catch); return null; } @@ -2405,5 +2419,11 @@ } } } + + public void finalBody(CodeCompiler compiler) throws Exception { + if (node instanceof TryFinally) { + suite(((TryFinally)node).getInternalFinalbody()); + } + } } } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <pj...@us...> - 2008-12-10 00:07:25
|
Revision: 5726 http://jython.svn.sourceforge.net/jython/?rev=5726&view=rev Author: pjenvey Date: 2008-12-10 00:07:22 +0000 (Wed, 10 Dec 2008) Log Message: ----------- match CPython's dir() more closely fixes #1196 pointed out by doublep Modified Paths: -------------- trunk/jython/Lib/test/test_builtin_jy.py trunk/jython/src/org/python/core/PyClass.java trunk/jython/src/org/python/core/PyObject.java trunk/jython/src/org/python/core/PyType.java Modified: trunk/jython/Lib/test/test_builtin_jy.py =================================================================== --- trunk/jython/Lib/test/test_builtin_jy.py 2008-12-09 22:25:56 UTC (rev 5725) +++ trunk/jython/Lib/test/test_builtin_jy.py 2008-12-10 00:07:22 UTC (rev 5726) @@ -16,6 +16,13 @@ raise TypeError() self.assert_(not hasattr(Foo(), 'bar')) + def test_dir(self): + # for http://bugs.jython.org/issue1063 + class Foo(object): + def __getattribute__(self, name): + return name + self.assertEqual(dir(Foo()), []) + class LoopTest(unittest.TestCase): def test_break(self): Modified: trunk/jython/src/org/python/core/PyClass.java =================================================================== --- trunk/jython/src/org/python/core/PyClass.java 2008-12-09 22:25:56 UTC (rev 5725) +++ trunk/jython/src/org/python/core/PyClass.java 2008-12-10 00:07:22 UTC (rev 5726) @@ -281,11 +281,7 @@ } public void __rawdir__(PyDictionary accum) { - addKeys(accum, "__dict__"); - PyObject[] bases = __bases__.getArray(); - for (PyObject base : bases) { - base.__rawdir__(accum); - } + mergeClassDict(accum, this); } /** Modified: trunk/jython/src/org/python/core/PyObject.java =================================================================== --- trunk/jython/src/org/python/core/PyObject.java 2008-12-09 22:25:56 UTC (rev 5725) +++ trunk/jython/src/org/python/core/PyObject.java 2008-12-10 00:07:22 UTC (rev 5726) @@ -903,24 +903,54 @@ return __findattr__(name); } - protected void addKeys(PyDictionary accum, String attr) { + protected void mergeListAttr(PyDictionary accum, String attr) { PyObject obj = __findattr__(attr); - if (obj == null) + if (obj == null) { return; + } if (obj instanceof PyList) { for (PyObject name : obj.asIterable()) { accum.__setitem__(name, Py.None); } - } else { + } + } + + protected void mergeDictAttr(PyDictionary accum, String attr) { + PyObject obj = __findattr__(attr); + if (obj == null) { + return; + } + if (obj instanceof PyDictionary || obj instanceof PyStringMap + || obj instanceof PyDictProxy) { accum.update(obj); } } + protected void mergeClassDict(PyDictionary accum, PyObject aClass) { + // Merge in the type's dict (if any) + aClass.mergeDictAttr(accum, "__dict__"); + + // Recursively merge in the base types' (if any) dicts + PyObject bases = aClass.__findattr__("__bases__"); + if (bases == null) { + return; + } + // We have no guarantee that bases is a real tuple + int len = bases.__len__(); + for (int i = 0; i < len; i++) { + mergeClassDict(accum, bases.__getitem__(i)); + } + } + protected void __rawdir__(PyDictionary accum) { - addKeys(accum, "__dict__"); - addKeys(accum, "__methods__"); - addKeys(accum, "__members__"); - fastGetClass().__rawdir__(accum); + mergeDictAttr(accum, "__dict__"); + mergeListAttr(accum, "__methods__"); + mergeListAttr(accum, "__members__"); + // Class dict is a slower, more manual merge to match CPython + PyObject itsClass = __findattr__("__class__"); + if (itsClass != null) { + mergeClassDict(accum, itsClass); + } } /** Modified: trunk/jython/src/org/python/core/PyType.java =================================================================== --- trunk/jython/src/org/python/core/PyType.java 2008-12-09 22:25:56 UTC (rev 5725) +++ trunk/jython/src/org/python/core/PyType.java 2008-12-10 00:07:22 UTC (rev 5726) @@ -1129,13 +1129,7 @@ } protected void __rawdir__(PyDictionary accum) { - PyObject[] mro = this.mro; - if (mro == null) { - return; - } - for (PyObject element : mro) { - element.addKeys(accum, "__dict__"); - } + mergeClassDict(accum, this); } public String fastGetName() { This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <pj...@us...> - 2008-12-11 05:20:59
|
Revision: 5735 http://jython.svn.sourceforge.net/jython/?rev=5735&view=rev Author: pjenvey Date: 2008-12-11 05:20:55 +0000 (Thu, 11 Dec 2008) Log Message: ----------- o fix imp.find_module not finding builtin modules o add __builtin__ and sys to sys.builtin_module_names and another hack for re-importing __builtin__ like we have for sys fixes #1161 thanks Sven Reimers Modified Paths: -------------- trunk/jython/Lib/test/test_import_jy.py trunk/jython/src/org/python/core/PySystemState.java trunk/jython/src/org/python/core/imp.java trunk/jython/src/org/python/modules/imp.java Modified: trunk/jython/Lib/test/test_import_jy.py =================================================================== --- trunk/jython/Lib/test/test_import_jy.py 2008-12-11 00:39:49 UTC (rev 5734) +++ trunk/jython/Lib/test/test_import_jy.py 2008-12-11 05:20:55 UTC (rev 5735) @@ -90,6 +90,7 @@ self.assertEquals(bytecode, read(init_compiled), 'bytecode was recompiled') + class OverrideBuiltinsImportTestCase(unittest.TestCase): def test_override(self): tests = [ @@ -127,9 +128,19 @@ finally: __builtin__.__import__ = oldimp +class ImpTestCase(unittest.TestCase): + + def test_imp_find_module_builtins(self): + self.assertEqual(imp.find_module('sys'), (None, 'sys', ('', '', 6))) + self.assertEqual(imp.find_module('__builtin__'), + (None, '__builtin__', ('', '', 6))) + self.assertEqual(imp.find_module('imp'), (None, 'imp', ('', '', 6))) + + def test_main(): - test_classes = [MislabeledImportTestCase, OverrideBuiltinsImportTestCase] - test_support.run_unittest(*test_classes) + test_support.run_unittest(MislabeledImportTestCase, + OverrideBuiltinsImportTestCase, + ImpTestCase) if __name__ == '__main__': test_main() Modified: trunk/jython/src/org/python/core/PySystemState.java =================================================================== --- trunk/jython/src/org/python/core/PySystemState.java 2008-12-11 00:39:49 UTC (rev 5734) +++ trunk/jython/src/org/python/core/PySystemState.java 2008-12-11 05:20:55 UTC (rev 5735) @@ -709,6 +709,10 @@ private static void initBuiltins(Properties props) { builtinNames = new Hashtable(); + // add the oddball builtins that are specially handled + builtinNames.put("__builtin__", ""); + builtinNames.put("sys", ""); + // add builtins specified in the Setup.java file for (int i=0; i < Setup.builtinModules.length; i++) addBuiltin(Setup.builtinModules[i]); @@ -727,7 +731,7 @@ builtin_module_names = new PyTuple(built_mod); } - static String getBuiltin(String name) { + public static String getBuiltin(String name) { return (String)builtinNames.get(name); } Modified: trunk/jython/src/org/python/core/imp.java =================================================================== --- trunk/jython/src/org/python/core/imp.java 2008-12-11 00:39:49 UTC (rev 5734) +++ trunk/jython/src/org/python/core/imp.java 2008-12-11 05:20:55 UTC (rev 5735) @@ -389,10 +389,13 @@ private static PyObject loadBuiltin(String name) { if (name == "sys") { - Py.writeComment(IMPORT_LOG, "'" + name + "' as sys in " - + "builtin modules"); + Py.writeComment(IMPORT_LOG, "'" + name + "' as sys in builtin modules"); return Py.java2py(Py.getSystemState()); } + if (name == "__builtin__") { + Py.writeComment(IMPORT_LOG, "'" + name + "' as __builtin__ in builtin modules"); + return new PyModule("__builtin__", PySystemState.builtins); + } String mod = PySystemState.getBuiltin(name); if (mod != null) { Class c = Py.findClassEx(mod, "builtin modules"); Modified: trunk/jython/src/org/python/modules/imp.java =================================================================== --- trunk/jython/src/org/python/modules/imp.java 2008-12-11 00:39:49 UTC (rev 5734) +++ trunk/jython/src/org/python/modules/imp.java 2008-12-11 05:20:55 UTC (rev 5735) @@ -129,10 +129,6 @@ return null; } - public static PyObject find_module(String name) { - return find_module(name, null); - } - public static PyObject load_source(String modname, String filename) { return load_source(modname, filename, null); } @@ -158,11 +154,20 @@ return mod; } + public static PyObject find_module(String name) { + return find_module(name, Py.None); + } + public static PyObject find_module(String name, PyObject path) { - if (path == null || path == Py.None) { + if (path == Py.None && PySystemState.getBuiltin(name) != null) { + return new PyTuple(Py.None, Py.newString(name), + new PyTuple(Py.EmptyString, Py.EmptyString, + Py.newInteger(C_BUILTIN))); + } + + if (path == Py.None) { path = Py.getSystemState().path; } - for (PyObject p : path.asIterable()) { ModuleInfo mi = findFromSource(name, p.toString(), false, true); if(mi == null) { This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <cg...@us...> - 2008-12-12 03:57:45
|
Revision: 5739 http://jython.svn.sourceforge.net/jython/?rev=5739&view=rev Author: cgroves Date: 2008-12-12 03:57:33 +0000 (Fri, 12 Dec 2008) Log Message: ----------- Merged revisions 5564,5566-5567,5605,5607,5622-5623,5625,5631-5632,5650-5654,5656-5659,5662-5663,5666-5669,5673-5676,5688-5689,5692-5694,5698-5701,5705,5707-5711,5727-5729 via svnmerge from https://jython.svn.sourceforge.net/svnroot/jython/branches/newstyle-java-types ........ r5564 | cgroves | 2008-11-09 19:31:53 -0800 (Sun, 09 Nov 2008) | 1 line Checkpoint of replacing PyJavaClass with PyJavaType. Works well enough that ProxyMaker creates PyObjects instead of PyJavaInstances and the interpreter starts up, but that's about it ........ r5566 | cgroves | 2008-11-09 19:56:44 -0800 (Sun, 09 Nov 2008) | 1 line Fill in Java inner classes ........ r5567 | cgroves | 2008-11-09 21:15:10 -0800 (Sun, 09 Nov 2008) | 1 line Implement the collection proxies as methods on PyJavaTypes ........ r5605 | cgroves | 2008-11-22 16:46:06 -0800 (Sat, 22 Nov 2008) | 1 line Use PyJavaType to initialize array, not PyJavaClass ........ r5607 | cgroves | 2008-11-22 18:36:05 -0800 (Sat, 22 Nov 2008) | 4 lines Rip out PyJavaClass and friends. This isn't even close to passing regrtest, but it runs well enough to start the interpreter and get through the first few. ........ r5622 | cgroves | 2008-11-23 15:12:46 -0800 (Sun, 23 Nov 2008) | 8 lines PyInstance ignored __tojava__ methods on its classes, so Java classes in the old world with a __tojava__ would be ignored as well. This differed from most other dunder methods, so the new PyJavaType exposes __tojava__ through PyObjectDerived. IOBase was using __tojava__ to mean something different than what PyObject was doing with it, so change the name to keep regular jython object conversion from picking up on it. ........ r5623 | cgroves | 2008-11-23 15:46:11 -0800 (Sun, 23 Nov 2008) | 1 line Create the java proxy object after __init__ runs if it wasn't created by __init__ ........ r5625 | cgroves | 2008-11-23 17:57:05 -0800 (Sun, 23 Nov 2008) | 1 line Don't strip the package out of wrapped Java types ........ r5631 | cgroves | 2008-11-23 21:37:21 -0800 (Sun, 23 Nov 2008) | 1 line Don't hork when exposing fields on an interface as it won't have a base class ........ r5632 | cgroves | 2008-11-23 21:52:36 -0800 (Sun, 23 Nov 2008) | 5 lines Reinstate the code from PyReflectedConstructor that redirectes to the proxy constructor whenever a Python subclass of a Java class attempts to call its Java-superclass constructor. PyJavaType can finally handle it. ........ r5650 | cgroves | 2008-11-28 00:12:30 -0800 (Fri, 28 Nov 2008) | 1 line Check for abstract classes and interfaces before attempting to auto-create a proxy ........ r5651 | cgroves | 2008-11-28 00:56:38 -0800 (Fri, 28 Nov 2008) | 8 lines Add an EQ_PROXY to PyJavaType to pass equals through to wrapped Java instances like PyJavaInstance did. Make PyBuiltinMethod Cloneable and use clone to implement a default bind implementation. This eliminates 75% of the crud that came with creating a builtin method in Java. ........ r5652 | cgroves | 2008-11-28 00:59:49 -0800 (Fri, 28 Nov 2008) | 1 line Whoops, didn't mean to remove Finn's copyright ........ r5653 | cgroves | 2008-11-28 01:13:19 -0800 (Fri, 28 Nov 2008) | 1 line PyObject needs to handle primitive conversion in the new world ........ r5654 | cgroves | 2008-11-28 02:06:54 -0800 (Fri, 28 Nov 2008) | 4 lines Expose static fields through PyBeanProperty if they share a name with the property. Instance fields supercede the propery. ........ r5656 | cgroves | 2008-11-28 13:29:14 -0800 (Fri, 28 Nov 2008) | 1 line Simplify PyBeanProperty construction ........ r5657 | cgroves | 2008-11-28 13:53:04 -0800 (Fri, 28 Nov 2008) | 1 line More cleanup ........ r5658 | cgroves | 2008-11-28 16:17:40 -0800 (Fri, 28 Nov 2008) | 12 lines Only attempt proxyInitting if __init__ has been found and worked, and only actually init instances of PyProxy. Add an __init__ for all Java classes, even interfaces and abstract classes. Handle throwing type errors for uninstantiable classes in PyReflectedConstructor. Pass _is and _isnot through to the javaproxy == if javaproxy is around. This assumes a constant mapping between a given Java type and the PyType wrapping it, but I think that's safe. ........ r5659 | cgroves | 2008-11-28 16:48:32 -0800 (Fri, 28 Nov 2008) | 9 lines Assign the type on PyBeanProperty to the type returned by its getter and only use a setter if its parameter's type matches that. Push accesses to PyObject.javaProxy that query information from the proxy through getJavaProxy. This calls proxyInit if the proxy doesn't already exist which keeps things from blowing up if something accesses the javaProxy in an __init__. ........ r5662 | cgroves | 2008-11-29 16:40:22 -0800 (Sat, 29 Nov 2008) | 6 lines Make java.lang.Object and Java interfaces descend from the Python object type. This changed the class initialization order, so put static constants in PyJavaType in a static method so they're actually initialized at time of use. ........ r5663 | cgroves | 2008-11-29 18:30:42 -0800 (Sat, 29 Nov 2008) | 1 line Hook bean events up in PyJavaType. All of test_java_integration passes again. ........ r5666 | cgroves | 2008-11-30 17:00:37 -0800 (Sun, 30 Nov 2008) | 7 lines Replace fillDict with init which encapsulates all the differences between PyType and PyJavaType initialization. Have bootstrap types use init as well to remove the duplication of type builder initialization. Include interfaces and superclasses in the mro of wrapped Java types. ........ r5667 | cgroves | 2008-11-30 17:06:33 -0800 (Sun, 30 Nov 2008) | 1 line PyReflectedFunction no longer exposes a String constructor ........ r5668 | cgroves | 2008-11-30 17:08:51 -0800 (Sun, 30 Nov 2008) | 1 line Go ahead and take multiple methods in PyReflectedFunction's constructor ........ r5669 | cgroves | 2008-11-30 17:14:21 -0800 (Sun, 30 Nov 2008) | 1 line Reset a PyJavaType's state when reload is called on it. This was just ignored on PyJavaClasses, so this is a little step up ........ r5673 | cgroves | 2008-12-01 21:23:26 -0800 (Mon, 01 Dec 2008) | 5 lines Changing the items in the dicts of loaded classes seemed to be confusing the exceptions module at least, so let's leave reloading Java classes a no-op until a later date. ........ r5674 | cgroves | 2008-12-01 23:46:14 -0800 (Mon, 01 Dec 2008) | 1 line Better error message for a bad version string, use the actual banner for checking ........ r5675 | cgroves | 2008-12-01 23:47:23 -0800 (Mon, 01 Dec 2008) | 3 lines Hook up container methods for Map separately as it isn't actually a Collection. ........ r5676 | cgroves | 2008-12-02 02:54:26 -0800 (Tue, 02 Dec 2008) | 4 lines Patch #1148 from Geoffrey French. Adds slice and negative index support to get, set and del methods on wrapped instances of java.util.List. ........ r5688 | cgroves | 2008-12-03 17:10:43 -0800 (Wed, 03 Dec 2008) | 8 lines Switch to using getJavaProxy() != null from getType() instanceof PyJavaType to detect if a PyObject is wrapping a Java object or a subclass of a Java object. This keeps PyObject subclasses from appearing to be proxy types. The old way was breaking copy as instances of classic classes - which have a type of PyJavaType by virtue of PyClass being a non-type subclass of PyObject - didn't have a Java proxy and were getting a different id with each call. ........ r5689 | cgroves | 2008-12-03 17:27:28 -0800 (Wed, 03 Dec 2008) | 1 line Only add inner classes to the dict of a Java type if there isn't already something with that name. Fixes test_cpickle ........ r5692 | cgroves | 2008-12-03 18:30:34 -0800 (Wed, 03 Dec 2008) | 7 lines Leave ExposedType annotations on processed types so they'll be visible at runtime. Use that to detect exposed inner classes in classes being loaded. Inner classes being loaded won't have set their builder in PyType yet, so they need to be added to BOOTSTRAP_TYPES so they're created as PyType instead of PyJavaType. ........ r5693 | cgroves | 2008-12-04 15:52:01 -0800 (Thu, 04 Dec 2008) | 1 line Expose __iter__ on Iterator in addition to Iterable and Map ........ r5694 | cgroves | 2008-12-04 16:26:54 -0800 (Thu, 04 Dec 2008) | 1 line Expose __hash__ on Object. I'm amazed at the number of things that passed without this ........ r5698 | cgroves | 2008-12-04 20:06:23 -0800 (Thu, 04 Dec 2008) | 1 line Get test_jy_internals passing again ........ r5699 | cgroves | 2008-12-05 01:06:12 -0800 (Fri, 05 Dec 2008) | 1 line Don't worry about the count, just assert the things that should and shouldn't be visible ........ r5700 | cgroves | 2008-12-05 03:21:55 -0800 (Fri, 05 Dec 2008) | 5 lines Make methods from superclasses and superinterfaces of private, protected or package protected classes call through their parent versions. Fixes blowups with a package protected implementation of attributes in sax. ........ r5701 | cgroves | 2008-12-05 03:38:02 -0800 (Fri, 05 Dec 2008) | 1 line Avoid non-public interface methods similarly to non-public class methods ........ r5705 | cgroves | 2008-12-05 18:35:31 -0800 (Fri, 05 Dec 2008) | 1 line Needs to be serializable for PySequence to be serializable ........ r5707 | cgroves | 2008-12-05 19:01:16 -0800 (Fri, 05 Dec 2008) | 1 line Tidying ........ r5708 | cgroves | 2008-12-05 19:23:28 -0800 (Fri, 05 Dec 2008) | 1 line Pull the proxy class directly out of the type. Fixes test_jser2 ........ r5709 | cgroves | 2008-12-05 20:19:46 -0800 (Fri, 05 Dec 2008) | 5 lines Add a target to run a single junit test from the tests directory. ant -Dtest=InterpreterTest singlejavatest will run just org.python.util.InterpreterTest and report to the console. ........ r5710 | cgroves | 2008-12-05 20:23:45 -0800 (Fri, 05 Dec 2008) | 6 lines Fix deserializing Jython objects while not in Python code. __builtin__.__import__ was changed to bail if Py.getFrame was null, but it can be called from Java code as in PyObjectInputStream, so it should just use PySystemState.builtins if it doesn't have a set of builtins from the frame. ........ r5711 | cgroves | 2008-12-05 21:18:08 -0800 (Fri, 05 Dec 2008) | 1 line Identify Java exceptions as exceptions ........ r5727 | cgroves | 2008-12-09 22:30:28 -0800 (Tue, 09 Dec 2008) | 1 line exceptions needs to extend PyObject to keep from being exposed as a descendent of Object ........ r5728 | cgroves | 2008-12-09 22:47:19 -0800 (Tue, 09 Dec 2008) | 4 lines Like exceptions, operator needs to extend PyObject to keep from picking up Object methods. Fixes test_richcmp. ........ r5729 | cgroves | 2008-12-09 23:09:49 -0800 (Tue, 09 Dec 2008) | 4 lines Allow setattr and delattr to access the dicts of PyJavaTypes. Fixes test_strptime as Time was expected to allow modification to its dict. ........ Modified Paths: -------------- trunk/jython/Lib/test/jser2_classes.py trunk/jython/Lib/test/test_array_jy.py trunk/jython/Lib/test/test_cmd_line.py trunk/jython/Lib/test/test_java_integration.py trunk/jython/Lib/test/test_java_visibility.py trunk/jython/Lib/test/test_joverload.py trunk/jython/Lib/test/test_jser2.py trunk/jython/Lib/test/test_jy_internals.py trunk/jython/build.xml trunk/jython/src/org/python/antlr/adapter/AliasAdapter.java trunk/jython/src/org/python/antlr/adapter/CmpopAdapter.java trunk/jython/src/org/python/antlr/adapter/ComprehensionAdapter.java trunk/jython/src/org/python/antlr/adapter/ExcepthandlerAdapter.java trunk/jython/src/org/python/antlr/adapter/ExprAdapter.java trunk/jython/src/org/python/antlr/adapter/IdentifierAdapter.java trunk/jython/src/org/python/antlr/adapter/KeywordAdapter.java trunk/jython/src/org/python/antlr/adapter/SliceAdapter.java trunk/jython/src/org/python/antlr/adapter/StmtAdapter.java trunk/jython/src/org/python/compiler/ProxyMaker.java trunk/jython/src/org/python/core/AstList.java trunk/jython/src/org/python/core/IdImpl.java trunk/jython/src/org/python/core/Options.java trunk/jython/src/org/python/core/Py.java trunk/jython/src/org/python/core/PyArray.java trunk/jython/src/org/python/core/PyArrayDerived.java trunk/jython/src/org/python/core/PyBaseExceptionDerived.java trunk/jython/src/org/python/core/PyBeanEvent.java trunk/jython/src/org/python/core/PyBeanEventProperty.java trunk/jython/src/org/python/core/PyBeanProperty.java trunk/jython/src/org/python/core/PyBooleanDerived.java trunk/jython/src/org/python/core/PyBuiltinCallable.java trunk/jython/src/org/python/core/PyBuiltinMethod.java trunk/jython/src/org/python/core/PyClass.java trunk/jython/src/org/python/core/PyClassMethodDerived.java trunk/jython/src/org/python/core/PyComplexDerived.java trunk/jython/src/org/python/core/PyCompoundCallable.java trunk/jython/src/org/python/core/PyDictionaryDerived.java trunk/jython/src/org/python/core/PyEnumerateDerived.java trunk/jython/src/org/python/core/PyException.java trunk/jython/src/org/python/core/PyFile.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/PyInstance.java trunk/jython/src/org/python/core/PyIntegerDerived.java trunk/jython/src/org/python/core/PyJavaPackage.java trunk/jython/src/org/python/core/PyJavaType.java trunk/jython/src/org/python/core/PyList.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/PyObject.java trunk/jython/src/org/python/core/PyObjectDerived.java trunk/jython/src/org/python/core/PyPropertyDerived.java trunk/jython/src/org/python/core/PyProxy.java trunk/jython/src/org/python/core/PyReflectedConstructor.java trunk/jython/src/org/python/core/PyReflectedFunction.java trunk/jython/src/org/python/core/PySequence.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/PyType.java trunk/jython/src/org/python/core/PyTypeDerived.java trunk/jython/src/org/python/core/PyUnicodeDerived.java trunk/jython/src/org/python/core/StdoutWrapper.java trunk/jython/src/org/python/core/ThreadState.java trunk/jython/src/org/python/core/__builtin__.java trunk/jython/src/org/python/core/adapter/ClassicPyObjectAdapter.java trunk/jython/src/org/python/core/adapter/PyObjectAdapter.java trunk/jython/src/org/python/core/exceptions.java trunk/jython/src/org/python/core/imp.java trunk/jython/src/org/python/core/io/BufferedIOMixin.java trunk/jython/src/org/python/core/io/FileIO.java trunk/jython/src/org/python/core/io/IOBase.java trunk/jython/src/org/python/core/io/StreamIO.java trunk/jython/src/org/python/core/io/TextIOBase.java trunk/jython/src/org/python/expose/generate/ExposedTypeProcessor.java trunk/jython/src/org/python/expose/generate/ExposedTypeVisitor.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/_hashlib.java trunk/jython/src/org/python/modules/_weakref/ReferenceTypeDerived.java trunk/jython/src/org/python/modules/cPickle.java trunk/jython/src/org/python/modules/cStringIO.java trunk/jython/src/org/python/modules/math.java trunk/jython/src/org/python/modules/operator.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 trunk/jython/src/org/python/util/PythonObjectInputStream.java trunk/jython/src/templates/object.derived trunk/jython/tests/java/org/python/expose/generate/ExposedTypeVisitorTest.java trunk/jython/tests/java/org/python/util/InterpreterTest.java Added Paths: ----------- trunk/jython/Lib/test/test_java_list_delegate.py trunk/jython/src/org/python/core/SequenceIndexDelegate.java trunk/jython/tests/java/org/python/tests/InterfaceCombination.java trunk/jython/tests/java/org/python/tests/SerializationTest.java Removed Paths: ------------- trunk/jython/Lib/jreload.py trunk/jython/Lib/jxxload_help/ trunk/jython/Lib/test/test_jreload.py trunk/jython/src/org/python/core/AutoInternalTables.java trunk/jython/src/org/python/core/CollectionIter.java trunk/jython/src/org/python/core/CollectionProxy.java trunk/jython/src/org/python/core/InternalTables.java trunk/jython/src/org/python/core/PyJavaClass.java trunk/jython/src/org/python/core/PyJavaInnerClass.java trunk/jython/src/org/python/core/PyJavaInstance.java trunk/jython/src/org/python/core/SoftIInternalTables.java trunk/jython/src/org/python/core/WeakInternalTables.java trunk/jython/src/org/python/modules/_jython.java Property Changed: ---------------- trunk/jython/ trunk/jython/Lib/test/jser2_classes.py trunk/jython/Lib/test/test_jser2.py Property changes on: trunk/jython ___________________________________________________________________ Modified: svnmerge-integrated - /branches/astwrite:1-5692 /branches/newstyle-java-types:1-5563 + /branches/astwrite:1-5692 /branches/newstyle-java-types:1-5738 Added: svn:mergeinfo + /branches/newstyle-java-types:5564-5663,5666-5729 Deleted: trunk/jython/Lib/jreload.py =================================================================== --- trunk/jython/Lib/jreload.py 2008-12-12 03:31:52 UTC (rev 5738) +++ trunk/jython/Lib/jreload.py 2008-12-12 03:57:33 UTC (rev 5739) @@ -1,119 +0,0 @@ -# java classes reload support (experimental) -# Copyright 2000 Samuele Pedroni - -# ?? could have problem with import pkg.jclass.inner (this should not be used in any case) -# ?? using import * with a load-set together with reloading can be confusing -# cannot be fixed => anyway import * is not for production code - -__version__ = "0.3" - -import sys -from org.python.core import imp,PyJavaPackage,PyJavaClass -from _jython import is_lazy as _is_lazy - -import jxxload_help - - -class _LoaderFactory(jxxload_help.JavaLoaderFactory): - def __init__(self,path): - vfs = jxxload_help.PathVFS() - for fname in path: - vfs.addVFS(fname) - self.vfs = vfs - - def makeLoader(self): - return jxxload_help.PathVFSJavaLoader(self.vfs,imp.getSyspathJavaLoader()) - -class _Unload: - - def __init__(self,ls): - self.ls = ls - self.ls_name = ls._name - self.loader = ls._mgr.loader - - def do_unload(self,pkg): - for n in pkg.__dict__.keys(): - e = pkg.__dict__[n] - if isinstance(e,PyJavaClass): - if _is_lazy(e): continue - if e.classLoader is self.loader: - del pkg.__dict__[n] - if pkg.__name__: - n = self.ls_name + '.' + pkg.__name__ + '.' +n - else: - n = self.ls_name + '.' + n - if sys.modules.has_key(n): del sys.modules[n] - - elif isinstance(e,PyJavaPackage): - self.do_unload(e) - - def __call__(self): - if self.loader: - if self.ls._mgr.checkLoader() is self.loader: - self.do_unload(self.ls._top) - self.ls._mgr.resetLoader() - loader = self.loader - jxxload_help.DiscardHelp.discard(loader,loader.interfaces) - self.loader = None - -class LoadSet: -# ?? for the moment from import * and dir do not work for LoadSet, but work for -# contained pkgs -# need java impl as PyObject - - def __init__(self,name,path): - mgr = jxxload_help.PackageManager(path,_LoaderFactory(path)) - self._name = name - self._mgr = mgr - self._top = mgr.topLevelPackage - - def __getattr__(self,name): - try: - return getattr(self._top,name) - except: - if name == 'unload': return _Unload(self) - raise - - - def __repr__(self): - return "<java load-set %s>" % self._name - -def unloadf(ls): - if not isinstance(ls,LoadSet): raise TypeError,"unloadf(): arg is not a load-set" - return _Unload(ls) - -def makeLoadSet(name,path): - if sys.modules.has_key(name): return sys.modules[name] - sys.modules[name] = ls = LoadSet(name,path) - return ls - -_reload = reload - -def _do_reload(ls_name,mgr,pkg): - pkg_name = pkg.__name__ - for n in pkg.__dict__.keys(): - e = pkg.__dict__[n] - if isinstance(e,PyJavaClass): - if _is_lazy(e): continue - del pkg.__dict__[n] - try : - c = mgr.findClass(pkg_name,n); - if c: - pkg.__dict__[n] = c - if pkg_name: - n = ls_name + '.' + pkg_name + '.' + n - else: - n = ls_name + '.' + n - if sys.modules.has_key(n): sys.modules[n] = c - except: - pass - elif isinstance(e,PyJavaPackage): - _do_reload(ls_name,mgr,e) - -def reload(ls): - if isinstance(ls,LoadSet): - ls._mgr.resetLoader() - _do_reload(ls._name,ls._mgr,ls._top) - return ls - else: - return _reload(ls) Modified: trunk/jython/Lib/test/jser2_classes.py =================================================================== (Binary files differ) Property changes on: trunk/jython/Lib/test/jser2_classes.py ___________________________________________________________________ Deleted: svn:mime-type - application/octet-stream Modified: trunk/jython/Lib/test/test_array_jy.py =================================================================== --- trunk/jython/Lib/test/test_array_jy.py 2008-12-12 03:31:52 UTC (rev 5738) +++ trunk/jython/Lib/test/test_array_jy.py 2008-12-12 03:57:33 UTC (rev 5739) @@ -12,7 +12,7 @@ def test_jarray(self): # until it is fully formally removed - # While jarray is still being phased out, just flex the initilaizers. + # While jarray is still being phased out, just flex the initializers. # The rest of the test for array will catch all the big problems. import jarray jarray.array(range(5), 'i') @@ -23,7 +23,7 @@ def test_java_object_arrays(self): jStringArr = array(String, [String("a"), String("b"), String("c")]) self.assert_( - Arrays.equals(jStringArr.typecode, str(String)), + Arrays.equals(jStringArr.typecode, 'java.lang.String'), "String array typecode of wrong type, expected %s, found %s" % (jStringArr.typecode, str(String))) self.assertEqual(zeros(String, 5), Array.newInstance(String, 5)) Modified: trunk/jython/Lib/test/test_cmd_line.py =================================================================== --- trunk/jython/Lib/test/test_cmd_line.py 2008-12-12 03:31:52 UTC (rev 5738) +++ trunk/jython/Lib/test/test_cmd_line.py 2008-12-12 03:57:33 UTC (rev 5739) @@ -45,8 +45,11 @@ self.assertTrue('usage' in self.start_python('-h')) def test_version(self): - version = 'Jython %d.%d' % sys.version_info[:2] - self.assertTrue(self.start_python('-V').startswith(version)) + from org.python.util import InteractiveConsole + expected = InteractiveConsole.getDefaultBanner() + reported = self.start_python('-V') + self.assertTrue(reported.startswith(expected), + "-V should start with '%s' but it printed '%s'" % (expected, reported)) def test_main(): test.test_support.run_unittest(CmdLineTest) Modified: trunk/jython/Lib/test/test_java_integration.py =================================================================== --- trunk/jython/Lib/test/test_java_integration.py 2008-12-12 03:31:52 UTC (rev 5738) +++ trunk/jython/Lib/test/test_java_integration.py 2008-12-12 03:57:33 UTC (rev 5739) @@ -6,7 +6,7 @@ from test import test_support from java.awt import (Dimension, Component, Rectangle, Button, Color, HeadlessException) -from java.util import Vector, Hashtable +from java.util import ArrayList, Vector, HashMap, Hashtable from java.io import FileOutputStream, FileWriter, OutputStreamWriter from java.lang import Runnable, Thread, ThreadGroup, System, Runtime, Math, Byte @@ -55,9 +55,6 @@ A() class InstantiationTest(unittest.TestCase): - def test_cant_create_abstract(self): - self.assertRaises(TypeError, Component) - def test_can_subclass_abstract(self): class A(Component): pass @@ -339,8 +336,11 @@ class ColorTest(unittest.TestCase): def test_static_fields(self): - Color.red - Color.blue + self.assertEquals(Color(255, 0, 0), Color.RED) + # The bean accessor for getRed should be active on instances, but the static field red + # should be visible on the class + self.assertEquals(255, Color.red.red) + self.assertEquals(Color(0, 0, 255), Color.blue) def test_is_operator(self): red = Color.red @@ -363,7 +363,7 @@ y = BigDecimalTest().asBigDecimal() self.assertEqual(type(x), type(y), "BigDecimal coerced") - self.assertEqual(x, y, "BigDecimal coerced") + self.assertEqual(x, y, "coerced BigDecimal not equal to directly created version") class MethodInvTest(unittest.TestCase): @@ -394,6 +394,37 @@ x = lang.String('test') self.assertRaises(TypeError, list, x) +class JavaDelegationTest(unittest.TestCase): + def test_list_delegation(self): + for c in ArrayList, Vector: + a = c() + a.add("blah") + self.assertTrue("blah" in a) + self.assertEquals(1, len(a)) + n = 0 + for i in a: + n += 1 + self.assertEquals("blah", i) + self.assertEquals(1, n) + self.assertEquals("blah", a[0]) + a[0] = "bleh" + del a[0] + self.assertEquals(0, len(a)) + + def test_map_delegation(self): + m = HashMap() + m["a"] = "b" + self.assertTrue("a" in m) + self.assertEquals("b", m["a"]) + n = 0 + for k in m: + n += 1 + self.assertEquals("a", k) + self.assertEquals(1, n) + del m["a"] + self.assertEquals(0, len(m)) + + def test_main(): test_support.run_unittest(AbstractOnSyspathTest, InstantiationTest, @@ -414,6 +445,7 @@ MethodInvTest, InterfaceTest, JavaStringTest, + JavaDelegationTest, ) if __name__ == "__main__": Copied: trunk/jython/Lib/test/test_java_list_delegate.py (from rev 5729, branches/newstyle-java-types/Lib/test/test_java_list_delegate.py) =================================================================== --- trunk/jython/Lib/test/test_java_list_delegate.py (rev 0) +++ trunk/jython/Lib/test/test_java_list_delegate.py 2008-12-12 03:57:33 UTC (rev 5739) @@ -0,0 +1,181 @@ +from java.util import ArrayList, List, Vector + +from copy import copy + +import unittest +import test.test_support + +class CollectionProxyTest(unittest.TestCase): + def _perform_op(self, value, op_func): + """ + Perform an operation + + value - the value to operate on + op_func - the function that applies the operation to value + + Returns: + the result of calling op_func, OR the exception that was raised in op_func + """ + try: + return op_func(value) + except Exception, e: + return type(e) + + def check_list(self, control, results, initial): + for result in results: + try: + len(result) + except: + print result + self.assertEquals(len(control), len(result), "%s is wrong for %s" % (type(result), initial)) + for pvalue, jvalue in zip(control, result): + self.assertEquals(pvalue, jvalue) + + def _list_op_test(self, initial_value, op_func, check_value): + """ + Tests a list operation + + Ensures that performing an operation on: + - a python list + - a java.util.List instance + + givens the same result in both cases + """ + lists = [list(initial_value), ArrayList(initial_value), Vector(initial_value)] + + results = [self._perform_op(l, op_func) for l in lists] + self.check_list(lists[0], lists[1:], initial_value) + if check_value or not isinstance(results[0], list): + for r in results[1:]: + self.assertEquals(results[0], r) + else: + self.check_list(results[0], results[1:], initial_value) + + def test_get_integer(self): + initial_value = range(0, 5) + + for i in xrange(-7, 7): + self._list_op_test(initial_value, lambda xs: xs[i], True) + + def test_set_integer(self): + initial_value = range(0, 5) + + def make_op_func(index): + def _f(xs): + xs[index] = 100 + return _f + + for i in xrange(-7, 7): + self._list_op_test(initial_value, make_op_func(i), True) + + def test_set_slice(self): + initial_value = range(0, 10) + + def make_op_func(i, j, k, v): + def _f(xs): + xs[i:j:k] = v + return _f + + for i in xrange(-12, 12): + for j in xrange(-12, 12): + for k in xrange(-12, 12): + self._list_op_test(initial_value, make_op_func(i, j, k, []), True) + self._list_op_test(initial_value, make_op_func(i, j, k, range(0,2)), True) + self._list_op_test(initial_value, make_op_func(i, j, k, range(0,4)), True) + self._list_op_test(initial_value, make_op_func(i, j, k, xrange(0,2)), True) + + def test_del_integer(self): + initial_value = range(0,5) + + def make_op_func(index): + def _f(xs): + del xs[index] + return _f + + for i in xrange(-7, 7): + self._list_op_test(initial_value, make_op_func(i), True) + + def test_del_slice(self): + initial_value = range(0,10) + + def make_op_func(i, j, k): + def _f(xs): + del xs[i:j:k] + return _f + + for i in xrange(-12, 12): + for j in xrange(-12, 12): + for k in xrange(-12, 12): + self._list_op_test(initial_value, make_op_func(i, j, k), True) + + def test_len(self): + jlist = ArrayList() + jlist.addAll(range(0, 10)) + + self.assert_(len(jlist) == 10) + + def test_iter(self): + jlist = ArrayList() + jlist.addAll(range(0, 10)) + + i = iter(jlist) + + x = list(i) + + self.assert_(x == range(0, 10)) + + def test_override_len(self): + class MyList (ArrayList): + def __len__(self): + return self.size() + 1; + + m = MyList() + m.addAll(range(0,10)) + + self.assert_(len(m) == 11) + + def test_override_iter(self): + class MyList (ArrayList): + def __iter__(self): + return iter(self.subList(0, self.size() - 1)); + + + m = MyList() + m.addAll(range(0,10)) + i = iter(m) + x = list(i) + + self.assert_(x == range(0, 9)) + + def test_override_getsetdelitem(self): + # Create an ArrayList subclass that provides some silly overrides for get/set/del item + class MyList (ArrayList): + def __getitem__(self, key): + return self.get(key) * 2; + + def __setitem__(self, key, value): + return self.set(key, value * 2); + + def __delitem__(self, key): + self.add(84) + + + m = MyList() + m.addAll(range(0,10)) + + self.assert_(m[1] == 2) + self.assert_(m.get(1) == 1) + + m[0] = 3 + self.assert_(m.get(0) == 6) + self.assert_(m[0] == 12) + + del m[0] + self.assert_(m.size() == 11) + self.assert_(m.get(10) == 84) + +def test_main(): + test.test_support.run_unittest(CollectionProxyTest) + +if __name__ == "__main__": + test_main() Modified: trunk/jython/Lib/test/test_java_visibility.py =================================================================== --- trunk/jython/Lib/test/test_java_visibility.py 2008-12-12 03:31:52 UTC (rev 5738) +++ trunk/jython/Lib/test/test_java_visibility.py 2008-12-12 03:57:33 UTC (rev 5739) @@ -1,11 +1,14 @@ import unittest from test import test_support -from org.python.tests import Invisible, SubVisible, Visible, VisibleOverride +from org.python.tests import InterfaceCombination, Invisible, SubVisible, Visible, VisibleOverride from org.python.tests import VisibilityResults as Results class VisibilityTest(unittest.TestCase): def test_invisible(self): - self.assertEquals([], dir(Invisible)) + for item in dir(Invisible): + self.assert_(not item.startswith("package")) + self.assert_(not item.startswith("private")) + self.assert_(not item.startswith("protected")) def test_protected_from_python_subclass(self): class SubVisible(Visible): @@ -22,8 +25,6 @@ self.assertEquals(Results.UNUSED, SubVisible(Results.UNUSED).visibleField) def test_visible(self): - self.assertEquals(5, len(dir(Visible))) - v = Visible() self.assertEquals(Results.PUBLIC_FIELD, v.visibleField) self.assertEquals(Results.PUBLIC_STATIC_FIELD, Visible.visibleStaticField) @@ -66,8 +67,21 @@ self.failUnless('visibleInstance' in c.__dict__, 'visibleInstance expected in %s __dict__' % c) + def test_interface_combination(self): + '''Checks that a private class that extends a public class and public interfaces has only the items + from the public bases visible''' + i = InterfaceCombination.newImplementation() + self.assertEquals(InterfaceCombination.NO_ARG_RESULT, i.getValue(), + "methods from IFace should be visible on Implementation") + self.assertEquals(InterfaceCombination.ONE_ARG_RESULT, i.getValue("one arg"), + "methods from IIFace should be visible on Implementation") + self.assertEquals(InterfaceCombination.TWO_ARG_RESULT, i.getValue("one arg", "two arg"), + "methods from Base should be visible on Implementation") + self.assertRaises(TypeError, i.getValue, "one arg", "two arg", "three arg", + "methods defined solely on Implementation shouldn't be visible") + self.assertFalse(hasattr(i, "internalMethod"), + "methods from private interfaces shouldn't be visible on a private class") - def test_main(): test_support.run_unittest(VisibilityTest) Modified: trunk/jython/Lib/test/test_joverload.py =================================================================== --- trunk/jython/Lib/test/test_joverload.py 2008-12-12 03:31:52 UTC (rev 5738) +++ trunk/jython/Lib/test/test_joverload.py 2008-12-12 03:57:33 UTC (rev 5739) @@ -6,14 +6,12 @@ import unittest import java -import org.python.core +from org.python.core import PyReflectedFunction class PyReflFuncEnvl: def __init__(self,name,meths): - self.reflfunc = org.python.core.PyReflectedFunction(name) - for meth in meths: - self.reflfunc.addMethod(meth) + self.reflfunc = PyReflectedFunction(meths) def __call__(self,inst,args): return self.reflfunc(inst,*args) Deleted: trunk/jython/Lib/test/test_jreload.py =================================================================== --- trunk/jython/Lib/test/test_jreload.py 2008-12-12 03:31:52 UTC (rev 5738) +++ trunk/jython/Lib/test/test_jreload.py 2008-12-12 03:57:33 UTC (rev 5739) @@ -1,33 +0,0 @@ -"""This test validates the fix for 511493 (jreload truncates large class files). - -We do this by loading a large class file Blob.class from blob.jar (source inside the jar). If the load failes with ClassFormatError, -the bug is present, if the load succeeds, the bug is fixed, if something else occurs, we don't know. -""" - -import unittest -from test import test_support - -from jreload import makeLoadSet -from java.lang import System, ClassFormatError - -import os - -class JreloadTestCase(unittest.TestCase): - - blobjar = test_support.findfile('blob.jar') - - def test( self ): - myls = makeLoadSet('myls', [self.blobjar]) - - try: - from myls import Blob - except ClassFormatError: - print "Reload Error is present" - raise - -def test_main(): - test_support.run_unittest(JreloadTestCase) - -if __name__ == "__main__": - test_main() - Modified: trunk/jython/Lib/test/test_jser2.py =================================================================== (Binary files differ) Property changes on: trunk/jython/Lib/test/test_jser2.py ___________________________________________________________________ Deleted: svn:mime-type - application/octet-stream Modified: trunk/jython/Lib/test/test_jy_internals.py =================================================================== --- trunk/jython/Lib/test/test_jy_internals.py 2008-12-12 03:31:52 UTC (rev 5738) +++ trunk/jython/Lib/test/test_jy_internals.py 2008-12-12 03:57:33 UTC (rev 5739) @@ -60,7 +60,7 @@ iarr = java.lang.Object.getClass(self.e) sdv = java.lang.Class.getMethod(long, 'scaledDoubleValue', [iarr]) import org.python.core.PyReflectedFunction as ReflFunc - self.sdv = ReflFunc(sdv) + self.sdv = ReflFunc([sdv]) def test_basic_roundtrip(self): e = self.e Modified: trunk/jython/build.xml =================================================================== --- trunk/jython/build.xml 2008-12-12 03:31:52 UTC (rev 5738) +++ trunk/jython/build.xml 2008-12-12 03:57:33 UTC (rev 5739) @@ -757,6 +757,16 @@ </target> <target name="test" depends="prepare-test,javatest,launchertest,regrtest"/> + <target name="singlejavatest" depends="compile,expose"> + <junit haltonfailure="true" fork="true"> + <formatter type="brief" usefile="false"/> + <sysproperty key="python.cachedir.skip" value="true"/> + <classpath refid="test.classpath"/> + <batchtest> + <fileset dir="${test.source.dir}" includes="**/${test}.java"/> + </batchtest> + </junit> + </target> <target name="prepare-test" depends="init"> <!-- Clean any old test output --> <delete dir="${junit.reports}"/> Modified: trunk/jython/src/org/python/antlr/adapter/AliasAdapter.java =================================================================== --- trunk/jython/src/org/python/antlr/adapter/AliasAdapter.java 2008-12-12 03:31:52 UTC (rev 5738) +++ trunk/jython/src/org/python/antlr/adapter/AliasAdapter.java 2008-12-12 03:57:33 UTC (rev 5739) @@ -1,14 +1,12 @@ package org.python.antlr.adapter; -import org.python.core.Py; -import org.python.core.PyObject; -import org.python.core.PyJavaInstance; - -import org.python.antlr.ast.alias; - import java.util.ArrayList; import java.util.List; +import org.python.antlr.ast.alias; +import org.python.core.Py; +import org.python.core.PyObject; + public class AliasAdapter implements AstAdapter { public Object py2ast(PyObject o) { @@ -29,7 +27,7 @@ public List iter2ast(PyObject iter) { List<alias> aliases = new ArrayList<alias>(); for(Object o : (Iterable)iter) { - aliases.add((alias)py2ast((PyObject)(PyObject)o)); + aliases.add((alias)py2ast((PyObject)o)); } return aliases; } Modified: trunk/jython/src/org/python/antlr/adapter/CmpopAdapter.java =================================================================== --- trunk/jython/src/org/python/antlr/adapter/CmpopAdapter.java 2008-12-12 03:31:52 UTC (rev 5738) +++ trunk/jython/src/org/python/antlr/adapter/CmpopAdapter.java 2008-12-12 03:57:33 UTC (rev 5739) @@ -1,28 +1,26 @@ package org.python.antlr.adapter; -import org.python.core.Py; -import org.python.core.PyObject; -import org.python.core.PyJavaInstance; +import java.util.ArrayList; +import java.util.List; import org.python.antlr.ast.cmpopType; import org.python.antlr.op.Eq; -import org.python.antlr.op.NotEq; -import org.python.antlr.op.Lt; -import org.python.antlr.op.LtE; import org.python.antlr.op.Gt; import org.python.antlr.op.GtE; +import org.python.antlr.op.In; import org.python.antlr.op.Is; import org.python.antlr.op.IsNot; -import org.python.antlr.op.In; +import org.python.antlr.op.Lt; +import org.python.antlr.op.LtE; +import org.python.antlr.op.NotEq; import org.python.antlr.op.NotIn; +import org.python.core.Py; +import org.python.core.PyObject; -import java.util.ArrayList; -import java.util.List; - public class CmpopAdapter implements AstAdapter { public Object py2ast(PyObject o) { - switch (((PyObject)o).asInt()) { + switch ((o).asInt()) { case 1: return cmpopType.Eq; case 2: @@ -53,23 +51,23 @@ switch ((cmpopType)o) { case Eq: return new Eq(); - case NotEq: + case NotEq: return new NotEq(); - case Lt: + case Lt: return new Lt(); - case LtE: + case LtE: return new LtE(); - case Gt: + case Gt: return new Gt(); - case GtE: + case GtE: return new GtE(); - case Is: + case Is: return new Is(); - case IsNot: + case IsNot: return new IsNot(); - case In: + case In: return new In(); - case NotIn: + case NotIn: return new NotIn(); } return Py.None; Modified: trunk/jython/src/org/python/antlr/adapter/ComprehensionAdapter.java =================================================================== --- trunk/jython/src/org/python/antlr/adapter/ComprehensionAdapter.java 2008-12-12 03:31:52 UTC (rev 5738) +++ trunk/jython/src/org/python/antlr/adapter/ComprehensionAdapter.java 2008-12-12 03:57:33 UTC (rev 5739) @@ -1,14 +1,12 @@ package org.python.antlr.adapter; -import org.python.core.Py; -import org.python.core.PyObject; -import org.python.core.PyJavaInstance; - -import org.python.antlr.ast.comprehension; - import java.util.ArrayList; import java.util.List; +import org.python.antlr.ast.comprehension; +import org.python.core.Py; +import org.python.core.PyObject; + public class ComprehensionAdapter implements AstAdapter { public Object py2ast(PyObject o) { Modified: trunk/jython/src/org/python/antlr/adapter/ExcepthandlerAdapter.java =================================================================== --- trunk/jython/src/org/python/antlr/adapter/ExcepthandlerAdapter.java 2008-12-12 03:31:52 UTC (rev 5738) +++ trunk/jython/src/org/python/antlr/adapter/ExcepthandlerAdapter.java 2008-12-12 03:57:33 UTC (rev 5739) @@ -1,15 +1,12 @@ package org.python.antlr.adapter; -import org.python.core.Py; -import org.python.core.PyObject; -import org.python.core.PyJavaInstance; - -import org.python.antlr.ast.ExceptHandler; -import org.python.antlr.ast.Num; - import java.util.ArrayList; import java.util.List; +import org.python.antlr.ast.ExceptHandler; +import org.python.core.Py; +import org.python.core.PyObject; + public class ExcepthandlerAdapter implements AstAdapter { public Object py2ast(PyObject o) { Modified: trunk/jython/src/org/python/antlr/adapter/ExprAdapter.java =================================================================== --- trunk/jython/src/org/python/antlr/adapter/ExprAdapter.java 2008-12-12 03:31:52 UTC (rev 5738) +++ trunk/jython/src/org/python/antlr/adapter/ExprAdapter.java 2008-12-12 03:57:33 UTC (rev 5739) @@ -1,24 +1,22 @@ package org.python.antlr.adapter; +import java.util.ArrayList; +import java.util.List; + +import org.python.antlr.ast.Num; +import org.python.antlr.ast.Str; +import org.python.antlr.base.expr; import org.python.core.Py; import org.python.core.PyComplex; import org.python.core.PyFloat; import org.python.core.PyInteger; import org.python.core.PyLong; -import org.python.core.PyJavaInstance; import org.python.core.PyObject; import org.python.core.PyString; import org.python.core.PyUnicode; -import org.python.antlr.base.expr; -import org.python.antlr.ast.Num; -import org.python.antlr.ast.Str; - -import java.util.ArrayList; -import java.util.List; - public class ExprAdapter implements AstAdapter { - + public Object py2ast(PyObject o) { if (o == null || o instanceof expr) { return o; Modified: trunk/jython/src/org/python/antlr/adapter/IdentifierAdapter.java =================================================================== --- trunk/jython/src/org/python/antlr/adapter/IdentifierAdapter.java 2008-12-12 03:31:52 UTC (rev 5738) +++ trunk/jython/src/org/python/antlr/adapter/IdentifierAdapter.java 2008-12-12 03:57:33 UTC (rev 5739) @@ -1,15 +1,11 @@ package org.python.antlr.adapter; -import org.python.core.Py; -import org.python.core.PyJavaInstance; -import org.python.core.PyObject; -import org.python.core.PyString; - -import org.python.antlr.ast.Num; - import java.util.ArrayList; import java.util.List; +import org.python.core.PyObject; +import org.python.core.PyString; + public class IdentifierAdapter implements AstAdapter { public Object py2ast(PyObject o) { Modified: trunk/jython/src/org/python/antlr/adapter/KeywordAdapter.java =================================================================== --- trunk/jython/src/org/python/antlr/adapter/KeywordAdapter.java 2008-12-12 03:31:52 UTC (rev 5738) +++ trunk/jython/src/org/python/antlr/adapter/KeywordAdapter.java 2008-12-12 03:57:33 UTC (rev 5739) @@ -1,14 +1,12 @@ package org.python.antlr.adapter; -import org.python.core.Py; -import org.python.core.PyJavaInstance; -import org.python.core.PyObject; - -import org.python.antlr.ast.keyword; - import java.util.ArrayList; import java.util.List; +import org.python.antlr.ast.keyword; +import org.python.core.Py; +import org.python.core.PyObject; + public class KeywordAdapter implements AstAdapter { public Object py2ast(PyObject o) { Modified: trunk/jython/src/org/python/antlr/adapter/SliceAdapter.java =================================================================== --- trunk/jython/src/org/python/antlr/adapter/SliceAdapter.java 2008-12-12 03:31:52 UTC (rev 5738) +++ trunk/jython/src/org/python/antlr/adapter/SliceAdapter.java 2008-12-12 03:57:33 UTC (rev 5739) @@ -1,15 +1,12 @@ package org.python.antlr.adapter; -import org.python.core.Py; -import org.python.core.PyJavaInstance; -import org.python.core.PyObject; - -import org.python.antlr.ast.Num; -import org.python.antlr.base.slice; - import java.util.ArrayList; import java.util.List; +import org.python.antlr.base.slice; +import org.python.core.Py; +import org.python.core.PyObject; + public class SliceAdapter implements AstAdapter { public Object py2ast(PyObject o) { Modified: trunk/jython/src/org/python/antlr/adapter/StmtAdapter.java =================================================================== --- trunk/jython/src/org/python/antlr/adapter/StmtAdapter.java 2008-12-12 03:31:52 UTC (rev 5738) +++ trunk/jython/src/org/python/antlr/adapter/StmtAdapter.java 2008-12-12 03:57:33 UTC (rev 5739) @@ -1,14 +1,12 @@ package org.python.antlr.adapter; -import org.python.core.Py; -import org.python.core.PyJavaInstance; -import org.python.core.PyObject; - -import org.python.antlr.base.stmt; - import java.util.ArrayList; import java.util.List; +import org.python.antlr.base.stmt; +import org.python.core.Py; +import org.python.core.PyObject; + public class StmtAdapter implements AstAdapter { public Object py2ast(PyObject o) { Modified: trunk/jython/src/org/python/compiler/ProxyMaker.java =================================================================== --- trunk/jython/src/org/python/compiler/ProxyMaker.java 2008-12-12 03:31:52 UTC (rev 5738) +++ trunk/jython/src/org/python/compiler/ProxyMaker.java 2008-12-12 03:57:33 UTC (rev 5739) @@ -12,6 +12,9 @@ import java.util.Set; import org.python.core.Py; +import org.python.core.PyJavaType; +import org.python.core.PyObject; +import org.python.core.PyProxy; import org.python.objectweb.asm.Label; import org.python.objectweb.asm.Opcodes; import org.python.util.Generic; @@ -53,13 +56,40 @@ else return ((Integer)i).intValue(); } + /** + * Retrieves <code>name</code> from the PyObject in <code>proxy</code> if it's defined in + * Python. This is a specialized helper function for internal PyProxy use. + */ + public static PyObject findPython(PyProxy proxy, String name) { + PyObject o = proxy._getPyInstance(); + if (o == null) { + proxy.__initProxy__(new Object[0]); + o = proxy._getPyInstance(); + } + PyObject ret = null; + if (o.getDict() != null) { + ret = o.getDict().__finditem__(name); + } + if (ret == null) { + PyObject[] definedOn = new PyObject[1]; + PyObject typeDefined = o.getType().lookup_where(name, definedOn); + if (!(definedOn[0] instanceof PyJavaType)) { + ret = typeDefined; + } + } + if (ret == null) { + return null; + } + Py.setSystemState(proxy._getPySystemState()); + return ret.__get__(o, null); + } + Class<?> superclass; Class<?>[] interfaces; Set<String> names; Set<String> supernames = Generic.set(); public ClassFile classfile; public String myClass; - public boolean isAdapter=false; public ProxyMaker(String classname, Class<?> superclass) { this.myClass = "org.python.proxies."+classname; @@ -432,7 +462,8 @@ if (!isAbstract) { int tmp = code.getLocal("org/python/core/PyObject"); - code.invokestatic("org/python/core/Py", "jfindattr", "(" + $pyProxy + $str + ")" + $pyObj); + code.invokestatic("org/python/compiler/ProxyMaker", "findPython", "(" + $pyProxy + $str + + ")" + $pyObj); code.astore(tmp); code.aload(tmp); @@ -449,20 +480,15 @@ addSuperMethod("super__"+name, name, superClass, parameters, ret, sig, access); } else { - if (!isAdapter) { - code.invokestatic("org/python/core/Py", "jgetattr", "(" + $pyProxy + $str + ")" + $pyObj); - callMethod(code, name, parameters, ret, method.getExceptionTypes()); - } else { - code.invokestatic("org/python/core/Py", "jfindattr", "(" + $pyProxy + $str + ")" + $pyObj); - code.dup(); - Label returnNull = new Label(); - code.ifnull(returnNull); - - callMethod(code, name, parameters, ret, method.getExceptionTypes()); - code.label(returnNull); - code.pop(); - doNullReturn(code, ret); - } + code.invokestatic("org/python/compiler/ProxyMaker", "findPython", "(" + $pyProxy + $str + + ")" + $pyObj); + code.dup(); + Label returnNull = new Label(); + code.ifnull(returnNull); + callMethod(code, name, parameters, ret, method.getExceptionTypes()); + code.label(returnNull); + code.pop(); + doNullReturn(code, ret); } } @@ -600,23 +626,23 @@ public void addProxy() throws Exception { // implement PyProxy interface - classfile.addField("__proxy", "Lorg/python/core/PyInstance;", + classfile.addField("__proxy", "Lorg/python/core/PyObject;", Modifier.PROTECTED); // setProxy methods Code code = classfile.addMethod("_setPyInstance", - "(Lorg/python/core/PyInstance;)V", + "(Lorg/python/core/PyObject;)V", Modifier.PUBLIC); code.aload(0); code.aload(1); - code.putfield(classfile.name, "__proxy", "Lorg/python/core/PyInstance;"); + code.putfield(classfile.name, "__proxy", "Lorg/python/core/PyObject;"); code.return_(); // getProxy method code = classfile.addMethod("_getPyInstance", - "()Lorg/python/core/PyInstance;", + "()Lorg/python/core/PyObject;", Modifier.PUBLIC); code.aload(0); - code.getfield(classfile.name, "__proxy", "Lorg/python/core/PyInstance;"); + code.getfield(classfile.name, "__proxy", "Lorg/python/core/PyObject;"); code.areturn(); // implement PyProxy interface Modified: trunk/jython/src/org/python/core/AstList.java =================================================================== --- trunk/jython/src/org/python/core/AstList.java 2008-12-12 03:31:52 UTC (rev 5738) +++ trunk/jython/src/org/python/core/AstList.java 2008-12-12 03:57:33 UTC (rev 5739) @@ -6,13 +6,6 @@ */ package org.python.core; -import org.python.antlr.adapter.AstAdapter; -import org.python.expose.ExposedGet; -import org.python.expose.ExposedMethod; -import org.python.expose.ExposedNew; -import org.python.expose.ExposedType; -import org.python.expose.MethodType; - import java.util.ArrayList; import java.util.Collection; import java.util.Collections; @@ -20,6 +13,12 @@ import java.util.List; import java.util.ListIterator; +import org.python.antlr.adapter.AstAdapter; +import org.python.expose.ExposedGet; +import org.python.expose.ExposedMethod; +import org.python.expose.ExposedType; +import org.python.expose.MethodType; + @ExposedType(name = "_ast.astlist", base = PyList.class) public class AstList extends PySequence implements Cloneable, List { @@ -269,7 +268,7 @@ final String astlist_toString() { return data.toString(); } - + public void append(PyObject o) { astlist_append(o); } @@ -331,8 +330,8 @@ private int _index(PyObject o, String message, int start, int stop) { // Follow Python 2.3+ behavior - int validStop = calculateIndex(stop); - int validStart = calculateIndex(start); + int validStop = boundToSequence(stop); + int validStart = boundToSequence(start); for(int i = validStart; i < validStop && i < size(); i++) { if(data.get(i).equals(o)) { return i; @@ -358,7 +357,7 @@ } } } - + @ExposedMethod final void astlist_extend(PyObject iterable){ int length = size(); @@ -401,7 +400,7 @@ } data.add(index, o); } - + @ExposedMethod final void astlist_remove(PyObject value){ del(_index(value, "astlist.remove(x): x not in list", 0, size())); @@ -434,7 +433,7 @@ return (PyObject)data.remove(n); } Object element = data.remove(n); - return (PyObject)adapter.ast2py(element); + return adapter.ast2py(element); } @@ -454,7 +453,7 @@ } return new AstList(newList); } - + protected void set(int i, PyObject value) { data.set(i, value); } Deleted: trunk/jython/src/org/python/core/AutoInternalTables.java =================================================================== --- trunk/jython/src/org/python/core/AutoInternalTables.java 2008-12-12 03:31:52 UTC (rev 5738) +++ trunk/jython/src/org/python/core/AutoInternalTables.java 2008-12-12 03:57:33 UTC (rev 5739) @@ -1,155 +0,0 @@ -// Copyright 2000 Samuele Pedroni - -package org.python.core; - -import java.lang.ref.Reference; -import java.lang.ref.ReferenceQueue; -import java.util.Map; - -public abstract class AutoInternalTables extends InternalTables { - - protected transient ReferenceQueue queue = new ReferenceQueue(); - - protected abstract Reference newAutoRef(short type, Object key, - Object obj); - protected abstract short getAutoRefType(Reference ref); - protected abstract Object getAutoRefKey(Reference ref); - - private synchronized void cleanup() { - if (this.keepstable >= this.GSTABLE) - return; - this.adapters.remove(null); // trick - Reference ref; - while ((ref = this.queue.poll()) != null) { - Object key = getAutoRefKey(ref); - switch(getAutoRefType(ref)) { - case JCLASS: - Class cl = (Class)key; - this.classes.remove(cl); - classesDec(cl.getName()); - break; - case LAZY_JCLASS: - this.lazyClasses.remove(key); - break; - case ADAPTER_CLASS: - this.adapterClasses.remove(key); - } - } - } - - - protected boolean queryCanonical(String name) { - cleanup(); - return super.queryCanonical(name); - } - - protected PyJavaClass getCanonical(Class c) { - cleanup(); - Reference ref = (Reference)classesGet(c); - if (ref == null) return null; - return (PyJavaClass)ref.get(); - } - - protected PyJavaClass getLazyCanonical(String name) { - cleanup(); - Reference ref = (Reference)this.lazyClasses.get(name); - if (ref == null) return null; - return (PyJavaClass)ref.get(); - } - - protected void putCanonical(Class c,PyJavaClass canonical) { - cleanup(); - classesPut(c,newAutoRef(JCLASS,c,canonical)); - } - - protected void putLazyCanonical(String name,PyJavaClass canonical) { - cleanup(); - this.lazyClasses.put(name,newAutoRef(LAZY_JCLASS,name,canonical)); - } - - protected Class getAdapterClass(Class c) { - cleanup(); - Reference ref = (Reference)this.adapterClasses.get(c); - if (ref == null) return null; - return (Class)ref.get(); - } - - protected void putAdapterClass(Class c,Class ac) { - cleanup(); - this.adapterClasses.put(c,newAutoRef(ADAPTER_CLASS,c,ac)); - } - - protected Object getAdapter(Object o,String evc) { - cleanup(); - return super.getAdapter(o,evc); - } - - protected void putAdapter(Object o,String evc,Object ad) { - cleanup(); - super.putAdapter(o,evc,ad); - } - - - public boolean _doesSomeAutoUnload() { return ... [truncated message content] |
From: <cg...@us...> - 2008-12-12 06:11:08
|
Revision: 5744 http://jython.svn.sourceforge.net/jython/?rev=5744&view=rev Author: cgroves Date: 2008-12-12 06:11:03 +0000 (Fri, 12 Dec 2008) Log Message: ----------- Move interface test to test_java_integration and add interface overloading test Modified Paths: -------------- trunk/jython/Lib/test/test_java_integration.py Added Paths: ----------- trunk/jython/tests/java/org/python/tests/Callbacker.java Removed Paths: ------------- trunk/jython/bugtests/classes/test082j1.java trunk/jython/bugtests/classes/test082j2.java trunk/jython/bugtests/test082.py Modified: trunk/jython/Lib/test/test_java_integration.py =================================================================== --- trunk/jython/Lib/test/test_java_integration.py 2008-12-12 05:40:12 UTC (rev 5743) +++ trunk/jython/Lib/test/test_java_integration.py 2008-12-12 06:11:03 UTC (rev 5744) @@ -387,6 +387,22 @@ self.assertEquals(s, "Foo!!!", "toString not overridden in interface") + def test_java_calling_python_interface_implementation(self): + from org.python.tests import Callbacker + called = [] + class PyCallback(Callbacker.Callback): + def call(self, extraarg=None): + called.append(extraarg) + Callbacker.callNoArg(PyCallback()) + Callbacker.callOneArg(PyCallback(), "arg") + self.assertEquals(None, called[0]) + self.assertEquals("arg", called[1]) + class PyBadCallback(Callbacker.Callback): + def call(pyself, extraarg): + self.fail("Shouldn't be callable with a no args") + self.assertRaises(TypeError, Callbacker.callNoArg, PyBadCallback()) + + class JavaStringTest(unittest.TestCase): def test_string_not_iterable(self): Deleted: trunk/jython/bugtests/classes/test082j1.java =================================================================== --- trunk/jython/bugtests/classes/test082j1.java 2008-12-12 05:40:12 UTC (rev 5743) +++ trunk/jython/bugtests/classes/test082j1.java 2008-12-12 06:11:03 UTC (rev 5744) @@ -1,6 +0,0 @@ - -public interface test082j1 { - public void doit( String dowhat ); - public void dosomethingelse( String dowhat ); -} - Deleted: trunk/jython/bugtests/classes/test082j2.java =================================================================== --- trunk/jython/bugtests/classes/test082j2.java 2008-12-12 05:40:12 UTC (rev 5743) +++ trunk/jython/bugtests/classes/test082j2.java 2008-12-12 06:11:03 UTC (rev 5744) @@ -1,7 +0,0 @@ - -public class test082j2 { - public static void doDoit( test082j1 callback ){ - callback.doit( "foo" ); - } -} - Deleted: trunk/jython/bugtests/test082.py =================================================================== --- trunk/jython/bugtests/test082.py 2008-12-12 05:40:12 UTC (rev 5743) +++ trunk/jython/bugtests/test082.py 2008-12-12 06:11:03 UTC (rev 5744) @@ -1,21 +0,0 @@ -""" -Passing an python implemented interface to a java method. -""" - -import support - -support.compileJava("classes/test082j1.java") -support.compileJava("classes/test082j2.java") - -import test082j1, test082j2 - -class pydoit( test082j1 ): - def doit( a, b): # too many arguments for interface - pass - - def dosomethingelse( a ): - pass - - -test082j2().doDoit( pydoit() ) - Added: trunk/jython/tests/java/org/python/tests/Callbacker.java =================================================================== --- trunk/jython/tests/java/org/python/tests/Callbacker.java (rev 0) +++ trunk/jython/tests/java/org/python/tests/Callbacker.java 2008-12-12 06:11:03 UTC (rev 5744) @@ -0,0 +1,19 @@ +package org.python.tests; + +public class Callbacker { + + public interface Callback { + + public void call(); + + public void call(String oneArg); + } + + public static void callNoArg(Callback c) { + c.call(); + } + + public static void callOneArg(Callback c, String arg) { + c.call(arg); + } +} This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <cg...@us...> - 2008-12-13 07:34:01
|
Revision: 5752 http://jython.svn.sourceforge.net/jython/?rev=5752&view=rev Author: cgroves Date: 2008-12-13 07:33:55 +0000 (Sat, 13 Dec 2008) Log Message: ----------- Move test087 into test_java_integration, and test088 and test090 are tested by test_java_integration and test_imp_jy respectively Modified Paths: -------------- trunk/jython/Lib/test/test_java_integration.py Removed Paths: ------------- trunk/jython/bugtests/classes/test090j.java trunk/jython/bugtests/test087.py trunk/jython/bugtests/test087m.py trunk/jython/bugtests/test088.py trunk/jython/bugtests/test088p/ trunk/jython/bugtests/test090.py Modified: trunk/jython/Lib/test/test_java_integration.py =================================================================== --- trunk/jython/Lib/test/test_java_integration.py 2008-12-12 15:46:58 UTC (rev 5751) +++ trunk/jython/Lib/test/test_java_integration.py 2008-12-13 07:33:55 UTC (rev 5752) @@ -99,6 +99,16 @@ return 'name' self.assertEquals('name', String.valueOf(A())) + def test_multiple_inheritance_prohibited(self): + try: + class MultiJava(Dimension, Color): + pass + self.fail("Shouldn't be able to subclass more than one concrete java class") + except TypeError: + pass + + + class SysIntegrationTest(unittest.TestCase): def test_stdout_outputstream(self): out = FileOutputStream(test_support.TESTFN) Deleted: trunk/jython/bugtests/classes/test090j.java =================================================================== --- trunk/jython/bugtests/classes/test090j.java 2008-12-12 15:46:58 UTC (rev 5751) +++ trunk/jython/bugtests/classes/test090j.java 2008-12-13 07:33:55 UTC (rev 5752) @@ -1,16 +0,0 @@ - -public class test090j { - public test090j() { - } - public int barTimesTwo(Bar bar) { - return (2*bar.n); - } - public static class Bar { - public Bar() { - } - public Bar(int n) { - this.n = n; - } - public int n; - } -} \ No newline at end of file Deleted: trunk/jython/bugtests/test087.py =================================================================== --- trunk/jython/bugtests/test087.py 2008-12-12 15:46:58 UTC (rev 5751) +++ trunk/jython/bugtests/test087.py 2008-12-13 07:33:55 UTC (rev 5752) @@ -1,12 +0,0 @@ -""" -Test multiple inheritance of 2 java classes -""" - -import support - -try: - import test087m -except TypeError, e: - support.compare(e, "multiple inheritance") -else: - raise support.TestError("multiple inheritance should fail") Deleted: trunk/jython/bugtests/test087m.py =================================================================== --- trunk/jython/bugtests/test087m.py 2008-12-12 15:46:58 UTC (rev 5751) +++ trunk/jython/bugtests/test087m.py 2008-12-13 07:33:55 UTC (rev 5752) @@ -1,10 +0,0 @@ -""" -Test multiple inheritance of 2 java classes -""" - -import support - -import java -class T(java.awt.Panel, java.awt.event.MouseAdapter): - def __init__(self): - pass Deleted: trunk/jython/bugtests/test088.py =================================================================== --- trunk/jython/bugtests/test088.py 2008-12-12 15:46:58 UTC (rev 5751) +++ trunk/jython/bugtests/test088.py 2008-12-13 07:33:55 UTC (rev 5752) @@ -1,10 +0,0 @@ -""" -Check namespace of code running in a module __init__.py -""" - -import support - -import test088p - -r = test088p.foobase.doit() -support.compare(r, "Done") Deleted: trunk/jython/bugtests/test090.py =================================================================== --- trunk/jython/bugtests/test090.py 2008-12-12 15:46:58 UTC (rev 5751) +++ trunk/jython/bugtests/test090.py 2008-12-13 07:33:55 UTC (rev 5752) @@ -1,16 +0,0 @@ -""" -Access to innerclasses -""" - -import support - -support.compileJava("classes/test090j.java") - -import test090j - -foo = test090j() -bar = test090j.Bar() -bar.n = 10 -r = foo.barTimesTwo(bar) - -support.compare(r, "20") This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <pj...@us...> - 2008-12-14 23:58:45
|
Revision: 5762 http://jython.svn.sourceforge.net/jython/?rev=5762&view=rev Author: pjenvey Date: 2008-12-14 23:58:41 +0000 (Sun, 14 Dec 2008) Log Message: ----------- o fix broken os.utime on 64 bit POSIX platforms, w/ jna-posix revision 92037116ce84 o fix grp/pwd to handle the new jna-posix Modified Paths: -------------- trunk/jython/Lib/grp.py trunk/jython/Lib/pwd.py trunk/jython/extlibs/jna-posix.jar Modified: trunk/jython/Lib/grp.py =================================================================== --- trunk/jython/Lib/grp.py 2008-12-14 23:57:35 UTC (rev 5761) +++ trunk/jython/Lib/grp.py 2008-12-14 23:58:41 UTC (rev 5762) @@ -18,7 +18,6 @@ __all__ = ['getgrgid', 'getgrnam', 'getgrall'] from os import _name, _posix -from java.lang import NullPointerException if _name == 'nt': raise ImportError, 'grp module not supported on Windows' @@ -44,28 +43,31 @@ except ValueError: raise AttributeError + def getgrgid(uid): """ getgrgid(id) -> tuple Return the group database entry for the given numeric group ID. If id is not valid, raise KeyError. """ - try: - return struct_group(_posix.getgrgid(uid)) - except NullPointerException: - raise KeyError, uid + entry = _posix.getgrgid(uid) + if not entry: + raise KeyError(uid) + return struct_group(entry) + def getgrnam(name): """ getgrnam(name) -> tuple Return the group database entry for the given group name. If name is not valid, raise KeyError. """ - try: - return struct_group(_posix.getgrnam(name)) - except NullPointerException: - raise KeyError, name + entry = _posix.getgrnam(name) + if not entry: + raise KeyError(name) + return struct_group(entry) + def getgrall(): """ getgrall() -> list of tuples @@ -73,8 +75,9 @@ in arbitrary order. """ groups = [] - try: - while True: - groups.append(struct_group(_posix.getgrent())) - except NullPointerException: - return groups + while True: + group = _posix.getgrent() + if not group: + break + groups.append(struct_group(group)) + return groups Modified: trunk/jython/Lib/pwd.py =================================================================== --- trunk/jython/Lib/pwd.py 2008-12-14 23:57:35 UTC (rev 5761) +++ trunk/jython/Lib/pwd.py 2008-12-14 23:58:41 UTC (rev 5762) @@ -11,7 +11,6 @@ __all__ = ['getpwuid', 'getpwnam', 'getpwall'] from os import _name, _posix -from java.lang import NullPointerException if _name == 'nt': raise ImportError, 'pwd module not supported on Windows' @@ -37,6 +36,7 @@ except ValueError: raise AttributeError + def getpwuid(uid): """ getpwuid(uid) -> (pw_name,pw_passwd,pw_uid, @@ -44,11 +44,12 @@ Return the password database entry for the given numeric user ID. See pwd.__doc__ for more on password database entries. """ - try: - return struct_passwd(_posix.getpwuid(uid)) - except NullPointerException: - raise KeyError, uid + entry = _posix.getpwuid(uid) + if not entry: + raise KeyError(uid) + return struct_passwd(entry) + def getpwnam(name): """ getpwnam(name) -> (pw_name,pw_passwd,pw_uid, @@ -56,11 +57,12 @@ Return the password database entry for the given user name. See pwd.__doc__ for more on password database entries. """ - try: - return struct_passwd(_posix.getpwnam(name)) - except NullPointerException: - raise KeyError, name + entry = _posix.getpwnam(name) + if not entry: + raise KeyError(name) + return struct_passwd(entry) + def getpwall(): """ getpwall() -> list_of_entries @@ -69,8 +71,9 @@ See pwd.__doc__ for more on password database entries. """ entries = [] - try: - while True: - entries.append(struct_passwd(_posix.getpwent())) - except NullPointerException: - return entries + while True: + entry = _posix.getpwent() + if not entry: + break + entries.append(struct_passwd(entry)) + return entries Modified: trunk/jython/extlibs/jna-posix.jar =================================================================== (Binary files differ) This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <fwi...@us...> - 2008-12-15 17:04:21
|
Revision: 5767 http://jython.svn.sourceforge.net/jython/?rev=5767&view=rev Author: fwierzbicki Date: 2008-12-15 17:04:17 +0000 (Mon, 15 Dec 2008) Log Message: ----------- results of object.derived change for http://bugs.jython.org/issue1758318. We now pass unmodified test_bool.py, so deleting our version of that as well. Modified Paths: -------------- trunk/jython/src/org/python/antlr/ast/AssertDerived.java trunk/jython/src/org/python/antlr/ast/AssignDerived.java trunk/jython/src/org/python/antlr/ast/AttributeDerived.java trunk/jython/src/org/python/antlr/ast/AugAssignDerived.java trunk/jython/src/org/python/antlr/ast/BinOpDerived.java trunk/jython/src/org/python/antlr/ast/BoolOpDerived.java trunk/jython/src/org/python/antlr/ast/BreakDerived.java trunk/jython/src/org/python/antlr/ast/CallDerived.java trunk/jython/src/org/python/antlr/ast/ClassDefDerived.java trunk/jython/src/org/python/antlr/ast/CompareDerived.java trunk/jython/src/org/python/antlr/ast/ContinueDerived.java trunk/jython/src/org/python/antlr/ast/DeleteDerived.java trunk/jython/src/org/python/antlr/ast/DictDerived.java trunk/jython/src/org/python/antlr/ast/EllipsisDerived.java trunk/jython/src/org/python/antlr/ast/ExceptHandlerDerived.java trunk/jython/src/org/python/antlr/ast/ExecDerived.java trunk/jython/src/org/python/antlr/ast/ExprDerived.java trunk/jython/src/org/python/antlr/ast/ExpressionDerived.java trunk/jython/src/org/python/antlr/ast/ExtSliceDerived.java trunk/jython/src/org/python/antlr/ast/ForDerived.java trunk/jython/src/org/python/antlr/ast/FunctionDefDerived.java trunk/jython/src/org/python/antlr/ast/GeneratorExpDerived.java trunk/jython/src/org/python/antlr/ast/GlobalDerived.java trunk/jython/src/org/python/antlr/ast/IfDerived.java trunk/jython/src/org/python/antlr/ast/IfExpDerived.java trunk/jython/src/org/python/antlr/ast/ImportDerived.java trunk/jython/src/org/python/antlr/ast/ImportFromDerived.java trunk/jython/src/org/python/antlr/ast/IndexDerived.java trunk/jython/src/org/python/antlr/ast/InteractiveDerived.java trunk/jython/src/org/python/antlr/ast/LambdaDerived.java trunk/jython/src/org/python/antlr/ast/ListCompDerived.java trunk/jython/src/org/python/antlr/ast/ListDerived.java trunk/jython/src/org/python/antlr/ast/ModuleDerived.java trunk/jython/src/org/python/antlr/ast/NameDerived.java trunk/jython/src/org/python/antlr/ast/NumDerived.java trunk/jython/src/org/python/antlr/ast/PassDerived.java trunk/jython/src/org/python/antlr/ast/PrintDerived.java trunk/jython/src/org/python/antlr/ast/RaiseDerived.java trunk/jython/src/org/python/antlr/ast/ReprDerived.java trunk/jython/src/org/python/antlr/ast/ReturnDerived.java trunk/jython/src/org/python/antlr/ast/SliceDerived.java trunk/jython/src/org/python/antlr/ast/StrDerived.java trunk/jython/src/org/python/antlr/ast/SubscriptDerived.java trunk/jython/src/org/python/antlr/ast/SuiteDerived.java trunk/jython/src/org/python/antlr/ast/TryExceptDerived.java trunk/jython/src/org/python/antlr/ast/TryFinallyDerived.java trunk/jython/src/org/python/antlr/ast/TupleDerived.java trunk/jython/src/org/python/antlr/ast/UnaryOpDerived.java trunk/jython/src/org/python/antlr/ast/WhileDerived.java trunk/jython/src/org/python/antlr/ast/WithDerived.java trunk/jython/src/org/python/antlr/ast/YieldDerived.java trunk/jython/src/org/python/antlr/ast/aliasDerived.java trunk/jython/src/org/python/antlr/ast/argumentsDerived.java trunk/jython/src/org/python/antlr/ast/comprehensionDerived.java trunk/jython/src/org/python/antlr/ast/keywordDerived.java trunk/jython/src/org/python/antlr/op/AddDerived.java trunk/jython/src/org/python/antlr/op/AndDerived.java trunk/jython/src/org/python/antlr/op/AugLoadDerived.java trunk/jython/src/org/python/antlr/op/AugStoreDerived.java trunk/jython/src/org/python/antlr/op/BitAndDerived.java trunk/jython/src/org/python/antlr/op/BitOrDerived.java trunk/jython/src/org/python/antlr/op/BitXorDerived.java trunk/jython/src/org/python/antlr/op/DelDerived.java trunk/jython/src/org/python/antlr/op/DivDerived.java trunk/jython/src/org/python/antlr/op/EqDerived.java trunk/jython/src/org/python/antlr/op/FloorDivDerived.java trunk/jython/src/org/python/antlr/op/GtDerived.java trunk/jython/src/org/python/antlr/op/GtEDerived.java trunk/jython/src/org/python/antlr/op/InDerived.java trunk/jython/src/org/python/antlr/op/InvertDerived.java trunk/jython/src/org/python/antlr/op/IsDerived.java trunk/jython/src/org/python/antlr/op/IsNotDerived.java trunk/jython/src/org/python/antlr/op/LShiftDerived.java trunk/jython/src/org/python/antlr/op/LoadDerived.java trunk/jython/src/org/python/antlr/op/LtDerived.java trunk/jython/src/org/python/antlr/op/LtEDerived.java trunk/jython/src/org/python/antlr/op/ModDerived.java trunk/jython/src/org/python/antlr/op/MultDerived.java trunk/jython/src/org/python/antlr/op/NotDerived.java trunk/jython/src/org/python/antlr/op/NotEqDerived.java trunk/jython/src/org/python/antlr/op/NotInDerived.java trunk/jython/src/org/python/antlr/op/OrDerived.java trunk/jython/src/org/python/antlr/op/ParamDerived.java trunk/jython/src/org/python/antlr/op/PowDerived.java trunk/jython/src/org/python/antlr/op/RShiftDerived.java trunk/jython/src/org/python/antlr/op/StoreDerived.java trunk/jython/src/org/python/antlr/op/SubDerived.java trunk/jython/src/org/python/antlr/op/UAddDerived.java trunk/jython/src/org/python/antlr/op/USubDerived.java 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 Removed Paths: ------------- trunk/jython/Lib/test/test_bool.py Deleted: trunk/jython/Lib/test/test_bool.py =================================================================== --- trunk/jython/Lib/test/test_bool.py 2008-12-15 17:01:52 UTC (rev 5766) +++ trunk/jython/Lib/test/test_bool.py 2008-12-15 17:04:17 UTC (rev 5767) @@ -1,351 +0,0 @@ -# Test properties of bool promised by PEP 285 - -import unittest -from test import test_support - -import os - -class BoolTest(unittest.TestCase): - - def assertIs(self, a, b): - self.assert_(a is b) - - def assertIsNot(self, a, b): - self.assert_(a is not b) - - def test_subclass(self): - try: - class C(bool): - pass - except TypeError: - pass - else: - self.fail("bool should not be subclassable") - - self.assertRaises(TypeError, int.__new__, bool, 0) - - def test_print(self): - try: - fo = open(test_support.TESTFN, "wb") - print >> fo, False, True - fo.close() - fo = open(test_support.TESTFN, "rb") - self.assertEqual(fo.read(), 'False True\n') - finally: - fo.close() - os.remove(test_support.TESTFN) - - def test_repr(self): - self.assertEqual(repr(False), 'False') - self.assertEqual(repr(True), 'True') - self.assertEqual(eval(repr(False)), False) - self.assertEqual(eval(repr(True)), True) - - def test_str(self): - self.assertEqual(str(False), 'False') - self.assertEqual(str(True), 'True') - - def test_int(self): - self.assertEqual(int(False), 0) - self.assertIsNot(int(False), False) - self.assertEqual(int(True), 1) - self.assertIsNot(int(True), True) - - def test_math(self): - self.assertEqual(+False, 0) - self.assertIsNot(+False, False) - self.assertEqual(-False, 0) - self.assertIsNot(-False, False) - self.assertEqual(abs(False), 0) - self.assertIsNot(abs(False), False) - self.assertEqual(+True, 1) - self.assertIsNot(+True, True) - self.assertEqual(-True, -1) - self.assertEqual(abs(True), 1) - self.assertIsNot(abs(True), True) - self.assertEqual(~False, -1) - self.assertEqual(~True, -2) - - self.assertEqual(False+2, 2) - self.assertEqual(True+2, 3) - self.assertEqual(2+False, 2) - self.assertEqual(2+True, 3) - - self.assertEqual(False+False, 0) - self.assertIsNot(False+False, False) - self.assertEqual(False+True, 1) - self.assertIsNot(False+True, True) - self.assertEqual(True+False, 1) - self.assertIsNot(True+False, True) - self.assertEqual(True+True, 2) - - self.assertEqual(True-True, 0) - self.assertIsNot(True-True, False) - self.assertEqual(False-False, 0) - self.assertIsNot(False-False, False) - self.assertEqual(True-False, 1) - self.assertIsNot(True-False, True) - self.assertEqual(False-True, -1) - - self.assertEqual(True*1, 1) - self.assertEqual(False*1, 0) - self.assertIsNot(False*1, False) - - self.assertEqual(True/1, 1) - self.assertIsNot(True/1, True) - self.assertEqual(False/1, 0) - self.assertIsNot(False/1, False) - - for b in False, True: - for i in 0, 1, 2: - self.assertEqual(b**i, int(b)**i) - self.assertIsNot(b**i, bool(int(b)**i)) - - for a in False, True: - for b in False, True: - self.assertIs(a&b, bool(int(a)&int(b))) - self.assertIs(a|b, bool(int(a)|int(b))) - self.assertIs(a^b, bool(int(a)^int(b))) - self.assertEqual(a&int(b), int(a)&int(b)) - self.assertIsNot(a&int(b), bool(int(a)&int(b))) - self.assertEqual(a|int(b), int(a)|int(b)) - self.assertIsNot(a|int(b), bool(int(a)|int(b))) - self.assertEqual(a^int(b), int(a)^int(b)) - self.assertIsNot(a^int(b), bool(int(a)^int(b))) - self.assertEqual(int(a)&b, int(a)&int(b)) - self.assertIsNot(int(a)&b, bool(int(a)&int(b))) - self.assertEqual(int(a)|b, int(a)|int(b)) - self.assertIsNot(int(a)|b, bool(int(a)|int(b))) - self.assertEqual(int(a)^b, int(a)^int(b)) - self.assertIsNot(int(a)^b, bool(int(a)^int(b))) - - self.assertIs(1==1, True) - self.assertIs(1==0, False) - self.assertIs(0<1, True) - self.assertIs(1<0, False) - self.assertIs(0<=0, True) - self.assertIs(1<=0, False) - self.assertIs(1>0, True) - self.assertIs(1>1, False) - self.assertIs(1>=1, True) - self.assertIs(0>=1, False) - self.assertIs(0!=1, True) - self.assertIs(0!=0, False) - - x = [1] - self.assertIs(x is x, True) - self.assertIs(x is not x, False) - - self.assertIs(1 in x, True) - self.assertIs(0 in x, False) - self.assertIs(1 not in x, False) - self.assertIs(0 not in x, True) - - x = {1: 2} - self.assertIs(x is x, True) - self.assertIs(x is not x, False) - - self.assertIs(1 in x, True) - self.assertIs(0 in x, False) - self.assertIs(1 not in x, False) - self.assertIs(0 not in x, True) - - self.assertIs(not True, False) - self.assertIs(not False, True) - - def test_convert(self): - self.assertRaises(TypeError, bool, 42, 42) - self.assertIs(bool(10), True) - self.assertIs(bool(1), True) - self.assertIs(bool(-1), True) - self.assertIs(bool(0), False) - self.assertIs(bool("hello"), True) - self.assertIs(bool(""), False) - self.assertIs(bool(), False) - - def test_hasattr(self): - self.assertIs(hasattr([], "append"), True) - self.assertIs(hasattr([], "wobble"), False) - - def test_callable(self): - self.assertIs(callable(len), True) - self.assertIs(callable(1), False) - - def test_isinstance(self): - self.assertIs(isinstance(True, bool), True) - self.assertIs(isinstance(False, bool), True) - self.assertIs(isinstance(True, int), True) - self.assertIs(isinstance(False, int), True) - self.assertIs(isinstance(1, bool), False) - self.assertIs(isinstance(0, bool), False) - - def test_issubclass(self): - self.assertIs(issubclass(bool, int), True) - self.assertIs(issubclass(int, bool), False) - - def test_haskey(self): - self.assertIs({}.has_key(1), False) - self.assertIs({1:1}.has_key(1), True) - - def test_string(self): - self.assertIs("xyz".endswith("z"), True) - self.assertIs("xyz".endswith("x"), False) - self.assertIs("xyz0123".isalnum(), True) - self.assertIs("@#$%".isalnum(), False) - self.assertIs("xyz".isalpha(), True) - self.assertIs("@#$%".isalpha(), False) - self.assertIs("0123".isdigit(), True) - self.assertIs("xyz".isdigit(), False) - self.assertIs("xyz".islower(), True) - self.assertIs("XYZ".islower(), False) - self.assertIs(" ".isspace(), True) - self.assertIs("XYZ".isspace(), False) - self.assertIs("X".istitle(), True) - self.assertIs("x".istitle(), False) - self.assertIs("XYZ".isupper(), True) - self.assertIs("xyz".isupper(), False) - self.assertIs("xyz".startswith("x"), True) - self.assertIs("xyz".startswith("z"), False) - - if test_support.have_unicode: - self.assertIs(unicode("xyz", 'ascii').endswith(unicode("z", 'ascii')), True) - self.assertIs(unicode("xyz", 'ascii').endswith(unicode("x", 'ascii')), False) - self.assertIs(unicode("xyz0123", 'ascii').isalnum(), True) - self.assertIs(unicode("@#$%", 'ascii').isalnum(), False) - self.assertIs(unicode("xyz", 'ascii').isalpha(), True) - self.assertIs(unicode("@#$%", 'ascii').isalpha(), False) - self.assertIs(unicode("0123", 'ascii').isdecimal(), True) - self.assertIs(unicode("xyz", 'ascii').isdecimal(), False) - self.assertIs(unicode("0123", 'ascii').isdigit(), True) - self.assertIs(unicode("xyz", 'ascii').isdigit(), False) - self.assertIs(unicode("xyz", 'ascii').islower(), True) - self.assertIs(unicode("XYZ", 'ascii').islower(), False) - self.assertIs(unicode("0123", 'ascii').isnumeric(), True) - self.assertIs(unicode("xyz", 'ascii').isnumeric(), False) - self.assertIs(unicode(" ", 'ascii').isspace(), True) - self.assertIs(unicode("XYZ", 'ascii').isspace(), False) - self.assertIs(unicode("X", 'ascii').istitle(), True) - self.assertIs(unicode("x", 'ascii').istitle(), False) - self.assertIs(unicode("XYZ", 'ascii').isupper(), True) - self.assertIs(unicode("xyz", 'ascii').isupper(), False) - self.assertIs(unicode("xyz", 'ascii').startswith(unicode("x", 'ascii')), True) - self.assertIs(unicode("xyz", 'ascii').startswith(unicode("z", 'ascii')), False) - - def test_boolean(self): - self.assertEqual(True & 1, 1) - self.assert_(not isinstance(True & 1, bool)) - self.assertIs(True & True, True) - - self.assertEqual(True | 1, 1) - self.assert_(not isinstance(True | 1, bool)) - self.assertIs(True | True, True) - - self.assertEqual(True ^ 1, 0) - self.assert_(not isinstance(True ^ 1, bool)) - self.assertIs(True ^ True, False) - - def test_fileclosed(self): - try: - f = file(test_support.TESTFN, "w") - self.assertIs(f.closed, False) - f.close() - self.assertIs(f.closed, True) - finally: - os.remove(test_support.TESTFN) - - def test_operator(self): - import operator - self.assertIs(operator.truth(0), False) - self.assertIs(operator.truth(1), True) - self.assertIs(operator.isCallable(0), False) - self.assertIs(operator.isCallable(len), True) - self.assertIs(operator.isNumberType(None), False) - self.assertIs(operator.isNumberType(0), True) - self.assertIs(operator.not_(1), False) - self.assertIs(operator.not_(0), True) - self.assertIs(operator.isSequenceType(0), False) - self.assertIs(operator.isSequenceType([]), True) - self.assertIs(operator.contains([], 1), False) - self.assertIs(operator.contains([1], 1), True) - self.assertIs(operator.isMappingType(1), False) - self.assertIs(operator.isMappingType({}), True) - self.assertIs(operator.lt(0, 0), False) - self.assertIs(operator.lt(0, 1), True) - self.assertIs(operator.is_(True, True), True) - self.assertIs(operator.is_(True, False), False) - self.assertIs(operator.is_not(True, True), False) - self.assertIs(operator.is_not(True, False), True) - - def test_marshal(self): - import marshal - self.assertIs(marshal.loads(marshal.dumps(True)), True) - self.assertIs(marshal.loads(marshal.dumps(False)), False) - - def test_pickle(self): - import pickle - self.assertIs(pickle.loads(pickle.dumps(True)), True) - self.assertIs(pickle.loads(pickle.dumps(False)), False) - self.assertIs(pickle.loads(pickle.dumps(True, True)), True) - self.assertIs(pickle.loads(pickle.dumps(False, True)), False) - - def test_cpickle(self): - import cPickle - self.assertIs(cPickle.loads(cPickle.dumps(True)), True) - self.assertIs(cPickle.loads(cPickle.dumps(False)), False) - self.assertIs(cPickle.loads(cPickle.dumps(True, True)), True) - self.assertIs(cPickle.loads(cPickle.dumps(False, True)), False) - - def test_mixedpickle(self): - import pickle, cPickle - self.assertIs(pickle.loads(cPickle.dumps(True)), True) - self.assertIs(pickle.loads(cPickle.dumps(False)), False) - self.assertIs(pickle.loads(cPickle.dumps(True, True)), True) - self.assertIs(pickle.loads(cPickle.dumps(False, True)), False) - - self.assertIs(cPickle.loads(pickle.dumps(True)), True) - self.assertIs(cPickle.loads(pickle.dumps(False)), False) - self.assertIs(cPickle.loads(pickle.dumps(True, True)), True) - self.assertIs(cPickle.loads(pickle.dumps(False, True)), False) - - def test_picklevalues(self): - import pickle, cPickle - - # Test for specific backwards-compatible pickle values - self.assertEqual(pickle.dumps(True), "I01\n.") - self.assertEqual(pickle.dumps(False), "I00\n.") - self.assertEqual(cPickle.dumps(True), "I01\n.") - self.assertEqual(cPickle.dumps(False), "I00\n.") - self.assertEqual(pickle.dumps(True, True), "I01\n.") - self.assertEqual(pickle.dumps(False, True), "I00\n.") - self.assertEqual(cPickle.dumps(True, True), "I01\n.") - self.assertEqual(cPickle.dumps(False, True), "I00\n.") - - def test_convert_to_bool(self): - # Verify that TypeError occurs when bad things are returned - # from __nonzero__(). This isn't really a bool test, but - # it's related. - check = lambda o: self.assertRaises(TypeError, bool, o) - class Foo(object): - def __nonzero__(self): - return self - check(Foo()) - - class Bar(object): - def __nonzero__(self): - return "Yes" - check(Bar()) - - class Baz(int): - def __nonzero__(self): - return self - check(Baz()) - -# StackOverflow if __nonzero__ returns self -# http://jython.org/bugs/1758318 -del BoolTest.test_convert_to_bool - -def test_main(): - test_support.run_unittest(BoolTest) - -if __name__ == "__main__": - test_main() Modified: trunk/jython/src/org/python/antlr/ast/AssertDerived.java =================================================================== --- trunk/jython/src/org/python/antlr/ast/AssertDerived.java 2008-12-15 17:01:52 UTC (rev 5766) +++ trunk/jython/src/org/python/antlr/ast/AssertDerived.java 2008-12-15 17:04:17 UTC (rev 5767) @@ -793,7 +793,12 @@ if (impl==null) return super.__nonzero__(); } - return impl.__get__(this,self_type).__call__().__nonzero__(); + PyObject o=impl.__get__(this,self_type).__call__(); + Class c=o.getClass(); + if (c!=PyInteger.class&&c!=PyBoolean.class) { + throw Py.TypeError(String.format("__nonzero__ should return bool or int, returned %s",self_type.getName())); + } + return o.__nonzero__(); } public boolean __contains__(PyObject o) { @@ -1093,6 +1098,7 @@ if (res!=Py.None) { throw Py.TypeError(String.format("__init__() should return None, not '%.200s'",res.getType().fastGetName())); } + proxyInit(); } } } Modified: trunk/jython/src/org/python/antlr/ast/AssignDerived.java =================================================================== --- trunk/jython/src/org/python/antlr/ast/AssignDerived.java 2008-12-15 17:01:52 UTC (rev 5766) +++ trunk/jython/src/org/python/antlr/ast/AssignDerived.java 2008-12-15 17:04:17 UTC (rev 5767) @@ -793,7 +793,12 @@ if (impl==null) return super.__nonzero__(); } - return impl.__get__(this,self_type).__call__().__nonzero__(); + PyObject o=impl.__get__(this,self_type).__call__(); + Class c=o.getClass(); + if (c!=PyInteger.class&&c!=PyBoolean.class) { + throw Py.TypeError(String.format("__nonzero__ should return bool or int, returned %s",self_type.getName())); + } + return o.__nonzero__(); } public boolean __contains__(PyObject o) { @@ -1093,6 +1098,7 @@ if (res!=Py.None) { throw Py.TypeError(String.format("__init__() should return None, not '%.200s'",res.getType().fastGetName())); } + proxyInit(); } } } Modified: trunk/jython/src/org/python/antlr/ast/AttributeDerived.java =================================================================== --- trunk/jython/src/org/python/antlr/ast/AttributeDerived.java 2008-12-15 17:01:52 UTC (rev 5766) +++ trunk/jython/src/org/python/antlr/ast/AttributeDerived.java 2008-12-15 17:04:17 UTC (rev 5767) @@ -793,7 +793,12 @@ if (impl==null) return super.__nonzero__(); } - return impl.__get__(this,self_type).__call__().__nonzero__(); + PyObject o=impl.__get__(this,self_type).__call__(); + Class c=o.getClass(); + if (c!=PyInteger.class&&c!=PyBoolean.class) { + throw Py.TypeError(String.format("__nonzero__ should return bool or int, returned %s",self_type.getName())); + } + return o.__nonzero__(); } public boolean __contains__(PyObject o) { @@ -1093,6 +1098,7 @@ if (res!=Py.None) { throw Py.TypeError(String.format("__init__() should return None, not '%.200s'",res.getType().fastGetName())); } + proxyInit(); } } } Modified: trunk/jython/src/org/python/antlr/ast/AugAssignDerived.java =================================================================== --- trunk/jython/src/org/python/antlr/ast/AugAssignDerived.java 2008-12-15 17:01:52 UTC (rev 5766) +++ trunk/jython/src/org/python/antlr/ast/AugAssignDerived.java 2008-12-15 17:04:17 UTC (rev 5767) @@ -793,7 +793,12 @@ if (impl==null) return super.__nonzero__(); } - return impl.__get__(this,self_type).__call__().__nonzero__(); + PyObject o=impl.__get__(this,self_type).__call__(); + Class c=o.getClass(); + if (c!=PyInteger.class&&c!=PyBoolean.class) { + throw Py.TypeError(String.format("__nonzero__ should return bool or int, returned %s",self_type.getName())); + } + return o.__nonzero__(); } public boolean __contains__(PyObject o) { @@ -1093,6 +1098,7 @@ if (res!=Py.None) { throw Py.TypeError(String.format("__init__() should return None, not '%.200s'",res.getType().fastGetName())); } + proxyInit(); } } } Modified: trunk/jython/src/org/python/antlr/ast/BinOpDerived.java =================================================================== --- trunk/jython/src/org/python/antlr/ast/BinOpDerived.java 2008-12-15 17:01:52 UTC (rev 5766) +++ trunk/jython/src/org/python/antlr/ast/BinOpDerived.java 2008-12-15 17:04:17 UTC (rev 5767) @@ -793,7 +793,12 @@ if (impl==null) return super.__nonzero__(); } - return impl.__get__(this,self_type).__call__().__nonzero__(); + PyObject o=impl.__get__(this,self_type).__call__(); + Class c=o.getClass(); + if (c!=PyInteger.class&&c!=PyBoolean.class) { + throw Py.TypeError(String.format("__nonzero__ should return bool or int, returned %s",self_type.getName())); + } + return o.__nonzero__(); } public boolean __contains__(PyObject o) { @@ -1093,6 +1098,7 @@ if (res!=Py.None) { throw Py.TypeError(String.format("__init__() should return None, not '%.200s'",res.getType().fastGetName())); } + proxyInit(); } } } Modified: trunk/jython/src/org/python/antlr/ast/BoolOpDerived.java =================================================================== --- trunk/jython/src/org/python/antlr/ast/BoolOpDerived.java 2008-12-15 17:01:52 UTC (rev 5766) +++ trunk/jython/src/org/python/antlr/ast/BoolOpDerived.java 2008-12-15 17:04:17 UTC (rev 5767) @@ -793,7 +793,12 @@ if (impl==null) return super.__nonzero__(); } - return impl.__get__(this,self_type).__call__().__nonzero__(); + PyObject o=impl.__get__(this,self_type).__call__(); + Class c=o.getClass(); + if (c!=PyInteger.class&&c!=PyBoolean.class) { + throw Py.TypeError(String.format("__nonzero__ should return bool or int, returned %s",self_type.getName())); + } + return o.__nonzero__(); } public boolean __contains__(PyObject o) { @@ -1093,6 +1098,7 @@ if (res!=Py.None) { throw Py.TypeError(String.format("__init__() should return None, not '%.200s'",res.getType().fastGetName())); } + proxyInit(); } } } Modified: trunk/jython/src/org/python/antlr/ast/BreakDerived.java =================================================================== --- trunk/jython/src/org/python/antlr/ast/BreakDerived.java 2008-12-15 17:01:52 UTC (rev 5766) +++ trunk/jython/src/org/python/antlr/ast/BreakDerived.java 2008-12-15 17:04:17 UTC (rev 5767) @@ -793,7 +793,12 @@ if (impl==null) return super.__nonzero__(); } - return impl.__get__(this,self_type).__call__().__nonzero__(); + PyObject o=impl.__get__(this,self_type).__call__(); + Class c=o.getClass(); + if (c!=PyInteger.class&&c!=PyBoolean.class) { + throw Py.TypeError(String.format("__nonzero__ should return bool or int, returned %s",self_type.getName())); + } + return o.__nonzero__(); } public boolean __contains__(PyObject o) { @@ -1093,6 +1098,7 @@ if (res!=Py.None) { throw Py.TypeError(String.format("__init__() should return None, not '%.200s'",res.getType().fastGetName())); } + proxyInit(); } } } Modified: trunk/jython/src/org/python/antlr/ast/CallDerived.java =================================================================== --- trunk/jython/src/org/python/antlr/ast/CallDerived.java 2008-12-15 17:01:52 UTC (rev 5766) +++ trunk/jython/src/org/python/antlr/ast/CallDerived.java 2008-12-15 17:04:17 UTC (rev 5767) @@ -793,7 +793,12 @@ if (impl==null) return super.__nonzero__(); } - return impl.__get__(this,self_type).__call__().__nonzero__(); + PyObject o=impl.__get__(this,self_type).__call__(); + Class c=o.getClass(); + if (c!=PyInteger.class&&c!=PyBoolean.class) { + throw Py.TypeError(String.format("__nonzero__ should return bool or int, returned %s",self_type.getName())); + } + return o.__nonzero__(); } public boolean __contains__(PyObject o) { @@ -1093,6 +1098,7 @@ if (res!=Py.None) { throw Py.TypeError(String.format("__init__() should return None, not '%.200s'",res.getType().fastGetName())); } + proxyInit(); } } } Modified: trunk/jython/src/org/python/antlr/ast/ClassDefDerived.java =================================================================== --- trunk/jython/src/org/python/antlr/ast/ClassDefDerived.java 2008-12-15 17:01:52 UTC (rev 5766) +++ trunk/jython/src/org/python/antlr/ast/ClassDefDerived.java 2008-12-15 17:04:17 UTC (rev 5767) @@ -793,7 +793,12 @@ if (impl==null) return super.__nonzero__(); } - return impl.__get__(this,self_type).__call__().__nonzero__(); + PyObject o=impl.__get__(this,self_type).__call__(); + Class c=o.getClass(); + if (c!=PyInteger.class&&c!=PyBoolean.class) { + throw Py.TypeError(String.format("__nonzero__ should return bool or int, returned %s",self_type.getName())); + } + return o.__nonzero__(); } public boolean __contains__(PyObject o) { @@ -1093,6 +1098,7 @@ if (res!=Py.None) { throw Py.TypeError(String.format("__init__() should return None, not '%.200s'",res.getType().fastGetName())); } + proxyInit(); } } } Modified: trunk/jython/src/org/python/antlr/ast/CompareDerived.java =================================================================== --- trunk/jython/src/org/python/antlr/ast/CompareDerived.java 2008-12-15 17:01:52 UTC (rev 5766) +++ trunk/jython/src/org/python/antlr/ast/CompareDerived.java 2008-12-15 17:04:17 UTC (rev 5767) @@ -793,7 +793,12 @@ if (impl==null) return super.__nonzero__(); } - return impl.__get__(this,self_type).__call__().__nonzero__(); + PyObject o=impl.__get__(this,self_type).__call__(); + Class c=o.getClass(); + if (c!=PyInteger.class&&c!=PyBoolean.class) { + throw Py.TypeError(String.format("__nonzero__ should return bool or int, returned %s",self_type.getName())); + } + return o.__nonzero__(); } public boolean __contains__(PyObject o) { @@ -1093,6 +1098,7 @@ if (res!=Py.None) { throw Py.TypeError(String.format("__init__() should return None, not '%.200s'",res.getType().fastGetName())); } + proxyInit(); } } } Modified: trunk/jython/src/org/python/antlr/ast/ContinueDerived.java =================================================================== --- trunk/jython/src/org/python/antlr/ast/ContinueDerived.java 2008-12-15 17:01:52 UTC (rev 5766) +++ trunk/jython/src/org/python/antlr/ast/ContinueDerived.java 2008-12-15 17:04:17 UTC (rev 5767) @@ -793,7 +793,12 @@ if (impl==null) return super.__nonzero__(); } - return impl.__get__(this,self_type).__call__().__nonzero__(); + PyObject o=impl.__get__(this,self_type).__call__(); + Class c=o.getClass(); + if (c!=PyInteger.class&&c!=PyBoolean.class) { + throw Py.TypeError(String.format("__nonzero__ should return bool or int, returned %s",self_type.getName())); + } + return o.__nonzero__(); } public boolean __contains__(PyObject o) { @@ -1093,6 +1098,7 @@ if (res!=Py.None) { throw Py.TypeError(String.format("__init__() should return None, not '%.200s'",res.getType().fastGetName())); } + proxyInit(); } } } Modified: trunk/jython/src/org/python/antlr/ast/DeleteDerived.java =================================================================== --- trunk/jython/src/org/python/antlr/ast/DeleteDerived.java 2008-12-15 17:01:52 UTC (rev 5766) +++ trunk/jython/src/org/python/antlr/ast/DeleteDerived.java 2008-12-15 17:04:17 UTC (rev 5767) @@ -793,7 +793,12 @@ if (impl==null) return super.__nonzero__(); } - return impl.__get__(this,self_type).__call__().__nonzero__(); + PyObject o=impl.__get__(this,self_type).__call__(); + Class c=o.getClass(); + if (c!=PyInteger.class&&c!=PyBoolean.class) { + throw Py.TypeError(String.format("__nonzero__ should return bool or int, returned %s",self_type.getName())); + } + return o.__nonzero__(); } public boolean __contains__(PyObject o) { @@ -1093,6 +1098,7 @@ if (res!=Py.None) { throw Py.TypeError(String.format("__init__() should return None, not '%.200s'",res.getType().fastGetName())); } + proxyInit(); } } } Modified: trunk/jython/src/org/python/antlr/ast/DictDerived.java =================================================================== --- trunk/jython/src/org/python/antlr/ast/DictDerived.java 2008-12-15 17:01:52 UTC (rev 5766) +++ trunk/jython/src/org/python/antlr/ast/DictDerived.java 2008-12-15 17:04:17 UTC (rev 5767) @@ -793,7 +793,12 @@ if (impl==null) return super.__nonzero__(); } - return impl.__get__(this,self_type).__call__().__nonzero__(); + PyObject o=impl.__get__(this,self_type).__call__(); + Class c=o.getClass(); + if (c!=PyInteger.class&&c!=PyBoolean.class) { + throw Py.TypeError(String.format("__nonzero__ should return bool or int, returned %s",self_type.getName())); + } + return o.__nonzero__(); } public boolean __contains__(PyObject o) { @@ -1093,6 +1098,7 @@ if (res!=Py.None) { throw Py.TypeError(String.format("__init__() should return None, not '%.200s'",res.getType().fastGetName())); } + proxyInit(); } } } Modified: trunk/jython/src/org/python/antlr/ast/EllipsisDerived.java =================================================================== --- trunk/jython/src/org/python/antlr/ast/EllipsisDerived.java 2008-12-15 17:01:52 UTC (rev 5766) +++ trunk/jython/src/org/python/antlr/ast/EllipsisDerived.java 2008-12-15 17:04:17 UTC (rev 5767) @@ -793,7 +793,12 @@ if (impl==null) return super.__nonzero__(); } - return impl.__get__(this,self_type).__call__().__nonzero__(); + PyObject o=impl.__get__(this,self_type).__call__(); + Class c=o.getClass(); + if (c!=PyInteger.class&&c!=PyBoolean.class) { + throw Py.TypeError(String.format("__nonzero__ should return bool or int, returned %s",self_type.getName())); + } + return o.__nonzero__(); } public boolean __contains__(PyObject o) { @@ -1093,6 +1098,7 @@ if (res!=Py.None) { throw Py.TypeError(String.format("__init__() should return None, not '%.200s'",res.getType().fastGetName())); } + proxyInit(); } } } Modified: trunk/jython/src/org/python/antlr/ast/ExceptHandlerDerived.java =================================================================== --- trunk/jython/src/org/python/antlr/ast/ExceptHandlerDerived.java 2008-12-15 17:01:52 UTC (rev 5766) +++ trunk/jython/src/org/python/antlr/ast/ExceptHandlerDerived.java 2008-12-15 17:04:17 UTC (rev 5767) @@ -793,7 +793,12 @@ if (impl==null) return super.__nonzero__(); } - return impl.__get__(this,self_type).__call__().__nonzero__(); + PyObject o=impl.__get__(this,self_type).__call__(); + Class c=o.getClass(); + if (c!=PyInteger.class&&c!=PyBoolean.class) { + throw Py.TypeError(String.format("__nonzero__ should return bool or int, returned %s",self_type.getName())); + } + return o.__nonzero__(); } public boolean __contains__(PyObject o) { @@ -1093,6 +1098,7 @@ if (res!=Py.None) { throw Py.TypeError(String.format("__init__() should return None, not '%.200s'",res.getType().fastGetName())); } + proxyInit(); } } } Modified: trunk/jython/src/org/python/antlr/ast/ExecDerived.java =================================================================== --- trunk/jython/src/org/python/antlr/ast/ExecDerived.java 2008-12-15 17:01:52 UTC (rev 5766) +++ trunk/jython/src/org/python/antlr/ast/ExecDerived.java 2008-12-15 17:04:17 UTC (rev 5767) @@ -793,7 +793,12 @@ if (impl==null) return super.__nonzero__(); } - return impl.__get__(this,self_type).__call__().__nonzero__(); + PyObject o=impl.__get__(this,self_type).__call__(); + Class c=o.getClass(); + if (c!=PyInteger.class&&c!=PyBoolean.class) { + throw Py.TypeError(String.format("__nonzero__ should return bool or int, returned %s",self_type.getName())); + } + return o.__nonzero__(); } public boolean __contains__(PyObject o) { @@ -1093,6 +1098,7 @@ if (res!=Py.None) { throw Py.TypeError(String.format("__init__() should return None, not '%.200s'",res.getType().fastGetName())); } + proxyInit(); } } } Modified: trunk/jython/src/org/python/antlr/ast/ExprDerived.java =================================================================== --- trunk/jython/src/org/python/antlr/ast/ExprDerived.java 2008-12-15 17:01:52 UTC (rev 5766) +++ trunk/jython/src/org/python/antlr/ast/ExprDerived.java 2008-12-15 17:04:17 UTC (rev 5767) @@ -793,7 +793,12 @@ if (impl==null) return super.__nonzero__(); } - return impl.__get__(this,self_type).__call__().__nonzero__(); + PyObject o=impl.__get__(this,self_type).__call__(); + Class c=o.getClass(); + if (c!=PyInteger.class&&c!=PyBoolean.class) { + throw Py.TypeError(String.format("__nonzero__ should return bool or int, returned %s",self_type.getName())); + } + return o.__nonzero__(); } public boolean __contains__(PyObject o) { @@ -1093,6 +1098,7 @@ if (res!=Py.None) { throw Py.TypeError(String.format("__init__() should return None, not '%.200s'",res.getType().fastGetName())); } + proxyInit(); } } } Modified: trunk/jython/src/org/python/antlr/ast/ExpressionDerived.java =================================================================== --- trunk/jython/src/org/python/antlr/ast/ExpressionDerived.java 2008-12-15 17:01:52 UTC (rev 5766) +++ trunk/jython/src/org/python/antlr/ast/ExpressionDerived.java 2008-12-15 17:04:17 UTC (rev 5767) @@ -793,7 +793,12 @@ if (impl==null) return super.__nonzero__(); } - return impl.__get__(this,self_type).__call__().__nonzero__(); + PyObject o=impl.__get__(this,self_type).__call__(); + Class c=o.getClass(); + if (c!=PyInteger.class&&c!=PyBoolean.class) { + throw Py.TypeError(String.format("__nonzero__ should return bool or int, returned %s",self_type.getName())); + } + return o.__nonzero__(); } public boolean __contains__(PyObject o) { @@ -1093,6 +1098,7 @@ if (res!=Py.None) { throw Py.TypeError(String.format("__init__() should return None, not '%.200s'",res.getType().fastGetName())); } + proxyInit(); } } } Modified: trunk/jython/src/org/python/antlr/ast/ExtSliceDerived.java =================================================================== --- trunk/jython/src/org/python/antlr/ast/ExtSliceDerived.java 2008-12-15 17:01:52 UTC (rev 5766) +++ trunk/jython/src/org/python/antlr/ast/ExtSliceDerived.java 2008-12-15 17:04:17 UTC (rev 5767) @@ -793,7 +793,12 @@ if (impl==null) return super.__nonzero__(); } - return impl.__get__(this,self_type).__call__().__nonzero__(); + PyObject o=impl.__get__(this,self_type).__call__(); + Class c=o.getClass(); + if (c!=PyInteger.class&&c!=PyBoolean.class) { + throw Py.TypeError(String.format("__nonzero__ should return bool or int, returned %s",self_type.getName())); + } + return o.__nonzero__(); } public boolean __contains__(PyObject o) { @@ -1093,6 +1098,7 @@ if (res!=Py.None) { throw Py.TypeError(String.format("__init__() should return None, not '%.200s'",res.getType().fastGetName())); } + proxyInit(); } } } Modified: trunk/jython/src/org/python/antlr/ast/ForDerived.java =================================================================== --- trunk/jython/src/org/python/antlr/ast/ForDerived.java 2008-12-15 17:01:52 UTC (rev 5766) +++ trunk/jython/src/org/python/antlr/ast/ForDerived.java 2008-12-15 17:04:17 UTC (rev 5767) @@ -793,7 +793,12 @@ if (impl==null) return super.__nonzero__(); } - return impl.__get__(this,self_type).__call__().__nonzero__(); + PyObject o=impl.__get__(this,self_type).__call__(); + Class c=o.getClass(); + if (c!=PyInteger.class&&c!=PyBoolean.class) { + throw Py.TypeError(String.format("__nonzero__ should return bool or int, returned %s",self_type.getName())); + } + return o.__nonzero__(); } public boolean __contains__(PyObject o) { @@ -1093,6 +1098,7 @@ if (res!=Py.None) { throw Py.TypeError(String.format("__init__() should return None, not '%.200s'",res.getType().fastGetName())); } + proxyInit(); } } } Modified: trunk/jython/src/org/python/antlr/ast/FunctionDefDerived.java =================================================================== --- trunk/jython/src/org/python/antlr/ast/FunctionDefDerived.java 2008-12-15 17:01:52 UTC (rev 5766) +++ trunk/jython/src/org/python/antlr/ast/FunctionDefDerived.java 2008-12-15 17:04:17 UTC (rev 5767) @@ -793,7 +793,12 @@ if (impl==null) return super.__nonzero__(); } - return impl.__get__(this,self_type).__call__().__nonzero__(); + PyObject o=impl.__get__(this,self_type).__call__(); + Class c=o.getClass(); + if (c!=PyInteger.class&&c!=PyBoolean.class) { + throw Py.TypeError(String.format("__nonzero__ should return bool or int, returned %s",self_type.getName())); + } + return o.__nonzero__(); } public boolean __contains__(PyObject o) { @@ -1093,6 +1098,7 @@ if (res!=Py.None) { throw Py.TypeError(String.format("__init__() should return None, not '%.200s'",res.getType().fastGetName())); } + proxyInit(); } } } Modified: trunk/jython/src/org/python/antlr/ast/GeneratorExpDerived.java =================================================================== --- trunk/jython/src/org/python/antlr/ast/GeneratorExpDerived.java 2008-12-15 17:01:52 UTC (rev 5766) +++ trunk/jython/src/org/python/antlr/ast/GeneratorExpDerived.java 2008-12-15 17:04:17 UTC (rev 5767) @@ -793,7 +793,12 @@ if (impl==null) return super.__nonzero__(); } - return impl.__get__(this,self_type).__call__().__nonzero__(); + PyObject o=impl.__get__(this,self_type).__call__(); + Class c=o.getClass(); + if (c!=PyInteger.class&&c!=PyBoolean.class) { + throw Py.TypeError(String.format("__nonzero__ should return bool or int, returned %s",self_type.getName())); + } + return o.__nonzero__(); } public boolean __contains__(PyObject o) { @@ -1093,6 +1098,7 @@ if (res!=Py.None) { throw Py.TypeError(String.format("__init__() should return None, not '%.200s'",res.getType().fastGetName())); } + proxyInit(); } } } Modified: trunk/jython/src/org/python/antlr/ast/GlobalDerived.java =================================================================== --- trunk/jython/src/org/python/antlr/ast/GlobalDerived.java 2008-12-15 17:01:52 UTC (rev 5766) +++ trunk/jython/src/org/python/antlr/ast/GlobalDerived.java 2008-12-15 17:04:17 UTC (rev 5767) @@ -793,7 +793,12 @@ if (impl==null) return super.__nonzero__(); } - return impl.__get__(this,self_type).__call__().__nonzero__(); + PyObject o=impl.__get__(this,self_type).__call__(); + Class c=o.getClass(); + if (c!=PyInteger.class&&c!=PyBoolean.class) { + throw Py.TypeError(String.format("__nonzero__ should return bool or int, returned %s",self_type.getName())); + } + return o.__nonzero__(); } public boolean __contains__(PyObject o) { @@ -1093,6 +1098,7 @@ if (res!=Py.None) { throw Py.TypeError(String.format("__init__() should return None, not '%.200s'",res.getType().fastGetName())); } + proxyInit(); } } } Modified: trunk/jython/src/org/python/antlr/ast/IfDerived.java =================================================================== --- trunk/jython/src/org/python/antlr/ast/IfDerived.java 2008-12-15 17:01:52 UTC (rev 5766) +++ trunk/jython/src/org/python/antlr/ast/IfDerived.java 2008-12-15 17:04:17 UTC (rev 5767) @@ -793,7 +793,12 @@ if (impl==null) return super.__nonzero__(); } - return impl.__get__(this,self_type).__call__().__nonzero__(); + PyObject o=impl.__get__(this,self_type).__call__(); + Class c=o.getClass(); + if (c!=PyInteger.class&&c!=PyBoolean.class) { + throw Py.TypeError(String.format("__nonzero__ should return bool or int, returned %s",self_type.getName())); + } + return o.__nonzero__(); } public boolean __contains__(PyObject o) { @@ -1093,6 +1098,7 @@ if (res!=Py.None) { throw Py.TypeError(String.format("__init__() should return None, not '%.200s'",res.getType().fastGetName())); } + proxyInit(); } } } Modified: trunk/jython/src/org/python/antlr/ast/IfExpDerived.java =================================================================== --- trunk/jython/src/org/python/antlr/ast/IfExpDerived.java 2008-12-15 17:01:52 UTC (rev 5766) +++ trunk/jython/src/org/python/antlr/ast/IfExpDerived.java 2008-12-15 17:04:17 UTC (rev 5767) @@ -793,7 +793,12 @@ if (impl==null) return super.__nonzero__(); } - return impl.__get__(this,self_type).__call__().__nonzero__(); + PyObject o=impl.__get__(this,self_type).__call__(); + Class c=o.getClass(); + if (c!=PyInteger.class&&c!=PyBoolean.class) { + throw Py.TypeError(String.format("__nonzero__ should return bool or int, returned %s",self_type.getName())); + } + return o.__nonzero__(); } public boolean __contains__(PyObject o) { @@ -1093,6 +1098,7 @@ if (res!=Py.None) { throw Py.TypeError(String.format("__init__() should return None, not '%.200s'",res.getType().fastGetName())); } + proxyInit(); } } } Modified: trunk/jython/src/org/python/antlr/ast/ImportDerived.java =================================================================== --- trunk/jython/src/org/python/antlr/ast/ImportDerived.java 2008-12-15 17:01:52 UTC (rev 5766) +++ trunk/jython/src/org/python/antlr/ast/ImportDerived.java 2008-12-15 17:04:17 UTC (rev 5767) @@ -793,7 +793,12 @@ if (impl==null) return super.__nonzero__(); } - return impl.__get__(this,self_type).__call__().__nonzero__(); + PyObject o=impl.__get__(this,self_type).__call__(); + Class c=o.getClass(); + if (c!=PyInteger.class&&c!=PyBoolean.class) { + throw Py.TypeError(String.format("__nonzero__ should return bool or int, returned %s",self_type.getName())); + } + return o.__nonzero__(); } public boolean __contains__(PyObject o) { @@ -1093,6 +1098,7 @@ if (res!=Py.None) { throw Py.TypeError(String.format("__init__() should return None, not '%.200s'",res.getType().fastGetName())); } + proxyInit(); } } } Modified: trunk/jython/src/org/python/antlr/ast/ImportFromDerived.java =================================================================== --- trunk/jython/src/org/python/antlr/ast/ImportFromDerived.java 2008-12-15 17:01:52 UTC (rev 5766) +++ trunk/jython/src/org/python/antlr/ast/ImportFromDerived.java 2008-12-15 17:04:17 UTC (rev 5767) @@ -793,7 +793,12 @@ if (impl==null) return super.__nonzero__(); } - return impl.__get__(this,self_type).__call__().__nonzero__(); + PyObject o=impl.__get__(this,self_type).__call__(); + Class c=o.getClass(); + if (c!=PyInteger.class&&c!=PyBoolean.class) { + throw Py.TypeError(String.format("__nonzero__ should return bool or int, returned %s",self_type.getName())); + } + return o.__nonzero__(); } public boolean __contains__(PyObject o) { @@ -1093,6 +1098,7 @@ if (res!=Py.None) { throw Py.TypeError(String.format("__init__() should return None, not '%.200s'",res.getType().fastGetName())); } + proxyInit(); } } } Modified: trunk/jython/src/org/python/antlr/ast/IndexDerived.java =================================================================== --- trunk/jython/src/org/python/antlr/ast/IndexDerived.java 2008-12-15 17:01:52 UTC (rev 5766) +++ trunk/jython/src/org/python/antlr/ast/IndexDerived.java 2008-12-15 17:04:17 UTC (rev 5767) @@ -793,7 +793,12 @@ if (impl==null) return super.__nonzero__(); } - return impl.__get__(this,self_type).__call__().__nonzero__(); + PyObject o=impl.__get__(this,self_type).__call__(); + Class c=o.getClass(); + if (c!=PyInteger.class&&c!=PyBoolean.class) { + throw Py.TypeError(String.format("__nonzero__ should return bool or int, returned %s",self_type.getName())); + } + return o.__nonzero__(); } public boolean __contains__(PyObject o) { @@ -1093,6 +1098,7 @@ if (res!=Py.None) { throw Py.TypeError(String.format("__init__() should return None, not '%.200s'",res.getType().fastGetName())); } + proxyInit(); } } } Modified: trunk/jython/src/org/python/antlr/ast/InteractiveDerived.java =================================================================== --- trunk/jython/src/org/python/antlr/ast/InteractiveDerived.java 2008-12-15 17:01:52 UTC (rev 5766) +++ trunk/jython/src/org/python/antlr/ast/InteractiveDerived.java 2008-12-15 17:04:17 UTC (rev 5767) @@ -793,7 +793,12 @@ if (impl==null) return super.__nonzero__(); } - return impl.__get__(this,self_type).__call__().__nonzero__(); + PyObject o=impl.__get__(this,self_type).__call__(); + Class c=o.getClass(); + if (c!=PyInteger.class&&c!=PyBoolean.class) { + throw Py.TypeError(String.format("__nonzero__ should return bool or int, returned %s",self_type.getName())); + } + return o.__nonzero__(); } public boolean __contains__(PyObject o) { @@ -1093,6 +1098,7 @@ if (res!=Py.None) { throw Py.TypeError(String.format("__init__() should return None, not '%.200s'",res.getType().fastGetName())); } + proxyInit(); } } } Modified: trunk/jython/src/org/python/antlr/ast/LambdaDerived.java =================================================================== --- trunk/jython/src/org/python/antlr/ast/LambdaDerived.java 2008-12-15 17:01:52 UTC (rev 5766) +++ trunk/jython/src/org/python/antlr/ast/LambdaDerived.java 2008-12-15 17:04:17 UTC (rev 5767) @@ -793,7 +793,12 @@ if (impl==null) return super.__nonzero__(); } - return impl.__get__(this,self_type).__call__().__nonzero__(); + PyObject o=impl.__get__(this,self_type).__call__(); + Class c=o.getClass(); + if (c!=PyInteger.class&&c!=PyBoolean.class) { + throw Py.TypeError(String.format("__nonzero__ should return bool or int, returned %s",self_type.getName())); + } + return o.__nonzero__(); } public boolean __contains__(PyObject o) { @@ -1093,6 +1098,7 @@ if (res!=Py.None) { throw Py.TypeError(String.format("__init__() should return None, not '%.200s'",res.getType().fastGetName())); } + proxyInit(); } } } Modified: trunk/jython/src/org/python/antlr/ast/ListCompDerived.java =================================================================== --- trunk/jython/src/org/python/antlr/ast/ListCompDerived.java 2008-12-15 17:01:52 UTC (rev 5766) +++ trunk/jython/src/org/python/antlr/ast/ListCompDerived.java 2008-12-15 17:04:17 UTC (rev 5767) @@ -793,7 +793,12 @@ if (impl==null) return super.__nonzero__(); } - return impl.__get__(this,self_type).__call__().__nonzero__(); + PyObject o=impl.__get__(this,self_type).__call__(); + Class c=o.getClass(); + if (c!=PyInteger.class&&c!=PyBoolean.class) { + throw Py.TypeError(String.format("__nonzero__ should return bool or int, returned %s",self_type.getName())); + } + return o.__nonzero__(); } public boolean __contains__(PyObject o) { @@ -1093,6 +1098,7 @@ if (res!=Py.None) { throw Py.TypeError(String.format("__init__() should return None, not '%.200s'",res.getType().fastGetName())); } + proxyInit(); } } } Modified: trunk/jython/src/org/python/antlr/ast/ListDerived.java =================================================================== --- trunk/jython/src/org/python/antlr/ast/ListDerived.java 2008-12-15 17:01:52 UTC (rev 5766) +++ trunk/jython/src/org/python/antlr/ast/ListDerived.java 2008-12-15 17:04:17 UTC (rev 5767) @@ -793,7 +793,12 @@ if (impl==null) return super.__nonzero__(); } - return impl.__get__(this,self_type).__call__().__nonzero__(); + PyObject o=impl.__get__(this,self_type).__call__(); + Class c=o.getClass(); + if (c!=PyInteger.class&&c!=PyBoolean.class) { + throw Py.TypeError(String.format("__nonzero__ should return bool or int, returned %s",self_type.getName())); + } + return o.__nonzero__(); } public boolean __contains__(PyObject o) { @@ -1093,6 +1098,7 @@ if (res!=Py.None) { throw Py.TypeError(String.format("__init__() should return None, not '%.200s'",res.getType().fastGetName())); } + proxyInit(); } } } Modified: trunk/jython/src/org/python/antlr/ast/ModuleDerived.java =================================================================== --- trunk/jython/src/org/python/antlr/ast/ModuleDerived.java 2008-12-15 17:01:52 UTC (rev 5766) +++ trunk/jython/src/org/python/antlr/ast/ModuleDerived.java 2008-12-15 17:04:17 UTC (rev 5767) @@ -793,7 +793,12 @@ if (impl==null) return super.__nonzero__(); } - return impl.__get__(this,self_type).__call__().__nonzero__(); + PyObject o=impl.__get__(this,self_type).__call__(); + Class c=o.getClass(); + if (c!=PyInteger.class&&c!=PyBoolean.class) { + throw Py.TypeError(String.format("__nonzero__ should return bool or int, returned %s",self_type.getName())); + } + return o.__nonzero__(); } public boolean __contains__(PyObject o) { @@ -1093,6 +1098,7 @@ if (res!=Py.None) { throw Py.TypeError(String.format("__init__() should return None, not '%.200s'",res.getType().fastGetName())); } + proxyInit(); } } } Modified: trunk/jython/src/org/python/antlr/ast/NameDerived.java =================================================================== --- trunk/jython/src/org/python/antlr/ast/NameDerived.java 2008-12-15 17:01:52 UTC (rev 5766) +++ trunk/jython/src/org/python/antlr/ast/NameDerived.java 2008-12-15 17:04:17 UTC (rev 5767) @@ -793,7 +793,12 @@ if (impl==null) return super.__nonzero__(); } - return impl.__get__(this,self_type).__call__().__nonzero__(); + PyObject o=impl.__get__(this,self_type).__call__(); + Class c=o.getClass(); + if (c!=PyInteger.class&&c!=PyBoolean.class) { + throw Py.TypeError(String.format("__nonzero__ should return bool or int, returned %s",self_type.getName())); + } + return o.__nonzero__(); } public boolean __contains__(PyObject o) { @@ -1093,6 +1098,7 @@ if (res!=Py.None) { throw Py.TypeError(String.format("__init__() should return None, not '%.200s'",res.getType().fastGetName())); } + proxyInit(); ... [truncated message content] |
From: <pj...@us...> - 2008-12-15 19:14:44
|
Revision: 5768 http://jython.svn.sourceforge.net/jython/?rev=5768&view=rev Author: pjenvey Date: 2008-12-15 19:14:40 +0000 (Mon, 15 Dec 2008) Log Message: ----------- update to jna-posix 76492a187ed8 for the utimes API change for large 64 bit timestamps fixes #1166 Modified Paths: -------------- trunk/jython/Lib/os.py trunk/jython/extlibs/jna-posix.jar Modified: trunk/jython/Lib/os.py =================================================================== --- trunk/jython/Lib/os.py 2008-12-15 17:04:17 UTC (rev 5767) +++ trunk/jython/Lib/os.py 2008-12-15 19:14:40 UTC (rev 5768) @@ -170,6 +170,9 @@ # successful termination EX_OK = 0 +# Java class representing the size of a time_t. internal use, lazily set +_time_t = None + class stat_result: _stat_members = ( @@ -537,13 +540,40 @@ if path is None: raise TypeError('path must be specified, not None') - if times is not None: - atime, mtime = times + if times is None: + atimeval = mtimeval = None + elif isinstance(times, tuple) and len(times) == 2: + atimeval = _to_timeval(times[0]) + mtimeval = _to_timeval(times[1]) else: - atime = mtime = time.time() + raise TypeError('utime() arg 2 must be a tuple (atime, mtime)') - _posix.utimes(path, long(atime * 1000), long(mtime * 1000)) + _posix.utimes(path, atimeval, mtimeval) +def _to_timeval(seconds): + """Convert seconds (with a fraction) from epoch to a 2 item tuple of + seconds, microseconds from epoch as longs + """ + global _time_t + if _time_t is None: + from java.lang import Integer, Long + from org.python.posix.util import Platform + _time_t = Integer if Platform.IS_32_BIT else Long + + try: + floor = long(seconds) + except TypeError: + raise TypeError('an integer is required') + if floor < _time_t.MIN_VALUE or floor > _time_t.MAX_VALUE: + raise OverflowError('long int too large to convert to int') + + # usec can't exceed 1000000 + usec = long((seconds - floor) * 1e6) + if usec < 0: + # If rounding gave us a negative number, truncate + usec = 0 + return floor, usec + def close(fd): """close(fd) Modified: trunk/jython/extlibs/jna-posix.jar =================================================================== (Binary files differ) This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |