From: <pj...@us...> - 2008-10-11 06:42:42
|
Revision: 5372 http://jython.svn.sourceforge.net/jython/?rev=5372&view=rev Author: pjenvey Date: 2008-10-11 06:42:35 +0000 (Sat, 11 Oct 2008) Log Message: ----------- fix solid_base potentially resolving the wrong type when called before the mro was initialized. caused best_base to blowup with a TypeError Modified Paths: -------------- trunk/jython/Lib/test/test_class_jy.py trunk/jython/src/org/python/core/PyType.java Modified: trunk/jython/Lib/test/test_class_jy.py =================================================================== --- trunk/jython/Lib/test/test_class_jy.py 2008-10-11 05:08:23 UTC (rev 5371) +++ trunk/jython/Lib/test/test_class_jy.py 2008-10-11 06:42:35 UTC (rev 5372) @@ -152,7 +152,17 @@ keys.sort() self.assertEqual(str(keys), "['__doc__', '__module__', 'moo']") + def test_metaclass_and_slotted_base(self): + class Meta(type): + pass + class SlottedBase(object): + __slots__ = 'foo' + # A regression up until 2.5a3: Defining Bar would cause a + # TypeError "mro() returned base with unsuitable layout ('Bar')" + class Bar(SlottedBase): + __metaclass__ = Meta + class ClassNamelessModuleTestCase(unittest.TestCase): def setUp(self): @@ -298,6 +308,7 @@ class Bar(object): self.assertEqual(__module__, module_name) + class ClassMetaclassRepr(unittest.TestCase): """Verifies #1131 is fixed""" def test_repr_with_metaclass(self): Modified: trunk/jython/src/org/python/core/PyType.java =================================================================== --- trunk/jython/src/org/python/core/PyType.java 2008-10-11 05:08:23 UTC (rev 5371) +++ trunk/jython/src/org/python/core/PyType.java 2008-10-11 06:42:35 UTC (rev 5372) @@ -47,7 +47,7 @@ private PyObject dict; /** __mro__, the method resolution. order */ - private PyObject[] mro = new PyObject[0]; + private PyObject[] mro = null; /** __flags__, the type's options. */ private long tp_flags; @@ -645,7 +645,7 @@ @ExposedGet(name = "__mro__") public PyTuple getMro() { - return new PyTuple(mro); + return mro == null ? Py.EmptyTuple : new PyTuple(mro); } @ExposedGet(name = "__flags__") @@ -929,11 +929,24 @@ public boolean isSubType(PyType supertype) { PyObject[] mro = this.mro; - for (int i = 0; i < mro.length; i++) { - if (mro[i] == supertype) + if (mro != null) { + for (PyObject base : mro) { + if (base == supertype) { + return true; + } + } + return false; + } + + // we're not completely initilized yet; follow tp_base + PyType type = this; + do { + if (type == supertype) { return true; - } - return false; + } + type = type.base; + } while (type != null); + return supertype == PyObject.TYPE; } /** @@ -945,6 +958,9 @@ */ public PyObject lookup(String name) { PyObject[] mro = this.mro; + if (mro == null) { + return null; + } for (int i = 0; i < mro.length; i++) { PyObject dict = mro[i].fastGetDict(); if (dict != null) { @@ -958,6 +974,9 @@ public PyObject lookup_where(String name, PyObject[] where) { PyObject[] mro = this.mro; + if (mro == null) { + return null; + } for (int i = 0; i < mro.length; i++) { PyObject t = mro[i]; PyObject dict = t.fastGetDict(); @@ -974,6 +993,9 @@ public PyObject super_lookup(PyType ref, String name) { PyObject[] mro = this.mro; + if (mro == null) { + return null; + } int i; for (i = 0; i < mro.length; i++) { if (mro[i] == ref) @@ -1235,6 +1257,9 @@ protected void __rawdir__(PyDictionary accum) { PyObject[] mro = this.mro; + if (mro == null) { + return; + } for (int i = 0; i < mro.length; i++) { mro[i].addKeys(accum, "__dict__"); } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <zy...@us...> - 2008-10-12 00:24:36
|
Revision: 5377 http://jython.svn.sourceforge.net/jython/?rev=5377&view=rev Author: zyasoft Date: 2008-10-12 00:24:30 +0000 (Sun, 12 Oct 2008) Log Message: ----------- Implemented struct.Struct as well as other updates in the struct module for 2.5 Modified Paths: -------------- trunk/jython/CoreExposed.includes trunk/jython/Lib/test/test_struct.py trunk/jython/src/org/python/core/PyArray.java trunk/jython/src/org/python/core/__builtin__.java trunk/jython/src/org/python/modules/struct.java Modified: trunk/jython/CoreExposed.includes =================================================================== --- trunk/jython/CoreExposed.includes 2008-10-12 00:18:38 UTC (rev 5376) +++ trunk/jython/CoreExposed.includes 2008-10-12 00:24:30 UTC (rev 5377) @@ -52,4 +52,5 @@ org/python/modules/thread/PyLocal.class org/python/modules/time/PyTimeTuple.class org/python/modules/zipimport/zipimporter.class +org/python/modules/PyStruct.class org/python/modules/PyTeeIterator.class Modified: trunk/jython/Lib/test/test_struct.py =================================================================== --- trunk/jython/Lib/test/test_struct.py 2008-10-12 00:18:38 UTC (rev 5376) +++ trunk/jython/Lib/test/test_struct.py 2008-10-12 00:24:30 UTC (rev 5377) @@ -1,9 +1,15 @@ -from test.test_support import TestFailed, verbose, verify, vereq +from test.test_support import TestFailed, verbose, verify, vereq, is_jython import test.test_support import struct import array import warnings +if is_jython: + # currently no buffer type, but this will work fine for this testing + def buffer(s): + return str(s) + + import sys ISBIGENDIAN = sys.byteorder == "big" del sys Modified: trunk/jython/src/org/python/core/PyArray.java =================================================================== --- trunk/jython/src/org/python/core/PyArray.java 2008-10-12 00:18:38 UTC (rev 5376) +++ trunk/jython/src/org/python/core/PyArray.java 2008-10-12 00:24:30 UTC (rev 5377) @@ -1393,6 +1393,23 @@ Array.set(data, i, o); } + // xxx - add more efficient comparable typecode lookup via an enumset, and expand + public void set(int i, int value) { + if ("u".equals(typecode) || type == Integer.TYPE || type == Long.TYPE) { + Array.setInt(data, i, value); + } else { + throw Py.TypeError("Type not compatible with array type"); + } + } + + public void set(int i, char value) { + if ("c".equals(typecode) || type == Integer.TYPE || type == Long.TYPE) { + Array.setChar(data, i, value); + } else { + throw Py.TypeError("Type not compatible with array type"); + } + } + private boolean isSigned() { return typecode.length() == 1 && typecode.equals(typecode.toUpperCase()); } Modified: trunk/jython/src/org/python/core/__builtin__.java =================================================================== --- trunk/jython/src/org/python/core/__builtin__.java 2008-10-12 00:18:38 UTC (rev 5376) +++ trunk/jython/src/org/python/core/__builtin__.java 2008-10-12 00:24:30 UTC (rev 5377) @@ -1233,6 +1233,7 @@ abstract class ExtendedBuiltinFunction extends PyObject { public static final PyType TYPE = PyType.fromClass(PyBuiltinFunction.class); @ExposedGet(name = "__class__") + @Override public PyType getType() { return TYPE; } Modified: trunk/jython/src/org/python/modules/struct.java =================================================================== --- trunk/jython/src/org/python/modules/struct.java 2008-10-12 00:18:38 UTC (rev 5376) +++ trunk/jython/src/org/python/modules/struct.java 2008-10-12 00:24:30 UTC (rev 5377) @@ -20,6 +20,13 @@ import org.python.core.PyTuple; import java.math.BigInteger; +import java.util.Arrays; +import org.python.core.ClassDictInit; +import org.python.core.PyArray; +import org.python.core.PyType; +import org.python.expose.ExposedGet; +import org.python.expose.ExposedNew; +import org.python.expose.ExposedType; /** * This module performs conversions between Python values and C @@ -399,11 +406,17 @@ } ByteStream(String s) { - int l = s.length(); + this(s, 0); + } + + ByteStream(String s, int offset) { + int l = s.length() - offset; data = new char[l]; - s.getChars(0, l, data, 0); + s.getChars(offset, s.length(), data, 0); len = l; pos = 0; + +// System.out.println("s.length()=" + s.length() + ",offset=" + offset + ",l=" + l + ",data=" + Arrays.toString(data)); } int readByte() { @@ -874,7 +887,7 @@ - private static FormatDef[] whichtable(String pfmt) { + static FormatDef[] whichtable(String pfmt) { char c = pfmt.charAt(0); switch (c) { case '<' : @@ -913,7 +926,7 @@ - private static int calcsize(String format, FormatDef[] f) { + static int calcsize(String format, FormatDef[] f) { int size = 0; int len = format.length(); @@ -973,10 +986,43 @@ FormatDef[] f = whichtable(format); int size = calcsize(format, f); + + return pack(format, f, size, 1, args).toString(); + } + + // xxx - may need to consider doing a generic arg parser here + static public void pack_into(PyObject[] args) { + if (args.length < 3) + Py.TypeError("illegal argument type for built-in operation"); + String format = args[0].toString(); + FormatDef[] f = whichtable(format); + int size = calcsize(format, f); + pack_into(format, f, size, 1, args); + } + + static void pack_into(String format, FormatDef[] f, int size, int argstart, PyObject[] args) { + if (args.length - argstart < 2) + Py.TypeError("illegal argument type for built-in operation"); + if (!(args[argstart] instanceof PyArray)) { + throw Py.TypeError("pack_into takes an array arg"); // as well as a buffer, what else? + } + PyArray buffer = (PyArray)args[argstart]; + int offset = args[argstart + 1].__int__().asInt(); + ByteStream res = pack(format, f, size, argstart + 2, args); + if (res.pos > buffer.__len__()) { + throw StructError("pack_into requires a buffer of at least " + res.pos + " bytes, got " + buffer.__len__()); + } + for (int i = 0; i < res.pos; i++, offset++) { + char val = res.data[i]; + buffer.set(offset, val); + } + } + + static ByteStream pack(String format, FormatDef[] f, int size, int start, PyObject[] args) { ByteStream res = new ByteStream(); - int i = 1; + int i = start; int len = format.length(); for (int j = 0; j < len; j++) { char c = format.charAt(j); @@ -995,7 +1041,7 @@ FormatDef e = getentry(c, f); - // Fill padd bytes with zeros + // Fill pad bytes with zeros int nres = align(res.size(), e) - res.size(); while (nres-- > 0) res.writeByte(0); @@ -1005,7 +1051,7 @@ if (i < args.length) throw StructError("too many arguments for pack format"); - return res.toString(); + return res; } @@ -1017,19 +1063,41 @@ * The string must contain exactly the amount of data required by * the format (i.e. len(string) must equal calcsize(fmt)). */ + public static PyTuple unpack(String format, String string) { + FormatDef[] f = whichtable(format); + int size = calcsize(format, f); int len = string.length(); - + if (size != len) + throw StructError("unpack str size does not match format"); + return unpack(f, size, format, new ByteStream(string)); + } + + public static PyTuple unpack(String format, PyArray buffer) { + String string = buffer.tostring(); FormatDef[] f = whichtable(format); int size = calcsize(format, f); - - if (size != len) + int len = string.length(); + if (size != len) throw StructError("unpack str size does not match format"); - + return unpack(f, size, format, new ByteStream(string)); + } + + public static PyTuple unpack_from(String format, String string) { + return unpack_from(format, string, 0); + } + + public static PyTuple unpack_from(String format, String string, int offset) { + FormatDef[] f = whichtable(format); + int size = calcsize(format, f); + int len = string.length(); + if (size >= (len - offset + 1)) + throw StructError("unpack_from str size does not match format"); + return unpack(f, size, format, new ByteStream(string, offset)); + } + + static PyTuple unpack(FormatDef[] f, int size, String format, ByteStream str) { PyList res = new PyList(); - - ByteStream str = new ByteStream(string); - int flen = format.length(); for (int j = 0; j < flen; j++) { char c = format.charAt(j); @@ -1057,8 +1125,7 @@ } - - private static PyException StructError(String explanation) { + static PyException StructError(String explanation) { return new PyException(error, explanation); } @@ -1067,4 +1134,9 @@ dict.__setitem__("__module__", new PyString("struct")); return dict; } + + public static PyStruct Struct(PyObject[] args, String[] keywords) { + return new PyStruct(args, keywords); + } } + This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <fwi...@us...> - 2008-10-13 17:19:51
|
Revision: 5384 http://jython.svn.sourceforge.net/jython/?rev=5384&view=rev Author: fwierzbicki Date: 2008-10-13 17:19:47 +0000 (Mon, 13 Oct 2008) Log Message: ----------- Fixed issue http://bugs.jython.org/issue1111: keyword arguments not supported on __import__ Modified Paths: -------------- trunk/jython/NEWS trunk/jython/src/org/python/core/__builtin__.java Modified: trunk/jython/NEWS =================================================================== --- trunk/jython/NEWS 2008-10-12 23:00:34 UTC (rev 5383) +++ trunk/jython/NEWS 2008-10-13 17:19:47 UTC (rev 5384) @@ -1,6 +1,9 @@ Jython NEWS Jython 2.5 + Bugs fixed (new numbering due to move to Roundup) + - [ 1111 ] keyword arguments not supported on __import__ + Incompatible Changes - The python.prepath property has been removed; use python.path instead. - To implement the Java Map interface, PyDictionary.values now returns a Modified: trunk/jython/src/org/python/core/__builtin__.java =================================================================== --- trunk/jython/src/org/python/core/__builtin__.java 2008-10-12 23:00:34 UTC (rev 5383) +++ trunk/jython/src/org/python/core/__builtin__.java 2008-10-13 17:19:47 UTC (rev 5384) @@ -1268,24 +1268,14 @@ "is the number of parent directories to search relative to the current module."); } -// public ImportFunction() { -// } - public PyObject __call__(PyObject args[], String keywords[]) { - if (!(args.length < 1 || args[0] instanceof PyString)) { - throw Py.TypeError("first argument must be a string"); - } - if (keywords.length > 0) { - throw Py.TypeError("__import__() takes no keyword arguments"); - } + ArgParser ap = new ArgParser("__import__", args, keywords, new String[]{"name", "globals", "locals", "fromlist", "level"}, 1); - int argc = args.length; - String module = args[0].__str__().toString(); + String module = ap.getString(0); + PyObject globals = ap.getPyObject(1, null); + PyObject fromlist = ap.getPyObject(3, Py.EmptyTuple); + int level = ap.getInt(4, imp.DEFAULT_LEVEL); - PyObject globals = (argc > 1 && args[1] != null) ? args[1] : null; - PyObject fromlist = (argc > 3 && args[3] != null) ? args[3] : Py.EmptyTuple; - int level = (argc > 4 && args[4] != null) ? Py.py2int(args[4]) : imp.DEFAULT_LEVEL; - return load(module, globals, fromlist, level); } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <le...@us...> - 2008-10-14 03:20:21
|
Revision: 5390 http://jython.svn.sourceforge.net/jython/?rev=5390&view=rev Author: leosoto Date: 2008-10-14 03:20:10 +0000 (Tue, 14 Oct 2008) Log Message: ----------- Now String is mapped to PyUnicode on ClassicPyObjectAdapter (instead of mapping it to PyString). Thus, for APIs which really need to return bytestrings (such as PyFile) we now have to explicitely declare the return type as PyString (and on code written in Python, use StringUtil.asPyString(String)). Fixes #1128 Modified Paths: -------------- trunk/jython/Lib/javapath.py trunk/jython/Lib/os.py trunk/jython/Lib/zlib.py trunk/jython/src/com/ziclix/python/sql/DataHandler.java trunk/jython/src/com/ziclix/python/sql/JDBC20DataHandler.java trunk/jython/src/com/ziclix/python/sql/Jython22DataHandler.java trunk/jython/src/com/ziclix/python/sql/handler/MySQLDataHandler.java trunk/jython/src/com/ziclix/python/sql/handler/PostgresqlDataHandler.java trunk/jython/src/org/python/core/PyFile.java trunk/jython/src/org/python/core/PyFunction.java trunk/jython/src/org/python/core/PyStringMap.java trunk/jython/src/org/python/core/PySystemState.java trunk/jython/src/org/python/core/PyTraceback.java trunk/jython/src/org/python/core/__builtin__.java trunk/jython/src/org/python/core/adapter/ClassicPyObjectAdapter.java trunk/jython/src/org/python/core/util/StringUtil.java trunk/jython/src/org/python/modules/binascii.java trunk/jython/src/org/python/modules/cPickle.java trunk/jython/src/org/python/modules/cStringIO.java trunk/jython/src/org/python/modules/struct.java trunk/jython/src/org/python/modules/time/Time.java Modified: trunk/jython/Lib/javapath.py =================================================================== --- trunk/jython/Lib/javapath.py 2008-10-14 01:47:30 UTC (rev 5389) +++ trunk/jython/Lib/javapath.py 2008-10-14 03:20:10 UTC (rev 5390) @@ -20,7 +20,9 @@ from java.lang import System import os +from org.python.core.util.StringUtil import asPyString + def _tostr(s, method): if isinstance(s, basestring): return s @@ -40,7 +42,7 @@ def dirname(path): """Return the directory component of a pathname""" path = _tostr(path, "dirname") - result = File(path).getParent() + result = asPyString(File(path).getParent()) if not result: if isabs(path): result = path # Must be root @@ -51,7 +53,7 @@ def basename(path): """Return the final component of a pathname""" path = _tostr(path, "basename") - return File(path).getName() + return asPyString(File(path).getName()) def split(path): """Split a pathname. @@ -128,7 +130,7 @@ if a == "": a = os.sep f = File(f, a) - return f.getPath() + return asPyString(f.getPath()) def normcase(path): """Normalize case of pathname. @@ -137,7 +139,7 @@ """ path = _tostr(path, "normcase") - return File(path).getPath() + return asPyString(File(path).getPath()) def commonprefix(m): "Given a list of pathnames, return the longest common leading component" @@ -197,7 +199,7 @@ if not c: return gethome() if c == os.sep: - return File(gethome(), path[2:]).getPath() + return asPyString(File(gethome(), path[2:]).getPath()) return path def getuser(): @@ -252,7 +254,7 @@ def _abspath(path): # Must use normpath separately because getAbsolutePath doesn't normalize # and getCanonicalPath would eliminate symlinks. - return normpath(File(sys.getPath(path)).getAbsolutePath()) + return normpath(asPyString(File(sys.getPath(path)).getAbsolutePath())) def realpath(path): """Return an absolute path normalized and symbolic links eliminated""" @@ -261,7 +263,7 @@ def _realpath(path): try: - return File(sys.getPath(path)).getCanonicalPath() + return asPyString(File(sys.getPath(path)).getCanonicalPath()) except java.io.IOException: return _abspath(path) Modified: trunk/jython/Lib/os.py =================================================================== --- trunk/jython/Lib/os.py 2008-10-14 01:47:30 UTC (rev 5389) +++ trunk/jython/Lib/os.py 2008-10-14 03:20:10 UTC (rev 5390) @@ -48,6 +48,7 @@ from java.io import File from org.python.core import PyFile from org.python.core.io import FileDescriptors, FileIO, IOBase +from org.python.core.util.StringUtil import asPyString # Mapping of: os._name: [name list, shell command list] _os_map = dict(nt=[ @@ -264,7 +265,7 @@ l = File(sys.getPath(path)).list() if l is None: raise OSError(0, 'No such directory', path) - return list(l) + return [asPyString(entry) for entry in l] def chmod(path, mode): """chmod(path, mode) @@ -629,7 +630,7 @@ from org.python.core.util import StringUtil rawio = FileDescriptors.get(fd) buf = _handle_oserror(rawio.read, buffersize) - return str(StringUtil.fromBytes(buf)) + return asPyString(StringUtil.fromBytes(buf)) def write(fd, string): """write(fd, string) -> byteswritten Modified: trunk/jython/Lib/zlib.py =================================================================== --- trunk/jython/Lib/zlib.py 2008-10-14 01:47:30 UTC (rev 5389) +++ trunk/jython/Lib/zlib.py 2008-10-14 03:20:10 UTC (rev 5390) @@ -1,8 +1,10 @@ import jarray, binascii from java.util.zip import Adler32, Deflater, Inflater -from java.lang import Long, String, StringBuffer +from java.lang import Long, String +from cStringIO import StringIO + class error(Exception): pass @@ -132,18 +134,19 @@ def _get_deflate_data(deflater): buf = jarray.zeros(1024, 'b') - sb = StringBuffer() + s = StringIO() while not deflater.finished(): l = deflater.deflate(buf) if l == 0: break - sb.append(String(buf, 0, 0, l)) - return sb.toString() + s.write(String(buf, 0, 0, l)) + s.seek(0) + return s.read() def _get_inflate_data(inflater, max_length=0): buf = jarray.zeros(1024, 'b') - sb = StringBuffer() + s = StringIO() total = 0 while not inflater.finished(): if max_length: @@ -154,7 +157,8 @@ break total += l - sb.append(String(buf, 0, 0, l)) + s.write(String(buf, 0, 0, l)) if max_length and total == max_length: break - return sb.toString() + s.seek(0) + return s.read() Modified: trunk/jython/src/com/ziclix/python/sql/DataHandler.java =================================================================== --- trunk/jython/src/com/ziclix/python/sql/DataHandler.java 2008-10-14 01:47:30 UTC (rev 5389) +++ trunk/jython/src/com/ziclix/python/sql/DataHandler.java 2008-10-14 03:20:10 UTC (rev 5390) @@ -177,7 +177,7 @@ case Types.LONGVARCHAR: if (object instanceof PyFile) { - object = new PyString(((PyFile) object).read()); + object = ((PyFile) object).read(); } String varchar = (String) object.__tojava__(String.class); @@ -192,7 +192,7 @@ default : if (object instanceof PyFile) { - object = new PyString(((PyFile) object).read()); + object = ((PyFile) object).read(); } stmt.setObject(index, object.__tojava__(Object.class), type); Modified: trunk/jython/src/com/ziclix/python/sql/JDBC20DataHandler.java =================================================================== --- trunk/jython/src/com/ziclix/python/sql/JDBC20DataHandler.java 2008-10-14 01:47:30 UTC (rev 5389) +++ trunk/jython/src/com/ziclix/python/sql/JDBC20DataHandler.java 2008-10-14 03:20:10 UTC (rev 5390) @@ -62,7 +62,7 @@ case Types.CLOB: if (object instanceof PyFile) { - object = new PyString(((PyFile) object).read()); + object = ((PyFile) object).read(); } String clob = (String) object.__tojava__(String.class); Modified: trunk/jython/src/com/ziclix/python/sql/Jython22DataHandler.java =================================================================== --- trunk/jython/src/com/ziclix/python/sql/Jython22DataHandler.java 2008-10-14 01:47:30 UTC (rev 5389) +++ trunk/jython/src/com/ziclix/python/sql/Jython22DataHandler.java 2008-10-14 03:20:10 UTC (rev 5390) @@ -163,7 +163,7 @@ case Types.LONGVARCHAR: if (object instanceof PyFile) { - object = new PyString(((PyFile) object).read()); + object = ((PyFile) object).read(); } String varchar = (String) object.__tojava__(String.class); @@ -178,7 +178,7 @@ default : if (object instanceof PyFile) { - object = new PyString(((PyFile) object).read()); + object = ((PyFile) object).read(); } stmt.setObject(index, object.__tojava__(Object.class), type); Modified: trunk/jython/src/com/ziclix/python/sql/handler/MySQLDataHandler.java =================================================================== --- trunk/jython/src/com/ziclix/python/sql/handler/MySQLDataHandler.java 2008-10-14 01:47:30 UTC (rev 5389) +++ trunk/jython/src/com/ziclix/python/sql/handler/MySQLDataHandler.java 2008-10-14 03:20:10 UTC (rev 5390) @@ -54,17 +54,19 @@ switch (type) { case Types.LONGVARCHAR: - String varchar; + // XXX: Only works with ASCII data! + byte[] bytes; if (object instanceof PyFile) { - varchar = ((PyFile) object).read(); + bytes = ((PyFile) object).read().toBytes(); } else { - varchar = (String) object.__tojava__(String.class); + String varchar = (String) object.__tojava__(String.class); + bytes = StringUtil.toBytes(varchar); } - InputStream stream = new ByteArrayInputStream(StringUtil.toBytes(varchar)); + InputStream stream = new ByteArrayInputStream(bytes); stream = new BufferedInputStream(stream); - stmt.setAsciiStream(index, stream, varchar.length()); + stmt.setAsciiStream(index, stream, bytes.length); break; default : Modified: trunk/jython/src/com/ziclix/python/sql/handler/PostgresqlDataHandler.java =================================================================== --- trunk/jython/src/com/ziclix/python/sql/handler/PostgresqlDataHandler.java 2008-10-14 01:47:30 UTC (rev 5389) +++ trunk/jython/src/com/ziclix/python/sql/handler/PostgresqlDataHandler.java 2008-10-14 03:20:10 UTC (rev 5390) @@ -111,7 +111,7 @@ String varchar; // Postgresql driver can't handle the setCharacterStream() method so use setObject() instead if (object instanceof PyFile) { - varchar = ((PyFile) object).read(); + varchar = ((PyFile) object).read().asString(); } else { varchar = (String) object.__tojava__(String.class); } Modified: trunk/jython/src/org/python/core/PyFile.java =================================================================== --- trunk/jython/src/org/python/core/PyFile.java 2008-10-14 01:47:30 UTC (rev 5389) +++ trunk/jython/src/org/python/core/PyFile.java 2008-10-14 03:20:10 UTC (rev 5390) @@ -286,16 +286,16 @@ } @ExposedMethod(defaults = {"-1"}) - final synchronized String file_read(int n) { + final synchronized PyString file_read(int n) { checkClosed(); - return file.read(n); + return new PyString(file.read(n)); } - public String read(int n) { + public PyString read(int n) { return file_read(n); } - public String read() { + public PyString read() { return file_read(-1); } @@ -310,16 +310,16 @@ } @ExposedMethod(defaults = {"-1"}) - final synchronized String file_readline(int max) { + final synchronized PyString file_readline(int max) { checkClosed(); - return file.readline(max); + return new PyString(file.readline(max)); } - public String readline(int max) { + public PyString readline(int max) { return file_readline(max); } - public String readline() { + public PyString readline() { return file_readline(-1); } Modified: trunk/jython/src/org/python/core/PyFunction.java =================================================================== --- trunk/jython/src/org/python/core/PyFunction.java 2008-10-14 01:47:30 UTC (rev 5389) +++ trunk/jython/src/org/python/core/PyFunction.java 2008-10-14 03:20:10 UTC (rev 5390) @@ -143,13 +143,13 @@ } @ExposedGet(name = "func_name") - public String getFuncName() { - return __name__; + public PyString getFuncName() { + return new PyString(__name__); } @ExposedSet(name = "func_name") - public void setFuncName(String func_name) { - __name__ = func_name; + public void setFuncName(PyString func_name) { + __name__ = func_name.asString(); } @ExposedGet(name = "func_doc") Modified: trunk/jython/src/org/python/core/PyStringMap.java =================================================================== --- trunk/jython/src/org/python/core/PyStringMap.java 2008-10-14 01:47:30 UTC (rev 5389) +++ trunk/jython/src/org/python/core/PyStringMap.java 2008-10-14 03:20:10 UTC (rev 5390) @@ -141,7 +141,9 @@ for (Entry<Object, PyObject> entry : table.entrySet()) { Object key = entry.getKey(); if (key instanceof String) { - buf.append(Py.java2py(key).__repr__().toString()); + // This is a bit complicated, but prevents us to duplicate + // PyString#__repr__ logic here. + buf.append(new PyString((String)key).__repr__().toString()); } else { buf.append(((PyObject)key).__repr__().toString()); } Modified: trunk/jython/src/org/python/core/PySystemState.java =================================================================== --- trunk/jython/src/org/python/core/PySystemState.java 2008-10-14 01:47:30 UTC (rev 5389) +++ trunk/jython/src/org/python/core/PySystemState.java 2008-10-14 03:20:10 UTC (rev 5390) @@ -41,7 +41,7 @@ private static final String JAR_URL_PREFIX = "jar:file:"; private static final String JAR_SEPARATOR = "!"; - public static String version = Version.getVersion(); + public static PyString version = new PyString(Version.getVersion()); public static int hexversion = ((Version.PY_MAJOR_VERSION << 24) | (Version.PY_MINOR_VERSION << 16) | (Version.PY_MICRO_VERSION << 8) | @@ -101,8 +101,8 @@ public PyList path_hooks; public PyObject path_importer_cache; - public static String platform = "java"; - public static String byteorder = "big"; + public static PyString platform = new PyString("java"); + public static PyString byteorder = new PyString("big"); public PyObject ps1 = new PyString(">>> "); public PyObject ps2 = new PyString("... "); @@ -288,8 +288,8 @@ } } - public String getdefaultencoding() { - return codecs.getDefaultEncoding(); + public PyString getdefaultencoding() { + return new PyString(codecs.getDefaultEncoding()); } public void setdefaultencoding(String encoding) { @@ -431,7 +431,7 @@ if (version.equals("12")) { version = "1.2"; } - platform = "java" + version; + platform = new PyString("java" + version); } private static void initRegistry(Properties preProperties, Properties postProperties, Modified: trunk/jython/src/org/python/core/PyTraceback.java =================================================================== --- trunk/jython/src/org/python/core/PyTraceback.java 2008-10-14 01:47:30 UTC (rev 5389) +++ trunk/jython/src/org/python/core/PyTraceback.java 2008-10-14 03:20:10 UTC (rev 5390) @@ -62,11 +62,12 @@ return null; } + String line = null; int i = 0; try { for (i = 0; i < tb_lineno; i++) { - line = pyFile.readline(); + line = pyFile.readline().asString(); if (line.equals("")) { break; } Modified: trunk/jython/src/org/python/core/__builtin__.java =================================================================== --- trunk/jython/src/org/python/core/__builtin__.java 2008-10-14 01:47:30 UTC (rev 5389) +++ trunk/jython/src/org/python/core/__builtin__.java 2008-10-14 03:20:10 UTC (rev 5390) @@ -1028,7 +1028,7 @@ private static PyString readline(PyObject file) { if (file instanceof PyFile) { - return new PyString(((PyFile) file).readline()); + return ((PyFile) file).readline(); } else { PyObject ret = file.invoke("readline"); if (!(ret instanceof PyString)) { Modified: trunk/jython/src/org/python/core/adapter/ClassicPyObjectAdapter.java =================================================================== --- trunk/jython/src/org/python/core/adapter/ClassicPyObjectAdapter.java 2008-10-14 01:47:30 UTC (rev 5389) +++ trunk/jython/src/org/python/core/adapter/ClassicPyObjectAdapter.java 2008-10-14 03:20:10 UTC (rev 5390) @@ -9,8 +9,8 @@ import org.python.core.PyLong; import org.python.core.PyObject; import org.python.core.PyProxy; -import org.python.core.PyString; import org.python.core.PyType; +import org.python.core.PyUnicode; /** * Implements the algorithm originally used in {@link Py#java2py} to adapt objects. @@ -60,7 +60,7 @@ add(new ClassAdapter(String.class) { public PyObject adapt(Object o) { - return new PyString((String) o); + return new PyUnicode((String) o); } }); Modified: trunk/jython/src/org/python/core/util/StringUtil.java =================================================================== --- trunk/jython/src/org/python/core/util/StringUtil.java 2008-10-14 01:47:30 UTC (rev 5389) +++ trunk/jython/src/org/python/core/util/StringUtil.java 2008-10-14 03:20:10 UTC (rev 5390) @@ -5,6 +5,7 @@ import java.nio.ByteBuffer; import org.python.core.Py; +import org.python.core.PyString; /** * String Utility methods. @@ -83,4 +84,8 @@ chars[0] = Character.toLowerCase(c0); return new String(chars); } + + public static PyString asPyString(String string) { + return new PyString(string); } +} Modified: trunk/jython/src/org/python/modules/binascii.java =================================================================== --- trunk/jython/src/org/python/modules/binascii.java 2008-10-14 01:47:30 UTC (rev 5389) +++ trunk/jython/src/org/python/modules/binascii.java 2008-10-14 03:20:10 UTC (rev 5390) @@ -272,12 +272,12 @@ * binary data. Lines normally contain 45 (binary) bytes, except for the * last line. Line data may be followed by whitespace. */ - public static String a2b_uu(String ascii_data) { + public static PyString a2b_uu(String ascii_data) { int leftbits = 0; int leftchar = 0; if (ascii_data.length() == 0) - return ""; + return new PyString(""); StringBuffer bin_data = new StringBuffer(); @@ -331,7 +331,7 @@ for (; i<bin_len; i++) bin_data.append((char)0); - return bin_data.toString(); + return new PyString(bin_data.toString()); } @@ -346,7 +346,7 @@ * is the converted line, including a newline char. The length of * <i>data</i> should be at most 45. */ - public static String b2a_uu(String bin_data) { + public static PyString b2a_uu(String bin_data) { int leftbits = 0; char this_ch; int leftchar = 0; @@ -379,7 +379,7 @@ } ascii_data.append('\n'); // Append a courtesy newline - return ascii_data.toString(); + return new PyString(ascii_data.toString()); } @@ -417,7 +417,7 @@ * Convert a block of base64 data back to binary and return the * binary data. More than one line may be passed at a time. */ - public static String a2b_base64(String ascii_data) { + public static PyString a2b_base64(String ascii_data) { int leftbits = 0; char this_ch; int leftchar = 0; @@ -468,7 +468,7 @@ if (leftbits != 0) { throw new PyException(Error, "Incorrect padding"); } - return bin_data.toString(); + return new PyString(bin_data.toString()); } @@ -482,7 +482,7 @@ * Convert binary data to a line of ASCII characters in base64 coding. * The return value is the converted line, including a newline char. */ - public static String b2a_base64(String bin_data) { + public static PyString b2a_base64(String bin_data) { int leftbits = 0; char this_ch; int leftchar = 0; @@ -516,7 +516,7 @@ } ascii_data.append('\n'); // Append a courtesy newline - return ascii_data.toString(); + return new PyString(ascii_data.toString()); } @@ -625,7 +625,7 @@ * resulting string. The argument should already be RLE-coded, and have a * length divisible by 3 (except possibly the last fragment). */ - public static String b2a_hqx(String bin_data) { + public static PyString b2a_hqx(String bin_data) { int leftbits = 0; char this_ch; int leftchar = 0; @@ -649,7 +649,7 @@ leftchar <<= (6-leftbits); ascii_data.append((char) table_b2a_hqx[leftchar & 0x3f]); } - return ascii_data.toString(); + return new PyString(ascii_data.toString()); } @@ -834,7 +834,7 @@ "This function is also available as \"hexlify()\"." ); - public static String b2a_hex(String argbuf) { + public static PyString b2a_hex(String argbuf) { int arglen = argbuf.length(); StringBuffer retbuf = new StringBuffer(arglen*2); @@ -845,12 +845,12 @@ retbuf.append(hexdigit[(ch >>> 4) & 0xF]); retbuf.append(hexdigit[ch & 0xF]); } - return retbuf.toString(); + return new PyString(retbuf.toString()); } - public static String hexlify(String argbuf) { + public static PyString hexlify(String argbuf) { return b2a_hex(argbuf); } @@ -864,7 +864,7 @@ ); - public static String a2b_hex(String argbuf) { + public static PyString a2b_hex(String argbuf) { int arglen = argbuf.length(); /* XXX What should we do about strings with an odd length? Should @@ -883,11 +883,11 @@ throw Py.TypeError("Non-hexadecimal digit found"); retbuf.append((char) ((top << 4) + bot)); } - return retbuf.toString(); + return new PyString(retbuf.toString()); } - public static String unhexlify(String argbuf) { + public static PyString unhexlify(String argbuf) { return a2b_hex(argbuf); } @@ -917,7 +917,7 @@ return val; } - public static String a2b_qp(PyObject[] arg, String[] kws) + public static PyString a2b_qp(PyObject[] arg, String[] kws) { ArgParser ap = new ArgParser("a2b_qp", arg, kws, new String[] {"s", "header"}); String s = ap.getString(0); @@ -951,8 +951,7 @@ sb.append(c); } } - - return sb.toString(); + return new PyString(sb.toString()); } final private static Pattern RN_TO_N = Pattern.compile("\r\n"); @@ -964,7 +963,7 @@ + "space at end of lines is. When istext is not set, \r and \n (CR/LF) are\n" + "both encoded. When quotetabs is set, space and tabs are encoded."); - public static String b2a_qp(PyObject[] arg, String[] kws) { + public static PyString b2a_qp(PyObject[] arg, String[] kws) { ArgParser ap = new ArgParser("b2a_qp", arg, kws, new String[] {"s", "quotetabs", "istext", "header"}); String s = ap.getString(0); boolean quotetabs = getIntFlagAsBool(ap, 1, 0, "an integer is required"); @@ -1034,7 +1033,7 @@ qpEscape(sb, c); } } - return sb.toString(); + return new PyString(sb.toString()); } private static boolean endOfLine(String s, String lineEnd, int i) { Modified: trunk/jython/src/org/python/modules/cPickle.java =================================================================== --- trunk/jython/src/org/python/modules/cPickle.java 2008-10-14 01:47:30 UTC (rev 5389) +++ trunk/jython/src/org/python/modules/cPickle.java 2008-10-14 03:20:10 UTC (rev 5390) @@ -614,7 +614,7 @@ * @param object a data object which should be pickled. * @returns a string representing the pickled object. */ - public static String dumps(PyObject object) { + public static PyString dumps(PyObject object) { return dumps(object, 0); } @@ -625,7 +625,7 @@ * @param protocol pickle protocol version (0 - text, 1 - pre-2.3 binary, 2 - 2.3) * @returns a string representing the pickled object. */ - public static String dumps(PyObject object, int protocol) { + public static PyString dumps(PyObject object, int protocol) { cStringIO.StringIO file = cStringIO.StringIO(); dump(object, file, protocol); return file.getvalue(); @@ -705,11 +705,11 @@ public void flush() {} public String read(int len) { - return file.read(len); + return file.read(len).asString(); } public String readlineNoNl() { - return file.readlineNoNl(); + return file.readlineNoNl().asString(); } } Modified: trunk/jython/src/org/python/modules/cStringIO.java =================================================================== --- trunk/jython/src/org/python/modules/cStringIO.java 2008-10-14 01:47:30 UTC (rev 5389) +++ trunk/jython/src/org/python/modules/cStringIO.java 2008-10-14 03:20:10 UTC (rev 5390) @@ -99,10 +99,10 @@ public PyObject __iternext__() { _complain_ifclosed(); - String r = readline(); - if(r.equals("")) + PyString r = readline(); + if (r.__len__() == 0) return null; - return new PyString(r); + return r; } /** @@ -176,7 +176,7 @@ * An empty string is returned when EOF is encountered immediately. * @returns A string containing the data. */ - public String read() { + public PyString read() { return read(-1); } @@ -190,7 +190,7 @@ * @returns A string containing the data read. */ - public synchronized String read(long size) { + public synchronized PyString read(long size) { _complain_ifclosed(); int size_int = _convert_to_int(size); int len = buf.length(); @@ -204,10 +204,9 @@ substr = buf.substring(pos, newpos); pos = newpos; } - return substr; + return new PyString(substr); } - /** * Read one entire line from the file. A trailing newline character * is kept in the string (but may be absent when a file ends with @@ -215,7 +214,7 @@ * An empty string is returned when EOF is hit immediately. * @returns data from the file up to and including the newline. */ - public String readline() { + public PyString readline() { return readline(-1); } @@ -229,12 +228,12 @@ * returned. * @returns data from the file up to and including the newline. */ - public synchronized String readline(long size) { + public synchronized PyString readline(long size) { _complain_ifclosed(); int size_int = _convert_to_int(size); int len = buf.length(); if (pos == len) { - return ""; + return new PyString(""); } int i = buf.indexOf("\n", pos); int newpos = (i < 0) ? len : i + 1; @@ -243,7 +242,7 @@ } String r = buf.substring(pos, newpos); pos = newpos; - return r; + return new PyString(r); } @@ -251,7 +250,7 @@ * Read and return a line without the trailing newline. * Usind by cPickle as an optimization. */ - public synchronized String readlineNoNl() { + public synchronized PyString readlineNoNl() { _complain_ifclosed(); int len = buf.length(); int i = buf.indexOf("\n", pos); @@ -260,7 +259,7 @@ pos = newpos; if (pos < len) // Skip the newline pos++; - return r; + return new PyString(r); } @@ -286,10 +285,10 @@ int sizehint_int = (int)sizehint; int total = 0; PyList lines = new PyList(); - String line = readline(); - while (line.length() > 0) { - lines.append(new PyString(line)); - total += line.length(); + PyString line = readline(); + while (line.__len__() > 0) { + lines.append(line); + total += line.__len__(); if (0 < sizehint_int && sizehint_int <= total) break; line = readline(); @@ -367,8 +366,8 @@ * before the StringIO object's close() method is called. * @return the contents of the StringIO. */ - public synchronized String getvalue() { - return buf.toString(); + public synchronized PyString getvalue() { + return new PyString(buf.toString()); } } Modified: trunk/jython/src/org/python/modules/struct.java =================================================================== --- trunk/jython/src/org/python/modules/struct.java 2008-10-14 01:47:30 UTC (rev 5389) +++ trunk/jython/src/org/python/modules/struct.java 2008-10-14 03:20:10 UTC (rev 5390) @@ -978,7 +978,7 @@ * to the given format. The arguments must match the * values required by the format exactly. */ - static public String pack(PyObject[] args) { + static public PyString pack(PyObject[] args) { if (args.length < 1) Py.TypeError("illegal argument type for built-in operation"); @@ -987,7 +987,7 @@ FormatDef[] f = whichtable(format); int size = calcsize(format, f); - return pack(format, f, size, 1, args).toString(); + return new PyString(pack(format, f, size, 1, args).toString()); } // xxx - may need to consider doing a generic arg parser here Modified: trunk/jython/src/org/python/modules/time/Time.java =================================================================== --- trunk/jython/src/org/python/modules/time/Time.java 2008-10-14 01:47:30 UTC (rev 5389) +++ trunk/jython/src/org/python/modules/time/Time.java 2008-10-14 03:20:10 UTC (rev 5390) @@ -308,11 +308,11 @@ return _timefields(parseTimeDoubleArg(arg), TimeZone.getTimeZone("GMT")); } - public static String ctime() { + public static PyString ctime() { return ctime(Py.None); } - public static String ctime(PyObject secs) { + public static PyString ctime(PyObject secs) { return asctime(localtime(secs)); } @@ -405,11 +405,11 @@ return yearstr.substring(yearstr.length()-2, yearstr.length()); } - public static String asctime() { + public static PyString asctime() { return asctime(localtime()); } - public static String asctime(PyTuple tup) { + public static PyString asctime(PyTuple tup) { StringBuffer buf = new StringBuffer(25); buf.append(enshortdays[item(tup, 6)]).append(' '); buf.append(enshortmonths[item(tup, 1)]).append(' '); @@ -421,7 +421,7 @@ buf.append(_twodigit(item(tup, 3))).append(':'); buf.append(_twodigit(item(tup, 4))).append(':'); buf.append(_twodigit(item(tup, 5))).append(' '); - return buf.append(item(tup, 0)).toString(); + return new PyString(buf.append(item(tup, 0)).toString()); } public static String locale_asctime(PyTuple tup) { @@ -454,11 +454,11 @@ // writable but ignore its value? public static final int accept2dyear = 0; - public static String strftime(String format) { + public static PyString strftime(String format) { return strftime(format, localtime()); } - public static String strftime(String format, PyTuple tup) { + public static PyString strftime(String format, PyTuple tup) { checkLocale(); // Immediately validate the tuple @@ -651,7 +651,18 @@ lastc = i+1; i++; } - return s; + // FIXME: This have problems with localized data: + // $ LANG=es_ES.UTF-8 jythont -c "import time; print time.strftime('%A')" + // s?bado + // + // On the other hand, returning unicode would break some doctests + // and will give problems when the return value of strftime is + // mixed with other strings and then the final result is stored + // on places which only support str and not unicode (such as + // os.environ) + // + // TODO: Check how CPython deals with this problem. + return new PyString(s); } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <fwi...@us...> - 2008-10-14 16:43:57
|
Revision: 5391 http://jython.svn.sourceforge.net/jython/?rev=5391&view=rev Author: fwierzbicki Date: 2008-10-14 16:43:46 +0000 (Tue, 14 Oct 2008) Log Message: ----------- Fix or skips for most remaining problems in test_syntax.py. All remaining problems are due to the lack of enforcement on continuations not being permitted in finally. Modified Paths: -------------- trunk/jython/Lib/test/test_syntax.py trunk/jython/grammar/Python.g trunk/jython/src/org/python/antlr/GrammarActions.java Modified: trunk/jython/Lib/test/test_syntax.py =================================================================== --- trunk/jython/Lib/test/test_syntax.py 2008-10-14 03:20:10 UTC (rev 5390) +++ trunk/jython/Lib/test/test_syntax.py 2008-10-14 16:43:46 UTC (rev 5391) @@ -61,7 +61,7 @@ Traceback (most recent call last): SyntaxError: can't assign to operator (<doctest test.test_syntax[6]>, line 1) ->>> (x for x in x) = 1 +>>> (x for x in x) = 1 #doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): SyntaxError: can't assign to generator expression (<doctest test.test_syntax[7]>, line 1) @@ -146,69 +146,71 @@ >>> f((x for x in L), 1) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] ->>> f(i0, i1, i2, i3, i4, i5, i6, i7, i8, i9, i10, i11, -... i12, i13, i14, i15, i16, i17, i18, i19, i20, i21, i22, -... i23, i24, i25, i26, i27, i28, i29, i30, i31, i32, i33, -... i34, i35, i36, i37, i38, i39, i40, i41, i42, i43, i44, -... i45, i46, i47, i48, i49, i50, i51, i52, i53, i54, i55, -... i56, i57, i58, i59, i60, i61, i62, i63, i64, i65, i66, -... i67, i68, i69, i70, i71, i72, i73, i74, i75, i76, i77, -... i78, i79, i80, i81, i82, i83, i84, i85, i86, i87, i88, -... i89, i90, i91, i92, i93, i94, i95, i96, i97, i98, i99, -... i100, i101, i102, i103, i104, i105, i106, i107, i108, -... i109, i110, i111, i112, i113, i114, i115, i116, i117, -... i118, i119, i120, i121, i122, i123, i124, i125, i126, -... i127, i128, i129, i130, i131, i132, i133, i134, i135, -... i136, i137, i138, i139, i140, i141, i142, i143, i144, -... i145, i146, i147, i148, i149, i150, i151, i152, i153, -... i154, i155, i156, i157, i158, i159, i160, i161, i162, -... i163, i164, i165, i166, i167, i168, i169, i170, i171, -... i172, i173, i174, i175, i176, i177, i178, i179, i180, -... i181, i182, i183, i184, i185, i186, i187, i188, i189, -... i190, i191, i192, i193, i194, i195, i196, i197, i198, -... i199, i200, i201, i202, i203, i204, i205, i206, i207, -... i208, i209, i210, i211, i212, i213, i214, i215, i216, -... i217, i218, i219, i220, i221, i222, i223, i224, i225, -... i226, i227, i228, i229, i230, i231, i232, i233, i234, -... i235, i236, i237, i238, i239, i240, i241, i242, i243, -... i244, i245, i246, i247, i248, i249, i250, i251, i252, -... i253, i254, i255) -Traceback (most recent call last): #doctest: +IGNORE_EXCEPTION_DETAIL -SyntaxError: more than 255 arguments (<doctest test.test_syntax[25]>, line 1) +### XXX: commented out -- jython lacks this limit -- should it have it? +#>>> f(i0, i1, i2, i3, i4, i5, i6, i7, i8, i9, i10, i11, +#... i12, i13, i14, i15, i16, i17, i18, i19, i20, i21, i22, +#... i23, i24, i25, i26, i27, i28, i29, i30, i31, i32, i33, +#... i34, i35, i36, i37, i38, i39, i40, i41, i42, i43, i44, +#... i45, i46, i47, i48, i49, i50, i51, i52, i53, i54, i55, +#... i56, i57, i58, i59, i60, i61, i62, i63, i64, i65, i66, +#... i67, i68, i69, i70, i71, i72, i73, i74, i75, i76, i77, +#... i78, i79, i80, i81, i82, i83, i84, i85, i86, i87, i88, +#... i89, i90, i91, i92, i93, i94, i95, i96, i97, i98, i99, +#... i100, i101, i102, i103, i104, i105, i106, i107, i108, +#... i109, i110, i111, i112, i113, i114, i115, i116, i117, +#... i118, i119, i120, i121, i122, i123, i124, i125, i126, +#... i127, i128, i129, i130, i131, i132, i133, i134, i135, +#... i136, i137, i138, i139, i140, i141, i142, i143, i144, +#... i145, i146, i147, i148, i149, i150, i151, i152, i153, +#... i154, i155, i156, i157, i158, i159, i160, i161, i162, +#... i163, i164, i165, i166, i167, i168, i169, i170, i171, +#... i172, i173, i174, i175, i176, i177, i178, i179, i180, +#... i181, i182, i183, i184, i185, i186, i187, i188, i189, +#... i190, i191, i192, i193, i194, i195, i196, i197, i198, +#... i199, i200, i201, i202, i203, i204, i205, i206, i207, +#... i208, i209, i210, i211, i212, i213, i214, i215, i216, +#... i217, i218, i219, i220, i221, i222, i223, i224, i225, +#... i226, i227, i228, i229, i230, i231, i232, i233, i234, +#... i235, i236, i237, i238, i239, i240, i241, i242, i243, +#... i244, i245, i246, i247, i248, i249, i250, i251, i252, +#... i253, i254, i255) +#Traceback (most recent call last): +#SyntaxError: more than 255 arguments (<doctest test.test_syntax[25]>, line 1) The actual error cases counts positional arguments, keyword arguments, and generator expression arguments separately. This test combines the three. ->>> f(i0, i1, i2, i3, i4, i5, i6, i7, i8, i9, i10, i11, -... i12, i13, i14, i15, i16, i17, i18, i19, i20, i21, i22, -... i23, i24, i25, i26, i27, i28, i29, i30, i31, i32, i33, -... i34, i35, i36, i37, i38, i39, i40, i41, i42, i43, i44, -... i45, i46, i47, i48, i49, i50, i51, i52, i53, i54, i55, -... i56, i57, i58, i59, i60, i61, i62, i63, i64, i65, i66, -... i67, i68, i69, i70, i71, i72, i73, i74, i75, i76, i77, -... i78, i79, i80, i81, i82, i83, i84, i85, i86, i87, i88, -... i89, i90, i91, i92, i93, i94, i95, i96, i97, i98, i99, -... i100, i101, i102, i103, i104, i105, i106, i107, i108, -... i109, i110, i111, i112, i113, i114, i115, i116, i117, -... i118, i119, i120, i121, i122, i123, i124, i125, i126, -... i127, i128, i129, i130, i131, i132, i133, i134, i135, -... i136, i137, i138, i139, i140, i141, i142, i143, i144, -... i145, i146, i147, i148, i149, i150, i151, i152, i153, -... i154, i155, i156, i157, i158, i159, i160, i161, i162, -... i163, i164, i165, i166, i167, i168, i169, i170, i171, -... i172, i173, i174, i175, i176, i177, i178, i179, i180, -... i181, i182, i183, i184, i185, i186, i187, i188, i189, -... i190, i191, i192, i193, i194, i195, i196, i197, i198, -... i199, i200, i201, i202, i203, i204, i205, i206, i207, -... i208, i209, i210, i211, i212, i213, i214, i215, i216, -... i217, i218, i219, i220, i221, i222, i223, i224, i225, -... i226, i227, i228, i229, i230, i231, i232, i233, i234, -... i235, i236, i237, i238, i239, i240, i241, i242, i243, -... (x for x in i244), i245, i246, i247, i248, i249, i250, i251, -... i252=1, i253=1, i254=1, i255=1) -Traceback (most recent call last): #doctest: +IGNORE_EXCEPTION_DETAIL -SyntaxError: more than 255 arguments (<doctest test.test_syntax[26]>, line 1) +### XXX: commented out -- jython lacks this limit -- should it have it? +#>>> f(i0, i1, i2, i3, i4, i5, i6, i7, i8, i9, i10, i11, +#... i12, i13, i14, i15, i16, i17, i18, i19, i20, i21, i22, +#... i23, i24, i25, i26, i27, i28, i29, i30, i31, i32, i33, +#... i34, i35, i36, i37, i38, i39, i40, i41, i42, i43, i44, +#... i45, i46, i47, i48, i49, i50, i51, i52, i53, i54, i55, +#... i56, i57, i58, i59, i60, i61, i62, i63, i64, i65, i66, +#... i67, i68, i69, i70, i71, i72, i73, i74, i75, i76, i77, +#... i78, i79, i80, i81, i82, i83, i84, i85, i86, i87, i88, +#... i89, i90, i91, i92, i93, i94, i95, i96, i97, i98, i99, +#... i100, i101, i102, i103, i104, i105, i106, i107, i108, +#... i109, i110, i111, i112, i113, i114, i115, i116, i117, +#... i118, i119, i120, i121, i122, i123, i124, i125, i126, +#... i127, i128, i129, i130, i131, i132, i133, i134, i135, +#... i136, i137, i138, i139, i140, i141, i142, i143, i144, +#... i145, i146, i147, i148, i149, i150, i151, i152, i153, +#... i154, i155, i156, i157, i158, i159, i160, i161, i162, +#... i163, i164, i165, i166, i167, i168, i169, i170, i171, +#... i172, i173, i174, i175, i176, i177, i178, i179, i180, +#... i181, i182, i183, i184, i185, i186, i187, i188, i189, +#... i190, i191, i192, i193, i194, i195, i196, i197, i198, +#... i199, i200, i201, i202, i203, i204, i205, i206, i207, +#... i208, i209, i210, i211, i212, i213, i214, i215, i216, +#... i217, i218, i219, i220, i221, i222, i223, i224, i225, +#... i226, i227, i228, i229, i230, i231, i232, i233, i234, +#... i235, i236, i237, i238, i239, i240, i241, i242, i243, +#... (x for x in i244), i245, i246, i247, i248, i249, i250, i251, +#... i252=1, i253=1, i254=1, i255=1) +#Traceback (most recent call last): +#SyntaxError: more than 255 arguments (<doctest test.test_syntax[26]>, line 1) >>> f(lambda x: x[0] = 3) #doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): @@ -453,10 +455,7 @@ self.fail("compile() did not raise SyntaxError") def test_assign_call(self): - if test_support.is_jython: - self._check_error("f() = 1") - else: - self._check_error("f() = 1", "assign") + self._check_error("f() = 1", "assign") def test_assign_del(self): self._check_error("del f()", "delete") Modified: trunk/jython/grammar/Python.g =================================================================== --- trunk/jython/grammar/Python.g 2008-10-14 03:20:10 UTC (rev 5390) +++ trunk/jython/grammar/Python.g 2008-10-14 16:43:46 UTC (rev 5391) @@ -110,7 +110,6 @@ import org.python.antlr.ast.expr_contextType; import org.python.antlr.ast.ExtSlice; import org.python.antlr.ast.For; -import org.python.antlr.ast.FunctionDef; import org.python.antlr.ast.GeneratorExp; import org.python.antlr.ast.Global; import org.python.antlr.ast.If; @@ -638,7 +637,7 @@ //del_stmt: 'del' exprlist del_stmt : DELETE del_list - -> ^(DELETE<Delete>[$DELETE, actions.castExprs($del_list.etypes)]) + -> ^(DELETE<Delete>[$DELETE, $del_list.etypes]) ; //pass_stmt: 'pass' @@ -1376,10 +1375,10 @@ //not in CPython's Grammar file //Needed as an exprlist that does not produce tuples for del_stmt. -del_list returns [List etypes] +del_list returns [exprType[\] etypes] : e+=expr[expr_contextType.Del] (options {k=2;}: COMMA e+=expr[expr_contextType.Del])* (COMMA)? { - $etypes = $e; + $etypes = actions.makeDeleteList($e); } ; Modified: trunk/jython/src/org/python/antlr/GrammarActions.java =================================================================== --- trunk/jython/src/org/python/antlr/GrammarActions.java 2008-10-14 03:20:10 UTC (rev 5390) +++ trunk/jython/src/org/python/antlr/GrammarActions.java 2008-10-14 16:43:46 UTC (rev 5391) @@ -327,12 +327,12 @@ if (snameToken == null) { s = null; } else { - s = snameToken.getText(); + s = cantBeNone(snameToken); } if (knameToken == null) { k = null; } else { - k = knameToken.getText(); + k = cantBeNone(knameToken); } return new argumentsType(t, p, s, k, d); } @@ -347,8 +347,12 @@ for(int i=0;i<args.size();i++) { exprType[] e = (exprType[])args.get(i); checkAssign(e[0]); - Name arg = (Name)e[0]; - k.add(new keywordType(arg, arg.id, e[1])); + if (e[0] instanceof Name) { + Name arg = (Name)e[0]; + k.add(new keywordType(arg, arg.id, e[1])); + } else { + errorHandler.error("keyword must be a name", e[0]); + } } return k.toArray(new keywordType[k.size()]); } @@ -495,26 +499,6 @@ return new ClassDef(t, nameToken.getText(), b, s); } - argumentsType makeArgumentsType(PythonTree t, List params, PythonTree snameToken, - PythonTree knameToken, List defaults) { - - exprType[] p = castExprs(params); - exprType[] d = castExprs(defaults); - String s; - String k; - if (snameToken == null) { - s = null; - } else { - s = snameToken.getText(); - } - if (knameToken == null) { - k = null; - } else { - k = knameToken.getText(); - } - return new argumentsType(t, p, s, k, d); - } - stmtType makeTryExcept(PythonTree t, List body, List handlers, List orelse, List finBody) { stmtType[] b = castStmts(body); excepthandlerType[] e = (excepthandlerType[])handlers.toArray(new excepthandlerType[handlers.size()]); @@ -632,27 +616,46 @@ errorHandler.error("can't assign to generator expression", e); } else if (e instanceof Num) { errorHandler.error("can't assign to number", e); + } else if (e instanceof Str) { + errorHandler.error("can't assign to string", e); } else if (e instanceof Yield) { errorHandler.error("can't assign to yield expression", e); } else if (e instanceof BinOp) { errorHandler.error("can't assign to operator", e); } else if (e instanceof Lambda) { errorHandler.error("can't assign to lambda", e); + } else if (e instanceof Call) { + errorHandler.error("can't assign to function call", e); + } else if (e instanceof Repr) { + errorHandler.error("can't assign to repr", e); + } else if (e instanceof IfExp) { + errorHandler.error("can't assign to conditional expression", e); } else if (e instanceof Tuple) { //XXX: performance problem? Any way to do this better? exprType[] elts = ((Tuple)e).elts; + if (elts.length == 0) { + errorHandler.error("can't assign to ()", e); + } for (int i=0;i<elts.length;i++) { checkAssign(elts[i]); } + } else if (e instanceof org.python.antlr.ast.List) { + //XXX: performance problem? Any way to do this better? + exprType[] elts = ((org.python.antlr.ast.List)e).elts; + for (int i=0;i<elts.length;i++) { + checkAssign(elts[i]); + } } } - void checkDelete(exprType[] exprs) { + exprType[] makeDeleteList(List e) { + exprType[] exprs = castExprs(e); for(int i=0;i<exprs.length;i++) { if (exprs[i] instanceof Call) { errorHandler.error("can't delete function call", exprs[i]); } } + return exprs; } sliceType makeSubscript(PythonTree lower, Token colon, PythonTree upper, PythonTree sliceop) { This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <pj...@us...> - 2008-10-15 00:46:13
|
Revision: 5394 http://jython.svn.sourceforge.net/jython/?rev=5394&view=rev Author: pjenvey Date: 2008-10-15 00:46:02 +0000 (Wed, 15 Oct 2008) Log Message: ----------- fix solid_base considering slotted objects with a __dict__ as solid Modified Paths: -------------- trunk/jython/Lib/test/test_class_jy.py trunk/jython/src/org/python/core/PyType.java Modified: trunk/jython/Lib/test/test_class_jy.py =================================================================== --- trunk/jython/Lib/test/test_class_jy.py 2008-10-14 23:08:45 UTC (rev 5393) +++ trunk/jython/Lib/test/test_class_jy.py 2008-10-15 00:46:02 UTC (rev 5394) @@ -162,6 +162,18 @@ class Bar(SlottedBase): __metaclass__ = Meta + def test_slotted_diamond_problem_bug(self): + class A(object): + __slots__ = 'foo' + class B(A): + pass + class C(A): + pass + # used to raise TypeError: multiple bases have instance lay-out + # conflict + class D(B, C): + pass + class ClassNamelessModuleTestCase(unittest.TestCase): Modified: trunk/jython/src/org/python/core/PyType.java =================================================================== --- trunk/jython/src/org/python/core/PyType.java 2008-10-14 23:08:45 UTC (rev 5393) +++ trunk/jython/src/org/python/core/PyType.java 2008-10-15 00:46:02 UTC (rev 5394) @@ -823,7 +823,8 @@ } /** - * Finds the parent of type with an underlying_class or with slots. + * Finds the parent of type with an underlying_class or with slots sans a __dict__ + * slot. */ private static PyType solid_base(PyType type) { do { @@ -836,7 +837,7 @@ } private static boolean isSolidBase(PyType type) { - return type.underlying_class != null || type.numSlots != 0; + return type.underlying_class != null || (type.numSlots != 0 && !type.needs_userdict); } /** This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <fwi...@us...> - 2008-10-15 20:22:08
|
Revision: 5402 http://jython.svn.sourceforge.net/jython/?rev=5402&view=rev Author: fwierzbicki Date: 2008-10-15 20:22:02 +0000 (Wed, 15 Oct 2008) Log Message: ----------- Move bugtests/test076.py into regrtest. Modified Paths: -------------- trunk/jython/Lib/test/test_exceptions_jy.py Removed Paths: ------------- trunk/jython/bugtests/test076.py Modified: trunk/jython/Lib/test/test_exceptions_jy.py =================================================================== --- trunk/jython/Lib/test/test_exceptions_jy.py 2008-10-15 20:16:53 UTC (rev 5401) +++ trunk/jython/Lib/test/test_exceptions_jy.py 2008-10-15 20:22:02 UTC (rev 5402) @@ -13,7 +13,19 @@ self.assertEquals(str(KeyError('')), "''") self.assertEquals(str(KeyError('', '')), "('', '')") + #From bugtests/test076.py + def test_raise_no_arg(self): + r = None + try: + try: + raise RuntimeError("dummy") + except RuntimeError: + raise + except RuntimeError, e: + r = str(e) + self.assertEquals(r, "dummy") + def test_main(): test_support.run_unittest(ExceptionsTestCase) Deleted: trunk/jython/bugtests/test076.py =================================================================== --- trunk/jython/bugtests/test076.py 2008-10-15 20:16:53 UTC (rev 5401) +++ trunk/jython/bugtests/test076.py 2008-10-15 20:22:02 UTC (rev 5402) @@ -1,20 +0,0 @@ -""" -raise with no arguments throws SyntaxError -""" - -import support - -r = None -try: - try: - raise support.TestError("dummy") - except support.TestError: - raise -except support.TestError, e: - r = str(e) - - -if r != "dummy": - raise support.TestError("Error not reraised") - - This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <fwi...@us...> - 2008-10-16 02:21:57
|
Revision: 5414 http://jython.svn.sourceforge.net/jython/?rev=5414&view=rev Author: fwierzbicki Date: 2008-10-16 02:21:51 +0000 (Thu, 16 Oct 2008) Log Message: ----------- Moved unique id test to test_jy_internals Modified Paths: -------------- trunk/jython/Lib/test/test_jy_internals.py Removed Paths: ------------- trunk/jython/bugtests/test099.py Modified: trunk/jython/Lib/test/test_jy_internals.py =================================================================== --- trunk/jython/Lib/test/test_jy_internals.py 2008-10-16 01:53:49 UTC (rev 5413) +++ trunk/jython/Lib/test/test_jy_internals.py 2008-10-16 02:21:51 UTC (rev 5414) @@ -141,7 +141,20 @@ self.assertEquals(datetime.datetime(2008, 5, 29, 16, 50, 1, 1), Py.newDatetime(Timestamp(108, 4, 29, 16, 50, 1, 1000))) +class IdTest(unittest.TestCase): + def test_unique_ids(self): + d = {} + cnt = 0 + for i in xrange(100000): + s = "test" + repr(i) + j = id(s) + if d.has_key(j): + cnt = cnt + 1 + d[j] = s + + self.assertEquals(cnt, 0) + def test_main(): test_suite = unittest.TestSuite() test_loader = unittest.TestLoader() @@ -151,6 +164,7 @@ suite_add(LongAsScaledDoubleValueTests) suite_add(ExtraMathTests) suite_add(DatetimeTypeMappingTest) + suite_add(IdTest) run_suite(test_suite) if __name__ == "__main__": Deleted: trunk/jython/bugtests/test099.py =================================================================== --- trunk/jython/bugtests/test099.py 2008-10-16 01:53:49 UTC (rev 5413) +++ trunk/jython/bugtests/test099.py 2008-10-16 02:21:51 UTC (rev 5414) @@ -1,18 +0,0 @@ -""" -Check if id() returns unique values for different objects. -""" - -import support - -d = {} -cnt = 0 - -for i in xrange(100000): - s = "test" + `i` - j = id(s) - if d.has_key(j): - cnt = cnt + 1 - d[j] = s - -if cnt != 0: - raise support.TestError("%d id() value conflicts" % cnt) This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <fwi...@us...> - 2008-10-16 03:11:32
|
Revision: 5416 http://jython.svn.sourceforge.net/jython/?rev=5416&view=rev Author: fwierzbicki Date: 2008-10-16 03:11:28 +0000 (Thu, 16 Oct 2008) Log Message: ----------- test102 moved to test_jy_internals.py Modified Paths: -------------- trunk/jython/Lib/test/test_jy_internals.py Removed Paths: ------------- trunk/jython/bugtests/test102.py Modified: trunk/jython/Lib/test/test_jy_internals.py =================================================================== --- trunk/jython/Lib/test/test_jy_internals.py 2008-10-16 02:56:10 UTC (rev 5415) +++ trunk/jython/Lib/test/test_jy_internals.py 2008-10-16 03:11:28 UTC (rev 5416) @@ -155,6 +155,23 @@ self.assertEquals(cnt, 0) +class FrameTest(unittest.TestCase): + def test_stack_frame_locals(self): + def h(): + a = 1 + b = 2 + raise AttributeError("spam") + + try: + h() + except: + import sys + tb = sys.exc_info()[2] + while tb.tb_next is not None: + tb = tb.tb_next + vars = tb.tb_frame.f_locals + self.assertEquals(sorted(vars.items()), [('a',1), ('b',2)]) + def test_main(): test_suite = unittest.TestSuite() test_loader = unittest.TestLoader() @@ -165,6 +182,7 @@ suite_add(ExtraMathTests) suite_add(DatetimeTypeMappingTest) suite_add(IdTest) + suite_add(FrameTest) run_suite(test_suite) if __name__ == "__main__": Deleted: trunk/jython/bugtests/test102.py =================================================================== --- trunk/jython/bugtests/test102.py 2008-10-16 02:56:10 UTC (rev 5415) +++ trunk/jython/bugtests/test102.py 2008-10-16 03:11:28 UTC (rev 5416) @@ -1,23 +0,0 @@ -""" -Check stack frame locals. -""" - -import sys - - -def vars(): - tb = sys.exc_info()[2] - while tb.tb_next is not None: - tb = tb.tb_next - return tb.tb_frame.f_locals - -def h(): - a = 1 - b = 2 - raise AttributeError("spam") - -try: - h() -except: - assert(vars() == {'a':1, 'b':2 }) - This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <fwi...@us...> - 2008-10-16 12:07:29
|
Revision: 5421 http://jython.svn.sourceforge.net/jython/?rev=5421&view=rev Author: fwierzbicki Date: 2008-10-16 12:07:24 +0000 (Thu, 16 Oct 2008) Log Message: ----------- Move essential part of test106 to test_jy_compile.py (bare return not permitted in exec). Modified Paths: -------------- trunk/jython/Lib/test/test_jy_compile.py Removed Paths: ------------- trunk/jython/bugtests/test106.py Modified: trunk/jython/Lib/test/test_jy_compile.py =================================================================== --- trunk/jython/Lib/test/test_jy_compile.py 2008-10-16 06:38:43 UTC (rev 5420) +++ trunk/jython/Lib/test/test_jy_compile.py 2008-10-16 12:07:24 UTC (rev 5421) @@ -159,6 +159,7 @@ ai("9+","eval") ai("lambda z:","eval") ai("a b","eval") + ai("return 2.3") def test_filename(self): self.assertEquals(compile_("a = 1\n", "abc").co_filename, Deleted: trunk/jython/bugtests/test106.py =================================================================== --- trunk/jython/bugtests/test106.py 2008-10-16 06:38:43 UTC (rev 5420) +++ trunk/jython/bugtests/test106.py 2008-10-16 12:07:24 UTC (rev 5421) @@ -1,18 +0,0 @@ -""" -Check the return in exec is illegal. -""" - -import support - -cmd = """print 'hi' -return 2.3 -print 'fred'""" - -try: - co = compile(cmd, "<string>", "exec") -except SyntaxError, e: - pass -else: - raise support.TestError("Should cause SyntaxError") - - This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <fwi...@us...> - 2008-10-16 12:42:16
|
Revision: 5423 http://jython.svn.sourceforge.net/jython/?rev=5423&view=rev Author: fwierzbicki Date: 2008-10-16 12:42:06 +0000 (Thu, 16 Oct 2008) Log Message: ----------- move test107 to test_jy_internals.py Modified Paths: -------------- trunk/jython/Lib/test/test_jy_internals.py Removed Paths: ------------- trunk/jython/bugtests/test107.py Modified: trunk/jython/Lib/test/test_jy_internals.py =================================================================== --- trunk/jython/Lib/test/test_jy_internals.py 2008-10-16 12:15:26 UTC (rev 5422) +++ trunk/jython/Lib/test/test_jy_internals.py 2008-10-16 12:42:06 UTC (rev 5423) @@ -172,6 +172,60 @@ vars = tb.tb_frame.f_locals self.assertEquals(sorted(vars.items()), [('a',1), ('b',2)]) + def test_frame_info(self): + import sys + from types import ClassType + + def getinfo(): + """ Returns a tuple consisting of: + the name of the current module + the name of the current class or None + the name of the current function + the current line number + """ + try: + 1/0 + except: + tb = sys.exc_info()[-1] + frame = tb.tb_frame.f_back + modulename = frame.f_globals['__name__'] + funcname = frame.f_code.co_name + lineno = frame.f_lineno + + if len(frame.f_code.co_varnames) == 0: + classname = None + else: + self = frame.f_locals[frame.f_code.co_varnames[0]] + myclass = self.__class__ + if type(myclass) == ClassType: + classname = myclass.__name__ + else: + classname = None + + return modulename, classname, funcname, lineno + + def foo(): + x = 99 + g = getinfo() + assert (g[0] == "__main__" or g[0] == "test.test_jy_internals") + self.assertEquals(g[1], None) + self.assertEquals(g[2], "foo") + + class Bar: + def baz(self): + g = getinfo() + assert (g[0] == "__main__" or g[0] == "test.test_jy_internals") + assert (g[1] == "Bar") + assert (g[2] == "baz") + + g = getinfo() + assert (g[0] == "__main__" or g[0] == "test.test_jy_internals") + self.assertEquals(g[1], None) + self.assertEquals(g[2], "test_frame_info") + + foo() + Bar().baz() + def test_main(): test_suite = unittest.TestSuite() test_loader = unittest.TestLoader() Deleted: trunk/jython/bugtests/test107.py =================================================================== --- trunk/jython/bugtests/test107.py 2008-10-16 12:15:26 UTC (rev 5422) +++ trunk/jython/bugtests/test107.py 2008-10-16 12:42:06 UTC (rev 5423) @@ -1,55 +0,0 @@ -""" -Check some internal frame info -""" -import sys -from types import ClassType - -def getinfo(): - """ Returns a tuple consisting of: - the name of the current module - the name of the current class or None - the name of the current function - the current line number - """ - try: - 1/0 - except: - tb = sys.exc_info()[-1] - frame = tb.tb_frame.f_back - modulename = frame.f_globals['__name__'] - funcname = frame.f_code.co_name - lineno = frame.f_lineno - - if len(frame.f_code.co_varnames) == 0: - classname = None - else: - self = frame.f_locals[frame.f_code.co_varnames[0]] - myclass = self.__class__ - if type(myclass) == ClassType: - classname = myclass.__name__ - else: - classname = None - - return modulename, classname, funcname, lineno - -def foo(): - x = 99 - g = getinfo() - assert (g[0] == "__main__" or g[0] == "test107") - assert (g[1] == None) - assert (g[2] == "foo") - -class Bar: - def baz(self): - g = getinfo() - assert (g[0] == "__main__" or g[0] == "test107") - assert (g[1] == "Bar") - assert (g[2] == "baz") - -g = getinfo() -assert (g[0] == "__main__" or g[0] == "test107") -assert (g[1] == None) -assert (g[2] == "<module>") - -foo() -Bar().baz() This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <fwi...@us...> - 2008-10-16 14:26:34
|
Revision: 5424 http://jython.svn.sourceforge.net/jython/?rev=5424&view=rev Author: fwierzbicki Date: 2008-10-16 14:26:23 +0000 (Thu, 16 Oct 2008) Log Message: ----------- Moved test108 to test_dict_jy Modified Paths: -------------- trunk/jython/Lib/test/test_dict_jy.py Removed Paths: ------------- trunk/jython/bugtests/test108.py Modified: trunk/jython/Lib/test/test_dict_jy.py =================================================================== --- trunk/jython/Lib/test/test_dict_jy.py 2008-10-16 12:42:06 UTC (rev 5423) +++ trunk/jython/Lib/test/test_dict_jy.py 2008-10-16 14:26:23 UTC (rev 5424) @@ -23,6 +23,21 @@ s[7] = 'called' self.assertEquals('called', s.createdInInit) + def testUnhashableKeys(self): + try: + a = {1:2} + except TypeError: + pass + else: + self.fail("list as dict key should raise TypeError") + + try: + a = {{1:2}:3} + except TypeError: + pass + else: + self.fail("dict as dict key should raise TypeError") + class DictCmpTest(unittest.TestCase): "Test for http://bugs.jython.org/issue1031" def testDictCmp(self): Deleted: trunk/jython/bugtests/test108.py =================================================================== --- trunk/jython/bugtests/test108.py 2008-10-16 12:42:06 UTC (rev 5423) +++ trunk/jython/bugtests/test108.py 2008-10-16 14:26:23 UTC (rev 5424) @@ -1,13 +0,0 @@ -""" -Check for lists and dicts as key in a dict. -""" - -import support - -try: - a = {[1]:2} - a = {{1:2}:3} -except TypeError, e: - pass -else: - raise support.TestError("Should fail, lists and dicts not allowed as key") This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <fwi...@us...> - 2008-10-16 16:18:13
|
Revision: 5432 http://jython.svn.sourceforge.net/jython/?rev=5432&view=rev Author: fwierzbicki Date: 2008-10-16 16:18:04 +0000 (Thu, 16 Oct 2008) Log Message: ----------- move test124 to test_jy_internals. Modified Paths: -------------- trunk/jython/Lib/test/test_jy_internals.py Removed Paths: ------------- trunk/jython/bugtests/test124.py Modified: trunk/jython/Lib/test/test_jy_internals.py =================================================================== --- trunk/jython/Lib/test/test_jy_internals.py 2008-10-16 16:13:52 UTC (rev 5431) +++ trunk/jython/Lib/test/test_jy_internals.py 2008-10-16 16:18:04 UTC (rev 5432) @@ -226,6 +226,17 @@ foo() Bar().baz() +class ModuleTest(unittest.TestCase): + def test_create_module(self): + from org.python.core import PyModule, PyInstance + test = PyModule("test", {}) + exec "a = 2" in test.__dict__ + self.assertEquals(len(test.__dict__), 3) + + #test = PyInstance.__tojava__(test, PyModule) + exec "b = 3" in test.__dict__ + self.assertEquals(len(test.__dict__), 4) + def test_main(): test_suite = unittest.TestSuite() test_loader = unittest.TestLoader() @@ -237,6 +248,7 @@ suite_add(DatetimeTypeMappingTest) suite_add(IdTest) suite_add(FrameTest) + suite_add(ModuleTest) run_suite(test_suite) if __name__ == "__main__": Deleted: trunk/jython/bugtests/test124.py =================================================================== --- trunk/jython/bugtests/test124.py 2008-10-16 16:13:52 UTC (rev 5431) +++ trunk/jython/bugtests/test124.py 2008-10-16 16:18:04 UTC (rev 5432) @@ -1,14 +0,0 @@ -""" -Create a new Module. -""" - -import support - -from org.python.core import PyModule, PyInstance -test = PyModule("test", {}) -exec "a = 2" in test.__dict__ -support.compare(len(test.__dict__), "3") - -#test = PyInstance.__tojava__(test, PyModule) -exec "b = 3" in test.__dict__ -support.compare(len(test.__dict__), "4") This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <fwi...@us...> - 2008-10-16 18:56:14
|
Revision: 5438 http://jython.svn.sourceforge.net/jython/?rev=5438&view=rev Author: fwierzbicki Date: 2008-10-16 18:56:04 +0000 (Thu, 16 Oct 2008) Log Message: ----------- moved test130 to test_cmp_jy. Modified Paths: -------------- trunk/jython/Lib/test/test_cmp_jy.py Removed Paths: ------------- trunk/jython/bugtests/test130.py Modified: trunk/jython/Lib/test/test_cmp_jy.py =================================================================== --- trunk/jython/Lib/test/test_cmp_jy.py 2008-10-16 17:51:59 UTC (rev 5437) +++ trunk/jython/Lib/test/test_cmp_jy.py 2008-10-16 18:56:04 UTC (rev 5438) @@ -21,8 +21,23 @@ self.assertNotEqual(Test(0), 'foo') self.assertTrue('foo' in [Test(12), 'foo']) +class IntStrCmp(unittest.TestCase): + def testIntStrCompares(self): + assert not (-1 > 'a') + assert (-1 < 'a') + assert not (4 > 'a') + assert (4 < 'a') + assert not (-2 > 'a') + assert (-2 < 'a') + assert not (-1 == 'a') + + def test_main(): - test_support.run_unittest(UnicodeDerivedCmp, LongDerivedCmp) + test_support.run_unittest( + UnicodeDerivedCmp, + LongDerivedCmp, + IntStrCmp, + ) if __name__ == '__main__': test_main() Deleted: trunk/jython/bugtests/test130.py =================================================================== --- trunk/jython/bugtests/test130.py 2008-10-16 17:51:59 UTC (rev 5437) +++ trunk/jython/bugtests/test130.py 2008-10-16 18:56:04 UTC (rev 5438) @@ -1,22 +0,0 @@ -""" -Comparing ints and strings -""" - -import support - -if -1 > 'a': - raise support.TestError("-1 > 'a'") -if not -1 < 'a': - raise support.TestError("-1 < 'a'") -if 4 > 'a': - raise support.TestError("4 > 'a'") -if not 4 < 'a': - raise support.TestError("4 < 'a'") -if -2 > 'a': - raise support.TestError("-2 > 'a'") -if not -2 < 'a': - raise support.TestError("-2 < 'a'") -if -1 == 'a': - raise support.TestError("-1 == 'a'") - - This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <fwi...@us...> - 2008-10-16 20:19:58
|
Revision: 5440 http://jython.svn.sourceforge.net/jython/?rev=5440&view=rev Author: fwierzbicki Date: 2008-10-16 20:19:50 +0000 (Thu, 16 Oct 2008) Log Message: ----------- moved test131 into test_java_integration Modified Paths: -------------- trunk/jython/Lib/test/test_java_integration.py Removed Paths: ------------- trunk/jython/bugtests/test131.py Modified: trunk/jython/Lib/test/test_java_integration.py =================================================================== --- trunk/jython/Lib/test/test_java_integration.py 2008-10-16 18:58:39 UTC (rev 5439) +++ trunk/jython/Lib/test/test_java_integration.py 2008-10-16 20:19:50 UTC (rev 5440) @@ -7,8 +7,8 @@ from java.awt import (Dimension, Component, Rectangle, Button, Color, HeadlessException) from java.util import Vector, Hashtable -from java.io import (FileOutputStream, FileWriter, OutputStreamWriter, - UnsupportedEncodingException) +from java.io import FileOutputStream, FileWriter, OutputStreamWriter + from java.lang import Runnable, Thread, ThreadGroup, System, Runtime, Math, Byte from javax.swing.tree import TreePath from java.math import BigDecimal @@ -149,12 +149,22 @@ def test_io_errors(self): "Check that IOException isn't mangled into an IOError" + from java.io import UnsupportedEncodingException try: - x = OutputStreamWriter(System.out, "garbage") + x = OutputStreamWriter(System.out, "garbage") except UnsupportedEncodingException: - pass + pass else: - raise self.fail("Should have raised java.io.UnsupportedEncodingException") + self.fail("Should have raised java.io.UnsupportedEncodingException") + + def test_fileio_error(self): + from java.io import FileInputStream, IOException + try: + stream = FileInputStream("garbage") + except IOException: + pass + else: + self.fail("Should raise java.io.IOException") class VectorTest(unittest.TestCase): Deleted: trunk/jython/bugtests/test131.py =================================================================== --- trunk/jython/bugtests/test131.py 2008-10-16 18:58:39 UTC (rev 5439) +++ trunk/jython/bugtests/test131.py 2008-10-16 20:19:50 UTC (rev 5440) @@ -1,14 +0,0 @@ -""" -""" - -import java -import support - -try: - stream = java.io.FileInputStream("missing") -except java.io.IOException, ioexc: - #support.compare(ioexc.message, "cannot find") - # this message is not portable across underlying operating systems - pass -else: - raise support.TestError("Should raise a IOException") This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <fwi...@us...> - 2008-10-16 20:32:51
|
Revision: 5443 http://jython.svn.sourceforge.net/jython/?rev=5443&view=rev Author: fwierzbicki Date: 2008-10-16 20:32:40 +0000 (Thu, 16 Oct 2008) Log Message: ----------- moved test136 to test_java_integration.py Modified Paths: -------------- trunk/jython/Lib/test/test_java_integration.py Removed Paths: ------------- trunk/jython/bugtests/test136.py Modified: trunk/jython/Lib/test/test_java_integration.py =================================================================== --- trunk/jython/Lib/test/test_java_integration.py 2008-10-16 20:24:04 UTC (rev 5442) +++ trunk/jython/Lib/test/test_java_integration.py 2008-10-16 20:32:40 UTC (rev 5443) @@ -397,6 +397,17 @@ self.assertEquals(s, "Foo!!!", "toString not overridden in interface") +class JavaStringTest(unittest.TestCase): + + def test_override(self): + from java import lang + x = lang.String('test') + try: + list(x) + except TypeError: + pass + else: + self.fail("Should have raised TypeError") def test_main(): test_support.run_unittest(AbstractOnSyspathTest, @@ -416,7 +427,9 @@ TreePathTest, BigDecimalTest, MethodInvTest, - InterfaceTest) + InterfaceTest, + JavaStringTest, + ) if __name__ == "__main__": test_main() Deleted: trunk/jython/bugtests/test136.py =================================================================== --- trunk/jython/bugtests/test136.py 2008-10-16 20:24:04 UTC (rev 5442) +++ trunk/jython/bugtests/test136.py 2008-10-16 20:32:40 UTC (rev 5443) @@ -1,19 +0,0 @@ -""" - -""" - -import support - -import java - -x = java.lang.String('test') - -try: - list(x) -except AttributeError, e: - support.compare(e, "__len__") -except TypeError, e: - # Changed to a TypeError in 2.2 - support.compare(e, "iteration over non-sequence") -else: - raise support.TestError("Should raise a AttributeError on __len__") This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <cg...@us...> - 2008-10-19 05:14:29
|
Revision: 5465 http://jython.svn.sourceforge.net/jython/?rev=5465&view=rev Author: cgroves Date: 2008-10-19 05:14:22 +0000 (Sun, 19 Oct 2008) Log Message: ----------- Rename PyBuiltinFunction to PyBuiltinCallable, and remake PyBuiltinFunction as a base for functions with the basic function stuff from PyBuiltinFunctionSet. Extend that with PyBuiltinFunctionNarrow for functions with a fixed set of args to match PyBuiltinMethodNarrow. Use the new function stuff to implement the builtin functions that were using ExtendedBuiltinFunction as real functions instead of PyObjects. Modified Paths: -------------- trunk/jython/src/org/python/core/ArgParser.java trunk/jython/src/org/python/core/Py.java trunk/jython/src/org/python/core/PyBuiltinFunction.java trunk/jython/src/org/python/core/PyBuiltinFunctionSet.java trunk/jython/src/org/python/core/PyBuiltinMethod.java trunk/jython/src/org/python/core/PyBuiltinMethodNarrow.java trunk/jython/src/org/python/core/PyBuiltinMethodSet.java trunk/jython/src/org/python/core/PyClassMethodDescr.java trunk/jython/src/org/python/core/PyDictionary.java trunk/jython/src/org/python/core/PyEnumerate.java trunk/jython/src/org/python/core/PyInstance.java trunk/jython/src/org/python/core/PyMethodDescr.java trunk/jython/src/org/python/core/PyNewWrapper.java trunk/jython/src/org/python/core/PyObject.java trunk/jython/src/org/python/core/PySet.java trunk/jython/src/org/python/core/PyStringMap.java trunk/jython/src/org/python/core/PySuper.java trunk/jython/src/org/python/core/PyType.java trunk/jython/src/org/python/core/__builtin__.java trunk/jython/src/org/python/core/exceptions.java trunk/jython/src/org/python/expose/generate/PyTypes.java trunk/jython/src/org/python/modules/_collections/PyDeque.java trunk/jython/src/org/python/modules/_jython.java trunk/jython/src/org/python/modules/_weakref/ReferenceType.java trunk/jython/src/org/python/modules/cPickle.java trunk/jython/tests/java/org/python/expose/generate/ExposedTypeProcessorTest.java trunk/jython/tests/java/org/python/expose/generate/MethodExposerTest.java Added Paths: ----------- trunk/jython/src/org/python/core/PyBuiltinCallable.java trunk/jython/src/org/python/core/PyBuiltinFunctionNarrow.java Modified: trunk/jython/src/org/python/core/ArgParser.java =================================================================== --- trunk/jython/src/org/python/core/ArgParser.java 2008-10-19 03:04:44 UTC (rev 5464) +++ trunk/jython/src/org/python/core/ArgParser.java 2008-10-19 05:14:22 UTC (rev 5465) @@ -112,9 +112,9 @@ this(funcname, args, kws); this.params = paramnames; check(); - if (!PyBuiltinFunction.DefaultInfo.check(args.length, minargs, + if (!PyBuiltinCallable.DefaultInfo.check(args.length, minargs, this.params.length)) { - throw PyBuiltinFunction.DefaultInfo.unexpectedCall(args.length, + throw PyBuiltinCallable.DefaultInfo.unexpectedCall(args.length, false, funcname, minargs, this.params.length); } } Modified: trunk/jython/src/org/python/core/Py.java =================================================================== --- trunk/jython/src/org/python/core/Py.java 2008-10-19 03:04:44 UTC (rev 5464) +++ trunk/jython/src/org/python/core/Py.java 2008-10-19 05:14:22 UTC (rev 5465) @@ -86,7 +86,7 @@ static { BOOTSTRAP_TYPES.add(PyObject.class); BOOTSTRAP_TYPES.add(PyType.class); - BOOTSTRAP_TYPES.add(PyBuiltinFunction.class); + BOOTSTRAP_TYPES.add(PyBuiltinCallable.class); BOOTSTRAP_TYPES.add(PyDataDescr.class); } Added: trunk/jython/src/org/python/core/PyBuiltinCallable.java =================================================================== --- trunk/jython/src/org/python/core/PyBuiltinCallable.java (rev 0) +++ trunk/jython/src/org/python/core/PyBuiltinCallable.java 2008-10-19 05:14:22 UTC (rev 5465) @@ -0,0 +1,144 @@ +package org.python.core; + +import org.python.expose.ExposedGet; +import org.python.expose.ExposedType; + +// XXX: not subclassable +@ExposedType(name = "builtin_function_or_method") +public abstract class PyBuiltinCallable extends PyObject { + + protected Info info; + + protected PyBuiltinCallable(PyType type, Info info) { + super(type); + this.info = info; + } + + protected PyBuiltinCallable(Info info) { + this.info = info; + } + + /** + * @return a new instance of this type of PyBuiltinFunction bound to self + */ + abstract public PyBuiltinCallable bind(PyObject self); + + @ExposedGet(name = "__name__") + public PyObject fastGetName() { + return Py.newString(this.info.getName()); + } + + @ExposedGet(name = "__doc__") + public PyObject fastGetDoc() { + return Py.None; + } + + @ExposedGet(name = "__module__") + public PyObject getModule() { + return Py.None; + } + + @ExposedGet(name = "__call__") + public PyObject makeCall() { + return this; + } + + @ExposedGet(name = "__self__") + public PyObject getSelf() { + return Py.None; + } + + public void setInfo(Info info) { + this.info = info; + } + + public String toString() { + PyObject self = getSelf(); + if (self == null) { + return String.format("<built-in function %s>", info.getName()); + } else { + return String.format("<built-in method %s of %s object at %s>", info.getName(), + self.getType().fastGetName(), Py.idstr(self)); + } + } + + public interface Info { + + String getName(); + + int getMaxargs(); + + int getMinargs(); + + PyException unexpectedCall(int nargs, boolean keywords); + } + + public static class DefaultInfo implements Info { + + public DefaultInfo(String name, int minargs, int maxargs) { + this.name = name; + this.minargs = minargs; + this.maxargs = maxargs; + } + + public DefaultInfo(String name) { + this(name, -1, -1); + } + + private String name; + + private int maxargs, minargs; + + public String getName() { + return name; + } + + public int getMaxargs() { + return maxargs; + } + + public int getMinargs() { + return minargs; + } + + public static boolean check(int nargs, int minargs, int maxargs) { + if(nargs < minargs) + return false; + if(maxargs != -1 && nargs > maxargs) + return false; + return true; + } + + public static PyException unexpectedCall(int nargs, + boolean keywords, + String name, + int minargs, + int maxargs) { + if(keywords) + return Py.TypeError(name + "() takes no keyword arguments"); + String argsblurb; + if(minargs == maxargs) { + if(minargs == 0) + argsblurb = "no arguments"; + else if(minargs == 1) + argsblurb = "exactly one argument"; + else + argsblurb = minargs + " arguments"; + } else if(maxargs == -1) { + return Py.TypeError(name + "() requires at least " + minargs + + " (" + nargs + " given)"); + } else { + if(minargs <= 0) + argsblurb = "at most " + maxargs + " arguments"; + else + argsblurb = minargs + "-" + maxargs + " arguments"; + } + return Py.TypeError(name + "() takes " + argsblurb + " (" + nargs + + " given)"); + } + + public PyException unexpectedCall(int nargs, boolean keywords) { + return unexpectedCall(nargs, keywords, name, minargs, maxargs); + } + } +} Modified: trunk/jython/src/org/python/core/PyBuiltinFunction.java =================================================================== --- trunk/jython/src/org/python/core/PyBuiltinFunction.java 2008-10-19 03:04:44 UTC (rev 5464) +++ trunk/jython/src/org/python/core/PyBuiltinFunction.java 2008-10-19 05:14:22 UTC (rev 5465) @@ -1,144 +1,41 @@ package org.python.core; -import org.python.expose.ExposedGet; -import org.python.expose.ExposedType; +import org.python.expose.ExposeAsSuperclass; -// XXX: not subclassable -@ExposedType(name = "builtin_function_or_method") -public abstract class PyBuiltinFunction extends PyObject { +public class PyBuiltinFunction extends PyBuiltinCallable implements ExposeAsSuperclass { - protected Info info; + private PyString doc; - protected PyBuiltinFunction(PyType type, Info info) { - super(type); - this.info = info; + protected PyBuiltinFunction(String name, String doc) { + this(name, -1, -1, doc); } - protected PyBuiltinFunction(Info info) { - this.info = info; + protected PyBuiltinFunction(String name, int minargs, int maxargs, String doc) { + super(new DefaultInfo(name, minargs, maxargs)); + this.doc = doc == null ? null : Py.newString(doc); } - /** - * @return a new instance of this type of PyBuiltinFunction bound to self - */ - abstract public PyBuiltinFunction bind(PyObject self); - - @ExposedGet(name = "__name__") - public PyObject fastGetName() { - return Py.newString(this.info.getName()); - } - - @ExposedGet(name = "__doc__") public PyObject fastGetDoc() { - return Py.None; + return doc; } - @ExposedGet(name = "__module__") - public PyObject getModule() { - return Py.None; + public boolean isMappingType() { + return false; } - @ExposedGet(name = "__call__") - public PyObject makeCall() { - return this; + public boolean isNumberType() { + return false; } - @ExposedGet(name = "__self__") - public PyObject getSelf() { - return Py.None; + public boolean isSequenceType() { + return false; } - public void setInfo(Info info) { - this.info = info; + public PyBuiltinCallable bind(PyObject self) { + throw Py.TypeError("Can't bind a builtin function"); } public String toString() { - PyObject self = getSelf(); - if (self == null) { - return String.format("<built-in function %s>", info.getName()); - } else { - return String.format("<built-in method %s of %s object at %s>", info.getName(), - self.getType().fastGetName(), Py.idstr(self)); - } + return "<built-in function " + info.getName() + ">"; } - - public interface Info { - - String getName(); - - int getMaxargs(); - - int getMinargs(); - - PyException unexpectedCall(int nargs, boolean keywords); - } - - public static class DefaultInfo implements Info { - - public DefaultInfo(String name, int minargs, int maxargs) { - this.name = name; - this.minargs = minargs; - this.maxargs = maxargs; - } - - public DefaultInfo(String name) { - this(name, -1, -1); - } - - private String name; - - private int maxargs, minargs; - - public String getName() { - return name; - } - - public int getMaxargs() { - return maxargs; - } - - public int getMinargs() { - return minargs; - } - - public static boolean check(int nargs, int minargs, int maxargs) { - if(nargs < minargs) - return false; - if(maxargs != -1 && nargs > maxargs) - return false; - return true; - } - - public static PyException unexpectedCall(int nargs, - boolean keywords, - String name, - int minargs, - int maxargs) { - if(keywords) - return Py.TypeError(name + "() takes no keyword arguments"); - String argsblurb; - if(minargs == maxargs) { - if(minargs == 0) - argsblurb = "no arguments"; - else if(minargs == 1) - argsblurb = "exactly one argument"; - else - argsblurb = minargs + " arguments"; - } else if(maxargs == -1) { - return Py.TypeError(name + "() requires at least " + minargs - + " (" + nargs + " given)"); - } else { - if(minargs <= 0) - argsblurb = "at most " + maxargs + " arguments"; - else - argsblurb = minargs + "-" + maxargs + " arguments"; - } - return Py.TypeError(name + "() takes " + argsblurb + " (" + nargs - + " given)"); - } - - public PyException unexpectedCall(int nargs, boolean keywords) { - return unexpectedCall(nargs, keywords, name, minargs, maxargs); - } - } } Added: trunk/jython/src/org/python/core/PyBuiltinFunctionNarrow.java =================================================================== --- trunk/jython/src/org/python/core/PyBuiltinFunctionNarrow.java (rev 0) +++ trunk/jython/src/org/python/core/PyBuiltinFunctionNarrow.java 2008-10-19 05:14:22 UTC (rev 5465) @@ -0,0 +1,58 @@ +package org.python.core; + +public class PyBuiltinFunctionNarrow extends PyBuiltinFunction { + + protected PyBuiltinFunctionNarrow(String name, int minargs, int maxargs, String doc) { + super(name, minargs, maxargs, doc); + } + + public PyObject fancyCall(PyObject[] args) { + throw info.unexpectedCall(args.length, false); + } + + public PyObject __call__(PyObject[] args) { + int nargs = args.length; + switch(nargs){ + case 0: + return __call__(); + case 1: + return __call__(args[0]); + case 2: + return __call__(args[0], args[1]); + case 3: + return __call__(args[0], args[1], args[2]); + case 4: + return __call__(args[0], args[1], args[2], args[3]); + default: + return fancyCall(args); + } + } + + public PyObject __call__(PyObject[] args, String[] kws) { + if (kws.length != 0) { + throw Py.TypeError(fastGetName() + "() takes no keyword arguments"); + } + return __call__(args); + } + + + public PyObject __call__() { + throw info.unexpectedCall(0, false); + } + + public PyObject __call__(PyObject arg1) { + throw info.unexpectedCall(1, false); + } + + public PyObject __call__(PyObject arg1, PyObject arg2) { + throw info.unexpectedCall(2, false); + } + + public PyObject __call__(PyObject arg1, PyObject arg2, PyObject arg3) { + throw info.unexpectedCall(3, false); + } + + public PyObject __call__(PyObject arg1, PyObject arg2, PyObject arg3, PyObject arg4) { + throw info.unexpectedCall(4, false); + } +} Modified: trunk/jython/src/org/python/core/PyBuiltinFunctionSet.java =================================================================== --- trunk/jython/src/org/python/core/PyBuiltinFunctionSet.java 2008-10-19 03:04:44 UTC (rev 5464) +++ trunk/jython/src/org/python/core/PyBuiltinFunctionSet.java 2008-10-19 05:14:22 UTC (rev 5465) @@ -1,34 +1,30 @@ // Copyright (c) Corporation for National Research Initiatives package org.python.core; -import org.python.expose.ExposeAsSuperclass; - /** * A helper class for faster implementations of commonly called methods. * <p> * Subclasses of PyBuiltinFunctionSet will implement some or all of the __call__ * method with a switch on the index number. - * + * */ -public class PyBuiltinFunctionSet extends PyBuiltinFunction implements ExposeAsSuperclass { +public class PyBuiltinFunctionSet extends PyBuiltinFunctionNarrow { // used as an index into a big switch statement in the various derived // class's __call__() methods. - protected int index; + protected final int index; - private PyObject doc = Py.None; - /** * Creates a PyBuiltinFunctionSet that expects 1 argument. */ public PyBuiltinFunctionSet(String name, int index){ this(name, index, 1); } - + public PyBuiltinFunctionSet(String name, int index, int numargs){ this(name, index, numargs, numargs); } - + public PyBuiltinFunctionSet(String name, int index, int minargs, int maxargs){ this(name, index, minargs, maxargs, null); } @@ -39,87 +35,8 @@ int minargs, int maxargs, String doc) { - super(new DefaultInfo(name, minargs, maxargs)); + super(name, minargs, maxargs, doc); this.index = index; - if(doc != null) { - this.doc = Py.newString(doc); - } } - public PyObject fastGetDoc() { - return doc; - } - - public boolean isMappingType() { - return false; - } - - public boolean isNumberType() { - return false; - } - - public boolean isSequenceType() { - return false; - } - - public PyObject fancyCall(PyObject[] args) { - throw info.unexpectedCall(args.length, false); - } - - public PyObject __call__(PyObject[] args) { - int nargs = args.length; - switch(nargs){ - case 0: - return __call__(); - case 1: - return __call__(args[0]); - case 2: - return __call__(args[0], args[1]); - case 3: - return __call__(args[0], args[1], args[2]); - case 4: - return __call__(args[0], args[1], args[2], args[3]); - default: - return fancyCall(args); - } - } - - public PyObject __call__(PyObject[] args, String[] kws) { - if (kws.length != 0) { - throw Py.TypeError(fastGetName() + "() takes no keyword arguments"); - } - return __call__(args); - } - - public PyObject __call__() { - throw info.unexpectedCall(0, false); - } - - public PyObject __call__(PyObject arg1) { - throw info.unexpectedCall(1, false); - } - - public PyObject __call__(PyObject arg1, PyObject arg2) { - throw info.unexpectedCall(2, false); - } - - public PyObject __call__(PyObject arg1, PyObject arg2, PyObject arg3) { - throw info.unexpectedCall(3, false); - } - - public PyObject __call__(PyObject arg1, - PyObject arg2, - PyObject arg3, - PyObject arg4) { - throw info.unexpectedCall(4, false); - } - - public PyBuiltinFunction bind(PyObject self) { - throw Py.TypeError("Can't bind a builtin function"); - } - - public String toString(){ - return "<built-in function "+info.getName()+">"; - } - } Modified: trunk/jython/src/org/python/core/PyBuiltinMethod.java =================================================================== --- trunk/jython/src/org/python/core/PyBuiltinMethod.java 2008-10-19 03:04:44 UTC (rev 5464) +++ trunk/jython/src/org/python/core/PyBuiltinMethod.java 2008-10-19 05:14:22 UTC (rev 5465) @@ -2,7 +2,7 @@ import org.python.expose.ExposeAsSuperclass; -public abstract class PyBuiltinMethod extends PyBuiltinFunction implements ExposeAsSuperclass { +public abstract class PyBuiltinMethod extends PyBuiltinCallable implements ExposeAsSuperclass { protected PyObject self; Modified: trunk/jython/src/org/python/core/PyBuiltinMethodNarrow.java =================================================================== --- trunk/jython/src/org/python/core/PyBuiltinMethodNarrow.java 2008-10-19 03:04:44 UTC (rev 5464) +++ trunk/jython/src/org/python/core/PyBuiltinMethodNarrow.java 2008-10-19 05:14:22 UTC (rev 5465) @@ -1,7 +1,5 @@ package org.python.core; -import org.python.core.PyBuiltinFunction.DefaultInfo; - public abstract class PyBuiltinMethodNarrow extends PyBuiltinMethod { protected PyBuiltinMethodNarrow(String name, int minArgs, int maxArgs) { Modified: trunk/jython/src/org/python/core/PyBuiltinMethodSet.java =================================================================== --- trunk/jython/src/org/python/core/PyBuiltinMethodSet.java 2008-10-19 03:04:44 UTC (rev 5464) +++ trunk/jython/src/org/python/core/PyBuiltinMethodSet.java 2008-10-19 05:14:22 UTC (rev 5465) @@ -25,7 +25,7 @@ return this; } - public PyBuiltinFunction bind(PyObject bindTo) { + public PyBuiltinCallable bind(PyObject bindTo) { if(__self__ == Py.None) { PyBuiltinMethodSet bindable; try { Modified: trunk/jython/src/org/python/core/PyClassMethodDescr.java =================================================================== --- trunk/jython/src/org/python/core/PyClassMethodDescr.java 2008-10-19 03:04:44 UTC (rev 5464) +++ trunk/jython/src/org/python/core/PyClassMethodDescr.java 2008-10-19 05:14:22 UTC (rev 5465) @@ -8,7 +8,7 @@ public static final PyType TYPE = PyType.fromClass(PyClassMethodDescr.class); - PyClassMethodDescr(PyType t, PyBuiltinFunction meth) { + PyClassMethodDescr(PyType t, PyBuiltinCallable meth) { super(t, meth); } Modified: trunk/jython/src/org/python/core/PyDictionary.java =================================================================== --- trunk/jython/src/org/python/core/PyDictionary.java 2008-10-19 03:04:44 UTC (rev 5464) +++ trunk/jython/src/org/python/core/PyDictionary.java 2008-10-19 05:14:22 UTC (rev 5465) @@ -422,7 +422,7 @@ private void updateCommon(PyObject[] args, String[] keywords, String methName) { int nargs = args.length - keywords.length; if (nargs > 1) { - throw PyBuiltinFunction.DefaultInfo.unexpectedCall(nargs, false, methName, 0, 1); + throw PyBuiltinCallable.DefaultInfo.unexpectedCall(nargs, false, methName, 0, 1); } if (nargs == 1) { PyObject arg = args[0]; Modified: trunk/jython/src/org/python/core/PyEnumerate.java =================================================================== --- trunk/jython/src/org/python/core/PyEnumerate.java 2008-10-19 03:04:44 UTC (rev 5464) +++ trunk/jython/src/org/python/core/PyEnumerate.java 2008-10-19 05:14:22 UTC (rev 5465) @@ -51,7 +51,7 @@ public final static PyObject enumerate_new(PyNewWrapper new_, boolean init, PyType subtype, PyObject[] args, String[] keywords) { if (args.length != 1) { - throw PyBuiltinFunction.DefaultInfo.unexpectedCall(args.length, false, "enumerate", 0, + throw PyBuiltinCallable.DefaultInfo.unexpectedCall(args.length, false, "enumerate", 0, 1); } if (new_.for_type == subtype) { Modified: trunk/jython/src/org/python/core/PyInstance.java =================================================================== --- trunk/jython/src/org/python/core/PyInstance.java 2008-10-19 03:04:44 UTC (rev 5464) +++ trunk/jython/src/org/python/core/PyInstance.java 2008-10-19 05:14:22 UTC (rev 5465) @@ -12,12 +12,12 @@ { // xxx doc, final name public transient PyClass instclass; - + // xxx public PyObject fastGetClass() { return instclass; } - + //This field is only used by Python subclasses of Java classes Object javaProxy; @@ -31,7 +31,7 @@ throws java.io.IOException, ClassNotFoundException { in.defaultReadObject(); - + String module = in.readUTF(); String name = in.readUTF(); @@ -153,9 +153,8 @@ return javaProxy; if (instclass.__tojava__ != null) { - //try { - PyObject ret = - instclass.__tojava__.__call__(this, PyJavaClass.lookup(c)); + // try { + PyObject ret = instclass.__tojava__.__call__(this, PyJavaClass.lookup(c)); if (ret == Py.None) return Py.NoConversion; @@ -221,8 +220,8 @@ PyObject[] result2 = instclass.lookupGivingClass(name, stopAtJava); if (result2[0] != null) // xxx do we need to use result2[1] (wherefound) for java cases for backw comp? - return result2[0].__get__(this, instclass); - // xxx do we need to use + return result2[0].__get__(this, instclass); + // xxx do we need to use return ifindfunction(name); } @@ -429,7 +428,7 @@ smod = ((PyString)mod).toString() + '.'; } } - return new PyString("<" + smod + instclass.__name__ + " instance at " + + return new PyString("<" + smod + instclass.__name__ + " instance at " + Py.idstr(this) + ">"); } @@ -483,8 +482,8 @@ if (coerced != null) { v = coerced[0]; w = coerced[1]; - if (!(v instanceof PyInstance) && - !(w instanceof PyInstance)) + if (!(v instanceof PyInstance) && + !(w instanceof PyInstance)) return v._cmp(w); } else { v = this; @@ -497,8 +496,8 @@ int result = ((PyInteger)ret).getValue(); return result < 0 ? -1 : result > 0 ? 1 : 0; } - throw Py.TypeError("__cmp__() must return int"); - } + throw Py.TypeError("__cmp__() must return int"); + } } if (w instanceof PyInstance) { ret = ((PyInstance)w).invoke_ex("__cmp__",v); @@ -507,9 +506,9 @@ int result = ((PyInteger)ret).getValue(); return -(result < 0 ? -1 : result > 0 ? 1 : 0); } - throw Py.TypeError("__cmp__() must return int"); - } - + throw Py.TypeError("__cmp__() must return int"); + } + } return -2; } Modified: trunk/jython/src/org/python/core/PyMethodDescr.java =================================================================== --- trunk/jython/src/org/python/core/PyMethodDescr.java 2008-10-19 03:04:44 UTC (rev 5464) +++ trunk/jython/src/org/python/core/PyMethodDescr.java 2008-10-19 05:14:22 UTC (rev 5465) @@ -5,13 +5,13 @@ import org.python.expose.ExposedType; @ExposedType(name = "method_descriptor", base = PyObject.class) -public class PyMethodDescr extends PyDescriptor implements PyBuiltinFunction.Info { +public class PyMethodDescr extends PyDescriptor implements PyBuiltinCallable.Info { protected int minargs, maxargs; - protected PyBuiltinFunction meth; + protected PyBuiltinCallable meth; - public PyMethodDescr(PyType t, PyBuiltinFunction func) { + public PyMethodDescr(PyType t, PyBuiltinCallable func) { name = func.info.getName(); dtype = t; minargs = func.info.getMinargs(); @@ -50,7 +50,7 @@ } public PyException unexpectedCall(int nargs, boolean keywords) { - return PyBuiltinFunction.DefaultInfo.unexpectedCall(nargs, keywords, name, minargs, + return PyBuiltinCallable.DefaultInfo.unexpectedCall(nargs, keywords, name, minargs, maxargs); } Modified: trunk/jython/src/org/python/core/PyNewWrapper.java =================================================================== --- trunk/jython/src/org/python/core/PyNewWrapper.java 2008-10-19 03:04:44 UTC (rev 5464) +++ trunk/jython/src/org/python/core/PyNewWrapper.java 2008-10-19 05:14:22 UTC (rev 5465) @@ -29,7 +29,7 @@ PyObject[] args, String[] keywords); - public PyBuiltinFunction bind(PyObject self) { + public PyBuiltinCallable bind(PyObject self) { throw Py.SystemError("__new__ wrappers are already bound"); } Modified: trunk/jython/src/org/python/core/PyObject.java =================================================================== --- trunk/jython/src/org/python/core/PyObject.java 2008-10-19 03:04:44 UTC (rev 5464) +++ trunk/jython/src/org/python/core/PyObject.java 2008-10-19 05:14:22 UTC (rev 5465) @@ -332,8 +332,8 @@ String name; if (this instanceof PyFunction) { name = ((PyFunction) this).__name__ + "() "; - } else if (this instanceof PyBuiltinFunction) { - name = ((PyBuiltinFunction)this).fastGetName().toString() + "() "; + } else if (this instanceof PyBuiltinCallable) { + name = ((PyBuiltinCallable)this).fastGetName().toString() + "() "; } else { name = getType().fastGetName() + " "; } Modified: trunk/jython/src/org/python/core/PySet.java =================================================================== --- trunk/jython/src/org/python/core/PySet.java 2008-10-19 03:04:44 UTC (rev 5464) +++ trunk/jython/src/org/python/core/PySet.java 2008-10-19 05:14:22 UTC (rev 5465) @@ -30,7 +30,7 @@ final void set___init__(PyObject[] args, String[] kwds) { int nargs = args.length - kwds.length; if (nargs > 1) { - throw PyBuiltinFunction.DefaultInfo.unexpectedCall(nargs, false, "Set", 0, 1); + throw PyBuiltinCallable.DefaultInfo.unexpectedCall(nargs, false, "Set", 0, 1); } if (nargs == 0) { return; Modified: trunk/jython/src/org/python/core/PyStringMap.java =================================================================== --- trunk/jython/src/org/python/core/PyStringMap.java 2008-10-19 03:04:44 UTC (rev 5464) +++ trunk/jython/src/org/python/core/PyStringMap.java 2008-10-19 05:14:22 UTC (rev 5465) @@ -242,7 +242,7 @@ public void update(PyObject[] args, String[] keywords) { int nargs = args.length - keywords.length; if (nargs > 1) { - throw PyBuiltinFunction.DefaultInfo.unexpectedCall(nargs, false, "update", 0, 1); + throw PyBuiltinCallable.DefaultInfo.unexpectedCall(nargs, false, "update", 0, 1); } if (nargs == 1) { PyObject arg = args[0]; Modified: trunk/jython/src/org/python/core/PySuper.java =================================================================== --- trunk/jython/src/org/python/core/PySuper.java 2008-10-19 03:04:44 UTC (rev 5464) +++ trunk/jython/src/org/python/core/PySuper.java 2008-10-19 05:14:22 UTC (rev 5465) @@ -34,8 +34,8 @@ @ExposedMethod @ExposedNew public void super___init__(PyObject[] args, String[] keywords) { - if (keywords.length != 0 || !PyBuiltinFunction.DefaultInfo.check(args.length, 1, 2)) { - throw PyBuiltinFunction.DefaultInfo.unexpectedCall(args.length, keywords.length != 0, + if (keywords.length != 0 || !PyBuiltinCallable.DefaultInfo.check(args.length, 1, 2)) { + throw PyBuiltinCallable.DefaultInfo.unexpectedCall(args.length, keywords.length != 0, "super", 1, 2); } if (!(args[0] instanceof PyType)) { Modified: trunk/jython/src/org/python/core/PyType.java =================================================================== --- trunk/jython/src/org/python/core/PyType.java 2008-10-19 03:04:44 UTC (rev 5464) +++ trunk/jython/src/org/python/core/PyType.java 2008-10-19 05:14:22 UTC (rev 5465) @@ -13,6 +13,7 @@ import java.util.HashSet; import java.util.Iterator; import java.util.List; +import java.util.Map; import org.python.core.util.StringUtil; import org.python.expose.ExposeAsSuperclass; @@ -260,8 +261,7 @@ newtype.has_delete = newtype.lookup("__delete__") != null; newtype.needs_finalizer = newtype.lookup("__del__") != null; - for (int i = 0; i < bases_list.length; i++) { - PyObject cur = bases_list[i]; + for (PyObject cur : bases_list) { if (cur instanceof PyType) ((PyType)cur).attachSubclass(newtype); } @@ -338,10 +338,9 @@ // BOOTSTRAP_TYPES will be filled in by addBuilder later return; } - HashMap<String, Object> propnames = new HashMap<String, Object>(); + Map<String, Object> propnames = new HashMap<String, Object>(); Method[] methods = c.getMethods(); - for (int i = 0; i < methods.length; i++) { - Method meth = methods[i]; + for (Method meth : methods) { Class declaring = meth.getDeclaringClass(); if (declaring != base && base.isAssignableFrom(declaring) && !ignore(meth)) { String methname = meth.getName(); @@ -369,8 +368,7 @@ } } } - for (int i = 0; i < methods.length; i++) { - Method meth = methods[i]; + for (Method meth : methods) { String nmethname = normalize_name(meth.getName()); PyReflectedFunction reflfunc = (PyReflectedFunction)dict.__finditem__(nmethname); if (reflfunc != null) { @@ -378,8 +376,7 @@ } } Field[] fields = c.getFields(); - for (int i = 0; i < fields.length; i++) { - Field field = fields[i]; + for (Field field : fields) { Class declaring = field.getDeclaringClass(); if (declaring != base && base.isAssignableFrom(declaring)) { String fldname = field.getName(); @@ -404,8 +401,7 @@ dict.__setitem__(normalize_name(fldname), new PyReflectedField(field)); } } - for (Iterator iter = propnames.keySet().iterator(); iter.hasNext();) { - String propname = (String)iter.next(); + for (String propname : propnames.keySet()) { String npropname = normalize_name(StringUtil.decapitalize(propname)); PyObject prev = dict.__finditem__(npropname); if (prev != null && prev instanceof PyReflectedFunction) { @@ -437,8 +433,8 @@ Constructor[] ctrs = c.getConstructors(); if (ctrs.length != 0) { final PyReflectedConstructor reflctr = new PyReflectedConstructor("_new_impl"); - for (int i = 0; i < ctrs.length; i++) { - reflctr.addConstructor(ctrs[i]); + for (Constructor ctr : ctrs) { + reflctr.addConstructor(ctr); } PyObject new_ = new PyNewWrapper(c, "__new__", -1, -1) { public PyObject new_impl(boolean init, PyType subtype, PyObject[] args, @@ -557,14 +553,14 @@ base = newBase; mro_internal(); mro_subclasses(savedSubMros); - for (int i = 0; i < savedBases.length; i++) { - if (savedBases[i] instanceof PyType) { - ((PyType)savedBases[i]).detachSubclass(this); + for (PyObject saved : savedBases) { + if (saved instanceof PyType) { + ((PyType)saved).detachSubclass(this); } } - for (int i = 0; i < newBases.length; i++) { - if (newBases[i] instanceof PyType) { - ((PyType)newBases[i]).attachSubclass(this); + for (PyObject newb : newBases) { + if (newb instanceof PyType) { + ((PyType)newb).attachSubclass(this); } } } catch (PyException t) { @@ -703,8 +699,8 @@ acc.add(classic_cl); } PyObject[] bases = classic_cl.__bases__.getArray(); - for (int i = 0; i < bases.length; i++) { - fill_classic_mro(acc,(PyClass)bases[i]); + for (PyObject base : bases) { + fill_classic_mro(acc,(PyClass)base); } } @@ -850,24 +846,22 @@ PyType winner = null; PyType candidate = null; PyType best = null; - for (int i = 0; i < bases.length; i++) { - PyObject base_proto = bases[i]; - if (base_proto instanceof PyClass) { + for (PyObject base : bases) { + if (base instanceof PyClass) { continue; } - if (!(base_proto instanceof PyType)) { + if (!(base instanceof PyType)) { throw Py.TypeError("bases must be types"); } - PyType base = (PyType)base_proto; - candidate = solid_base(base); + candidate = solid_base((PyType)base); if (winner == null) { winner = candidate; - best = base; + best = (PyType)base; } else if (winner.isSubType(candidate)) { ; } else if (candidate.isSubType(winner)) { winner = candidate; - best = base; + best = (PyType)base; } else { throw Py.TypeError("multiple bases have instance lay-out conflict"); } @@ -889,18 +883,17 @@ */ private static PyType findMostDerivedMetatype(PyObject[] bases_list, PyType initialMetatype) { PyType winner = initialMetatype; - for (int i = 0; i < bases_list.length; i++) { - PyObject bases_i = bases_list[i]; - if (bases_i instanceof PyJavaClass) { + for (PyObject base : bases_list) { + if (base instanceof PyJavaClass) { throw Py.TypeError("can't mix new-style and java classes"); } - if (bases_i instanceof PyClass) { - if (((PyClass)bases_i).proxyClass != null) { + if (base instanceof PyClass) { + if (((PyClass)base).proxyClass != null) { throw Py.TypeError("can't mix new-style and java classes"); } continue; } - PyType curtype = bases_i.getType(); + PyType curtype = base.getType(); if (winner.isSubType(curtype)) { continue; } @@ -962,8 +955,8 @@ if (mro == null) { return null; } - for (int i = 0; i < mro.length; i++) { - PyObject dict = mro[i].fastGetDict(); + for (PyObject element : mro) { + PyObject dict = element.fastGetDict(); if (dict != null) { PyObject obj = dict.__finditem__(name); if (obj != null) @@ -978,8 +971,7 @@ if (mro == null) { return null; } - for (int i = 0; i < mro.length; i++) { - PyObject t = mro[i]; + for (PyObject t : mro) { PyObject dict = t.fastGetDict(); if (dict != null) { PyObject obj = dict.__finditem__(name); @@ -1047,8 +1039,8 @@ private static boolean ignore(Method meth) { Class[] exceptions = meth.getExceptionTypes(); - for (int j = 0; j < exceptions.length; j++) { - if (exceptions[j] == PyIgnoreMethodTag.class) { + for (Class exception : exceptions) { + if (exception == PyIgnoreMethodTag.class) { return true; } } @@ -1261,8 +1253,8 @@ if (mro == null) { return; } - for (int i = 0; i < mro.length; i++) { - mro[i].addKeys(accum, "__dict__"); + for (PyObject element : mro) { + element.addKeys(accum, "__dict__"); } } Modified: trunk/jython/src/org/python/core/__builtin__.java =================================================================== --- trunk/jython/src/org/python/core/__builtin__.java 2008-10-19 03:04:44 UTC (rev 5464) +++ trunk/jython/src/org/python/core/__builtin__.java 2008-10-19 05:14:22 UTC (rev 5465) @@ -1,15 +1,11 @@ // Copyright (c) Corporation for National Research Initiatives package org.python.core; -import java.util.Arrays; import java.util.Iterator; import java.util.Map; import org.python.antlr.ast.modType; import org.python.core.util.RelativeFile; -import org.python.expose.ExposedGet; -import org.python.expose.ExposedNew; -import org.python.expose.ExposedType; class BuiltinFunctions extends PyBuiltinFunctionSet { @@ -236,7 +232,7 @@ /** * @param intern - should the resulting string be interned - * @return arg as a String, or throws TypeError with message if asString throws a ConversionException. + * @return arg as a String, or throws TypeError with message if asString throws a ConversionException. */ private String asString(PyObject arg, String message, boolean intern) { @@ -280,7 +276,7 @@ } if (args[0] instanceof PyUnicode) { - flags += PyTableCode.PyCF_SOURCE_IS_UTF8; + flags += PyTableCode.PyCF_SOURCE_IS_UTF8; } return __builtin__.compile(args[0].toString(), args[1].toString(), args[2].toString(), flags, dont_inherit); case 29: @@ -373,23 +369,23 @@ dict.__setitem__("iter", new BuiltinFunctions("iter", 27, 1, 2)); dict.__setitem__("locals", new BuiltinFunctions("locals", 28, 0)); dict.__setitem__("map", new BuiltinFunctions("map", 29, 2, -1)); - dict.__setitem__("max", MaxFunction.INSTANCE); - dict.__setitem__("min", MinFunction.INSTANCE); + dict.__setitem__("max", new MaxFunction()); + dict.__setitem__("min", new MinFunction()); dict.__setitem__("oct", new BuiltinFunctions("oct", 32, 1)); dict.__setitem__("pow", new BuiltinFunctions("pow", 33, 2, 3)); dict.__setitem__("raw_input", new BuiltinFunctions("raw_input", 34, 0, 1)); dict.__setitem__("reduce", new BuiltinFunctions("reduce", 35, 2, 3)); dict.__setitem__("reload", new BuiltinFunctions("reload", 36, 1)); dict.__setitem__("repr", new BuiltinFunctions("repr", 37, 1)); - dict.__setitem__("round", RoundFunction.INSTANCE); + dict.__setitem__("round", new RoundFunction()); dict.__setitem__("setattr", new BuiltinFunctions("setattr", 39, 3)); dict.__setitem__("vars", new BuiltinFunctions("vars", 41, 0, 1)); dict.__setitem__("zip", new BuiltinFunctions("zip", 43, 0, -1)); dict.__setitem__("reversed", new BuiltinFunctions("reversed", 45, 1)); - dict.__setitem__("__import__", ImportFunction.INSTANCE); - dict.__setitem__("sorted", SortedFunction.INSTANCE); - dict.__setitem__("all", AllFunction.INSTANCE); - dict.__setitem__("any", AnyFunction.INSTANCE); + dict.__setitem__("__import__", new ImportFunction()); + dict.__setitem__("sorted", new SortedFunction()); + dict.__setitem__("all", new AllFunction()); + dict.__setitem__("any", new AnyFunction()); } public static PyObject abs(PyObject o) { @@ -399,7 +395,7 @@ public static PyObject apply(PyObject o) { return o.__call__(); } - + public static PyObject apply(PyObject o, PyObject args) { return o.__call__(Py.make_array(args)); } @@ -465,7 +461,7 @@ public static PyObject compile(modType node, String filename, String kind) { return Py.compile_flags(node, filename, kind, Py.getCompilerFlags()); } - + public static PyObject compile(String data, String filename, String kind, int flags, boolean dont_inherit) { if ((flags & ~PyTableCode.CO_ALL_FEATURES) != 0) { throw Py.ValueError("compile(): unrecognised flags"); @@ -518,16 +514,16 @@ (o.__findattr__("__getitem__") != null && (!rw || o.__findattr__("__setitem__") != null)); } - + private static void verify_mappings(PyObject globals, PyObject locals, boolean rw) { if (!PyMapping_check(globals, rw)) { throw Py.TypeError("globals must be a mapping"); - } + } if (!PyMapping_check(locals, rw)) { throw Py.TypeError("locals must be a mapping"); } } - + public static PyObject eval(PyObject o, PyObject globals, PyObject locals) { verify_mappings(globals, locals, false); PyCode code; @@ -900,7 +896,7 @@ throw Py.TypeError("ord() expected a character, but string of length " + length + " found"); } - + public static PyObject pow(PyObject x, PyObject y) { return x._pow(y); } @@ -1037,7 +1033,7 @@ return (PyString) ret; } } - + public static String raw_input(PyObject prompt, PyObject file) { PyObject stdout = Py.getSystemState().stdout; if (stdout instanceof PyAttributeDeleted) { @@ -1157,7 +1153,7 @@ public static PyObject zip() { return new PyList(); } - + public static PyObject zip(PyObject[] argstar) { int itemsize = argstar.length; @@ -1233,81 +1229,40 @@ } } -// simulates a PyBuiltinFunction for functions not using the PyBuiltinFunctionSet approach of above -abstract class ExtendedBuiltinFunction extends PyObject { - public static final PyType TYPE = PyType.fromClass(PyBuiltinFunction.class); - @ExposedGet(name = "__class__") - @Override - public PyType getType() { - return TYPE; +class ImportFunction extends PyBuiltinFunction { + ImportFunction() { + super("__import__", + "__import__(name, globals={}, locals={}, fromlist=[], level=-1) -> module\n\n" + + "Import a module. The globals are only used to determine the context;\n" + + "they are not modified. The locals are currently unused. The fromlist\n" + + "should be a list of names to emulate ``from name import ...'', or an\n" + + "empty list to emulate ``import name''.\n" + + "When importing a module from a package, note that __import__('A.B', ...)\n" + + "returns package A when fromlist is empty, but its submodule B when\n" + + "fromlist is not empty. Level is used to determine whether to perform \n" + + "absolute or relative imports. -1 is the original strategy of attempting\n" + + "both absolute and relative imports, 0 is absolute, a positive number\n" + + "is the number of parent directories to search relative to the current module."); } -} -class ImportFunction extends ExtendedBuiltinFunction { - static final ImportFunction INSTANCE = new ImportFunction(); - - private ImportFunction() {} - - @ExposedNew - public static PyObject __new__(PyObject[] args, String[] keyword) { - return INSTANCE; - } - - @ExposedGet(name = "__doc__") - public PyObject getDoc() { - return new PyString("__import__(name, globals={}, locals={}, fromlist=[], level=-1) -> module\n\n" + - "Import a module. The globals are only used to determine the context;\n" + - "they are not modified. The locals are currently unused. The fromlist\n" + - "should be a list of names to emulate ``from name import ...'', or an\n" + - "empty list to emulate ``import name''.\n" + - "When importing a module from a package, note that __import__('A.B', ...)\n" + - "returns package A when fromlist is empty, but its submodule B when\n" + - "fromlist is not empty. Level is used to determine whether to perform \n" + - "absolute or relative imports. -1 is the original strategy of attempting\n" + - "both absolute and relative imports, 0 is absolute, a positive number\n" + - "is the number of parent directories to search relative to the current module."); - } - public PyObject __call__(PyObject args[], String keywords[]) { - ArgParser ap = new ArgParser("__import__", args, keywords, new String[]{"name", "globals", "locals", "fromlist", "level"}, 1); - + ArgParser ap = new ArgParser("__import__", args, keywords, + new String[]{"name", "globals", "locals", "fromlist", "level"}, + 1); String module = ap.getString(0); PyObject globals = ap.getPyObject(1, null); PyObject fromlist = ap.getPyObject(3, Py.EmptyTuple); int level = ap.getInt(4, imp.DEFAULT_LEVEL); - - return load(module, globals, fromlist, level); + return imp.importName(module.intern(), fromlist.__len__() == 0, globals, fromlist, level); } +} - private PyObject load(String module, PyObject globals, PyObject fromlist, int level) { - PyObject mod = imp.importName(module.intern(), fromlist.__len__() == 0, globals, fromlist, level); - return mod; +class SortedFunction extends PyBuiltinFunction { + SortedFunction() { + super("sorted", "sorted(iterable, cmp=None, key=None, reverse=False) --> new sorted list"); } - public String toString() { - return "<built-in function __import__>"; - } - - -} - -class SortedFunction extends ExtendedBuiltinFunction { - static final SortedFunction INSTANCE = new SortedFunction(); - - private SortedFunction() {} - - @ExposedNew - public static PyObject __new__(PyObject[] args, String[] keyword) { - return INSTANCE; - } - - @ExposedGet(name = "__doc__") @Override - public PyObject getDoc() { - return new PyString("sorted(iterable, cmp=None, key=None, reverse=False) --> new sorted list"); - } - - @Override public PyObject __call__(PyObject args[], String kwds[]) { if (args.length == 0) { throw Py.TypeError(" sorted() takes at least 1 argument (0 given)"); @@ -1333,37 +1288,20 @@ seq.sort(cmp, key, reverse); return seq; } - - @Override - public String toString() { - return "<built-in function sorted>"; - } } -class AllFunction extends ExtendedBuiltinFunction { - static final AllFunction INSTANCE = new AllFunction(); - - private AllFunction() {} - - @ExposedNew - public static PyObject __new__(PyObject[] args, String[] keyword) { - return INSTANCE; - } - - @ExposedGet(name = "__doc__") - @Override - public PyObject getDoc() { - return new PyString("all(iterable) -> bool\n\nReturn True if bool(x) is True for all values x in the iterable."); +class AllFunction extends PyBuiltinFunctionNarrow { + AllFunction() { + super("all", 1, 1, + "all(iterable) -> bool\n\n" + + "Return True if bool(x) is True for all values x in the iterable."); } @Override - public PyObject __call__(PyObject args[], String kwds[]) { - if (args.length !=1) { - throw Py.TypeError(" all() takes exactly one argument (" + args.length + " given)"); - } - PyObject iter = args[0].__iter__(); + public PyObject __call__(PyObject arg) { + PyObject iter = arg.__iter__(); if (iter == null) { - throw Py.TypeError("'" + args[0].getType().fastGetName() + "' object is not iterable"); + throw Py.TypeError("'" + arg.getType().fastGetName() + "' object is not iterable"); } for (PyObject item : iter.asIterable()) { if (!item.__nonzero__()) { @@ -1372,78 +1310,44 @@ } return Py.True; } - - @Override - public String toString() { - return "<built-in function all>"; - } } -class AnyFunction extends ExtendedBuiltinFunction { - static final AnyFunction INSTANCE = new AnyFunction(); - - private AnyFunction() {} - - @ExposedNew - public static PyObject __new__(PyObject[] args, String[] keyword) { - return INSTANCE; - } - - @ExposedGet(name = "__doc__") - @Override - public PyObject getDoc() { - return new PyString("any(iterable) -> bool\n\nReturn True if bool(x) is True for any x in the iterable."); +class AnyFunction extends PyBuiltinFunctionNarrow { + AnyFunction() { + super("any", 1, 1, + "any(iterable) -> bool\n\nReturn True if bool(x) is True for any x in the iterable."); } @Override - public PyObject __call__(PyObject args[], String kwds[]) { - if (args.length !=1) { - throw Py.TypeError(" any() takes exactly one argument (" + args.length + " given)"); - } - PyObject iter = args[0].__iter__(); + public PyObject __call__(PyObject arg) { + PyObject iter = arg.__iter__(); if (iter == null) { - throw Py.TypeError("'" + args[0].getType().fastGetName() + "' object is not iterable"); + throw Py.TypeError("'" + arg.getType().fastGetName() + "' object is not iterable"); } for (PyObject item : iter.asIterable()) { if (item.__nonzero__()) { return Py.True; } } - return Py.False; + return Py.False; } - - @Override - public String toString() { - return "<built-in function any>"; - } } -class MaxFunction extends ExtendedBuiltinFunction { - static final MaxFunction INSTANCE = new MaxFunction(); - - private MaxFunction() {} - - @ExposedNew - public static PyObject __new__(PyObject[] args, String[] keyword) { - return INSTANCE; - } - - @ExposedGet(name = "__doc__") - @Override - public PyObject getDoc() { - return new PyString( - "max(iterable[, key=func]) -> value\nmax(a, b, c, ...[, key=func]) -> value\n\n" + - "With a single iterable argument, return its largest item.\n" + - "With two or more arguments, return the largest argument."); +class MaxFunction extends PyBuiltinFunction { + MaxFunction() { + super("max", + "max(iterable[, key=func]) -> value\nmax(a, b, c, ...[, key=func]) -> value\n\n" + + "With a single iterable argument, return its largest item.\n" + + "With two or more arguments, return the largest argument."); } @Override public PyObject __call__(PyObject args[], String kwds[]) { int argslen = args.length; PyObject key = null; - + if (args.length - kwds.length == 0) { - throw Py.TypeError(" max() expected 1 arguments, got 0"); + throw Py.TypeError("max() expected 1 arguments, got 0"); } if (kwds.length > 0) { if (kwds[0].equals("key")) { @@ -1453,23 +1357,18 @@ args = newargs; } else { - throw Py.TypeError(" max() got an unexpected keyword argument"); + throw Py.TypeError("max() got an unexpected keyword argument"); } } - + if (args.length > 1) { return max(new PyTuple(args), key); } else { return max(args[0], key); } - } - - @Override - public String toString() { - return "<built-in function max>"; } - + private static PyObject max(PyObject o, PyObject key) { PyObject max = null; PyObject maxKey = null; @@ -1494,31 +1393,19 @@ } -class MinFunction extends ExtendedBuiltinFunction { - static final MinFunction INSTANCE = new MinFunction(); - - private MinFunction() {} - - @ExposedNew - public static PyObject __new__(PyObject[] args, String[] keyword) { - return INSTANCE; - } - - - @ExposedGet(name = "__doc__") - @Override - public PyObject getDoc() { - return new PyString( - "min(iterable[, key=func]) -> value\nmin(a, b, c, ...[, key=func]) -> value\n\n" + - "With a single iterable argument, return its smallest item.\n" + - "With two or more arguments, return the smallest argument.'"); +class MinFunction extends PyBuiltinFunction { + MinFunction() { + super("min", + "min(iterable[, key=func]) -> value\nmin(a, b, c, ...[, key=func]) -> value\n\n" + + "With a single iterable argument, return its smallest item.\n" + + "With two or more arguments, return the smallest argument.'"); } @Override public PyObject __call__(PyObject args[], String kwds[]) { int argslen = args.length; PyObject key = null; - + if (args.length - kwds.length == 0) { throw Py.TypeError(" min() expected 1 arguments, got 0"); } @@ -1530,10 +1417,10 @@ args = newargs; } else { - throw Py.TypeError(" min() got an unexpected keyword argument"); + throw Py.TypeError("min() got an unexpected keyword argument"); } } - + if (args.length > 1) { return min(new PyTuple(args), key); } @@ -1541,12 +1428,7 @@ return min(args[0], key); } } - - @Override - public String toString() { - return "<built-in function min>"; - } - + private static PyObject min(PyObject o, PyObject key) { PyObject min = null; PyObject minKey = null; @@ -1570,37 +1452,20 @@ } } -class RoundFunction extends ExtendedBuiltinFunction { - static final RoundFunction INSTANCE = new RoundFunction(); - private RoundFunction() {} - - @ExposedNew - public static PyObject __new__(PyObject[] args, String[] keyword) { - return INSTANCE; - } - - @ExposedGet(name = "__doc__") - @Override - public PyObject getDoc() { - return new PyString( - "round(number[, ndigits]) -> floating point number\n\n" + - "Round a number to a given precision in decimal digits (default 0 digits).\n" + - "This always returns a floating point number. Precision may be negative."); +class RoundFunction extends PyBuiltinFunction { + RoundFunction() { + super("round", "round(number[, ndigits]) -> floating point number\n\n" + + "Round a number to a given precision in decimal digits (default 0 digits).\n" + + "This always returns a floating point number. Precision may be negative."); } - - @Override - public String toString() { - return "<built-in function round>"; - } - - @Override + public PyObject __call__(PyObject args[], String kwds[]) { - ArgParser ap = new ArgParser("round", args, kwds, new String[]{"number", "ndigits"}, 0); + ArgParser ap = new ArgParser("round", args, kwds, new String[] {"number", "ndigits"}, 0); PyObject number = ap.getPyObject(0); int ndigits = ap.getInt(1, 0); return round(Py.py2double(number), ndigits); } - + private static PyFloat round(double f, int digits) { boolean neg = f < 0; double multiple = Math.pow(10., digits); Modified: trunk/jython/src/org/python/core/exceptions.java =================================================================== --- trunk/jython/src/org/python/core/exceptions.java 2008-10-19 03:04:44 UTC (rev 5464) +++ trunk/jython/src/org/python/core/exceptions.java 2008-10-19 05:14:22 UTC (rev 5465) @@ -661,7 +661,7 @@ this.javaMethod = javaMethod; } - public PyBuiltinFunction bind(PyObject self) { + public PyBuiltinCallable bind(PyObject self) { return new BoundStaticJavaMethod(getType(), self, info, javaMethod); } Modified: trunk/jython/src/org/python/expose/generate/Py... [truncated message content] |
From: <zy...@us...> - 2008-10-19 22:04:59
|
Revision: 5470 http://jython.svn.sourceforge.net/jython/?rev=5470&view=rev Author: zyasoft Date: 2008-10-19 22:04:51 +0000 (Sun, 19 Oct 2008) Log Message: ----------- Make error handling in codecs so that it is also surrogate-aware. Fixes test_codeccallbacks Skip tests from test_threading not applicable to Jython. Modified Paths: -------------- trunk/jython/Lib/test/test_codeccallbacks.py trunk/jython/Lib/test/test_threading.py trunk/jython/Lib/unicodedata.py trunk/jython/src/org/python/core/codecs.java trunk/jython/src/org/python/core/exceptions.java Modified: trunk/jython/Lib/test/test_codeccallbacks.py =================================================================== --- trunk/jython/Lib/test/test_codeccallbacks.py 2008-10-19 20:51:56 UTC (rev 5469) +++ trunk/jython/Lib/test/test_codeccallbacks.py 2008-10-19 22:04:51 UTC (rev 5470) @@ -589,7 +589,7 @@ ("ascii", "\xff"), ("utf-8", "\xff"), ("utf-7", "+x-"), - ("unicode-internal", "\x00"), + # ("unicode-internal", "\x00"), - not valid for Jython because PyUnicode/PyString share internal representation ): self.assertRaises( TypeError, @@ -794,6 +794,9 @@ text.translate(charmap) def test_main(): + if test.test_support.is_jython: + del CodecCallbackTest.test_decodeunicodeinternal # PyUnicode/PyString share the same internal rep, so n/a + test.test_support.run_unittest(CodecCallbackTest) if __name__ == "__main__": Modified: trunk/jython/Lib/test/test_threading.py =================================================================== --- trunk/jython/Lib/test/test_threading.py 2008-10-19 20:51:56 UTC (rev 5469) +++ trunk/jython/Lib/test/test_threading.py 2008-10-19 22:04:51 UTC (rev 5470) @@ -1,7 +1,7 @@ # Very rudimentary test of threading module import test.test_support -from test.test_support import verbose +from test.test_support import verbose, is_jython import random import sys import threading @@ -118,7 +118,7 @@ # 3. This behavior doesn't make sense for Jython since any foreign # Java threads can use the same underlying locks, etc - def na_for_jython_test_foreign_thread(self): + def test_foreign_thread(self): # Check that a "foreign" thread can use the threading module. def f(mutex): # Acquiring an RLock forces an entry for the foreign @@ -208,7 +208,7 @@ t.join() # else the thread is still running, and we have no way to kill it - def na_for_jython_test_enumerate_after_join(self): + def test_enumerate_after_join(self): # Try hard to trigger #1703448: a thread is still returned in # threading.enumerate() after it has been join()ed. enum = threading.enumerate @@ -225,6 +225,10 @@ finally: sys.setcheckinterval(old_interval) +if is_jython: + del ThreadTests.test_enumerate_after_join + del ThreadTests.test_foreign_thread + del ThreadTests.test_PyThreadState_SetAsyncExc def test_main(): test.test_support.run_unittest(ThreadTests) Modified: trunk/jython/Lib/unicodedata.py =================================================================== --- trunk/jython/Lib/unicodedata.py 2008-10-19 20:51:56 UTC (rev 5469) +++ trunk/jython/Lib/unicodedata.py 2008-10-19 22:04:51 UTC (rev 5470) @@ -41,6 +41,10 @@ cols = row.split(';') codepoint = int(cols[0], 16) name = cols[1] + if name == '<CJK Ideograph, Last>': + lookup_name = 'CJK UNIFIED IDEOGRAPH' + else: + lookup_name = name data = ( cols[2], get_int(cols[3]), @@ -49,7 +53,9 @@ get_int(cols[6]), get_int(cols[7]), get_numeric(cols[8]), - get_yn(cols[9])) + get_yn(cols[9]), + lookup_name, + ) if name.find('First') >= 0: start = codepoint @@ -86,15 +92,27 @@ init(my_path) init_east_asian_width(my_path) +# xxx - need to normalize the segments, so +# <CJK Ideograph, Last> ==> CJK UNIFIED IDEOGRAPH; +# may need to do some sort of analysis against CPython for the normalization! + def name(unichr, default=None): - try: - return _codepoints[ord(unichr)].name - except KeyError: - if default is not None: + codepoint = get_codepoint(unichr, "name") + v = _codepoints.get(codepoint, None) + if v is None: + v = check_segments(codepoint, _segments) + if v is not None: + return "%s-%X" % (v[8], codepoint) + + if v is None: + if default is not Nonesuch: return default - else: - raise ValueError() + raise ValueError() + return v[8] +# xxx - also need to add logic here so that if it's CJK UNIFIED +# IDEOGRAPH-8000, we go against the segment to verify the prefix + def lookup(name): return _names[name] Modified: trunk/jython/src/org/python/core/codecs.java =================================================================== --- trunk/jython/src/org/python/core/codecs.java 2008-10-19 20:51:56 UTC (rev 5469) +++ trunk/jython/src/org/python/core/codecs.java 2008-10-19 22:04:51 UTC (rev 5470) @@ -243,9 +243,17 @@ ArgParser ap = new ArgParser("replace_errors", args, kws, "exc"); PyObject exc = ap.getPyObject(0); if (Py.isInstance(exc, Py.UnicodeDecodeError)) { + PyObject object = exc.__getattr__("object"); + if (!Py.isInstance(object, PyString.TYPE) || Py.isInstance(object, PyUnicode.TYPE)) { + throw Py.TypeError("object attribute must be str"); + } PyObject end = exc.__getattr__("end"); return new PyTuple(new PyUnicode(Py_UNICODE_REPLACEMENT_CHARACTER), end); } else if (Py.isInstance(exc, Py.UnicodeEncodeError)) { + PyObject object = exc.__getattr__("object"); + if (!Py.isInstance(object, PyUnicode.TYPE)) { + throw Py.TypeError("object attribute must be unicode"); + } PyObject end = exc.__getattr__("end"); return new PyTuple(Py.java2py("?"), end); } else if (Py.isInstance(exc, Py.UnicodeTranslateError)) { @@ -343,9 +351,9 @@ } private static void backslashreplace_internal(int start, int end, String object, StringBuilder replacement) { - for (int i = start; i < end; i++) { + for (Iterator<Integer> iter = new StringSubsequenceIterator(object, start, end, 1); iter.hasNext();) { + int c = iter.next(); replacement.append('\\'); - char c = object.charAt(i); if (c >= 0x00010000) { replacement.append('U'); replacement.append(hexdigits[(c >> 28) & 0xf]); @@ -1257,3 +1265,75 @@ } } } + + +class StringSubsequenceIterator implements Iterator { + + private final String s; + private int current, k, start, stop, step; + + StringSubsequenceIterator(String s, int start, int stop, int step) { +// System.out.println("s=" + s.length() + ",start=" + start + ",stop=" + stop); + this.s = s; + k = 0; + current = start; + this.start = start; + this.stop = stop; + this.step = step; + + // this bounds checking is necessary to convert between use of code units elsewhere, and codepoints here + // it would be nice if it were unnecessary! + int count = getCodePointCount(s); + if (start >= count) { + this.stop = -1; + } + else if (stop >= count) { + this.stop = count; + } + + for (int i = 0; i < start; i++) { + nextCodePoint(); + } + } + + StringSubsequenceIterator(String s) { + this(s, 0, getCodePointCount(s), 1); + } + + private static int getCodePointCount(String s) { + return s.codePointCount(0, s.length()); + } + + public boolean hasNext() { + return current < stop; + } + + public Object next() { + int codePoint = nextCodePoint(); + current += 1; + for (int j = 1; j < step && hasNext(); j++) { + nextCodePoint(); + current += 1; + } + return codePoint; + } + + private int nextCodePoint() { + int U; +// System.out.println("k=" + k); + int W1 = s.charAt(k); + if (W1 >= 0xD800 && W1 < 0xDC00) { + int W2 = s.charAt(k + 1); + U = (((W1 & 0x3FF) << 10) | (W2 & 0x3FF)) + 0x10000; + k += 2; + } else { + U = W1; + k += 1; + } + return U; + } + + public void remove() { + throw new UnsupportedOperationException("Not supported on String objects (immutable)"); + } +} Modified: trunk/jython/src/org/python/core/exceptions.java =================================================================== --- trunk/jython/src/org/python/core/exceptions.java 2008-10-19 20:51:56 UTC (rev 5469) +++ trunk/jython/src/org/python/core/exceptions.java 2008-10-19 22:04:51 UTC (rev 5470) @@ -381,7 +381,7 @@ if (end == (start + 1)) { PyObject object = self.__getattr__("object"); int badByte = (object.toString().charAt(start)) & 0xff; - result = String.format("'%.400s' codec can't decode byte 0x%s in position %d: %.400s", + result = String.format("'%.400s' codec can't decode byte 0x%x in position %d: %.400s", encoding, badByte, start, reason); } else { result = String.format("'%.400s' codec can't decode bytes in position %d-%d: %.400s", @@ -413,7 +413,7 @@ String result; if (end == (start + 1)) { PyObject object = self.__getattr__("object"); - int badchar = object.toString().charAt(start); + int badchar = object.toString().codePointAt(start); String badcharStr; if (badchar <= 0xff) { badcharStr = String.format("x%02x", badchar); @@ -460,7 +460,7 @@ String result; if (end == (start + 1)) { - int badchar = (self.__getattr__("object").toString().charAt(start)); + int badchar = (self.__getattr__("object").toString().codePointAt(start)); String badCharStr; if (badchar <= 0xff) { badCharStr = String.format("x%02x", badchar); This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <cg...@us...> - 2008-10-19 23:17:51
|
Revision: 5471 http://jython.svn.sourceforge.net/jython/?rev=5471&view=rev Author: cgroves Date: 2008-10-19 23:17:44 +0000 (Sun, 19 Oct 2008) Log Message: ----------- Add a couple tests for subclass constructor visibility Modified Paths: -------------- trunk/jython/Lib/test/test_java_visibility.py trunk/jython/tests/java/org/python/tests/VisibilityResults.java trunk/jython/tests/java/org/python/tests/Visible.java Modified: trunk/jython/Lib/test/test_java_visibility.py =================================================================== --- trunk/jython/Lib/test/test_java_visibility.py 2008-10-19 22:04:51 UTC (rev 5470) +++ trunk/jython/Lib/test/test_java_visibility.py 2008-10-19 23:17:44 UTC (rev 5471) @@ -8,15 +8,21 @@ self.assertEquals([], dir(Invisible)) def test_protected_from_python_subclass(self): - class SubInvisible(Invisible): - pass + class SubVisible(Visible): + def __init__(self, publicValue=None): + if publicValue is not None: + Visible.__init__(self, publicValue) + else: + Visible.__init__(self) # TODO - protectedStaticMethod, protectedStaticField, and protectedField should # be here - s = SubInvisible() + s = SubVisible() self.assertEquals(Results.PROTECTED_METHOD, s.protectedMethod(0)) + self.assertEquals(Results.OVERLOADED_PROTECTED_METHOD, s.protectedMethod('foo')) + self.assertEquals(Results.UNUSED, SubVisible(Results.UNUSED).visibleField) def test_visible(self): - self.assertEquals(4, len(dir(Visible))) + self.assertEquals(5, len(dir(Visible))) v = Visible() self.assertEquals(Results.PUBLIC_FIELD, v.visibleField) Modified: trunk/jython/tests/java/org/python/tests/VisibilityResults.java =================================================================== --- trunk/jython/tests/java/org/python/tests/VisibilityResults.java 2008-10-19 22:04:51 UTC (rev 5470) +++ trunk/jython/tests/java/org/python/tests/VisibilityResults.java 2008-10-19 23:17:44 UTC (rev 5471) @@ -1,9 +1,9 @@ package org.python.tests; -/** - * - */ public interface VisibilityResults { + // Value not used by default by any of the visible classes + public static final int UNUSED = -1; + // Returns for Invisible.java public static final int PROTECTED_STATIC_FIELD = 1; public static final int PROTECTED_FIELD = 2; @@ -15,7 +15,7 @@ public static final int OVERLOADED_PROTECTED_METHOD = 8; public static final int PACKAGE_STATIC_METHOD = 9; public static final int PACKAGE_METHOD = 10; - + // Returns for Visible.java public static final int PUBLIC_FIELD = 101; public static final int PUBLIC_STATIC_FIELD = 102; @@ -28,7 +28,7 @@ public static final int EXTRA_ARG_PUBLIC_STATIC_METHOD = 109; public static final int PUBLIC_METHOD_FIELD = 110; public static final int PUBLIC_STATIC_METHOD_FIELD = 111; - + // Returns for SubVisible.java public static final int SUBCLASS_OVERRIDE = 201; public static final int SUBCLASS_OVERLOAD = 202; Modified: trunk/jython/tests/java/org/python/tests/Visible.java =================================================================== --- trunk/jython/tests/java/org/python/tests/Visible.java 2008-10-19 22:04:51 UTC (rev 5470) +++ trunk/jython/tests/java/org/python/tests/Visible.java 2008-10-19 23:17:44 UTC (rev 5471) @@ -1,17 +1,25 @@ package org.python.tests; -/** +/** * Exposes several methods that should be visible statically and on instances in Python. */ public class Visible extends Invisible { - public int visibleField = PUBLIC_FIELD; - + public int visibleField; + public static int visibleStaticField = PUBLIC_STATIC_FIELD; public int visibleInstance = PUBLIC_METHOD_FIELD; public static int visibleStatic = PUBLIC_STATIC_METHOD_FIELD; + public Visible() { + this(PUBLIC_FIELD); + } + + public Visible(int visibileFieldValue) { + visibleField = visibileFieldValue; + } + public int visibleInstance(int input) { return PUBLIC_METHOD; } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <zy...@us...> - 2008-10-19 23:18:28
|
Revision: 5472 http://jython.svn.sourceforge.net/jython/?rev=5472&view=rev Author: zyasoft Date: 2008-10-19 23:18:22 +0000 (Sun, 19 Oct 2008) Log Message: ----------- PEP 342 specifies that an exception raised by close during finalization should be output to stderr, so we now do that. Fixed a minor doctest output formatting issue so that the desired syntax error is properly seen. Modified Paths: -------------- trunk/jython/Lib/test/test_generators.py trunk/jython/src/org/python/core/PyGenerator.java Modified: trunk/jython/Lib/test/test_generators.py =================================================================== --- trunk/jython/Lib/test/test_generators.py 2008-10-19 23:17:44 UTC (rev 5471) +++ trunk/jython/Lib/test/test_generators.py 2008-10-19 23:18:22 UTC (rev 5472) @@ -867,7 +867,7 @@ <type 'generator'> ->>> def f(): +>>> def f(): #doctest: +IGNORE_EXCEPTION_DETAIL, +NORMALIZE_WHITESPACE ... if 0: ... lambda x: x # shouldn't trigger here ... return # or here @@ -1646,8 +1646,6 @@ >>> g.close() # close normally And finalization. But we have to force the timing of GC here, since we are running on Jython: ->>> import gc ->>> from time import sleep >>> def f(): ... try: yield ... finally: @@ -1655,7 +1653,7 @@ >>> g = f() >>> g.next() ->>> del g; gc.collect(); sleep(1); gc.collect() +>>> del g; extra_collect() exiting @@ -1680,7 +1678,7 @@ >>> old, sys.stderr = sys.stderr, StringIO.StringIO() >>> g = f() >>> g.next() ->>> del g; gc.collect(); sleep(1); gc.collect() +>>> del g; extra_collect() >>> sys.stderr.getvalue().startswith( ... "Exception RuntimeError" ... ) @@ -1789,7 +1787,6 @@ >>> import sys, StringIO >>> from time import sleep ->>> import gc >>> old = sys.stderr >>> try: ... sys.stderr = StringIO.StringIO() @@ -1798,7 +1795,7 @@ ... raise RuntimeError ... ... l = Leaker() -... del l; gc.collect(); sleep(1); gc.collect() +... del l; extra_collect() ... err = sys.stderr.getvalue().strip() ... err.startswith( ... "Exception RuntimeError in <" @@ -1837,6 +1834,13 @@ from test import test_support, test_generators test_support.run_doctest(test_generators, verbose) +def extra_collect(): + import gc + from time import sleep + + gc.collect(); sleep(1); gc.collect(); sleep(0.1); gc.collect() + + # This part isn't needed for regrtest, but for running the test directly. if __name__ == "__main__": test_main(1) Modified: trunk/jython/src/org/python/core/PyGenerator.java =================================================================== --- trunk/jython/src/org/python/core/PyGenerator.java 2008-10-19 23:17:44 UTC (rev 5471) +++ trunk/jython/src/org/python/core/PyGenerator.java 2008-10-19 23:18:22 UTC (rev 5472) @@ -82,7 +82,23 @@ return; try { close(); + } catch (PyException e) { + // PEP 342 specifies that if an exception is raised by close, + // we output to stderr and then forget about it; + String className = PyException.exceptionClassName(e.type); + int lastDot = className.lastIndexOf('.'); + if (lastDot != -1) { + className = className.substring(lastDot + 1); + } + PyString m = Py.newString( + String.format("Exception %s: %s in %s", + className, + e.value.__repr__().toString(), + this.__repr__().toString())); + Py.println(Py.getSystemState().stderr, m); } catch (Throwable e) { + // but we currently ignore any Java exception completely. perhaps we + // can also output something meaningful too? } finally { super.finalize(); } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <cg...@us...> - 2008-10-19 23:30:41
|
Revision: 5473 http://jython.svn.sourceforge.net/jython/?rev=5473&view=rev Author: cgroves Date: 2008-10-19 23:30:32 +0000 (Sun, 19 Oct 2008) Log Message: ----------- Replace StringUtil.asPyString with Py.newString Modified Paths: -------------- trunk/jython/Lib/javapath.py trunk/jython/Lib/os.py trunk/jython/Lib/socket.py trunk/jython/src/org/python/core/util/StringUtil.java Modified: trunk/jython/Lib/javapath.py =================================================================== --- trunk/jython/Lib/javapath.py 2008-10-19 23:18:22 UTC (rev 5472) +++ trunk/jython/Lib/javapath.py 2008-10-19 23:30:32 UTC (rev 5473) @@ -20,7 +20,7 @@ from java.lang import System import os -from org.python.core.util.StringUtil import asPyString +from org.python.core.Py import newString as asPyString def _tostr(s, method): Modified: trunk/jython/Lib/os.py =================================================================== --- trunk/jython/Lib/os.py 2008-10-19 23:18:22 UTC (rev 5472) +++ trunk/jython/Lib/os.py 2008-10-19 23:30:32 UTC (rev 5473) @@ -48,7 +48,7 @@ from java.io import File from org.python.core import PyFile from org.python.core.io import FileDescriptors, FileIO, IOBase -from org.python.core.util.StringUtil import asPyString +from org.python.core.Py import newString as asPyString # Mapping of: os._name: [name list, shell command list] _os_map = dict(nt=[ Modified: trunk/jython/Lib/socket.py =================================================================== --- trunk/jython/Lib/socket.py 2008-10-19 23:18:22 UTC (rev 5472) +++ trunk/jython/Lib/socket.py 2008-10-19 23:30:32 UTC (rev 5473) @@ -81,7 +81,7 @@ import org.python.core.io.DatagramSocketIO import org.python.core.io.ServerSocketIO import org.python.core.io.SocketIO -from org.python.core.util.StringUtil import asPyString +from org.python.core.Py import newString as asPyString class error(Exception): pass class herror(error): pass Modified: trunk/jython/src/org/python/core/util/StringUtil.java =================================================================== --- trunk/jython/src/org/python/core/util/StringUtil.java 2008-10-19 23:18:22 UTC (rev 5472) +++ trunk/jython/src/org/python/core/util/StringUtil.java 2008-10-19 23:30:32 UTC (rev 5473) @@ -5,7 +5,6 @@ import java.nio.ByteBuffer; import org.python.core.Py; -import org.python.core.PyString; /** * String Utility methods. @@ -84,8 +83,4 @@ chars[0] = Character.toLowerCase(c0); return new String(chars); } - - public static PyString asPyString(String string) { - return new PyString(string); } -} This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <cg...@us...> - 2008-10-20 01:01:47
|
Revision: 5475 http://jython.svn.sourceforge.net/jython/?rev=5475&view=rev Author: cgroves Date: 2008-10-20 01:01:39 +0000 (Mon, 20 Oct 2008) Log Message: ----------- Add an ant resource collection that's like union except it combines based on the name of the resource instead of its full path. Use this to exclude the unexposed version of classes from jython.jar to keep it quiet. Resource collections didn't appear until Ant 1.7, but that came out nearly 2 years ago, so I'm hoping most people already have it. Modified Paths: -------------- trunk/jython/build.xml Added Paths: ----------- trunk/jython/src/org/python/util/NameUnionAntType.java Modified: trunk/jython/build.xml =================================================================== --- trunk/jython/build.xml 2008-10-20 00:44:52 UTC (rev 5474) +++ trunk/jython/build.xml 2008-10-20 01:01:39 UTC (rev 5475) @@ -549,9 +549,17 @@ </target> <target name="jar" depends="compile,expose,jarjar"> - <jar destfile="${dist.dir}/jython.jar" duplicate="preserve"> - <fileset dir="${exposed.dir}"/> - <fileset dir="${compile.dir}"/> + <typedef name="nameunion" classname="org.python.util.NameUnionAntType"> + <classpath> + <path refid="main.classpath" /> + <pathelement path="${compile.dir}" /> + </classpath> + </typedef> + <jar destfile="${dist.dir}/jython.jar" duplicate="fail"> + <nameunion> + <fileset dir="${exposed.dir}"/> + <fileset dir="${compile.dir}"/> + </nameunion> <fileset dir="${jarjar.dir}"> <include name="org/python/objectweb/asm/ClassReader.class" /> </fileset> Added: trunk/jython/src/org/python/util/NameUnionAntType.java =================================================================== --- trunk/jython/src/org/python/util/NameUnionAntType.java (rev 0) +++ trunk/jython/src/org/python/util/NameUnionAntType.java 2008-10-20 01:01:39 UTC (rev 5475) @@ -0,0 +1,35 @@ +package org.python.util; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashSet; +import java.util.Iterator; +import java.util.List; +import java.util.Set; + +import org.apache.tools.ant.types.Resource; +import org.apache.tools.ant.types.ResourceCollection; +import org.apache.tools.ant.types.resources.BaseResourceCollectionContainer; + +/** + * Unions several resource collections by the name of their contained resources. + */ +public class NameUnionAntType extends BaseResourceCollectionContainer { + @SuppressWarnings("unchecked") + @Override + protected Collection<Resource> getCollection() { + List<ResourceCollection> collections = getResourceCollections(); + // preserve order-encountered using a list; keep track of the items with a set + Set<String> seenNames = new HashSet<String>(); + List<Resource> union = new ArrayList(); + for (ResourceCollection rc : collections) { + for (Iterator<Resource> resources = rc.iterator(); resources.hasNext();) { + Resource r = resources.next(); + if (seenNames.add(r.getName())) { + union.add(r); + } + } + } + return union; + } +} This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <cg...@us...> - 2008-10-20 01:41:40
|
Revision: 5477 http://jython.svn.sourceforge.net/jython/?rev=5477&view=rev Author: cgroves Date: 2008-10-20 01:41:32 +0000 (Mon, 20 Oct 2008) Log Message: ----------- Move BaseTypeBuilder out of TypeExposer so the compile time bits of the exposing system can be excluded from jython.jar Modified Paths: -------------- trunk/jython/build.xml trunk/jython/src/org/python/expose/generate/TypeExposer.java Added Paths: ----------- trunk/jython/src/org/python/expose/BaseTypeBuilder.java Modified: trunk/jython/build.xml =================================================================== --- trunk/jython/build.xml 2008-10-20 01:40:25 UTC (rev 5476) +++ trunk/jython/build.xml 2008-10-20 01:41:32 UTC (rev 5477) @@ -558,7 +558,7 @@ <jar destfile="${dist.dir}/jython.jar" duplicate="fail"> <nameunion> <fileset dir="${exposed.dir}"/> - <fileset dir="${compile.dir}"/> + <fileset dir="${compile.dir}" excludes="org/python/expose/generate/**"/> </nameunion> <fileset dir="${jarjar.dir}"> <include name="org/python/objectweb/asm/ClassReader.class" /> Added: trunk/jython/src/org/python/expose/BaseTypeBuilder.java =================================================================== --- trunk/jython/src/org/python/expose/BaseTypeBuilder.java (rev 0) +++ trunk/jython/src/org/python/expose/BaseTypeBuilder.java 2008-10-20 01:41:32 UTC (rev 5477) @@ -0,0 +1,67 @@ +package org.python.expose; + +import org.python.core.PyBuiltinMethod; +import org.python.core.PyDataDescr; +import org.python.core.PyMethodDescr; +import org.python.core.PyNewWrapper; +import org.python.core.PyObject; +import org.python.core.PyStringMap; +import org.python.core.PyType; + +public class BaseTypeBuilder implements TypeBuilder { + + private PyNewWrapper newWrapper; + + private PyBuiltinMethod[] meths; + + private PyDataDescr[] descrs; + + private Class typeClass; + + private Class baseClass; + + private String name; + + public BaseTypeBuilder(String name, + Class typeClass, + Class baseClass, + PyBuiltinMethod[] meths, + PyDataDescr[] descrs, + PyNewWrapper newWrapper) { + this.typeClass = typeClass; + this.baseClass = baseClass; + this.name = name; + this.descrs = descrs; + this.meths = meths; + this.newWrapper = newWrapper; + } + + public PyObject getDict(PyType type) { + PyObject dict = new PyStringMap(); + for(PyBuiltinMethod func : meths) { + PyMethodDescr pmd = func.makeDescriptor(type); + dict.__setitem__(pmd.getName(), pmd); + } + for(PyDataDescr descr : descrs) { + descr.setType(type); + dict.__setitem__(descr.getName(), descr); + } + if(newWrapper != null) { + dict.__setitem__("__new__", newWrapper); + newWrapper.setWrappedType(type); + } + return dict; + } + + public String getName() { + return name; + } + + public Class getTypeClass() { + return typeClass; + } + + public Class getBase() { + return baseClass; + } +} \ No newline at end of file Modified: trunk/jython/src/org/python/expose/generate/TypeExposer.java =================================================================== --- trunk/jython/src/org/python/expose/generate/TypeExposer.java 2008-10-20 01:40:25 UTC (rev 5476) +++ trunk/jython/src/org/python/expose/generate/TypeExposer.java 2008-10-20 01:41:32 UTC (rev 5477) @@ -6,13 +6,7 @@ import org.python.objectweb.asm.Type; import org.python.core.BytecodeLoader; -import org.python.core.PyBuiltinMethod; -import org.python.core.PyDataDescr; -import org.python.core.PyMethodDescr; -import org.python.core.PyNewWrapper; -import org.python.core.PyObject; -import org.python.core.PyStringMap; -import org.python.core.PyType; +import org.python.expose.BaseTypeBuilder; import org.python.expose.ExposedType; import org.python.expose.TypeBuilder; @@ -144,62 +138,4 @@ superConstructor(STRING, CLASS, CLASS, ABUILTIN_METHOD, ADATA_DESCR, PYNEWWRAPPER); endConstructor(); } - - protected static class BaseTypeBuilder implements TypeBuilder { - - private PyNewWrapper newWrapper; - - private PyBuiltinMethod[] meths; - - private PyDataDescr[] descrs; - - private Class typeClass; - - private Class baseClass; - - private String name; - - public BaseTypeBuilder(String name, - Class typeClass, - Class baseClass, - PyBuiltinMethod[] meths, - PyDataDescr[] descrs, - PyNewWrapper newWrapper) { - this.typeClass = typeClass; - this.baseClass = baseClass; - this.name = name; - this.descrs = descrs; - this.meths = meths; - this.newWrapper = newWrapper; - } - - public PyObject getDict(PyType type) { - PyObject dict = new PyStringMap(); - for(PyBuiltinMethod func : meths) { - PyMethodDescr pmd = func.makeDescriptor(type); - dict.__setitem__(pmd.getName(), pmd); - } - for(PyDataDescr descr : descrs) { - descr.setType(type); - dict.__setitem__(descr.getName(), descr); - } - if(newWrapper != null) { - dict.__setitem__("__new__", newWrapper); - newWrapper.setWrappedType(type); - } - return dict; - } - - public String getName() { - return name; - } - - public Class getTypeClass() { - return typeClass; - } - - public Class getBase() { - return baseClass; - } - } } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <th...@us...> - 2008-10-20 11:13:43
|
Revision: 5480 http://jython.svn.sourceforge.net/jython/?rev=5480&view=rev Author: thobes Date: 2008-10-20 11:13:38 +0000 (Mon, 20 Oct 2008) Log Message: ----------- Fixed the evaluation order bug made visual by test_generators. Added a test file for evaluation order tests. Modified Paths: -------------- trunk/jython/src/org/python/compiler/CodeCompiler.java Added Paths: ----------- trunk/jython/Lib/test/test_evalorder.py Added: trunk/jython/Lib/test/test_evalorder.py =================================================================== --- trunk/jython/Lib/test/test_evalorder.py (rev 0) +++ trunk/jython/Lib/test/test_evalorder.py 2008-10-20 11:13:38 UTC (rev 5480) @@ -0,0 +1,65 @@ +from unittest import TestCase +from test import test_support + +class Bucket(object): + def __init__(self, value): + self.__value = value + def _get(self): + return self.__value + def _set(self, value): + assert self.__value == value, "Value changed!" + value = property(_get,_set) + +class PropBucket(object): + def __init__(self): + self.__dict__['_d'] = {} + def __getattr__(self, attr): + value = self._d.setdefault(attr, 0) + self._d[attr] = value + 1 + return Bucket(value) + def __setattr__(self, attr, value): + value.append(attr) + +class EvaluationOrder(TestCase): + def test_TestFunctionality(self): + bucket = PropBucket() + try: + bucket.prop.value = bucket.prop.value + 0 + except AssertionError: + pass + else: + assert False, "PropBucket is not working" + def test_augassign(self): + bucket = PropBucket() + bucket.prop.value += 0 + def test_AssignOrder(self): + bucket = PropBucket() + expected = ['one','two','three'] + result = [] + bucket.one = bucket.two = bucket.three = result + assert result == expected, "expected %s, got %s" % (expected, result) + def test_operands(self): + m = [(2,), (1,)].pop + assert m() + m() == (1,2), "faulty operand order" + def test_arguments(self): + def one(a,b,c,d,*extra): + return reduce(lambda r,x: r+x,extra,a+b+c+d) + m = list((x,) for x in xrange(100,0,-1)).pop + value = one(m(),m(),m(),m()) + assert value == (1,2,3,4), "simple call, got: %s " % (value,) + value = one(m(),m(),d=m(),c=m()) + assert value == (5,6,8,7), "call with keywords, got: %s" % (value,) + value = one(m(),m(),m(),m(),m(),m()) + assert value == (9,10,11,12,13,14), "long call, got: %s" % (value,) + value = one(m(),m(),*[m(),m(),m(),m()]) + assert value == (15,16,17,18,19,20), "varcalls, got: %s" % (value,) + value = one(m(),m(),**dict(c=m(),d=m())) + assert value == (21,22,23,24), "varkeywordcall, got: %s" % (value,) + value = one(*[m(),m()],**dict(c=m(),d=m())) + assert value == (25,26,27,28), "bothvarcalls, got: %s" % (value,) + +def test_main(): + test_support.run_unittest(EvaluationOrder) + +if __name__ == '__main__': + test_main() Modified: trunk/jython/src/org/python/compiler/CodeCompiler.java =================================================================== --- trunk/jython/src/org/python/compiler/CodeCompiler.java 2008-10-20 06:29:50 UTC (rev 5479) +++ trunk/jython/src/org/python/compiler/CodeCompiler.java 2008-10-20 11:13:38 UTC (rev 5480) @@ -457,13 +457,13 @@ visit(node.value); if (node.targets.length == 1) { set(node.targets[0]); - return null; + } else { + int tmp = storeTop(); + for (exprType target : node.targets) { + set(target, tmp); + } + code.freeLocal(tmp); } - int tmp = storeTop(); - for (int i=node.targets.length-1; i>=0; i--) { - set(node.targets[i], tmp); - } - code.freeLocal(tmp); return null; } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <th...@us...> - 2008-10-20 17:20:08
|
Revision: 5482 http://jython.svn.sourceforge.net/jython/?rev=5482&view=rev Author: thobes Date: 2008-10-20 17:19:57 +0000 (Mon, 20 Oct 2008) Log Message: ----------- Added support for class decorators. The test file added for this (test_classdecorators) should be removed when we import test_decorators from CPython 3.x, because that is where the caes come from. This is also documented in that file. Modified Paths: -------------- trunk/jython/Lib/test/test_ast.py trunk/jython/ast/Python.asdl trunk/jython/grammar/Python.g trunk/jython/grammar/PythonPartial.g trunk/jython/src/org/python/antlr/GrammarActions.java trunk/jython/src/org/python/antlr/ast/ClassDef.java trunk/jython/src/org/python/compiler/CodeCompiler.java Added Paths: ----------- trunk/jython/Lib/test/test_classdecorators.py Modified: trunk/jython/Lib/test/test_ast.py =================================================================== --- trunk/jython/Lib/test/test_ast.py 2008-10-20 11:50:13 UTC (rev 5481) +++ trunk/jython/Lib/test/test_ast.py 2008-10-20 17:19:57 UTC (rev 5482) @@ -168,14 +168,15 @@ (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 + assert to_tuple(ast_tree) == o, "expected %s, got %s" % ( + o, to_tuple(ast_tree)) test_order(ast_tree, (0, 0)) # XXX: AugStore added for Jython. Short term it is too hard to emit just "Store" as CPython does. #### 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))]), Added: trunk/jython/Lib/test/test_classdecorators.py =================================================================== --- trunk/jython/Lib/test/test_classdecorators.py (rev 0) +++ trunk/jython/Lib/test/test_classdecorators.py 2008-10-20 17:19:57 UTC (rev 5482) @@ -0,0 +1,46 @@ +# This test is temporary until we can import test_decorators from CPython 3.x +# The reason for not doing that already is that in Python 3.x the name of a +# function is stored in func.__name__, in 2.x it's func.func_name +import unittest +from test import test_support + +class TestClassDecorators(unittest.TestCase): + + def test_simple(self): + def plain(x): + x.extra = 'Hello' + return x + @plain + class C(object): pass + self.assertEqual(C.extra, 'Hello') + + def test_double(self): + def ten(x): + x.extra = 10 + return x + def add_five(x): + x.extra += 5 + return x + + @add_five + @ten + class C(object): pass + self.assertEqual(C.extra, 15) + + def test_order(self): + def applied_first(x): + x.extra = 'first' + return x + def applied_second(x): + x.extra = 'second' + return x + @applied_second + @applied_first + class C(object): pass + self.assertEqual(C.extra, 'second') + +def test_main(): + test_support.run_unittest(TestClassDecorators) + +if __name__ == '__main__': + test_main() Modified: trunk/jython/ast/Python.asdl =================================================================== --- trunk/jython/ast/Python.asdl 2008-10-20 11:50:13 UTC (rev 5481) +++ trunk/jython/ast/Python.asdl 2008-10-20 17:19:57 UTC (rev 5482) @@ -11,7 +11,8 @@ stmt = FunctionDef(identifier name, arguments args, stmt* body, expr* decorators) - | ClassDef(identifier name, expr* bases, stmt* body) + | ClassDef(identifier name, expr* bases, + stmt* body, expr* decorators) | Return(expr? value) | Delete(expr* targets) Modified: trunk/jython/grammar/Python.g =================================================================== --- trunk/jython/grammar/Python.g 2008-10-20 11:50:13 UTC (rev 5481) +++ trunk/jython/grammar/Python.g 2008-10-20 17:19:57 UTC (rev 5482) @@ -800,7 +800,7 @@ | for_stmt | try_stmt | with_stmt - | funcdef + | (decorators? DEF) => funcdef | classdef ; @@ -1421,10 +1421,16 @@ @after { $classdef.tree = stype; } - : CLASS NAME (LPAREN testlist[expr_contextType.Load]? RPAREN)? COLON suite[false] + : decorators? CLASS NAME (LPAREN testlist[expr_contextType.Load]? RPAREN)? COLON suite[false] { - stype = new ClassDef($CLASS, actions.cantBeNone($NAME), actions.makeBases(actions.castExpr($testlist.tree)), - actions.castStmts($suite.stypes)); + Token t = $CLASS; + if ($decorators.start != null) { + t = $decorators.start; + } + stype = new ClassDef(t, actions.cantBeNone($NAME), + actions.makeBases(actions.castExpr($testlist.tree)), + actions.castStmts($suite.stypes), + actions.castExprs($decorators.etypes)); } ; Modified: trunk/jython/grammar/PythonPartial.g =================================================================== --- trunk/jython/grammar/PythonPartial.g 2008-10-20 11:50:13 UTC (rev 5481) +++ trunk/jython/grammar/PythonPartial.g 2008-10-20 17:19:57 UTC (rev 5482) @@ -298,7 +298,7 @@ | for_stmt | try_stmt | with_stmt - | funcdef + | (decorators? DEF) => funcdef | classdef ; @@ -455,7 +455,7 @@ dictmaker : test COLON test (options {k=2;}:COMMA test COLON test)* (COMMA)? ; -classdef: CLASS NAME (LPAREN testlist? RPAREN)? COLON suite +classdef: decorators? CLASS NAME (LPAREN testlist? RPAREN)? COLON suite ; arglist : argument (COMMA argument)* Modified: trunk/jython/src/org/python/antlr/GrammarActions.java =================================================================== --- trunk/jython/src/org/python/antlr/GrammarActions.java 2008-10-20 11:50:13 UTC (rev 5481) +++ trunk/jython/src/org/python/antlr/GrammarActions.java 2008-10-20 17:19:57 UTC (rev 5482) @@ -489,14 +489,15 @@ return new Interactive(t, s); } - stmtType makeClassDef(PythonTree t, PythonTree nameToken, List bases, List body) { + stmtType makeClassDef(PythonTree t, PythonTree nameToken, List bases, List body, List decorators) { if (nameToken == null) { return errorHandler.errorStmt(t); } cantBeNone(nameToken); exprType[] b = castExprs(bases); stmtType[] s = castStmts(body); - return new ClassDef(t, nameToken.getText(), b, s); + exprType[] d = castExprs(decorators); + return new ClassDef(t, nameToken.getText(), b, s, d); } stmtType makeTryExcept(PythonTree t, List body, List handlers, List orelse, List finBody) { Modified: trunk/jython/src/org/python/antlr/ast/ClassDef.java =================================================================== --- trunk/jython/src/org/python/antlr/ast/ClassDef.java 2008-10-20 11:50:13 UTC (rev 5481) +++ trunk/jython/src/org/python/antlr/ast/ClassDef.java 2008-10-20 17:19:57 UTC (rev 5482) @@ -10,11 +10,13 @@ public String name; public exprType[] bases; public stmtType[] body; + public exprType[] decorators; - public static final String[] _fields = new String[] {"name","bases","body"}; + public static final String[] _fields = new String[] + {"name","bases","body","decorators"}; public ClassDef(Token token, String name, exprType[] bases, stmtType[] - body) { + body, exprType[] decorators) { super(token); this.name = name; this.bases = bases; @@ -29,10 +31,16 @@ addChild(body[ibody]); } } + this.decorators = decorators; + if (decorators != null) { + for(int idecorators=0;idecorators<decorators.length;idecorators++) { + addChild(decorators[idecorators]); + } + } } public ClassDef(int ttype, Token token, String name, exprType[] bases, - stmtType[] body) { + stmtType[] body, exprType[] decorators) { super(ttype, token); this.name = name; this.bases = bases; @@ -47,10 +55,16 @@ addChild(body[ibody]); } } + this.decorators = decorators; + if (decorators != null) { + for(int idecorators=0;idecorators<decorators.length;idecorators++) { + addChild(decorators[idecorators]); + } + } } public ClassDef(PythonTree tree, String name, exprType[] bases, stmtType[] - body) { + body, exprType[] decorators) { super(tree); this.name = name; this.bases = bases; @@ -65,6 +79,12 @@ addChild(body[ibody]); } } + this.decorators = decorators; + if (decorators != null) { + for(int idecorators=0;idecorators<decorators.length;idecorators++) { + addChild(decorators[idecorators]); + } + } } public String toString() { @@ -82,6 +102,9 @@ sb.append("body="); sb.append(dumpThis(body)); sb.append(","); + sb.append("decorators="); + sb.append(dumpThis(decorators)); + sb.append(","); sb.append(")"); return sb.toString(); } @@ -103,6 +126,12 @@ body[i].accept(visitor); } } + if (decorators != null) { + for (int i = 0; i < decorators.length; i++) { + if (decorators[i] != null) + decorators[i].accept(visitor); + } + } } public int getLineno() { Modified: trunk/jython/src/org/python/compiler/CodeCompiler.java =================================================================== --- trunk/jython/src/org/python/compiler/CodeCompiler.java 2008-10-20 11:50:13 UTC (rev 5481) +++ trunk/jython/src/org/python/compiler/CodeCompiler.java 2008-10-20 17:19:57 UTC (rev 5482) @@ -422,19 +422,18 @@ } set(new Name(node, node.name, expr_contextType.Store)); - doDecorators(node); + doDecorators(node, node.decorators, node.name); return null; } - private void doDecorators(FunctionDef func) throws Exception { - if (func.decorators.length > 0) { - exprType currentExpr = new Name(func, func.name, expr_contextType.Load); - exprType[] decs = func.decorators; + private void doDecorators(stmtType node, exprType[] decs, String name) throws Exception { + if (decs.length > 0) { + exprType currentExpr = new Name(node, name, expr_contextType.Load); for (int i=decs.length - 1;i > -1;i--) { - currentExpr = new Call(func, decs[i], new exprType[]{currentExpr}, new keywordType[0], null, null); + currentExpr = new Call(node, decs[i], new exprType[]{currentExpr}, new keywordType[0], null, null); } visit(currentExpr); - set(new Name(func, func.name, expr_contextType.Store)); + set(new Name(node, name, expr_contextType.Store)); } } @@ -2007,6 +2006,7 @@ //Assign this new class to the given name set(new Name(node, node.name, expr_contextType.Store)); + doDecorators(node, node.decorators, node.name); return null; } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |