From: <pj...@us...> - 2009-04-10 03:32:37
|
Revision: 6198 http://jython.svn.sourceforge.net/jython/?rev=6198&view=rev Author: pjenvey Date: 2009-04-10 03:32:30 +0000 (Fri, 10 Apr 2009) Log Message: ----------- o cleanup/refactor PyType.newType and add __weakref__ support fixes #1200 o actually encode unicode slot names o ensure __doc__ on all types Modified Paths: -------------- trunk/jython/Lib/test/test_descr.py trunk/jython/Lib/test/test_slots_jy.py trunk/jython/src/org/python/core/PyType.java trunk/jython/src/org/python/modules/_weakref/ReferenceType.java Modified: trunk/jython/Lib/test/test_descr.py =================================================================== --- trunk/jython/Lib/test/test_descr.py 2009-04-10 03:14:42 UTC (rev 6197) +++ trunk/jython/Lib/test/test_descr.py 2009-04-10 03:32:30 UTC (rev 6198) @@ -1346,9 +1346,6 @@ a.foo = 42 vereq(a.__dict__, {"foo": 42}) - # XXX: Jython doesn't support __weakref__ - return - class W(object): __slots__ = ["__weakref__"] a = W() @@ -3442,11 +3439,7 @@ if verbose: print "Testing dict-proxy iterkeys..." keys = [ key for key in C.__dict__.iterkeys() ] keys.sort() - if is_jython: - # XXX: It should include __doc__, but no __weakref__ (for now) - vereq(keys, ['__dict__', '__module__', 'meth']) - else: - vereq(keys, ['__dict__', '__doc__', '__module__', '__weakref__', 'meth']) + vereq(keys, ['__dict__', '__doc__', '__module__', '__weakref__', 'meth']) def dictproxyitervalues(): class C(object): @@ -3454,8 +3447,7 @@ pass if verbose: print "Testing dict-proxy itervalues..." values = [ values for values in C.__dict__.itervalues() ] - # XXX: See dictproxyiterkeys - vereq(len(values), is_jython and 3 or 5) + vereq(len(values), 5) def dictproxyiteritems(): class C(object): @@ -3464,10 +3456,7 @@ if verbose: print "Testing dict-proxy iteritems..." keys = [ key for (key, value) in C.__dict__.iteritems() ] keys.sort() - if is_jython: - vereq(keys, ['__dict__', '__module__', 'meth']) - else: - vereq(keys, ['__dict__', '__doc__', '__module__', '__weakref__', 'meth']) + vereq(keys, ['__dict__', '__doc__', '__module__', '__weakref__', 'meth']) def funnynew(): if verbose: print "Testing __new__ returning something unexpected..." Modified: trunk/jython/Lib/test/test_slots_jy.py =================================================================== --- trunk/jython/Lib/test/test_slots_jy.py 2009-04-10 03:14:42 UTC (rev 6197) +++ trunk/jython/Lib/test/test_slots_jy.py 2009-04-10 03:32:30 UTC (rev 6198) @@ -124,9 +124,20 @@ self.assertEqual(baz.__dict__, {'bar': 'hello bar'}) +class SlottedWithWeakrefTestCase(unittest.TestCase): + + def test_subclass_oldstyle(self): + class OldBase: + pass + class Foo(OldBase, object): + __slots__ = '__dict__' + self.assert_(hasattr(Foo, '__weakref__')) + + def test_main(): test_support.run_unittest(SlottedTestCase, - SlottedWithDictTestCase) + SlottedWithDictTestCase, + SlottedWithWeakrefTestCase) if __name__ == '__main__': Modified: trunk/jython/src/org/python/core/PyType.java =================================================================== --- trunk/jython/src/org/python/core/PyType.java 2009-04-10 03:14:42 UTC (rev 6197) +++ trunk/jython/src/org/python/core/PyType.java 2009-04-10 03:32:30 UTC (rev 6198) @@ -1,3 +1,4 @@ +/* Copyright (c) Jython Developers */ package org.python.core; import java.io.Serializable; @@ -17,6 +18,7 @@ import org.python.expose.ExposedSet; import org.python.expose.ExposedType; import org.python.expose.TypeBuilder; +import org.python.modules._weakref.GlobalRef; import org.python.util.Generic; /** @@ -27,7 +29,10 @@ public static PyType TYPE = fromClass(PyType.class); - /** The type's name. builtin types include their fully qualified name, e.g.: time.struct_time. */ + /** + * The type's name. builtin types include their fully qualified name, e.g.: + * time.struct_time. + */ protected String name; /** __base__, the direct base type or null. */ @@ -46,8 +51,8 @@ private long tp_flags; /** - * The Java Class instances of this type will be represented as, or null if it's determined by a - * base type. + * The Java Class instances of this type will be represented as, or null if it's + * determined by a base type. */ protected Class<?> underlying_class; @@ -64,12 +69,15 @@ /** Whether this type allows subclassing. */ private boolean isBaseType = true; + /** Whether this type has a __dict__. */ + protected boolean needs_userdict; + + /** Whether this type has a __weakref__ slot (however all types are weakrefable). */ + protected boolean needs_weakref; + /** Whether finalization is required for this type's instances (implements __del__). */ private boolean needs_finalizer; - /** Whether this type's instances require a __dict__. */ - protected boolean needs_userdict; - /** The number of __slots__ defined. */ private int numSlots; @@ -86,9 +94,9 @@ super(subtype); } + private PyType() { + } - private PyType() {} - /** * Creates the PyType instance for type itself. The argument just exists to make the constructor * distinct. @@ -100,33 +108,31 @@ @ExposedNew public static PyObject type___new__(PyNewWrapper new_, boolean init, PyType subtype, PyObject[] args, String[] keywords) { + // Special case: type(x) should return x.getType() if (args.length == 1 && keywords.length == 0) { return args[0].getType(); } + // If that didn't trigger, we need 3 arguments. but ArgParser below may give a msg + // saying type() needs exactly 3. if (args.length + keywords.length != 3) { - throw Py.TypeError("type() takes exactly 1 or 3 arguments"); + throw Py.TypeError("type() takes 1 or 3 arguments"); } ArgParser ap = new ArgParser("type()", args, keywords, "name", "bases", "dict"); String name = ap.getString(0); - PyObject bases = ap.getPyObject(1); - - if (!(bases instanceof PyTuple)) { - throw Py.TypeError("type(): bases must be tuple"); - } + PyTuple bases = (PyTuple)ap.getPyObjectByType(1, PyTuple.TYPE); PyObject dict = ap.getPyObject(2); if (!(dict instanceof PyDictionary || dict instanceof PyStringMap)) { - throw Py.TypeError("type(): dict must be dict"); + throw Py.TypeError("type(): argument 3 must be dict, not " + dict.getType()); } - return newType(new_, subtype, name, (PyTuple)bases, dict); + return newType(new_, subtype, name, bases, dict); } public static PyObject newType(PyNewWrapper new_, PyType metatype, String name, PyTuple bases, PyObject dict) { - PyType object_type = fromClass(PyObject.class); + PyObject[] tmpBases = bases.getArray(); + PyType winner = findMostDerivedMetatype(tmpBases, metatype); - PyObject[] bases_list = bases.getArray(); - PyType winner = findMostDerivedMetatype(bases_list, metatype); if (winner != metatype) { PyObject winner_new_ = winner.lookup("__new__"); if (winner_new_ != null && winner_new_ != new_) { @@ -136,166 +142,146 @@ } metatype = winner; } - // Use PyType as the metaclass for Python subclasses of Java classes rather than PyJavaType. - // Using PyJavaType as metaclass exposes the java.lang.Object methods on the type, which - // doesn't make sense for python subclasses. + + // Use PyType as the metaclass for Python subclasses of Java classes rather than + // PyJavaType. Using PyJavaType as metaclass exposes the java.lang.Object methods + // on the type, which doesn't make sense for python subclasses. if (metatype == PyType.fromClass(Class.class)) { metatype = TYPE; } - if (bases_list.length == 0) { - bases_list = new PyObject[] {object_type}; - } - List<Class<?>> interfaces = Generic.list(); - Class<?> baseClass = null; - for (PyObject base : bases_list) { - if (!(base instanceof PyType)) { - continue; - } - Class<?> proxy = ((PyType)base).getProxyType(); - if (proxy == null) { - continue; - } - if (proxy.isInterface()) { - interfaces.add(proxy); - } else { - if (baseClass != null) { - throw Py.TypeError("no multiple inheritance for Java classes: " - + proxy.getName() + " and " + baseClass.getName()); - } - baseClass = proxy; - } - } - Class<?> proxyClass = null; - if (baseClass != null || interfaces.size() != 0) { - String proxyName = name; - PyObject module = dict.__finditem__("__module__"); - if (module != null) { - proxyName = module.toString() + "$" + proxyName; - } - proxyClass = MakeProxies.makeProxy(baseClass, interfaces, name, proxyName, dict); - PyType proxyType = PyType.fromClass(proxyClass); - List<PyObject> cleanedBases = Generic.list(); - boolean addedProxyType = false; - for (PyObject base : bases_list) { - if (!(base instanceof PyType)) { - cleanedBases.add(base); - continue; - } - Class<?> proxy = ((PyType)base).getProxyType(); - if (proxy == null) { - cleanedBases.add(base);// non-proxy types go straight into our lookup - } else { - if (!(base instanceof PyJavaType)) { - // python subclasses of proxy types need to be added as a base so their - // version of methods will show up - cleanedBases.add(base); - } else if (!addedProxyType) { - // Only add a single Java type, since everything's going to go through the - // proxy type - cleanedBases.add(proxyType); - addedProxyType = true; - } - } - } - bases_list = cleanedBases.toArray(new PyObject[cleanedBases.size()]); - } - PyType newtype; + PyType type; if (new_.for_type == metatype || metatype == PyType.fromClass(Class.class)) { - newtype = new PyType(); // XXX set metatype + // XXX: set metatype + type = new PyType(); } else { - newtype = new PyTypeDerived(metatype); + type = new PyTypeDerived(metatype); } - if (proxyClass != null) { - newtype.javaProxy = proxyClass; - } + if (dict instanceof PyStringMap) { dict = ((PyStringMap)dict).copy(); } else { dict = ((PyDictionary)dict).copy(); } - if (dict.__finditem__("__module__") == null) { - PyFrame frame = Py.getFrame(); - if (frame != null) { - PyObject globals = frame.f_globals; - PyObject modname; - if ((modname = globals.__finditem__("__name__")) != null) { - dict.__setitem__("__module__", modname); - } - } - } - // XXX also __doc__ __module__ + type.name = name; + type.bases = tmpBases.length == 0 ? new PyObject[] {PyObject.TYPE} : tmpBases; + type.dict = dict; + type.tp_flags = Py.TPFLAGS_HEAPTYPE | Py.TPFLAGS_BASETYPE; - newtype.dict = dict; - newtype.name = name; - newtype.base = best_base(bases_list); - newtype.numSlots = newtype.base.numSlots; - newtype.bases = bases_list; + // immediately setup the javaProxy if applicable. may modify bases + List<Class<?>> interfaces = Generic.list(); + Class<?> baseProxyClass = getJavaLayout(type.bases, interfaces); + type.setupProxy(baseProxyClass, interfaces); - if (!newtype.base.isBaseType) { + PyType base = type.base = best_base(type.bases); + if (!base.isBaseType) { throw Py.TypeError(String.format("type '%.100s' is not an acceptable base type", - newtype.base.name)); + base.name)); } + type.createAllSlots(!base.needs_userdict, !base.needs_weakref); + type.ensureAttributes(); + + for (PyObject cur : type.bases) { + if (cur instanceof PyType) + ((PyType)cur).attachSubclass(type); + } + + return type; + } + + /** + * Create all slots and related descriptors. + * + * @param mayAddDict whether a __dict__ descriptor is allowed on this type + * @param mayAddWeak whether a __weakref__ descriptor is allowed on this type + */ + private void createAllSlots(boolean mayAddDict, boolean mayAddWeak) { + numSlots = base.numSlots; + boolean wantDict = false; + boolean wantWeak = false; PyObject slots = dict.__finditem__("__slots__"); - boolean needsDictDescr = false; + if (slots == null) { - newtype.needs_userdict = true; - // a dict descriptor is required if base doesn't already provide a dict - needsDictDescr = !newtype.base.needs_userdict; + wantDict = mayAddDict; + wantWeak = mayAddWeak; } else { - // have slots, but may inherit a dict - newtype.needs_userdict = newtype.base.needs_userdict; + if (slots instanceof PyString) { + slots = new PyTuple(slots); + } - if (slots instanceof PyString) { - addSlot(newtype, slots); - } else { - for (PyObject slotname : slots.asIterable()) { - addSlot(newtype, slotname); + // Check for valid slot names and create them. Handle two special cases + for (PyObject slot : slots.asIterable()) { + String slotName = confirmIdentifier(slot); + + if (slotName.equals("__dict__")) { + if (!mayAddDict || wantDict) { + throw Py.TypeError("__dict__ slot disallowed: we already got one"); + } + wantDict = true; + } else if (slotName.equals("__weakref__")) { + if (!mayAddWeak || wantWeak) { + throw Py.TypeError("__weakref__ slot disallowed: we already got one"); + } + wantWeak = true; + } else { + slotName = mangleName(name, slotName); + if (dict.__finditem__(slotName) == null) { + dict.__setitem__(slotName, new PySlot(this, slotName, numSlots++)); + } } } - if (!newtype.base.needs_userdict && newtype.needs_userdict) { - // base doesn't provide dict but addSlot found the __dict__ slot - needsDictDescr = true; - } else if (bases_list.length > 0 && !newtype.needs_userdict) { - // secondary bases may provide dict - for (PyObject base : bases_list) { - if (base == newtype.base) { + // Secondary bases may provide weakrefs or dict + if (bases.length > 1 + && ((mayAddDict && !wantDict) || (mayAddWeak && !wantWeak))) { + for (PyObject base : bases) { + if (base == this.base) { // Skip primary base continue; } + if (base instanceof PyClass) { - // Classic base class provides dict - newtype.needs_userdict = true; - needsDictDescr = true; + // Classic base class provides both + if (mayAddDict && !wantDict) { + wantDict = true; + } + if (mayAddWeak && !wantWeak) { + wantWeak = true; + } break; } - PyType tmpType = (PyType)base; - if (tmpType.needs_userdict) { - newtype.needs_userdict = true; - needsDictDescr = true; + + PyType baseType = (PyType)base; + if (mayAddDict && !wantDict && baseType.needs_userdict) { + wantDict = true; + } + if (mayAddWeak && !wantWeak && baseType.needs_weakref) { + wantWeak = true; + } + if ((!mayAddDict || wantDict) && (!mayAddWeak || wantWeak)) { // Nothing more to check break; } } } } - - newtype.tp_flags = Py.TPFLAGS_HEAPTYPE | Py.TPFLAGS_BASETYPE; - - // special case __new__, if function => static method - PyObject tmp = dict.__finditem__("__new__"); - if (tmp != null && tmp instanceof PyFunction) { // XXX java functions? - dict.__setitem__("__new__", new PyStaticMethod(tmp)); + + if (wantDict) { + createDictSlot(); } + if (wantWeak) { + createWeakrefSlot(); + } + needs_finalizer = lookup("__del__") != null; + } - newtype.mro_internal(); - // __dict__ descriptor - if (needsDictDescr && dict.__finditem__("__dict__") == null) { - dict.__setitem__("__dict__", new PyDataDescr(newtype, "__dict__", PyObject.class) { - + /** + * Create the __dict__ descriptor. + */ + private void createDictSlot() { + dict.__setitem__("__dict__", new PyDataDescr(this, "__dict__", PyObject.class) { @Override public Object invokeGet(PyObject obj) { return obj.getDict(); @@ -321,16 +307,93 @@ obj.delDict(); } }); + needs_userdict = true; + } + + /** + * Create the __weakref__ descriptor. + */ + private void createWeakrefSlot() { + dict.__setitem__("__weakref__", new PyDataDescr(this, "__weakref__", PyObject.class) { + private static final String writeMsg = + "attribute '%s' of '%s' objects is not writable"; + + private void notWritable(PyObject obj) { + throw Py.AttributeError(String.format(writeMsg, "__weakref__", + obj.getType().fastGetName())); + } + + @Override + public Object invokeGet(PyObject obj) { + PyList weakrefs = GlobalRef.newInstance(obj).refs(); + switch (weakrefs.size()) { + case 0: + return Py.None; + case 1: + return weakrefs.pyget(0); + default: + return weakrefs; + + } + } + + @Override + public boolean implementsDescrSet() { + return true; + } + + @Override + public void invokeSet(PyObject obj, Object value) { + // XXX: Maybe have PyDataDescr do notWritable() for us + notWritable(obj); + } + + @Override + public boolean implementsDescrDelete() { + return true; + } + + @Override + public void invokeDelete(PyObject obj) { + notWritable(obj); + } + }); + needs_weakref = true; + } + + /** + * Setup this type's special attributes. + */ + private void ensureAttributes() { + inheritSpecial(); + + // special case __new__, if function => static method + PyObject new_ = dict.__finditem__("__new__"); + // XXX: java functions? + if (new_ != null && new_ instanceof PyFunction) { + dict.__setitem__("__new__", new PyStaticMethod(new_)); } - newtype.fillHasSetAndDelete(); - newtype.needs_finalizer = newtype.lookup("__del__") != null; + // NOTE: __module__ is already guaranteed by Py.makeClass + if (dict.__finditem__("__doc__") == null) { + dict.__setitem__("__doc__", Py.None); + } - for (PyObject cur : bases_list) { - if (cur instanceof PyType) - ((PyType)cur).attachSubclass(newtype); + // Calculate method resolution order + mro_internal(); + fillHasSetAndDelete(); + } + + /** + * Inherit special attributes from the dominant base. + */ + private void inheritSpecial() { + if (!needs_userdict && base.needs_userdict) { + needs_userdict = true; } - return newtype; + if (!needs_weakref && base.needs_weakref) { + needs_weakref = true; + } } private static PyObject invoke_new_(PyObject new_, PyType type, boolean init, PyObject[] args, @@ -436,6 +499,89 @@ return base.getLayout(); } + /** + * Get the most parent Java proxy Class from bases, tallying any encountered Java + * interfaces. + * + * @param bases array of base Jython classes + * @param interfaces List for collecting interfaces to + * @return base Java proxy Class + * @raises Py.TypeError if multiple Java inheritance was attempted + */ + private static Class<?> getJavaLayout(PyObject[] bases, List<Class<?>> interfaces) { + Class<?> baseProxy = null; + + for (PyObject base : bases) { + if (!(base instanceof PyType)) { + continue; + } + Class<?> proxy = ((PyType)base).getProxyType(); + if (proxy == null) { + continue; + } + if (proxy.isInterface()) { + interfaces.add(proxy); + } else { + if (baseProxy != null) { + String msg = "no multiple inheritance for Java classes: %s and %s"; + throw Py.TypeError(String.format(msg, proxy.getName(), baseProxy.getName())); + } + baseProxy = proxy; + } + } + + return baseProxy; + } + + /** + * Setup the javaProxy for this type. + * + * @param baseProxyClass this type's base proxyClass + * @param interfaces a list of Java interfaces in bases + */ + private void setupProxy(Class<?> baseProxyClass, List<Class<?>> interfaces) { + if (baseProxyClass == null && interfaces.size() == 0) { + // javaProxy not applicable + return; + } + + String proxyName = name; + PyObject module = dict.__finditem__("__module__"); + if (module != null) { + proxyName = module.toString() + "$" + proxyName; + } + Class<?> proxyClass = MakeProxies.makeProxy(baseProxyClass, interfaces, name, proxyName, + dict); + javaProxy = proxyClass; + + PyType proxyType = PyType.fromClass(proxyClass); + List<PyObject> cleanedBases = Generic.list(); + boolean addedProxyType = false; + for (PyObject base : bases) { + if (!(base instanceof PyType)) { + cleanedBases.add(base); + continue; + } + Class<?> proxy = ((PyType)base).getProxyType(); + if (proxy == null) { + // non-proxy types go straight into our lookup + cleanedBases.add(base); + } else { + if (!(base instanceof PyJavaType)) { + // python subclasses of proxy types need to be added as a base so their + // version of methods will show up + cleanedBases.add(base); + } else if (!addedProxyType) { + // Only add a single Java type, since everything's going to go through the + // proxy type + cleanedBases.add(proxyType); + addedProxyType = true; + } + } + } + bases = cleanedBases.toArray(new PyObject[cleanedBases.size()]); + } + //XXX: needs __doc__ @ExposedGet(name = "__base__") public PyObject getBase() { @@ -828,20 +974,6 @@ return winner; } - private static void addSlot(PyType newtype, PyObject slotname) { - confirmIdentifier(slotname); - String slotstring = mangleName(newtype.name, slotname.toString()); - if (slotstring.equals("__dict__")) { - if (newtype.base.needs_userdict || newtype.needs_userdict) { - throw Py.TypeError("__dict__ slot disallowed: we already got one"); - } - newtype.needs_userdict = true; - } else if (newtype.dict.__finditem__(slotstring) == null) { - newtype.dict.__setitem__(slotstring, new PySlot(newtype, slotstring, - newtype.numSlots++)); - } - } - public boolean isSubType(PyType supertype) { if (mro != null) { for (PyObject base : mro) { @@ -1342,22 +1474,28 @@ //XXX: consider pulling this out into a generally accessible place // I bet this is duplicated more or less in other places. - private static void confirmIdentifier(PyObject o) { + private static String confirmIdentifier(PyObject obj) { + String identifier; + if (!(obj instanceof PyString)) { + throw Py.TypeError(String.format("__slots__ items must be strings, not '%.200s'", + obj.getType().fastGetName())); + } else if (obj instanceof PyUnicode) { + identifier = ((PyUnicode)obj).encode(); + } else { + identifier = obj.toString(); + } + String msg = "__slots__ must be identifiers"; - if (o == Py.None) { - throw Py.TypeError(msg); - } - String identifier = o.toString(); - if (identifier == null || identifier.length() < 1 + if (identifier.length() == 0 || (!Character.isLetter(identifier.charAt(0)) && identifier.charAt(0) != '_')) { throw Py.TypeError(msg); } - char[] chars = identifier.toCharArray(); - for (int i = 0; i < chars.length; i++) { - if (!Character.isLetterOrDigit(chars[i]) && chars[i] != '_') { + for (char c : identifier.toCharArray()) { + if (!Character.isLetterOrDigit(c) && c != '_') { throw Py.TypeError(msg); } } + return identifier; } //XXX: copied from CodeCompiler.java and changed variable names. Modified: trunk/jython/src/org/python/modules/_weakref/ReferenceType.java =================================================================== --- trunk/jython/src/org/python/modules/_weakref/ReferenceType.java 2009-04-10 03:14:42 UTC (rev 6197) +++ trunk/jython/src/org/python/modules/_weakref/ReferenceType.java 2009-04-10 03:32:30 UTC (rev 6198) @@ -35,7 +35,10 @@ GlobalRef gref = GlobalRef.newInstance(ob); if (new_.for_type == subtype) { - // XXX: Reject types that aren't weak referenceable + // NOTE: CPython disallows weakrefs to many builtin types (e.g. dict, list) + // and would check weakrefability here. We aren't as strict since the JVM can + // weakref anything. Our types' needs_weakref flag only refers to whether it + // has a __weakref__ descriptor, not weakrefability if (callback == null) { ReferenceType ret = (ReferenceType)gref.find(ReferenceType.class); if (ret != null) { This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <pj...@us...> - 2009-04-10 19:21:04
|
Revision: 6209 http://jython.svn.sourceforge.net/jython/?rev=6209&view=rev Author: pjenvey Date: 2009-04-10 19:21:01 +0000 (Fri, 10 Apr 2009) Log Message: ----------- cleanup class __module__ setup: o type/ClassType must default a __module__ (instead of Py.makeClass) for when types are constructed via type(name, bases, dict) o simplify the compiler's __module__ setup as it should just fail fast Modified Paths: -------------- trunk/jython/Lib/test/test_class_jy.py trunk/jython/src/org/python/compiler/Module.java trunk/jython/src/org/python/core/Py.java trunk/jython/src/org/python/core/PyClass.java trunk/jython/src/org/python/core/PyFrame.java trunk/jython/src/org/python/core/PyType.java trunk/jython/src/org/python/core/imp.java Modified: trunk/jython/Lib/test/test_class_jy.py =================================================================== --- trunk/jython/Lib/test/test_class_jy.py 2009-04-10 15:36:58 UTC (rev 6208) +++ trunk/jython/Lib/test/test_class_jy.py 2009-04-10 19:21:01 UTC (rev 6209) @@ -17,17 +17,24 @@ self.assertEqual(str.__module__, '__builtin__') class Foo: pass - self.assertEqual(Foo.__module__, __name__) - self.assertEqual(str(Foo), '%s.Foo' % __name__) - self.assert_(repr(Foo).startswith('<class %s.Foo at' % __name__)) - foo = Foo() - self.assert_(str(foo).startswith('<%s.Foo instance at' % __name__)) + Fu = types.ClassType('Fu', (), {}) + for cls in Foo, Fu: + self.assert_('__module__' in cls.__dict__) + self.assertEqual(cls.__module__, __name__) + self.assertEqual(str(cls), '%s.%s' % (__name__, cls.__name__)) + self.assert_(repr(cls).startswith('<class %s.%s at' % + (__name__, cls.__name__))) + obj = cls() + self.assert_(str(obj).startswith('<%s.%s instance at' % + (__name__, cls.__name__))) class Bar(object): pass class Baz(Object): pass - for cls in Bar, Baz: + Bang = type('Bang', (), {}) + for cls in Bar, Baz, Bang: + self.assert_('__module__' in cls.__dict__) self.assertEqual(cls.__module__, __name__) self.assertEqual(str(cls), "<class '%s.%s'>" % (__name__, cls.__name__)) self.assertEqual(repr(cls), "<class '%s.%s'>" % (__name__, cls.__name__)) Modified: trunk/jython/src/org/python/compiler/Module.java =================================================================== --- trunk/jython/src/org/python/compiler/Module.java 2009-04-10 15:36:58 UTC (rev 6208) +++ trunk/jython/src/org/python/compiler/Module.java 2009-04-10 19:21:01 UTC (rev 6209) @@ -438,25 +438,14 @@ CodeCompiler compiler = new CodeCompiler(this, printResults); if (classBody) { - Label label_got_name = new Label(); - int module_tmp = c.getLocal("org/python/core/PyObject"); - + // Set the class's __module__ to __name__. fails when there's no __name__ c.aload(1); c.ldc("__module__"); - c.invokevirtual("org/python/core/PyFrame", "getname_or_null", "(" + $str + ")" + $pyObj); - c.dup(); - c.ifnonnull(label_got_name); - c.pop(); c.aload(1); c.ldc("__name__"); - c.invokevirtual("org/python/core/PyFrame", "getname_or_null", "(" + $str + ")" + $pyObj); + c.invokevirtual("org/python/core/PyFrame", "getname", "(" + $str + ")" + $pyObj); - c.label(label_got_name); - c.astore(module_tmp); - c.aload(1); - c.ldc("__module__"); - c.aload(module_tmp); c.invokevirtual("org/python/core/PyFrame", "setlocal", "(" + $str + $pyObj + ")V"); } Modified: trunk/jython/src/org/python/core/Py.java =================================================================== --- trunk/jython/src/org/python/core/Py.java 2009-04-10 15:36:58 UTC (rev 6208) +++ trunk/jython/src/org/python/core/Py.java 2009-04-10 19:21:01 UTC (rev 6209) @@ -1566,14 +1566,6 @@ * @return a new Python Class PyObject */ public static PyObject makeClass(String name, PyObject[] bases, PyObject dict) { - PyFrame frame = getFrame(); - if (dict.__finditem__("__module__") == null) { - PyObject module = frame.getglobal("__name__"); - if (module != null) { - dict.__setitem__("__module__", module); - } - } - PyObject metaclass = dict.__finditem__("__metaclass__"); if (metaclass == null) { @@ -1584,7 +1576,7 @@ metaclass = base.getType(); } } else { - PyObject globals = frame.f_globals; + PyObject globals = getFrame().f_globals; if (globals != null) { metaclass = globals.__finditem__("__metaclass__"); } Modified: trunk/jython/src/org/python/core/PyClass.java =================================================================== --- trunk/jython/src/org/python/core/PyClass.java 2009-04-10 15:36:58 UTC (rev 6208) +++ trunk/jython/src/org/python/core/PyClass.java 2009-04-10 19:21:01 UTC (rev 6209) @@ -55,10 +55,8 @@ if (!(dict instanceof PyStringMap || dict instanceof PyDictionary)) { throw Py.TypeError("PyClass_New: dict must be a dictionary"); } - if (dict.__finditem__("__doc__") == null) { - dict.__setitem__("__doc__", Py.None); - } - findModule(dict); + PyType.ensureDoc(dict); + PyType.ensureModule(dict); if (!(bases instanceof PyTuple)) { throw Py.TypeError("PyClass_New: bases must be a tuple"); @@ -94,19 +92,6 @@ __contains__ = lookup("__contains__"); } - private static void findModule(PyObject dict) { - PyObject module = dict.__finditem__("__module__"); - if (module == null || module == Py.None) { - PyFrame f = Py.getFrame(); - if (f != null) { - PyObject nm = f.f_globals.__finditem__("__name__"); - if (nm != null) { - dict.__setitem__("__module__", nm); - } - } - } - } - PyObject lookup(String name) { PyObject result = __dict__.__finditem__(name); if (result == null && __bases__ != null) { Modified: trunk/jython/src/org/python/core/PyFrame.java =================================================================== --- trunk/jython/src/org/python/core/PyFrame.java 2009-04-10 15:36:58 UTC (rev 6208) +++ trunk/jython/src/org/python/core/PyFrame.java 2009-04-10 19:21:01 UTC (rev 6209) @@ -276,20 +276,6 @@ throw Py.NameError(String.format(NAME_ERROR_MSG, index)); } - public PyObject getname_or_null(String index) { - PyObject ret; - if (f_locals == null || f_locals == f_globals) { - ret = doGetglobal(index); - } else { - ret = f_locals.__finditem__(index); - if (ret != null) { - return ret; - } - ret = doGetglobal(index); - } - return ret; - } - public PyObject getglobal(String index) { PyObject ret = doGetglobal(index); if (ret != null) { Modified: trunk/jython/src/org/python/core/PyType.java =================================================================== --- trunk/jython/src/org/python/core/PyType.java 2009-04-10 15:36:58 UTC (rev 6208) +++ trunk/jython/src/org/python/core/PyType.java 2009-04-10 19:21:01 UTC (rev 6209) @@ -374,10 +374,8 @@ dict.__setitem__("__new__", new PyStaticMethod(new_)); } - // NOTE: __module__ is already guaranteed by Py.makeClass - if (dict.__finditem__("__doc__") == null) { - dict.__setitem__("__doc__", Py.None); - } + ensureDoc(dict); + ensureModule(dict); // Calculate method resolution order mro_internal(); @@ -396,6 +394,37 @@ } } + /** + * Ensure dict contains a __doc__. + * + * @param dict a PyObject mapping + */ + public static void ensureDoc(PyObject dict) { + if (dict.__finditem__("__doc__") == null) { + dict.__setitem__("__doc__", Py.None); + } + } + + /** + * Ensure dict contains a __module__, retrieving it from the current frame if it + * doesn't exist. + * + * @param dict a PyObject mapping + */ + public static void ensureModule(PyObject dict) { + if (dict.__finditem__("__module__") != null) { + return; + } + PyFrame frame = Py.getFrame(); + if (frame == null) { + return; + } + PyObject name = frame.f_globals.__finditem__("__name__"); + if (name != null) { + dict.__setitem__("__module__", name); + } + } + private static PyObject invoke_new_(PyObject new_, PyType type, boolean init, PyObject[] args, String[] keywords) { PyObject newobj; Modified: trunk/jython/src/org/python/core/imp.java =================================================================== --- trunk/jython/src/org/python/core/imp.java 2009-04-10 15:36:58 UTC (rev 6208) +++ trunk/jython/src/org/python/core/imp.java 2009-04-10 19:21:01 UTC (rev 6209) @@ -20,7 +20,7 @@ private static final String UNKNOWN_SOURCEFILE = "<unknown>"; - public static final int APIVersion = 19; + public static final int APIVersion = 20; public static final int NO_MTIME = -1; This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <pj...@us...> - 2009-04-11 00:25:30
|
Revision: 6213 http://jython.svn.sourceforge.net/jython/?rev=6213&view=rev Author: pjenvey Date: 2009-04-11 00:25:21 +0000 (Sat, 11 Apr 2009) Log Message: ----------- o reapply test_cmd_line workaround o fix error handling of bad -c/-m command lines Modified Paths: -------------- trunk/jython/Lib/test/test_cmd_line.py trunk/jython/src/org/python/util/jython.java trunk/jython/src/shell/jython Modified: trunk/jython/Lib/test/test_cmd_line.py =================================================================== --- trunk/jython/Lib/test/test_cmd_line.py 2009-04-11 00:24:56 UTC (rev 6212) +++ trunk/jython/Lib/test/test_cmd_line.py 2009-04-11 00:25:21 UTC (rev 6213) @@ -50,7 +50,8 @@ self.assertTrue('usage' in self.start_python('-h')) def test_version(self): - version = 'Python %d.%d' % sys.version_info[:2] + prefix = 'J' if test.test_support.is_jython else 'P' + version = prefix + 'ython %d.%d' % sys.version_info[:2] self.assertTrue(self.start_python('-V').startswith(version)) def test_run_module(self): Modified: trunk/jython/src/org/python/util/jython.java =================================================================== --- trunk/jython/src/org/python/util/jython.java 2009-04-11 00:24:56 UTC (rev 6212) +++ trunk/jython/src/org/python/util/jython.java 2009-04-11 00:25:21 UTC (rev 6213) @@ -259,6 +259,7 @@ interp.exec(opts.command); } catch (Throwable t) { Py.printException(t); + System.exit(1); } } @@ -273,7 +274,7 @@ } catch (Throwable t) { Py.printException(t); interp.cleanup(); - System.exit(0); + System.exit(-1); } } } @@ -407,8 +408,20 @@ Options.importSite = false; } else if (arg.equals("-c")) { - command = args[++index]; - if (!fixInteractive) interactive = false; + if (arg.length() > 2) { + command = arg.substring(2); + } + else if ((index + 1) < args.length) { + command = args[++index]; + } else { + System.err.println("Argument expected for the -c option"); + System.err.print(jython.usageHeader); + System.err.println("Try `jython -h' for more information."); + return false; + } + if (!fixInteractive) { + interactive = false; + } index++; break; } Modified: trunk/jython/src/shell/jython =================================================================== --- trunk/jython/src/shell/jython 2009-04-11 00:24:56 UTC (rev 6212) +++ trunk/jython/src/shell/jython 2009-04-11 00:25:21 UTC (rev 6213) @@ -117,9 +117,13 @@ fi ;; # Match switches that take an argument - -c|-C|-jar|-Q|-W) - python_args=("${python_args[@]}" "$1" "$2") - shift + -c|-C|-m|-jar|-Q|-W) + if [ $# = 1 ]; then + python_args=("${python_args[@]}" "$1") + else + python_args=("${python_args[@]}" "$1" "$2") + shift + fi; ;; # Match -Dprop=val type args -D*) This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <fwi...@us...> - 2009-04-14 21:16:08
|
Revision: 6224 http://jython.svn.sourceforge.net/jython/?rev=6224&view=rev Author: fwierzbicki Date: 2009-04-14 21:16:03 +0000 (Tue, 14 Apr 2009) Log Message: ----------- Applied patch from http://bugs.jython.org/issue1271: Bean property accessors in derived class overide methods in base class. I altered his tests so that they are easily runnable by "ant javatest". Thanks to Geoffrey French for the fix. Also fixed a bad comment in IdentityTest.java. Modified Paths: -------------- trunk/jython/NEWS trunk/jython/src/org/python/core/PyJavaType.java trunk/jython/tests/java/org/python/tests/identity/IdentityTest.java trunk/jython/tests/java/org/python/tests/props/BeanPropertyTest.java Added Paths: ----------- trunk/jython/tests/python/prop_test.py Modified: trunk/jython/NEWS =================================================================== --- trunk/jython/NEWS 2009-04-13 17:12:00 UTC (rev 6223) +++ trunk/jython/NEWS 2009-04-14 21:16:03 UTC (rev 6224) @@ -2,6 +2,7 @@ Jython 2.5.0 rc 1 Bugs fixed (new numbering due to move to Roundup) + - [ 1271 ] Bean property accessors in derived class overide methods in base class - [ 1264 ] 'is not' test exhibits incorrect behaviour when wrapping Java objects - [ 1295 ] Setting a write-only bean property causes a NPE - [ 1272 ] ASTList ClassCastException Modified: trunk/jython/src/org/python/core/PyJavaType.java =================================================================== --- trunk/jython/src/org/python/core/PyJavaType.java 2009-04-13 17:12:00 UTC (rev 6223) +++ trunk/jython/src/org/python/core/PyJavaType.java 2009-04-14 21:16:03 UTC (rev 6224) @@ -407,7 +407,8 @@ // If one of our superclasses has something defined for this name, check if its a bean // property, and if so, try to fill in any gaps in our property from there - PyObject superForName = lookup(prop.__name__); + PyObject fromType[] = new PyObject[] { null }; + PyObject superForName = lookup_where(prop.__name__, fromType); if (superForName instanceof PyBeanProperty) { PyBeanProperty superProp = ((PyBeanProperty)superForName); // If it has a set method and we don't, take it regardless. If the types don't line @@ -426,6 +427,12 @@ // If the parent bean is hiding a static field, we need it as well. prop.field = superProp.field; } + } else if (superForName != null && fromType[0] != this && !(superForName instanceof PyBeanEvent)) { + // There is already an entry for this name + // It came from a type which is not @this; it came from a superclass + // It is not a bean event + // Do not override methods defined in superclass + continue; } // If the return types on the set and get methods for a property don't agree, the get // method takes precedence Modified: trunk/jython/tests/java/org/python/tests/identity/IdentityTest.java =================================================================== --- trunk/jython/tests/java/org/python/tests/identity/IdentityTest.java 2009-04-13 17:12:00 UTC (rev 6223) +++ trunk/jython/tests/java/org/python/tests/identity/IdentityTest.java 2009-04-14 21:16:03 UTC (rev 6224) @@ -18,7 +18,6 @@ } public void testReadonly() { - //This used to cause an NPE see http://bugs.jython.org/issue1295 interp.execfile("tests/python/identity_test.py"); } } Modified: trunk/jython/tests/java/org/python/tests/props/BeanPropertyTest.java =================================================================== --- trunk/jython/tests/java/org/python/tests/props/BeanPropertyTest.java 2009-04-13 17:12:00 UTC (rev 6223) +++ trunk/jython/tests/java/org/python/tests/props/BeanPropertyTest.java 2009-04-14 21:16:03 UTC (rev 6224) @@ -20,25 +20,8 @@ interp.exec("from org.python.tests.props import Readonly;Readonly().a = 'test'"); } - //This test is for http://bugs.jython.org/issue1271 - public void testBaseProp() { - /* - interp.exec("from org.python.tests.props import PropShadow"); - interp.exec("a = PropShadow.Derived()"); - interp.exec("assert a.foo() == 1, 'a'"); - interp.exec("assert a.bar() == 2, 'b'"); - */ + public void testShadowing() { + interp.execfile("tests/python/prop_test.py"); } - //This test is for http://bugs.jython.org/issue1271 - public void testDerivedProp() { - /* - interp.exec("from org.python.tests.props import PropShadow"); - interp.exec("b = PropShadow.Derived()"); - interp.exec("assert b.getBaz() == 4, 'c'"); - interp.exec("assert b.getFoo() == 3, 'd'"); - interp.exec("assert b.foo() == 1, 'e'"); - interp.exec("assert b.foo() == 1, 'f'"); - */ - } } Added: trunk/jython/tests/python/prop_test.py =================================================================== --- trunk/jython/tests/python/prop_test.py (rev 0) +++ trunk/jython/tests/python/prop_test.py 2009-04-14 21:16:03 UTC (rev 6224) @@ -0,0 +1,16 @@ +from org.python.tests.identity import IdentityObject + +#This test is for http://bugs.jython.org/issue1271 +from org.python.tests.props import PropShadow + +a = PropShadow.Derived() +assert a.foo() == 1, 'a' +assert a.bar() == 2, 'b' + +from org.python.tests.props import PropShadow +b = PropShadow.Derived() +assert b.getBaz() == 4, 'c' +assert b.baz == 4, 'e' +assert b.getFoo() == 3, 'd' +assert b.foo() == 1, 'f' + This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <pj...@us...> - 2009-04-17 03:44:56
|
Revision: 6235 http://jython.svn.sourceforge.net/jython/?rev=6235&view=rev Author: pjenvey Date: 2009-04-17 03:44:35 +0000 (Fri, 17 Apr 2009) Log Message: ----------- o fix memoization with cyclic structures: http://bugs.python.org/issue998998 o cleanup persistent_id/load handling, allow persistent_load as a list Modified Paths: -------------- trunk/jython/Lib/test/test_cpickle_jy.py trunk/jython/src/org/python/modules/cPickle.java Modified: trunk/jython/Lib/test/test_cpickle_jy.py =================================================================== --- trunk/jython/Lib/test/test_cpickle_jy.py 2009-04-17 01:38:24 UTC (rev 6234) +++ trunk/jython/Lib/test/test_cpickle_jy.py 2009-04-17 03:44:35 UTC (rev 6235) @@ -7,13 +7,34 @@ import unittest from test import test_support +class MyClass(object): + pass + + class CPickleTestCase(unittest.TestCase): def test_zero_long(self): self.assertEqual(cPickle.loads(cPickle.dumps(0L, 2)), 0L) self.assertEqual(cPickle.dumps(0L, 2), pickle.dumps(0L, 2)) + def test_cyclic_memoize(self): + # http://bugs.python.org/issue998998 - cPickle shouldn't fail + # this, though pickle.py still does + m = MyClass() + m2 = MyClass() + s = set([m]) + m.foo = set([m2]) + m2.foo = s + + s2 = cPickle.loads(cPickle.dumps(s)) + self.assertEqual(len(s2), 1) + m3 = iter(s2).next() + self.assertEqual(len(m3.foo), 1) + m4 = iter(m3.foo).next() + self.assertEqual(m4.foo, s2) + + def test_main(): test_support.run_unittest(CPickleTestCase) Modified: trunk/jython/src/org/python/modules/cPickle.java =================================================================== --- trunk/jython/src/org/python/modules/cPickle.java 2009-04-17 01:38:24 UTC (rev 6234) +++ trunk/jython/src/org/python/modules/cPickle.java 2009-04-17 03:44:35 UTC (rev 6235) @@ -770,14 +770,8 @@ private void save(PyObject object, boolean pers_save) { - if (!pers_save) { - if (persistent_id != null) { - PyObject pid = persistent_id.__call__(object); - if (pid != Py.None) { - save_pers(pid); - return; - } - } + if (!pers_save && persistent_id != null && save_pers(object, persistent_id)) { + return; } int d = get_id(object); @@ -801,12 +795,8 @@ if (save_type(object, t)) return; - if (inst_persistent_id != null) { - PyObject pid = inst_persistent_id.__call__(object); - if (pid != Py.None) { - save_pers(pid); - return; - } + if (!pers_save && inst_persistent_id != null && save_pers(object, inst_persistent_id)) { + return; } if (Py.isSubClass(t, PyType.TYPE)) { @@ -859,13 +849,20 @@ "Second element of tupe returned by " + reduce.__repr__() + " must be a tuple"); } - save_reduce(callable, arg_tup, state, listitems, dictitems, putMemo(d, object)); - + save_reduce(callable, arg_tup, state, listitems, dictitems, object); } - final private void save_pers(PyObject pid) { + final private boolean save_pers(PyObject object, PyObject pers_func) { + PyObject pid = pers_func.__call__(object); + if (pid == Py.None) { + return false; + } + if (protocol == 0) { + if (!Py.isInstance(pid, PyString.TYPE)) { + throw new PyException(PicklingError, "persistent id must be string"); + } file.write(PERSID); file.write(pid.toString()); file.write("\n"); @@ -873,10 +870,12 @@ save(pid, true); file.write(BINPERSID); } + return true; } final private void save_reduce(PyObject callable, PyObject arg_tup, - PyObject state, PyObject listitems, PyObject dictitems, int memoId) + PyObject state, PyObject listitems, PyObject dictitems, + PyObject object) { PyObject callableName = callable.__findattr__("__name__"); if(protocol >= 2 && callableName != null @@ -894,7 +893,10 @@ save(arg_tup); file.write(REDUCE); } - put(memoId); + + // Memoize + put(putMemo(get_id(object), object)); + if (listitems != Py.None) { batch_appends(listitems); } @@ -1697,17 +1699,30 @@ final private void load_persid() { - String pid = file.readlineNoNl(); - push(persistent_load.__call__(new PyString(pid))); + load_persid(new PyString(file.readlineNoNl())); } final private void load_binpersid() { - PyObject pid = pop(); - push(persistent_load.__call__(pid)); + load_persid(pop()); } + final private void load_persid(PyObject pid) { + if (persistent_load == null) { + throw new PyException(UnpicklingError, + "A load persistent id instruction was encountered,\n" + + "but no persistent_load function was specified."); + } + if (persistent_load instanceof PyList) { + ((PyList)persistent_load).append(pid); + } else { + pid = persistent_load.__call__(pid); + } + push(pid); + } + + final private void load_none() { push(Py.None); } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <zy...@us...> - 2009-04-19 00:01:14
|
Revision: 6244 http://jython.svn.sourceforge.net/jython/?rev=6244&view=rev Author: zyasoft Date: 2009-04-19 00:01:11 +0000 (Sun, 19 Apr 2009) Log Message: ----------- Merged revisions 6168,6176,6186,6190-6192,6195-6197,6199-6202,6215-6217,6222-6223,6227-6228,6231,6237-6240 via svnmerge from https://jython.svn.sourceforge.net/svnroot/jython/branches/newlist Replaces PyList with a java.util.List and PyTuple with PyObject[] backed representations, respectively. Modified Paths: -------------- trunk/jython/Lib/test/test_javalist.py trunk/jython/src/org/python/core/JavaImportHelper.java trunk/jython/src/org/python/core/Py.java trunk/jython/src/org/python/core/PyList.java trunk/jython/src/org/python/core/PySequenceList.java trunk/jython/src/org/python/core/PyTuple.java trunk/jython/src/org/python/core/packagecache/PackageManager.java trunk/jython/src/templates/README.txt Added Paths: ----------- trunk/jython/src/org/python/core/PyComparator.java trunk/jython/src/templates/newtuple.derived Removed Paths: ------------- trunk/jython/src/org/python/core/PyObjectArray.java trunk/jython/src/org/python/core/PyObjectList.java Property Changed: ---------------- trunk/jython/ Property changes on: trunk/jython ___________________________________________________________________ Modified: svnmerge-integrated - /branches/modjy:1-6074 /branches/pbcvm:1-6045 /branches/newlist:1-6160 + /branches/modjy:1-6074 /branches/pbcvm:1-6045 /branches/newlist:1-6243 Modified: trunk/jython/Lib/test/test_javalist.py =================================================================== --- trunk/jython/Lib/test/test_javalist.py 2009-04-18 23:32:59 UTC (rev 6243) +++ trunk/jython/Lib/test/test_javalist.py 2009-04-19 00:01:11 UTC (rev 6244) @@ -1,4 +1,3 @@ -from test_support import * from javatests import ListTest class PyListTest(ListTest): Modified: trunk/jython/src/org/python/core/JavaImportHelper.java =================================================================== --- trunk/jython/src/org/python/core/JavaImportHelper.java 2009-04-18 23:32:59 UTC (rev 6243) +++ trunk/jython/src/org/python/core/JavaImportHelper.java 2009-04-19 00:01:11 UTC (rev 6244) @@ -120,6 +120,9 @@ Iterator iterator = ((PyTuple) fromlist).iterator(); while (iterator.hasNext()) { Object obj = iterator.next(); + if (obj instanceof PyString) { + obj = ((PyString)obj).string; + } if (obj instanceof String) { String fromName = (String) obj; if (!"*".equals(fromName)) { Modified: trunk/jython/src/org/python/core/Py.java =================================================================== --- trunk/jython/src/org/python/core/Py.java 2009-04-18 23:32:59 UTC (rev 6243) +++ trunk/jython/src/org/python/core/Py.java 2009-04-19 00:01:11 UTC (rev 6244) @@ -21,6 +21,8 @@ import org.python.antlr.base.mod; import com.kenai.constantine.platform.Errno; +import java.util.ArrayList; +import java.util.List; import org.python.compiler.Module; import org.python.core.adapter.ClassicPyObjectAdapter; import org.python.core.adapter.ExtensiblePyObjectAdapter; @@ -1932,13 +1934,12 @@ } catch (PyException exc) { } - PyObjectArray objs = new PyObjectArray(n); + List<PyObject> objs = new ArrayList<PyObject>(n); for (PyObject item : o.asIterable()) { objs.add(item); } - // Cut back if guess was too large. - objs.trimToSize(); - return (PyObject[]) objs.getArray(); + PyObject dest[] = new PyObject[0]; + return (objs.toArray(dest)); } } /** @deprecated */ Copied: trunk/jython/src/org/python/core/PyComparator.java (from rev 6202, branches/newlist/src/org/python/core/PyComparator.java) =================================================================== --- trunk/jython/src/org/python/core/PyComparator.java (rev 0) +++ trunk/jython/src/org/python/core/PyComparator.java 2009-04-19 00:01:11 UTC (rev 6244) @@ -0,0 +1,53 @@ +package org.python.core; + +import java.util.Comparator; + +public class PyComparator implements Comparator<PyObject> { + + protected PyList list; + protected PyObject cmp; + protected PyObject key; + protected boolean reverse = false; + + PyComparator(PyList list, PyObject cmp, PyObject key, boolean reverse) { + this.list = list; + this.cmp = cmp; + this.key = key; + this.reverse = reverse; + } + + // First cut at an implementation. FIXME: In CPython key is supposed to + // make things fast, accessing each element once. For this first cut I am + // cheating and calling the key function on every pass to get something + // that works right away. + public int compare(PyObject o1, PyObject o2) { + int result; + if (key != null && key != Py.None) { + o1 = key.__call__(o1); + o2 = key.__call__(o2); + } + if (cmp != null && cmp != Py.None) { + result = cmp.__call__(o1, o2).asInt(); + } else { + result = o1._cmp(o2); + } + if (reverse) { + return -result; + } + if (this.list.gListAllocatedStatus >= 0) { + throw Py.ValueError("list modified during sort"); + } + return result; + } + + public boolean equals(Object o) { + if(o == this) { + return true; + } + + if (o instanceof PyComparator) { + return key.equals(((PyComparator)o).key) && cmp.equals(((PyComparator)o).cmp); + } + return false; + } +} Modified: trunk/jython/src/org/python/core/PyList.java =================================================================== --- trunk/jython/src/org/python/core/PyList.java 2009-04-18 23:32:59 UTC (rev 6243) +++ trunk/jython/src/org/python/core/PyList.java 2009-04-19 00:01:11 UTC (rev 6244) @@ -1,38 +1,59 @@ // Copyright (c) Corporation for National Research Initiatives package org.python.core; -import java.util.Collection; -import java.util.Iterator; -import java.util.List; - +import java.util.ArrayList; +import java.util.Arrays; import org.python.expose.ExposedMethod; import org.python.expose.ExposedNew; import org.python.expose.ExposedType; import org.python.expose.MethodType; import org.python.util.Generic; -/** - * A builtin python list. - */ +import java.util.Collection; +import java.util.Collections; +import java.util.ConcurrentModificationException; +import java.util.Iterator; +import java.util.List; +import java.util.ListIterator; + @ExposedType(name = "list", base = PyObject.class) -public class PyList extends PySequenceList { +public class PyList extends PySequenceList implements List { public static final PyType TYPE = PyType.fromClass(PyList.class); + protected final List<PyObject> list; public PyList() { - this(TYPE, Py.EmptyObjects); + this(TYPE); } public PyList(PyType type) { super(type); + list = Generic.list(); } + private PyList(List list, boolean convert) { + super(TYPE); + if (!convert) { + this.list = list; + } else { + this.list = Generic.list(); + for (Object o : list) { + add(o); + } + } + } + public PyList(PyType type, PyObject[] elements) { - super(type, elements); + super(type); + list = new ArrayList<PyObject>(Arrays.asList(elements)); } public PyList(PyType type, Collection c) { - super(type, c); + super(type); + list = new ArrayList<PyObject>(c.size()); + for (Object o : c) { + add(o); + } } public PyList(PyObject[] elements) { @@ -40,23 +61,28 @@ } public PyList(Collection c) { - super(TYPE, c); + this(TYPE, c); } public PyList(PyObject o) { this(TYPE); for (PyObject item : o.asIterable()) { - append(item); + list.add(item); } } + public static PyList fromList(List<PyObject> list) { + return new PyList(list, false); + } + private static List<PyObject> listify(Iterator<PyObject> iter) { - List<PyObject> list = Generic.list(); - while (iter.hasNext()) { + List<PyObject> list = Generic.list(); + while (iter.hasNext()) { list.add(iter.next()); - } - return list; + } + return list; } + public PyList(Iterator<PyObject> iter) { this(TYPE, listify(iter)); } @@ -64,15 +90,16 @@ @ExposedNew @ExposedMethod(doc = BuiltinDocs.list___init___doc) final void list___init__(PyObject[] args, String[] kwds) { - ArgParser ap = new ArgParser("list", args, kwds, new String[] {"sequence"}, 0); + ArgParser ap = new ArgParser("list", args, kwds, new String[]{"sequence"}, 0); PyObject seq = ap.getPyObject(0, null); clear(); - if(seq == null) { + if (seq == null) { return; } - if(seq instanceof PySequenceList) { - PySequenceList p = (PySequenceList)seq.__getslice__(Py.None, Py.None, Py.One); - this.list = p.list; + if (seq instanceof PyList) { + list.addAll(((PyList) seq).list); // don't convert + } else if (seq instanceof PyTuple) { + list.addAll(((PyTuple) seq).getList()); } else { for (PyObject item : seq.asIterable()) { append(item); @@ -80,6 +107,7 @@ } } + @Override public int __len__() { return list___len__(); } @@ -89,105 +117,92 @@ return size(); } - protected PyObject getslice(int start, int stop, int step) { - if(step > 0 && stop < start) { - stop = start; - } - int n = sliceLength(start, stop, step); - PyObject[] newList = new PyObject[n]; - PyObject[] array = getArray(); - if(step == 1) { - System.arraycopy(array, start, newList, 0, stop - start); - return new PyList(newList); - } - int j = 0; - for(int i = start; j < n; i += step) { - newList[j] = array[i]; - j++; - } - return new PyList(newList); - } - + @Override protected void del(int i) { remove(i); } + @Override protected void delRange(int start, int stop) { remove(start, stop); } + @Override protected void setslice(int start, int stop, int step, PyObject value) { - if(stop < start) { + if (stop < start) { stop = start; } - if(value instanceof PySequence) { - PySequence sequence = (PySequence) value; - setslicePySequence(start, stop, step, sequence); - } else if(value instanceof List) { - List list = (List)value.__tojava__(List.class); - if(list != null && list != Py.NoConversion) { - setsliceList(start, stop, step, list); + if (value instanceof PyList) { + if (value == this) { // copy + value = new PyList((PySequence) value); } + setslicePyList(start, stop, step, (PyList) value); + } else if (value instanceof PySequence) { + setsliceIterator(start, stop, step, value.asIterable().iterator()); + } else if (value != null && !(value instanceof List)) { + value = new PyList(value); + setsliceIterator(start, stop, step, value.asIterable().iterator()); } else { - setsliceIterable(start, stop, step, value); + List valueList = (List) value.__tojava__(List.class); + if (valueList != null && valueList != Py.NoConversion) { + setsliceList(start, stop, step, valueList); + } } } - protected void setslicePySequence(int start, int stop, int step, PySequence value) { - if(step == 1) { - PyObject[] otherArray; - PyObject[] array = getArray(); + protected void setsliceList(int start, int stop, int step, List value) { + int n = sliceLength(start, stop, step); + if (list instanceof ArrayList) { + ((ArrayList) list).ensureCapacity(start + n); + } + ListIterator src = value.listIterator(); + for (int j = start; src.hasNext(); j += step) { + set(j, src.next()); + } + } - int n = value.__len__(); - if (value instanceof PySequenceList) { - otherArray = ((PySequenceList)value).getArray(); - } else { - otherArray = Py.unpackSequence(value, value.__len__()); + protected void setsliceIterator(int start, int stop, int step, Iterator<PyObject> iter) { + if (step == 1) { + List<PyObject> insertion = new ArrayList<PyObject>(); + if (iter != null) { + while (iter.hasNext()) { + insertion.add(iter.next()); + } } - if (otherArray == array) { - otherArray = otherArray.clone(); - } - list.replaceSubArray(start, stop, otherArray, 0, n); - } else if(step != 0) { - if(value == this) { - PyList newseq = new PyList(); - PyObject iter = value.__iter__(); - for(PyObject item = null; (item = iter.__iternext__()) != null;) { - newseq.append(item); + list.subList(start, stop).clear(); + list.addAll(start, insertion); + } else { + int size = list.size(); + for (int j = start; iter.hasNext(); j += step) { + PyObject item = iter.next(); + if (j >= size) { + list.add(item); + } else { + list.set(j, item); } - value = newseq; } - int n = value.__len__(); - for (int i = 0, j = start; i < n; i++, j += step) { - list.pyset(j, value.pyget(i)); - } } } - protected void setsliceList(int start, int stop, int step, List value) { - if(step != 1) { - throw Py.TypeError("setslice with java.util.List and step != 1 not supported yet"); - } - int n = value.size(); - list.ensureCapacity(start + n); - for(int i = 0; i < n; i++) { - list.add(i + start, value.get(i)); - } - } - - protected void setsliceIterable(int start, int stop, int step, PyObject value) { - PyObject[] seq; - try { - seq = Py.make_array(value); - } catch (PyException pye) { - if (Py.matchException(pye, Py.TypeError)) { - throw Py.TypeError("can only assign an iterable"); + protected void setslicePyList(int start, int stop, int step, PyList other) { + if (step == 1) { + list.subList(start, stop).clear(); + list.addAll(start, other.list); + } else { + int size = list.size(); + Iterator<PyObject> iter = other.list.listIterator(); + for (int j = start; iter.hasNext(); j += step) { + PyObject item = iter.next(); + if (j >= size) { + list.add(item); + } else { + list.set(j, item); + } } - throw pye; } - setslicePySequence(start, stop, step, new PyList(seq)); } + @Override protected PyObject repeat(int count) { if (count < 0) { count = 0; @@ -198,12 +213,11 @@ throw Py.MemoryError(""); } - PyObject[] array = getArray(); - PyObject[] newArray = new PyObject[newSize]; - for(int i = 0; i < count; i++) { - System.arraycopy(array, 0, newArray, i * size, size); + PyList newList = new PyList(); + for (int i = 0; i < count; i++) { + newList.addAll(list); } - return new PyList(newArray); + return newList; } @ExposedMethod(type = MethodType.BINARY, doc = BuiltinDocs.list___ne___doc) @@ -236,6 +250,7 @@ return seq___ge__(o); } + @Override public PyObject __imul__(PyObject o) { return list___imul__(o); } @@ -262,12 +277,14 @@ } int newSize = size * count; - list.setSize(newSize); - PyObject[] array = getArray(); + if (list instanceof ArrayList) { + ((ArrayList) list).ensureCapacity(newSize); + } + List oldList = new ArrayList<PyObject>(list); for (int i = 1; i < count; i++) { - System.arraycopy(array, 0, array, i * size, size); + list.addAll(oldList); } - gListAllocatedStatus = __len__(); + gListAllocatedStatus = __len__(); // now omit? return this; } @@ -297,6 +314,7 @@ return repeat(o.asIndex(Py.OverflowError)); } + @Override public PyObject __add__(PyObject o) { return list___add__(o); } @@ -304,22 +322,22 @@ @ExposedMethod(type = MethodType.BINARY, doc = BuiltinDocs.list___add___doc) final PyObject list___add__(PyObject o) { PyList sum = null; - if(o instanceof PyList) { - PyList other = (PyList)o; - int thisLen = size(); - int otherLen = other.size(); - PyObject[] newList = new PyObject[thisLen + otherLen]; - System.arraycopy(getArray(), 0, newList, 0, thisLen); - System.arraycopy(other.getArray(), 0, newList, thisLen, otherLen); - sum = new PyList(newList); - } else if(!(o instanceof PySequenceList)) { + if (o instanceof PySequenceList && !(o instanceof PyTuple)) { + if (o instanceof PyList) { + List oList = ((PyList) o).list; + List newList = new ArrayList(list.size() + oList.size()); + newList.addAll(list); + newList.addAll(oList); + sum = fromList(newList); + } + } else if (!(o instanceof PySequenceList)) { // also support adding java lists (but not PyTuple!) Object oList = o.__tojava__(List.class); - if(oList != Py.NoConversion && oList != null) { + if (oList != Py.NoConversion && oList != null) { List otherList = (List) oList; sum = new PyList(); sum.list_extend(this); - for(Iterator i = otherList.iterator(); i.hasNext();) { + for (Iterator i = otherList.iterator(); i.hasNext();) { sum.add(i.next()); } } @@ -327,6 +345,7 @@ return sum; } + @Override public PyObject __radd__(PyObject o) { return list___radd__(o); } @@ -335,9 +354,9 @@ @ExposedMethod(type = MethodType.BINARY) final PyObject list___radd__(PyObject o) { // Support adding java.util.List, but prevent adding PyTuple. - // 'o' should never be a PyList since __add__ is defined. + // 'o' should never be a PyNewList since __add__ is defined. PyList sum = null; - if(o instanceof PySequence) { + if (o instanceof PySequence) { return null; } Object oList = o.__tojava__(List.class); @@ -367,12 +386,13 @@ @ExposedMethod(doc = BuiltinDocs.list___getitem___doc) final PyObject list___getitem__(PyObject o) { PyObject ret = seq___finditem__(o); - if(ret == null) { + if (ret == null) { throw Py.IndexError("index out of range: " + o); } return ret; } + @Override public PyObject __iter__() { return list___iter__(); } @@ -397,8 +417,9 @@ seq___delslice__(start, stop, step); } + @Override protected String unsupportedopMessage(String op, PyObject o2) { - if(op.equals("+")) { + if (op.equals("+")) { return "can only concatenate list (not \"{2}\") to list"; } return super.unsupportedopMessage(op, o2); @@ -412,19 +433,19 @@ @ExposedMethod(names = "__repr__") final String list_toString() { ThreadState ts = Py.getThreadState(); - if(!ts.enterRepr(this)) { + if (!ts.enterRepr(this)) { return "[...]"; } StringBuilder buf = new StringBuilder("["); int length = size(); - PyObject[] array = getArray(); - for(int i = 0; i < length - 1; i++) { - buf.append((array[i]).__repr__().toString()); - buf.append(", "); + int i = 0; + for (PyObject item : list) { + buf.append(item.__repr__().toString()); + if (i < length - 1) { + buf.append(", "); + } + i++; } - if(length > 0) { - buf.append((array[length - 1]).__repr__().toString()); - } buf.append("]"); ts.exitRepr(this); return buf.toString(); @@ -459,9 +480,8 @@ @ExposedMethod(doc = BuiltinDocs.list_count_doc) final int list_count(PyObject o) { int count = 0; - PyObject[] array = getArray(); - for(int i = 0, n = size(); i < n; i++) { - if(array[i].equals(o)) { + for (PyObject item : list) { + if (item.equals(o)) { count++; } } @@ -509,10 +529,17 @@ // Follow Python 2.3+ behavior int validStop = boundToSequence(stop); int validStart = boundToSequence(start); - PyObject[] array = getArray(); - for(int i = validStart; i < validStop && i < size(); i++) { - if(array[i].equals(o)) { - return i; + int i = validStart; + if (validStart <= validStop) { + try { + for (PyObject item : list.subList(validStart, validStop)) { + if (item.equals(o)) { + return i; + } + i++; + } + } catch (ConcurrentModificationException ex) { + throw Py.ValueError(message); } } throw Py.ValueError(message); @@ -533,13 +560,13 @@ @ExposedMethod(doc = BuiltinDocs.list_insert_doc) final void list_insert(int index, PyObject o) { - if(index < 0) { + if (index < 0) { index = Math.max(0, size() + index); } - if(index > size()) { + if (index > size()) { index = size(); } - list.pyadd(index, o); + pyadd(index, o); gListAllocatedStatus = __len__(); } @@ -572,15 +599,7 @@ @ExposedMethod(doc = BuiltinDocs.list_reverse_doc) final void list_reverse() { - PyObject tmp; - int n = size(); - PyObject[] array = getArray(); - int j = n - 1; - for(int i = 0; i < n / 2; i++, j--) { - tmp = array[i]; - array[i] = array[j]; - array[j] = tmp; - } + Collections.reverse(list); gListAllocatedStatus = __len__(); } @@ -604,17 +623,16 @@ @ExposedMethod(defaults = "-1", doc = BuiltinDocs.list_pop_doc) final PyObject list_pop(int n) { int length = size(); - if(length == 0) { + if (length == 0) { throw Py.IndexError("pop from empty list"); } - if(n < 0) { + if (n < 0) { n += length; } - if(n < 0 || n >= length) { + if (n < 0 || n >= length) { throw Py.IndexError("pop index out of range"); } - PyObject v = pyget(n); - setslice(n, n + 1, 1, Py.EmptyTuple); + PyObject v = list.remove(n); return v; } @@ -631,11 +649,17 @@ @ExposedMethod(doc = BuiltinDocs.list_extend_doc) final void list_extend(PyObject o) { - int length = size(); - setslice(length, length, 1, o); + if (o instanceof PyList) { + list.addAll(((PyList) o).list); + } else { + for (PyObject item : o.asIterable()) { + list.add(item); + } + } gListAllocatedStatus = __len__(); } + @Override public PyObject __iadd__(PyObject o) { return list___iadd__(o); } @@ -672,13 +696,10 @@ * @param compare * the comparison function. */ - - /** + /** * Sort the items of the list in place. Items is compared with the normal relative comparison * operators. */ - - @ExposedMethod(doc = BuiltinDocs.list_sort_doc) final void list_sort(PyObject[] args, String[] kwds) { ArgParser ap = new ArgParser("list", args, kwds, new String[]{"cmp", "key", "reverse"}, 0); @@ -696,9 +717,11 @@ sort(Py.None, Py.None, Py.False); } - public void sort(PyObject cmp, PyObject key, PyObject reverse) { - MergeState ms = new MergeState(this, cmp, key, reverse.__nonzero__()); - ms.sort(); + public synchronized void sort(PyObject cmp, PyObject key, PyObject reverse) { + gListAllocatedStatus = -1; + PyComparator c = new PyComparator(this, cmp, key, reverse.__nonzero__()); + Collections.sort(list, c); + gListAllocatedStatus = __len__(); } public int hashCode() { @@ -710,7 +733,249 @@ throw Py.TypeError(String.format("unhashable type: '%.200s'", getType().fastGetName())); } + @Override public PyTuple __getnewargs__() { - return new PyTuple(new PyTuple(list.getArray())); + return new PyTuple(new PyTuple(getArray())); } + + @Override + public void add(int index, Object element) { + pyadd(index, Py.java2py(element)); + } + + @Override + public boolean add(Object o) { + pyadd(Py.java2py(o)); + return true; + } + + @Override + public boolean addAll(int index, Collection c) { + PyList elements = new PyList(c); + return list.addAll(index, elements.list); + } + + @Override + public boolean addAll(Collection c) { + return addAll(0, c); + } + + @Override + public void clear() { + list.clear(); + } + + @Override + public boolean contains(Object o) { + return list.contains(Py.java2py(o)); + } + + @Override + public boolean containsAll(Collection c) { + if (c instanceof PySequenceList) { + return list.containsAll(c); + } else { + return list.containsAll(new PyList(c)); + } + } + + @Override + public boolean equals(Object o) { + if (o instanceof PyList) { + return (((PyList) o).list.equals(list)); + } else if (o instanceof List) { // XXX copied from PyList, but... + return o.equals(this); // XXX shouldn't this compare using py2java? + } + return false; + } + + @Override + public Object get(int index) { + return list.get(index).__tojava__(Object.class); + } + + /** @deprecated */ + @Override + public PyObject[] getArray() { + PyObject a[] = null; // = new PyObject[list.size()]; + return list.toArray(a); + } + + @Override + public int indexOf(Object o) { + return list.indexOf(o); + } + + @Override + public boolean isEmpty() { + return list.isEmpty(); + } + + @Override + public Iterator iterator() { + return list.iterator(); + } + + @Override + public int lastIndexOf(Object o) { + return list.lastIndexOf(Py.java2py(o)); + } + + @Override + public ListIterator listIterator() { + return listIterator(0); + } + + @Override + public ListIterator listIterator(final int index) { + return new ListIterator() { + + private final ListIterator<PyObject> iter = list.listIterator(index); + + public boolean hasNext() { + return iter.hasNext(); + } + + public Object next() { + return iter.next().__tojava__(Object.class); + } + + public boolean hasPrevious() { + return iter.hasPrevious(); + } + + public Object previous() { + return iter.previous().__tojava__(Object.class); + } + + public int nextIndex() { + return iter.nextIndex(); + } + + public int previousIndex() { + return iter.previousIndex(); + } + + public void remove() { + iter.remove(); + } + + public void set(Object o) { + iter.set(Py.java2py(o)); + } + + public void add(Object o) { + iter.add(Py.java2py(o)); + } + }; + } + + @Override + public void pyadd(int index, PyObject element) { + list.add(index, element); + } + + @Override + public boolean pyadd(PyObject o) { + list.add(o); + return true; + } + + @Override + public PyObject pyget(int index) { + return list.get(index); + } + + public void pyset(int index, PyObject element) { + list.set(index, element); + } + + @Override + public Object remove(int index) { + return list.remove(index); + } + + @Override + public void remove(int start, int stop) { + list.subList(start, stop).clear(); + } + + @Override + public boolean removeAll(Collection c) { + if (c instanceof PySequenceList) { + return list.removeAll(c); + } else { + return list.removeAll(new PyList(c)); + } + } + + @Override + public boolean retainAll(Collection c) { + if (c instanceof PySequenceList) { + return list.retainAll(c); + } else { + return list.retainAll(new PyList(c)); + } + } + + @Override + public Object set(int index, Object element) { + return list.set(index, Py.java2py(element)).__tojava__(Object.class); + } + + @Override + public int size() { + return list.size(); + } + + @Override + public List subList(int fromIndex, int toIndex) { + return fromList(list.subList(fromIndex, toIndex)); + } + + @Override + public Object[] toArray() { + Object copy[] = list.toArray(); + for (int i = 0; i < copy.length; i++) { + copy[i] = ((PyObject) copy[i]).__tojava__(Object.class); + } + return copy; + } + + @Override + public Object[] toArray(Object[] a) { + Object copy[] = list.toArray(); + if (a.length != copy.length) { + a = copy; + } + for (int i = 0; i < copy.length; i++) { + a[i] = ((PyObject) copy[i]).__tojava__(Object.class); + } + for (int i = copy.length; i < a.length; i++) { + a[i] = null; + } + return a; + } + + protected PyObject getslice(int start, int stop, int step) { + if (step > 0 && stop < start) { + stop = start; + } + int n = sliceLength(start, stop, step); + List newList; + if (step == 1) { + newList = new ArrayList<PyObject>(list.subList(start, stop)); + } else { + newList = new ArrayList<PyObject>(n); + for (int i = start, j = 0; j < n; i += step, j++) { + newList.add(list.get(i)); + } + } + return fromList(newList); + } + + @Override + public boolean remove(Object o) { + return list.remove(Py.java2py(o)); + } } Deleted: trunk/jython/src/org/python/core/PyObjectArray.java =================================================================== --- trunk/jython/src/org/python/core/PyObjectArray.java 2009-04-18 23:32:59 UTC (rev 6243) +++ trunk/jython/src/org/python/core/PyObjectArray.java 2009-04-19 00:01:11 UTC (rev 6244) @@ -1,213 +0,0 @@ -//Copyright (c) Corporation for National Research Initiatives -package org.python.core; - - -/** - * Provides mutable behavior on a PyObject array. Supports operations for - * implementing <CODE>java.util.List</CODE>. - * @author Clark Updike - */ -public class PyObjectArray extends AbstractArray { - - public void remove(int start, int stop) { - super.remove(start, stop); - } - - /** - * The underlying array used for storing the data. - */ - protected PyObject[] baseArray; - - /** - * Create the array with the specified size. - */ - public PyObjectArray() { - super(PyObject.class); - } - - public PyObjectArray(PyObject[] rawArray) { - super(rawArray == null ? 0 : rawArray.length); - baseArray = (rawArray == null) ? new PyObject[] {} : rawArray; - } - - /** - * Create the array with the specified size. - * @param size number of int values initially allowed in array - */ - public PyObjectArray(int size) { - super(PyObject.class, size); - } - - /** - * @param toCopy - */ - public PyObjectArray(PyObjectArray toCopy) { - - super(toCopy); - this.baseArray = (PyObject[])toCopy.copyArray(); - } - - /** - * Add a value at a specified index in the array. - * <P><CODE>AbstractList</CODE> subclasses should update their - * <CODE>modCount</CODE> after calling this method. - * - * @param index index position at which to insert element - * @param value value to be inserted into array - */ - public void add(int index, PyObject value) { - makeInsertSpace(index); - baseArray[index] = value; - } - - /** - * Add a value to the array, appending it after the current values. - * <P><CODE>AbstractList</CODE> subclasses should update their - * <CODE>modCount</CODE> after calling this method. - * - * @param value value to be added - * @return index number of added element - */ - public int add(PyObject value) { - int index = getAddIndex(); - baseArray[index] = value; - return index; - } - - /** - * Duplicates the object with the generic call. - * - * @return a copy of the object - */ - public Object clone() { - return new PyObjectArray(this); - } - - public boolean equals(Object o) { - if(o instanceof PyObjectArray) { - PyObjectArray arr = (PyObjectArray)o; - if (size != arr.size) return false; - for (int i = 0; i < size; i++) { - PyObject thisElem = baseArray[i]; - PyObject otherElem = arr.baseArray[i]; - if (thisElem == null) { - if (otherElem == null) continue; - return false; - } - if (!thisElem.equals(otherElem)) return false; - } - return true; - } - return false; - } - - public int hashCode() { - int x, y; - int len = size; - x = 0x345678; - - for (len--; len>=0; len--) { - y = baseArray[len].hashCode(); - x = (x + x + x) ^ y; - } - x ^= size; - return x; - } - - /** - * Discards values for a range of indices from the array. For the array of - * <code>int</code> values, just sets the values to null. - * - * @param from index of first value to be discarded - * @param to index past last value to be discarded - */ - protected void discardValues(int from, int to) { - for (int i = from; i < to; i++) { - baseArray[i] = null; - } - } - - /** - * Retrieve the value present at an index position in the array. - * - * @param index index position for value to be retrieved - * @return value from position in the array - */ - public PyObject get(int index) { - - if (index >= 0 && index < size) { - return baseArray[index]; - } - - String message = (size == 0) - ? "No data was added, unable to get entry at " + index - : "Index must be between " + 0 + " and " + - (size - 1) + ", but was " + index; - throw new ArrayIndexOutOfBoundsException(message); - - } - - /** - * Get the backing array. This method is used by the type-agnostic base - * class code to access the array used for type-specific storage. The array - * should generally not be modified. To get a copy of the array, see - * {@link #toArray()} which returns a copy. Note that - * <CODE>getSize()</CODE> should be used to determine the number of elements - * in the array, not the array's length (which may reflect excess capacity). - * <CODE>toArray()</CODE> returns an array whose length equals the value - * returned by <CODE>getSize()</CODE>. - * - * @return backing array object - */ - public Object getArray() { - return baseArray; - } - - /** - * Set the value at an index position in the array. - * - * @param index index position to be set - * @param value value to be set - */ - public PyObject set(int index, PyObject value) { - if (index >= 0 && index < size) { - PyObject existing = baseArray[index]; - baseArray[index] = value; - return existing; - } - throw new ArrayIndexOutOfBoundsException( - "Index must be between " + 0 + " and " + - (size - 1) + ", but was " + index); - } - - /** - * Set the backing array. This method is used by the type-agnostic base - * class code to set the array used for type-specific storage. - * - * @param array the backing array object - */ - protected void setArray(Object array) { - baseArray = (PyObject[]) array; - } - - /** - * Constructs and returns a simple array containing the same data as held - * in this growable array. The array's length matches the value returned - * by <CODE>getSize()</CODE> - * - * @return array containing a copy of the data - */ - public PyObject[] toArray() { - return (PyObject[]) copyArray(); - } - - public void ensureCapacity(int minCapacity) { - super.ensureCapacity(minCapacity); - } - - @Override - protected PyObject[] createArray(int size) { - return new PyObject[size]; - } -} - Deleted: trunk/jython/src/org/python/core/PyObjectList.java =================================================================== --- trunk/jython/src/org/python/core/PyObjectList.java 2009-04-18 23:32:59 UTC (rev 6243) +++ trunk/jython/src/org/python/core/PyObjectList.java 2009-04-19 00:01:11 UTC (rev 6244) @@ -1,186 +0,0 @@ -//Copyright (c) Corporation for National Research Initiatives -package org.python.core; - -import java.io.Serializable; -import java.util.AbstractList; -import java.util.Collection; -import java.util.RandomAccess; - -/** - * <CODE>java.util.List</CODE> implementation using an underlying PyObject - * array for higher performance. Jython should use the following methods - * where possible, instead of their <CODE>List</CODE> counterparts: - * <UL> - * <LI>pyadd(int, PyObject)</LI> - * <LI>pyadd(PyObject)</LI> - * <LI>pyset(PyObject)</LI> - * <LI>pyget()</LI> - * </UL> - * @author Clark Updike - */ -public class PyObjectList - extends AbstractList<Object> implements RandomAccess, Cloneable, Serializable { - - /* - * Design note: This class lets PySequenceList implement java.util.List by delegating to it. The - * major distinction is that the backing array is PyObject[], not Object[] (as you'd get by - * delegating to ArrayList). There are 2 major benefits: 1) A lot of casting can be avoided - * internally (although use of PySequenceList descendants as java collections does involve some - * casting); 2) PySequenceList descendants can still do bulk array operations, allowing better - * performance and reuse of much of the pre-collections bulk operation implementation. - */ - - - /** - * Provides mutable operations on a PyObject[] array, including features - * that help with implementing java.util.List. - */ - protected PyObjectArray array; - - public PyObjectList() { - array = new PyObjectArray(); - } - - public PyObjectList(PyObject[] pyObjArr) { - array = new PyObjectArray(pyObjArr); - array.baseArray = pyObjArr; - } - - public PyObjectList(Collection<PyObject> c) { - array = new PyObjectArray(); - array.appendArray(c.toArray()); - } - - public PyObjectList(int size) { - array = new PyObjectArray(size); - } - - /** - * For internal jython usage, use {@link #pyadd(int, PyObject)}. - */ - public void add(int index, Object element) { - pyadd(index, Py.java2py(element)); - } - - public void pyadd(int index, PyObject element) { - array.add(index, element); - modCount += array.getModCountIncr(); - } - - /** - * For internal jython usage, use {@link #pyadd(PyObject)}. - */ - public boolean add(Object o) { - pyadd(Py.java2py(o)); - return true; - } - - public boolean pyadd(PyObject o) { - array.add(o); - modCount += array.getModCountIncr(); - return true; - } - - public Object clone(){ - try { - PyObjectList tol = (PyObjectList) super.clone(); - tol.array = (PyObjectArray) array.clone(); - tol.modCount = 0; - return tol; - } catch (CloneNotSupportedException eCNSE) { - throw new InternalError("Unexpected CloneNotSupportedException.\n" - + eCNSE.getMessage()); - } - } - - public boolean equals(Object o) { - if(o instanceof PyObjectList) { - return array.equals(((PyObjectList)o).array); - } - return false; - } - - public int hashCode() { - return array.hashCode(); - } - - /** - * Use <code>pyget(int)</code> for internal jython usage. - */ - public Object get(int index) { - return array.get(index).__tojava__(Object.class); - } - - PyObject pyget(int index) { - return array.get(index); - } - - public Object remove(int index) { - modCount++; - Object existing = array.get(index); - array.remove(index); - return existing; - } - - public void remove(int start, int stop) { - modCount++; - array.remove(start, stop); - } - - /** - * Use <code>pyset(int, PyObject)</code> for internal jython usage. - */ - public Object set(int index, Object element) { - return pyset(index, Py.java2py(element)).__tojava__(Object.class); - } - - PyObject pyset(int index, PyObject element) { - return array.set(index, element); - } - - public int size() { - return array.getSize(); - } - - public boolean addAll(Collection<? extends Object> c) { - return addAll(size(), c); - } - - public boolean addAll(int index, Collection<? extends Object> c) { - if (c instanceof PySequenceList) { - PySequenceList cList = (PySequenceList)c; - PyObject[] cArray = cList.getArray(); - int cOrigSize = cList.size(); - array.makeInsertSpace(index, cOrigSize); - array.replaceSubArray(index, index + cOrigSize, cArray, 0, cOrigSize); - } else { - // need to use add to convert anything pulled from a collection into a PyObject - for (Object element : c) { - add(element); - } - } - return c.size() > 0; - } - - /** - * Get the backing array. The array should generally not be modified. To get a copy of the - * array, see {@link #toArray()} which returns a copy. - * - * @return backing array object - */ - protected PyObject[] getArray() { - return (PyObject[])array.getArray(); - } - - void ensureCapacity(int minCapacity) { - array.ensureCapacity(minCapacity); - } - - void replaceSubArray(int destStart, int destStop, Object srcArray, int srcStart, int srcStop) { - array.replaceSubArray(destStart, destStop, srcArray, srcStart, srcStop); - } - - void setSize(int count) { - array.setSize(count); - } -} Modified: trunk/jython/src/org/python/core/PySequenceList.java =================================================================== --- trunk/jython/src/org/python/core/PySequenceList.java 2009-04-18 23:32:59 UTC (rev 6243) +++ trunk/jython/src/org/python/core/PySequenceList.java 2009-04-19 00:01:11 UTC (rev 6244) @@ -5,171 +5,81 @@ import java.util.List; import java.util.ListIterator; -public abstract class PySequenceList extends PySequence implements List { +public abstract class PySequenceList extends PySequence { - protected PyObjectList list; - public PySequenceList() { - list = new PyObjectList(); } protected PySequenceList(PyType type) { super(type); - list = new PyObjectList(); } - protected PySequenceList(PyType type, PyObject[] elements) { - super(type); - list = new PyObjectList(elements); - } + public abstract void add(int index, Object element); - /** - * Creates an instance directly backed by the array of PyObject elements. - */ - public PySequenceList(PyObject[] elements) { - list = new PyObjectList(elements); - } + public abstract boolean add(Object o); - public PySequenceList(PyType type, Collection<PyObject> c) { - super(type); - list = new PyObjectList(c); - } + public abstract boolean addAll(int index, Collection c); - public void add(int index, Object element) { - list.add(index, element); - } + public abstract boolean addAll(Collection c); - public boolean add(Object o) { - return list.add(o); - } + public abstract void clear(); - public boolean addAll(int index, Collection c) { - return list.addAll(index, c); - } + public abstract boolean contains(Object o); - public boolean addAll(Collection c) { - return list.addAll(c); - } + public abstract boolean containsAll(Collection c); - public void clear() { - list.clear(); - } + public abstract boolean equals(Object o); - public boolean contains(Object o) { - return list.contains(o); - } + public abstract Object get(int index); - public boolean containsAll(Collection c) { - return list.containsAll(c); - } + /** + * Get the backing array. The array should not be modified. To get a copy of the array, see + * {@link #toArray()}. + */ + public abstract PyObject[] getArray(); - public Object get(int index) { - return list.get(index); - } + public abstract int hashCode(); - public int indexOf(Object o) { - return list.indexOf(o); - } + public abstract int indexOf(Object o); - public boolean isEmpty() { - return list.isEmpty(); - } + public abstract boolean isEmpty(); - public Iterator iterator() { - return list.iterator(); - } + public abstract Iterator iterator(); - public int lastIndexOf(Object o) { - return list.lastIndexOf(o); - } + public abstract int lastIndexOf(Object o); - public ListIterator listIterator() { - return list.listIterator(); - } + public abstract ListIterator listIterator(); - public ListIterator listIterator(int index) { - return list.listIterator(index); - } + public abstract ListIterator listIterator(int index); - public void pyadd(int index, PyObject element) { - list.pyadd(index, element); - } + public abstract void pyadd(int index, PyObject element); - public PyObject pyget(int index) { - return list.pyget(index); - } + public abstract boolean pyadd(PyObject o); - public void pyset(int index, PyObject element) { - list.pyset(index, element); - } + public abstract PyObject pyget(int index); - public Object remove(int index) { - return list.remove(index); - } + public abstract void pyset(int index, PyObject element); - public void remove(int start, int stop) { - list.remove(start, stop); - } + public abstract Object remove(int index); - public boolean remove(Object o) { - return list.remove(o); - } + public abstract void remove(int start, int stop); - public boolean removeAll(Collection c) { - return list.removeAll(c); - } + public abstract boolean remove(Object o); - public boolean retainAll(Collection c) { - return list.retainAll(c); - } + public abstract boolean removeAll(Collection c); - public Object set(int index, Object element) { - return list.set(index, element); - } + public abstract boolean retainAll(Collection c); - public int size() { - return list.size(); - } + public abstract Object set(int index, Object element); - public List subList(int fromIndex, int toIndex) { - return list.subList(fromIndex, toIndex); - } + public abstract int size(); - public Object[] toArray() { - return list.toArray(); - } + public abstract List subList(int fromIndex, int toIndex); - public Object[] toArray(Object[] a) { - return list.toArray(a); - } + public abstract Object[] toArray(); - public String toString() { - return list.toString(); - } + public abstract Object[] toArray(Object[] a); - public boolean pyadd(PyObject o) { - return list.pyadd(o); - } + public abstract String toString(); - public boolean equals(Object o) { - if(o instanceof PySequenceList) { - return list.equals(((PySequenceList)o).list); - } else if(o instanceof List) { - return o.equals(this); - } else { - return super.equals(o); - } - } - - public int hashCode() { - return list.hashCode(); - } - - /** - * Get the backing array. The array should not be modified. To get a copy of the array, see - * {@link #toArray()}. - */ - public PyObject[] getArray() { - return list.getArray(); - } } Modified: trunk/jython/src/org/python/core/PyTuple.java =================================================================== --- trunk/jython/src/org/python/core/PyTuple.java 2009-04-18 23:32:59 UTC (rev 6243) +++ trunk/jython/src/org/python/core/PyTuple.java 2009-04-19 00:01:11 UTC (rev 6244) @@ -1,6 +1,7 @@ // Copyright (c) Corporation for National Research Initiatives package org.python.core; +import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Iterator; @@ -15,11 +16,12 @@ /** * A builtin python tuple. */ +@ExposedType(name = "tuple", base = PyObject.class) +public class PyTuple extends PySequenceList implements List { -@ExposedType(name = "tuple", base = PyObject.class) -public class PyTuple extends PySequenceList -{ public static final PyType TYPE = PyType.fromClass(PyTuple.class); + private final PyObject[] array; + private static final PyTuple EMPTY_TUPLE = new PyTuple(); public PyTuple() { this(TYPE, Py.EmptyObjects); @@ -30,25 +32,58 @@ } public PyTuple(PyType subtype, PyObject[] elements) { - super(subtype, elements); + super(subtype); + if (elements == null) { + array = new PyObject[0]; + } else { + array = new PyObject[elements.length]; + System.arraycopy(elements, 0, array, 0, elements.length); + } } + public PyTuple(PyObject[] elements, boolean copy) { + this(TYPE, elements, copy); + } + + public PyTuple(PyType subtype, PyObject[] elements, boolean copy) { + super(subtype); + + if (copy) { + array = new PyObject[elements.length]; + System.arraycopy(elements, 0, array, 0, elements.length); + } else { + array = elements; + } + } + + private static PyTuple fromArrayNoCopy(PyObject[] elements) { + return new PyTuple(elements, false); + } + private volatile List<PyObject> cachedList = null; + + List<PyObject> getList() { + if (cachedList == null) { + cachedList = Arrays.asList(array); + } + return cachedList; + } + @ExposedNew final static PyObject tuple_new(PyNewWrapper new_, boolean init, PyType subtype, PyObject[] args, String[] keywords) { - ArgParser ap = new ArgParser("tuple", args, keywords, new String[] { "sequence" }, 0); + ArgParser ap = new ArgParser("newtuple", args, keywords, new String[]{"sequence"}, 0); PyObject S = ap.getPyObject(0, null); if (new_.for_type == subtype) { if (S == null) { - return new PyTuple(); + return EMPTY_TUPLE; } if (S instanceof PyTupleDerived) { - return new PyTuple(((PyTuple)S).getArray()); + return new PyTuple(((PyTuple) S).getArray()); } if (S instanceof PyTuple) { return S; } - return new PyTuple(Py.make_array(S)); + return fromArrayNoCopy(Py.make_array(S)); } else { if (S == null) { return new PyTupleDerived(subtype, Py.EmptyObjects); @@ -66,26 +101,26 @@ * @return a PyTuple containing each item in the iterable */ public static PyTuple fromIterable(PyObject iterable) { - return new PyTuple(Py.make_array(iterable)); + return fromArrayNoCopy(Py.make_array(iterable)); } protected PyObject getslice(int start, int stop, int step) { - if (step > 0 && stop < start) + if (step > 0 && stop < start) { stop = start; + } int n = sliceLength(start, stop, step); PyObject[] newArray = new PyObject[n]; - PyObject[] array = getArray(); if (step == 1) { - System.arraycopy(array, start, newArray, 0, stop-start); - return new PyTuple(newArray); + System.arraycopy(array, start, newArray, 0, stop - start); + return fromArrayNoCopy(newArray); } int j = 0; - for (int i=start; j<n; i+=step) { + for (int i = start; j < n; i += step) { newArray[j] = array[i]; j++; } - return new PyTuple(newArray); + return fromArrayNoCopy(newArray); } protected PyObject repeat(int count) { @@ -99,7 +134,7 @@ return this; } if (size == 0) { - return new PyTuple(); + return EMPTY_TUPLE; } } @@ -108,14 +143,14 @@ throw Py.MemoryError(""); } - PyObject[] array = getArray(); PyObject[] newArray = new PyObject[newSize]; for (int i = 0; i < count; i++) { System.arraycopy(array, 0, newArray, i * size, size); } - return new PyTuple(newArray); + return fromArrayNoCopy(newArray); } + @Override public int __len__() { return tuple___len__(); } @@ -124,7 +159,7 @@ final int tuple___len__() { return size(); } - + @ExposedMethod(doc = BuiltinDocs.tuple___contains___doc) final boolean tuple___contains__(PyObject o) { return super.__contains__(o); @@ -160,6 +195,7 @@ return super.__le__(o); } + @Override public PyObject __add__(PyObject generic_other) { return tuple___add__(generic_other); } @@ -168,15 +204,11 @@ final PyObject tuple___add__(PyObject generic_other) { PyTuple sum = null; if (generic_other instanceof PyTuple) { - PyTuple otherTuple = (PyTuple)generic_other; - PyObject[] array = getArray(); - PyObject[] otherArray = otherTuple.getArray(); - int thisLen = size(); - int otherLen = otherTuple.size(); - PyObject[] newArray = new PyObject[thisLen + otherLen]; - System.arraycopy(array, 0, newArray, 0, thisLen); - System.arraycopy(otherArray, 0, newArray, thisLen, otherLen); - sum = new PyTuple(newArray); + PyTuple other = (PyTuple) generic_other; + PyObject[] newArray = new PyObject[array.length + other.array.length]; + System.arraycopy(array, 0, newArray, 0, array.length); + System.arraycopy(other.array, 0, newArray, array.length, other.array.length); + sum = fromArrayNoCopy(newArray); } return sum; } @@ -207,6 +239,7 @@ return repeat(o.asIndex(Py.OverflowError)); } + @Override public PyObject __iter__() { return tuple___iter__(); } @@ -218,13 +251,13 @@ @ExposedMethod(defaults = "null", doc = BuiltinDocs.tuple___getslice___doc) final PyObject tuple___getslice__(PyObject s_start, PyObject s_stop, PyObject s_step) { - return seq___getslice__(s_start,s_stop,s_step); + return seq___getslice__(s_start, s_stop, s_step); } @ExposedMethod(doc = BuiltinDocs.tuple___getitem___doc) final PyObject tuple___getitem__(PyObject index) { PyObject ret = seq___finditem__(index); - if(ret == null) { + if (ret == null) { throw Py.IndexError("index out of range: " + index); } return ret; @@ -232,13 +265,15 @@ @ExposedMethod(doc = BuiltinDocs.tuple___getnewargs___doc) final PyTuple tuple___getnewargs__() { - return new PyTuple(new PyTuple(list.getArray())); + return new PyTuple(new PyTuple(getArray())); } + @Override public PyTuple __getnewargs__() { return tuple___getnewargs__(); } + @Override public int hashCode() { return tuple___hash__(); } @@ -251,7 +286,6 @@ int len = size(); int mult = 1000003; int x = 0x345678; - PyObject[] array = getArray(); while (--len >= 0) { y = array[len].hashCode(); x = (x ^ y) * mult; @@ -261,11 +295,13 @@ } private String subobjRepr(PyObject o) { - if (o == null) + if (o == null) { return "null"; + } return o.__repr__().toString(); } + @Override public String toString() { return tuple___repr__(); } @@ -273,43 +309,54 @@ @ExposedMethod(doc = BuiltinDocs.tuple___repr___doc) final String tuple___repr__() { StringBuilder buf = new StringBuilder("("); - PyObject[] array = getArray(); - int arrayLen = size(); - for (int i = 0; i < arrayLen-1; i++) { + for (int i = 0; i < array.length - 1; i++) { buf.append(subobjRepr(array[i])); buf.append(", "); } - if (arrayLen > 0) - buf.append(subobjRepr(array[arrayLen-1])); - if (arrayLen == 1) + if (array.length > 0) { + buf.append(subobjRepr(array[array.length - 1])); + } + if (array.length == 1) { buf.append(","); + } buf.append(")"); return buf.toString(); } public List subList(int fromIndex, int toIndex) { - return Collections.unmodifiableList(list.subList(fromIndex, toIndex)); + if (fromIndex < 0 || toIndex > size()) { + throw new IndexOutOfBoundsException(); + } else if (fromIndex > toIndex) { + throw new IllegalArgumentException(); + } + System.err.println("subList" + fromIndex + "," + toIndex); + PyObject elements[] = new PyObject[toIndex - fromIndex]; + for (int i = 0, j = fromIndex; i < elements.length; i++, j++) { + elements[i] = array[j]; + } + return new PyTuple(elements); } - // Make PyTuple immutable from the collections interfaces by overriding - // all the mutating methods to throw UnsupportedOperationException exception. - // This is how Collections.unmodifiableList() does it. public Iterator iterator() { return new Iterator() { - Iterator i = list.iterator(); + + private final Iterator<PyObject> iter = getList().iterator(); + public void remove() { throw new UnsupportedOperationException(); } + public boolean hasNext() { ... [truncated message content] |
From: <zy...@us...> - 2009-04-21 02:37:32
|
Revision: 6248 http://jython.svn.sourceforge.net/jython/?rev=6248&view=rev Author: zyasoft Date: 2009-04-21 02:37:28 +0000 (Tue, 21 Apr 2009) Log Message: ----------- Fixes #1317 - PyTuple#equals should only compare if the other obj is a List, but not a PyList, so as to balance both the Java and Python semantics. Modified Paths: -------------- trunk/jython/Lib/test/test_list_jy.py trunk/jython/src/org/python/core/PyTuple.java Modified: trunk/jython/Lib/test/test_list_jy.py =================================================================== --- trunk/jython/Lib/test/test_list_jy.py 2009-04-20 17:47:43 UTC (rev 6247) +++ trunk/jython/Lib/test/test_list_jy.py 2009-04-21 02:37:28 UTC (rev 6248) @@ -41,6 +41,9 @@ self.assertEquals(glmt.silly, "spam") glmt['my-key'] self.assertEquals(glmt.silly, "eggs") + + def test_tuple_equality(self): + self.assertEqual([(1,), [1]].count([1]), 1) # http://bugs.jython.org/issue1317 def test_main(): test.test_support.run_unittest(ListTestCase) Modified: trunk/jython/src/org/python/core/PyTuple.java =================================================================== --- trunk/jython/src/org/python/core/PyTuple.java 2009-04-20 17:47:43 UTC (rev 6247) +++ trunk/jython/src/org/python/core/PyTuple.java 2009-04-21 02:37:28 UTC (rev 6248) @@ -467,7 +467,7 @@ public boolean equals(Object o) { if (o instanceof PyTuple) { return Arrays.equals(array, ((PyTuple) o).array); - } else if (o instanceof List) { + } else if (o instanceof List && !(o instanceof PyList)) { return o.equals(this); } return false; This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <fwi...@us...> - 2009-04-22 03:03:10
|
Revision: 6252 http://jython.svn.sourceforge.net/jython/?rev=6252&view=rev Author: fwierzbicki Date: 2009-04-22 03:03:00 +0000 (Wed, 22 Apr 2009) Log Message: ----------- Applied patch from http://bugs.jython.org/issue1188: Patch against trunk to handle SecurityExceptions. This should make it much easier to run Jython in GAE! Thanks to James Robinson for the patch! Modified Paths: -------------- trunk/jython/ACKNOWLEDGMENTS trunk/jython/NEWS trunk/jython/src/org/python/core/BytecodeLoader.java trunk/jython/src/org/python/core/PyTraceback.java trunk/jython/src/org/python/core/SyspathJavaLoader.java trunk/jython/src/org/python/core/imp.java trunk/jython/src/org/python/core/packagecache/PathPackageManager.java trunk/jython/src/org/python/modules/zipimport/zipimporter.java Modified: trunk/jython/ACKNOWLEDGMENTS =================================================================== --- trunk/jython/ACKNOWLEDGMENTS 2009-04-22 02:23:54 UTC (rev 6251) +++ trunk/jython/ACKNOWLEDGMENTS 2009-04-22 03:03:00 UTC (rev 6252) @@ -82,6 +82,7 @@ Sean McGrath Clark Updike Leonardo Soto + James Robinson Local Variables: mode: indented-text Modified: trunk/jython/NEWS =================================================================== --- trunk/jython/NEWS 2009-04-22 02:23:54 UTC (rev 6251) +++ trunk/jython/NEWS 2009-04-22 03:03:00 UTC (rev 6252) @@ -2,6 +2,7 @@ Jython 2.5.0 rc 1 Bugs fixed (new numbering due to move to Roundup) + - [ 1188 ] Patch against trunk to handle SecurityExceptions - [ 1271 ] Bean property accessors in derived class overide methods in base class - [ 1264 ] 'is not' test exhibits incorrect behaviour when wrapping Java objects - [ 1295 ] Setting a write-only bean property causes a NPE Modified: trunk/jython/src/org/python/core/BytecodeLoader.java =================================================================== --- trunk/jython/src/org/python/core/BytecodeLoader.java 2009-04-22 02:23:54 UTC (rev 6251) +++ trunk/jython/src/org/python/core/BytecodeLoader.java 2009-04-22 03:03:00 UTC (rev 6252) @@ -1,7 +1,8 @@ // Copyright (c) Corporation for National Research Initiatives package org.python.core; -import java.security.SecureClassLoader; +import java.net.URL; +import java.net.URLClassLoader; import java.util.List; import org.objectweb.asm.ClassReader; @@ -30,7 +31,8 @@ if (cur != null) { loader.addParent(cur); } - } catch (SecurityException e) {} + } catch (SecurityException e) { + } } return loader.loadClassFromBytes(name, data); } @@ -71,11 +73,12 @@ } } - public static class Loader extends SecureClassLoader { + public static class Loader extends URLClassLoader { private List<ClassLoader> parents = Generic.list(); public Loader() { + super(new URL[0]); parents.add(imp.getSyspathJavaLoader()); } @@ -115,7 +118,6 @@ } Class<?> c = defineClass(name, data, 0, data.length, getClass().getProtectionDomain()); resolveClass(c); - Compiler.compileClass(c); return c; } } Modified: trunk/jython/src/org/python/core/PyTraceback.java =================================================================== --- trunk/jython/src/org/python/core/PyTraceback.java 2009-04-22 02:23:54 UTC (rev 6251) +++ trunk/jython/src/org/python/core/PyTraceback.java 2009-04-22 03:03:00 UTC (rev 6252) @@ -50,9 +50,13 @@ */ private String getLine(String filename, int lineno) { RelativeFile file = new RelativeFile(filename); - if (!file.isFile() || !file.canRead()) { - // XXX: We should run through sys.path until the filename is found - return null; + try { + if (!file.isFile() || !file.canRead()) { + // XXX: We should run through sys.path until the filename is found + return null; + } + } catch (SecurityException e) { + return null; // If we don't have read access to the file, return null } PyFile pyFile; Modified: trunk/jython/src/org/python/core/SyspathJavaLoader.java =================================================================== --- trunk/jython/src/org/python/core/SyspathJavaLoader.java 2009-04-22 02:23:54 UTC (rev 6251) +++ trunk/jython/src/org/python/core/SyspathJavaLoader.java 2009-04-22 03:03:00 UTC (rev 6252) @@ -105,13 +105,16 @@ // Search the sys.path for a .class file matching the named class. try { return Class.forName(name); - } catch(ClassNotFoundException e) {} + } catch(ClassNotFoundException e) { + } // The current class loader may be null (e.g., when Jython is loaded // from the boot classpath); try the system class loader. try { return Class.forName(name, true, ClassLoader.getSystemClassLoader()); - } catch(ClassNotFoundException e) {} + } catch(ClassNotFoundException e) { + } catch (SecurityException se) { + } Class<?> c = findLoadedClass(name); if(c != null) { @@ -143,11 +146,13 @@ if (file == null) { continue; } - size = (int)file.length(); try { + size = (int)file.length(); fis = new FileInputStream(file); } catch (FileNotFoundException e) { continue; + } catch(SecurityException e) { + continue; } } try { @@ -163,7 +168,8 @@ } finally { try { fis.close(); - } catch (IOException e) {} + } catch (IOException e) { + } } } Modified: trunk/jython/src/org/python/core/imp.java =================================================================== --- trunk/jython/src/org/python/core/imp.java 2009-04-22 02:23:54 UTC (rev 6251) +++ trunk/jython/src/org/python/core/imp.java 2009-04-22 03:03:00 UTC (rev 6252) @@ -214,6 +214,10 @@ } FileOutputStream fop = null; try { + SecurityManager man = System.getSecurityManager(); + if (man != null) { + man.checkWrite(compiledFilename); + } fop = new FileOutputStream(compiledFilename); fop.write(compiledSource); fop.close(); @@ -223,6 +227,11 @@ Py.writeDebug(IMPORT_LOG, "Unable to write to source cache file '" + compiledFilename + "' due to " + exc); return null; + } catch(SecurityException exc) { + // If we can't write the cache file, just log and continue + Py.writeDebug(IMPORT_LOG, "Unable to write to source cache file '" + + compiledFilename + "' due to " + exc); + return null; } finally { if(fop != null) { try { @@ -463,8 +472,12 @@ File sourceFile = new File(dir, sourceName); File compiledFile = new File(dir, compiledName); - boolean pkg = dir.isDirectory() && caseok(dir, name) && (sourceFile.isFile() + boolean pkg = false; + try { + pkg = dir.isDirectory() && caseok(dir, name) && (sourceFile.isFile() || compiledFile.isFile()); + } catch (SecurityException e) { + } if (!pkg) { Py.writeDebug(IMPORT_LOG, "trying source " + dir.getPath()); sourceName = name + ".py"; @@ -479,28 +492,33 @@ m.__dict__.__setitem__("__path__", new PyList(new PyObject[] {filename})); } - if (sourceFile.isFile() && caseok(sourceFile, sourceName)) { - long pyTime = sourceFile.lastModified(); - if (compiledFile.isFile() && caseok(compiledFile, compiledName)) { - Py.writeDebug(IMPORT_LOG, "trying precompiled " + compiledFile.getPath()); - long classTime = compiledFile.lastModified(); - if (classTime >= pyTime) { - PyObject ret = createFromPyClass(modName, makeStream(compiledFile), true, - displaySourceName, displayCompiledName, pyTime); - if (ret != null) { - return ret; + try { + if (sourceFile.isFile() && caseok(sourceFile, sourceName)) { + long pyTime = sourceFile.lastModified(); + if (compiledFile.isFile() && caseok(compiledFile, compiledName)) { + Py.writeDebug(IMPORT_LOG, "trying precompiled " + compiledFile.getPath()); + long classTime = compiledFile.lastModified(); + if (classTime >= pyTime) { + PyObject ret = createFromPyClass(modName, makeStream(compiledFile), true, + displaySourceName, displayCompiledName, pyTime); + if (ret != null) { + return ret; + } } + return createFromSource(modName, makeStream(sourceFile), displaySourceName, + compiledFile.getPath()); } + return createFromSource(modName, makeStream(sourceFile), displaySourceName, + compiledFile.getPath(), pyTime); } - return createFromSource(modName, makeStream(sourceFile), displaySourceName, - compiledFile.getPath(), pyTime); - } - // If no source, try loading precompiled - Py.writeDebug(IMPORT_LOG, "trying precompiled with no source " + compiledFile.getPath()); - if (compiledFile.isFile() && caseok(compiledFile, compiledName)) { - return createFromPyClass(modName, makeStream(compiledFile), true, displaySourceName, - displayCompiledName); + // If no source, try loading precompiled + Py.writeDebug(IMPORT_LOG, "trying precompiled with no source " + compiledFile.getPath()); + if (compiledFile.isFile() && caseok(compiledFile, compiledName)) { + return createFromPyClass(modName, makeStream(compiledFile), true, displaySourceName, + displayCompiledName); + } + } catch (SecurityException e) { } return null; } Modified: trunk/jython/src/org/python/core/packagecache/PathPackageManager.java =================================================================== --- trunk/jython/src/org/python/core/packagecache/PathPackageManager.java 2009-04-22 02:23:54 UTC (rev 6251) +++ trunk/jython/src/org/python/core/packagecache/PathPackageManager.java 2009-04-22 03:03:00 UTC (rev 6252) @@ -41,20 +41,24 @@ String dir = path.pyget(i).__str__().toString(); File f = new RelativeFile(dir, child); - if (f.isDirectory() && imp.caseok(f, name)) { - /* - * Figure out if we have a directory a mixture of python and - * java or just an empty directory (which means Java) or a - * directory with only Python source (which means Python). - */ - PackageExistsFileFilter m = new PackageExistsFileFilter(); - f.listFiles(m); - boolean exists = m.packageExists(); - if (exists) { - Py.writeComment("import", "java package as '" - + f.getAbsolutePath() + "'"); + try { + if (f.isDirectory() && imp.caseok(f, name)) { + /* + * Figure out if we have a directory a mixture of python and + * java or just an empty directory (which means Java) or a + * directory with only Python source (which means Python). + */ + PackageExistsFileFilter m = new PackageExistsFileFilter(); + f.listFiles(m); + boolean exists = m.packageExists(); + if (exists) { + Py.writeComment("import", "java package as '" + + f.getAbsolutePath() + "'"); + } + return exists; } - return exists; + } catch (SecurityException se) { + return false; } } return false; Modified: trunk/jython/src/org/python/modules/zipimport/zipimporter.java =================================================================== --- trunk/jython/src/org/python/modules/zipimport/zipimporter.java 2009-04-22 02:23:54 UTC (rev 6251) +++ trunk/jython/src/org/python/modules/zipimport/zipimporter.java 2009-04-22 03:03:00 UTC (rev 6252) @@ -91,11 +91,12 @@ prefix = ""; while (true) { File fullPathFile = new File(sys.getPath(pathFile.getPath())); - if (fullPathFile.exists()) { - if (fullPathFile.isFile()) { - archive = pathFile.getPath(); - } - break; + try { + if (fullPathFile.isFile()) { + archive = pathFile.getPath(); + break; + } + } catch (SecurityException se) { } // back up one path element This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <pj...@us...> - 2009-04-24 05:17:15
|
Revision: 6259 http://jython.svn.sourceforge.net/jython/?rev=6259&view=rev Author: pjenvey Date: 2009-04-24 05:16:57 +0000 (Fri, 24 Apr 2009) Log Message: ----------- default to -Xmx512m Modified Paths: -------------- trunk/jython/build.xml trunk/jython/src/shell/jython trunk/jython/src/shell/jython.bat Modified: trunk/jython/build.xml =================================================================== --- trunk/jython/build.xml 2009-04-23 07:45:20 UTC (rev 6258) +++ trunk/jython/build.xml 2009-04-24 05:16:57 UTC (rev 6259) @@ -170,9 +170,6 @@ <pathelement path="${compile.dir}" /> <pathelement path="${cpptasks.jar.dir}" /> </path> - <!-- 64 bit Java 6 needs roughly 96m for regrtest on most platforms, but Apple's needs - more --> - <property name="regrtest.Xmx" value="-Xmx160m" /> <property name="jython.dev.jar" value="jython-dev.jar" /> <property name="jython.deploy.jar" value="jython.jar" /> </target> @@ -834,7 +831,6 @@ <target name="regrtest" depends="developer-build,regrtest-unix,regrtest-windows"/> <target name="regrtest-unix" if="os.family.unix"> <exec executable="${dist.dir}/bin/jython"> - <arg value="-J${regrtest.Xmx}"/> <arg value="${dist.dir}/Lib/test/regrtest.py"/> <!-- Only run the tests that are expected to work on Jython --> <arg value="--expected"/> @@ -844,7 +840,6 @@ </target> <target name="regrtest-windows" if="os.family.windows"> <exec executable="${dist.dir}/bin/jython.bat"> - <arg value="-J${regrtest.Xmx}"/> <arg value="${dist.dir}/Lib/test/regrtest.py"/> <!-- Only run the tests that are expected to work on Jython --> <arg value="--expected"/> Modified: trunk/jython/src/shell/jython =================================================================== --- trunk/jython/src/shell/jython 2009-04-23 07:45:20 UTC (rev 6258) +++ trunk/jython/src/shell/jython 2009-04-24 05:16:57 UTC (rev 6259) @@ -96,6 +96,10 @@ # ----- Execute the requested command ----------------------------------------- +if [ -z "$JAVA_MEM" ] ; then + JAVA_MEM=-Xmx512m +fi + if [ -z "$JAVA_STACK" ]; then # 32 bit Java 6 needs the stack increased to at least 512k for # test_cpickle to pass, but we don't want to shrink 64 bit Java's @@ -110,8 +114,18 @@ # Stuff after '-J' in this argument goes to JVM -J*) val=${1:2} - if [ "${val:0:4}" = "-Xss" ] ; then + if [ "${val:0:4}" = "-Xmx" ]; then + JAVA_MEM=$val + elif [ "${val:0:4}" = "-Xss" ]; then JAVA_STACK=$val + elif [ "${val}" = "" ]; then + $JAVA_CMD -help + echo "(Prepend -J in front of these options when using 'jython' command)" + exit + elif [ "${val}" = "-X" ]; then + $JAVA_CMD -X + echo "(Prepend -J in front of these options when using 'jython' command)" + exit else java_args=("${java_args[@]}" "${1:2}") fi @@ -187,7 +201,7 @@ # Put the python_args back into the position arguments $1, $2 etc set -- "${python_args[@]}" -JAVA_OPTS="$JAVA_OPTS $JAVA_STACK" +JAVA_OPTS="$JAVA_OPTS $JAVA_MEM $JAVA_STACK" if $cygwin; then JAVA_HOME=`cygpath --mixed "$JAVA_HOME"` Modified: trunk/jython/src/shell/jython.bat =================================================================== --- trunk/jython/src/shell/jython.bat 2009-04-23 07:45:20 UTC (rev 6258) +++ trunk/jython/src/shell/jython.bat 2009-04-24 05:16:57 UTC (rev 6259) @@ -76,6 +76,7 @@ rem ----- Execute the requested command ---------------------------------------- :run +set _JAVA_MEM=-Xmx512m set _JAVA_STACK=-Xss512k rem Escape any quotes. Use _S for ', _D for ", and _U to escape _ itself. @@ -152,14 +153,14 @@ :jvmArg set _VAL=%_CMP:~2% -if "%_VAL:~0,4%" == "-Xss" ( +if "%_VAL:~0,4%" == "-Xmx" ( + set _JAVA_MEM=%_VAL% +) else if "%_VAL:~0,4%" == "-Xss" ( set _JAVA_STACK=%_VAL% - echo %_VAL% - goto nextArg +) else ( + set _JAVA_OPTS=%_JAVA_OPTS% %_VAL% ) -set _JAVA_OPTS=%_JAVA_OPTS% %_VAL% - :nextArg set _CMP= goto scanArgs @@ -172,7 +173,7 @@ set CLASSPATH=%_CP:"=% ) ) -set _FULL_CMD=%_JAVA_CMD% %_JAVA_OPTS% %_JAVA_STACK% %_BOOT_CP% -Dpython.home=%_JYTHON_HOME% -Dpython.executable="%~f0" -classpath "%CLASSPATH%" org.python.util.jython %_JYTHON_OPTS% %_JYTHON_ARGS% %_ARGS% +set _FULL_CMD=%_JAVA_CMD% %_JAVA_OPTS% %_JAVA_MEM% %_JAVA_STACK% %_BOOT_CP% -Dpython.home=%_JYTHON_HOME% -Dpython.executable="%~f0" -classpath "%CLASSPATH%" org.python.util.jython %_JYTHON_OPTS% %_JYTHON_ARGS% %_ARGS% if defined _PRINT ( echo %_FULL_CMD% ) else ( @@ -190,6 +191,7 @@ set _FULL_CMD= set _JAVA_CMD= set _JAVA_OPTS= +set _JAVA_MEM= set _JAVA_STACK= set _JYTHON_HOME= set _JYTHON_OPTS= This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <cg...@us...> - 2009-04-27 00:56:17
|
Revision: 6264 http://jython.svn.sourceforge.net/jython/?rev=6264&view=rev Author: cgroves Date: 2009-04-27 00:56:11 +0000 (Mon, 27 Apr 2009) Log Message: ----------- Whoops, forgot the test for issue1297. Modified Paths: -------------- trunk/jython/Lib/test/test_java_subclasses.py Added Paths: ----------- trunk/jython/tests/java/org/python/tests/OwnMethodCaller.java Modified: trunk/jython/Lib/test/test_java_subclasses.py =================================================================== --- trunk/jython/Lib/test/test_java_subclasses.py 2009-04-27 00:53:26 UTC (rev 6263) +++ trunk/jython/Lib/test/test_java_subclasses.py 2009-04-27 00:56:11 UTC (rev 6264) @@ -12,7 +12,7 @@ from java.awt import Color, Component, Dimension, Rectangle from javax.swing.table import AbstractTableModel -from org.python.tests import BeanInterface, Callbacker, Coercions +from org.python.tests import BeanInterface, Callbacker, Coercions, OwnMethodCaller class InterfaceTest(unittest.TestCase): def test_java_calling_python_interface_implementation(self): @@ -211,7 +211,20 @@ aa.name self.assertEquals("getName", output.pop()) + def test_python_subclass_of_python_subclass_of_java_class_overriding(self): + '''Test for http://bugs.jython.org/issue1297. + Checks that getValue on SecondSubclass is overriden correctly when called from Java.''' + class FirstSubclass(OwnMethodCaller): + pass + + class SecondSubclass(FirstSubclass): + def getValue(self): + return 10 + + self.assertEquals(10, SecondSubclass().callGetValue()) + + """ public abstract class Abstract { public Abstract() { Added: trunk/jython/tests/java/org/python/tests/OwnMethodCaller.java =================================================================== --- trunk/jython/tests/java/org/python/tests/OwnMethodCaller.java (rev 0) +++ trunk/jython/tests/java/org/python/tests/OwnMethodCaller.java 2009-04-27 00:56:11 UTC (rev 6264) @@ -0,0 +1,12 @@ +package org.python.tests; + +public class OwnMethodCaller { + + public int getValue() { + return 7; + } + + public int callGetValue() { + return getValue(); + } +} This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <cg...@us...> - 2009-04-27 05:00:44
|
Revision: 6266 http://jython.svn.sourceforge.net/jython/?rev=6266&view=rev Author: cgroves Date: 2009-04-27 05:00:40 +0000 (Mon, 27 Apr 2009) Log Message: ----------- Climb all the way up the stack of superclasses to find methods with respectJavaAccessibility is false. Fixes issue1285. This is going to lead to some weirdness if a superclass defines a method with more restrictive types than a subclass, but ignoring Java accessibility is always going to lead to weirdness, and we already try to steer people away from this flag. Modified Paths: -------------- trunk/jython/Lib/test/test_java_visibility.py trunk/jython/src/org/python/core/PyJavaType.java Added Paths: ----------- trunk/jython/Lib/test/call_overridden_method.py trunk/jython/tests/java/org/python/tests/RespectJavaAccessibility.java Added: trunk/jython/Lib/test/call_overridden_method.py =================================================================== --- trunk/jython/Lib/test/call_overridden_method.py (rev 0) +++ trunk/jython/Lib/test/call_overridden_method.py 2009-04-27 05:00:40 UTC (rev 6266) @@ -0,0 +1,14 @@ +from org.python.tests.RespectJavaAccessibility import Banana, Pear + +p = Pear() +b = Banana() +assert b.amethod() == 'Banana.amethod()' +assert p.amethod() == 'Banana.amethod()' +assert b.amethod(1,2) == 'Banana.amethod(x,y)' +assert p.amethod(1,2) == 'Pear.amethod(x,y)' +assert b.privBanana() == 'Banana.privBanana()' +assert p.privPear() == 'Pear.privPear()' +assert b.protMethod() == 'Banana.protMethod()' +assert p.protMethod() == 'Banana.protMethod()' +assert b.protMethod(1,2) == 'Banana.protMethod(x,y)' +assert p.protMethod(1,2) == 'Pear.protMethod(x,y)' Modified: trunk/jython/Lib/test/test_java_visibility.py =================================================================== --- trunk/jython/Lib/test/test_java_visibility.py 2009-04-27 00:56:29 UTC (rev 6265) +++ trunk/jython/Lib/test/test_java_visibility.py 2009-04-27 05:00:40 UTC (rev 6266) @@ -228,6 +228,9 @@ def test_protected_class(self): self.run_accessibility_script("access_protected_class.py", TypeError) + def test_overriding(self): + self.run_accessibility_script("call_overridden_method.py") + class ClassloaderTest(unittest.TestCase): def test_loading_classes_without_import(self): cl = test_support.make_jar_classloader("../callbacker_test.jar") Modified: trunk/jython/src/org/python/core/PyJavaType.java =================================================================== --- trunk/jython/src/org/python/core/PyJavaType.java 2009-04-27 00:56:29 UTC (rev 6265) +++ trunk/jython/src/org/python/core/PyJavaType.java 2009-04-27 05:00:40 UTC (rev 6266) @@ -229,10 +229,15 @@ // returns just the public methods methods = forClass.getMethods(); } else { - methods = forClass.getDeclaredMethods(); - for (Method method : methods) { - method.setAccessible(true); + // Grab all methods on this class and all of its superclasses and make them accessible + List<Method> allMethods = Generic.list(); + for(Class<?> c = forClass; c != null; c = c.getSuperclass()) { + for (Method meth : c.getDeclaredMethods()) { + allMethods.add(meth); + meth.setAccessible(true); + } } + methods = allMethods.toArray(new Method[allMethods.size()]); } boolean isInAwt = name.startsWith("java.awt.") && name.indexOf('.', 9) == -1; Added: trunk/jython/tests/java/org/python/tests/RespectJavaAccessibility.java =================================================================== --- trunk/jython/tests/java/org/python/tests/RespectJavaAccessibility.java (rev 0) +++ trunk/jython/tests/java/org/python/tests/RespectJavaAccessibility.java 2009-04-27 05:00:40 UTC (rev 6266) @@ -0,0 +1,42 @@ +package org.python.tests; + +public class RespectJavaAccessibility { + + public static class Banana { + + public String amethod() { + return "Banana.amethod()"; + } + + public String amethod(int x, int y) { + return "Banana.amethod(x,y)"; + } + + protected String protMethod() { + return "Banana.protMethod()"; + } + + protected String protMethod(int x, int y) { + return "Banana.protMethod(x,y)"; + } + + private String privBanana() { + return "Banana.privBanana()"; + } + } + + public static class Pear extends Banana { + + public String amethod(int x, int y) { + return "Pear.amethod(x,y)"; + } + + protected String protMethod(int x, int y) { + return "Pear.protMethod(x,y)"; + } + + private String privPear() { + return "Pear.privPear()"; + } + } +} This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <pj...@us...> - 2009-04-29 01:24:37
|
Revision: 6269 http://jython.svn.sourceforge.net/jython/?rev=6269&view=rev Author: pjenvey Date: 2009-04-29 01:24:23 +0000 (Wed, 29 Apr 2009) Log Message: ----------- fix int __mul__ assuming sequences wouldnt't overload __rmul__ fixes #1332 Modified Paths: -------------- trunk/jython/Lib/test/test_descr_jy.py trunk/jython/src/org/python/core/PyInteger.java Modified: trunk/jython/Lib/test/test_descr_jy.py =================================================================== --- trunk/jython/Lib/test/test_descr_jy.py 2009-04-28 17:35:27 UTC (rev 6268) +++ trunk/jython/Lib/test/test_descr_jy.py 2009-04-29 01:24:23 UTC (rev 6269) @@ -232,7 +232,16 @@ return 3 self.assertEqual(Foo() + Bar(), 3) + def test_int_mul(self): + # http://bugs.jython.org/issue1332 + class Foo(tuple): + def __rmul__(self, other): + return 'foo' + foo = Foo() + self.assertEqual(3.0 * foo, 'foo') + self.assertEqual(4 * foo, 'foo') + class InPlaceTestCase(unittest.TestCase): def test_iadd(self): Modified: trunk/jython/src/org/python/core/PyInteger.java =================================================================== --- trunk/jython/src/org/python/core/PyInteger.java 2009-04-28 17:35:27 UTC (rev 6268) +++ trunk/jython/src/org/python/core/PyInteger.java 2009-04-29 01:24:23 UTC (rev 6269) @@ -257,9 +257,6 @@ @ExposedMethod(type = MethodType.BINARY, doc = BuiltinDocs.int___mul___doc) final PyObject int___mul__(PyObject right) { - if (right instanceof PySequence) - return ((PySequence) right).repeat(getValue()); - if (!canCoerce(right)) return null; int rightv = coerce(right); This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <pj...@us...> - 2009-05-03 06:09:33
|
Revision: 6287 http://jython.svn.sourceforge.net/jython/?rev=6287&view=rev Author: pjenvey Date: 2009-05-03 06:09:20 +0000 (Sun, 03 May 2009) Log Message: ----------- match CPython's object.c::try_rich_compare: don't bother swapping the binop if the first op returned NotImplemented (null). _eq and friends already do this Modified Paths: -------------- trunk/jython/Lib/test/test_cmp_jy.py trunk/jython/src/org/python/core/PyObject.java Modified: trunk/jython/Lib/test/test_cmp_jy.py =================================================================== --- trunk/jython/Lib/test/test_cmp_jy.py 2009-05-02 07:55:28 UTC (rev 6286) +++ trunk/jython/Lib/test/test_cmp_jy.py 2009-05-03 06:09:20 UTC (rev 6287) @@ -56,6 +56,13 @@ # object.c:default_3way_compare, and gets 1 here. we don't care self.assert_(cmp(100, baz) in (-1, 1)) + def test_cmp_stops_short(self): + class Foo(object): + __eq__ = lambda self, other: False + class Bar(object): + __eq__ = lambda self, other: True + self.assertEqual(cmp(Foo(), Bar()), 1) + def test_main(): test_support.run_unittest( UnicodeDerivedCmp, Modified: trunk/jython/src/org/python/core/PyObject.java =================================================================== --- trunk/jython/src/org/python/core/PyObject.java 2009-05-02 07:55:28 UTC (rev 6286) +++ trunk/jython/src/org/python/core/PyObject.java 2009-05-03 06:09:20 UTC (rev 6287) @@ -1260,27 +1260,30 @@ return 0; } - PyObject r; - r = __eq__(o); - if (r != null && r.__nonzero__()) + PyObject result; + result = __eq__(o); + if (result == null) { + result = o.__eq__(this); + } + if (result != null && result.__nonzero__()) { return 0; - r = o.__eq__(this); - if (r != null && r.__nonzero__()) - return 0; + } - r = __lt__(o); - if (r != null && r.__nonzero__()) + result = __lt__(o); + if (result == null) { + result = o.__gt__(this); + } + if (result != null && result.__nonzero__()) { return -1; - r = o.__gt__(this); - if (r != null && r.__nonzero__()) - return -1; + } - r = __gt__(o); - if (r != null && r.__nonzero__()) + result = __gt__(o); + if (result == null) { + result = o.__lt__(this); + } + if (result != null && result.__nonzero__()) { return 1; - r = o.__lt__(this); - if (r != null && r.__nonzero__()) - return 1; + } return _cmp_unsafe(o); } finally { This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <pj...@us...> - 2009-05-04 06:07:20
|
Revision: 6291 http://jython.svn.sourceforge.net/jython/?rev=6291&view=rev Author: pjenvey Date: 2009-05-04 06:07:19 +0000 (Mon, 04 May 2009) Log Message: ----------- o sequence cmp and generic __contains__ should compare identity for equality -- so change them to use equals (analogous to CPython's PyObject_RichCompareBool) instead of plain _eq (analogous to its PyObject_RichCompare) o fix list/tuple equals on their subclasses Modified Paths: -------------- trunk/jython/src/org/python/core/PyList.java trunk/jython/src/org/python/core/PyObject.java trunk/jython/src/org/python/core/PySequence.java trunk/jython/src/org/python/core/PyTuple.java trunk/jython/src/org/python/modules/_collections/PyDeque.java Added Paths: ----------- trunk/jython/Lib/test/test_seq_jy.py Added: trunk/jython/Lib/test/test_seq_jy.py =================================================================== --- trunk/jython/Lib/test/test_seq_jy.py (rev 0) +++ trunk/jython/Lib/test/test_seq_jy.py 2009-05-04 06:07:19 UTC (rev 6291) @@ -0,0 +1,60 @@ +"""Additional seq_tests + +Made for Jython. +""" +import unittest +from collections import deque +from test import test_support + +class SeqTestCase(unittest.TestCase): + + types2test = list, tuple, deque + + def test_seq_item_equality(self): + eq_called = [] + class Foo(object): + def __eq__(self, other): + eq_called.append(other) + return False + for type2test in self.types2test: + foo = Foo() + seq1 = type2test([foo]) + self.assertEqual(seq1, seq1) + self.assertEqual(cmp(seq1, seq1), 0) + seq2 = type2test([foo]) + self.assertEqual(seq1, seq2) + self.assertEqual(cmp(seq1, seq2), 0) + self.assertTrue(foo in seq1) + self.assertFalse(eq_called) + + def test_seq_subclass_equality(self): + # Various combinations of PyObject._eq, overriden Object.equals, + # and cmp implementations + for type2test in self.types2test: + class Foo(type2test): + def __eq__(self, other): + return False + l = type2test(['bar', 'baz']) + foo = Foo(l) + self.assertNotEqual(l, foo) + self.assertEqual(cmp(l, foo), 1) + self.assertEqual(cmp(foo, foo), 0) + + seqs1 = type2test([l, foo]) + seqs2 = type2test([l, foo]) + self.assertEqual(seqs1, seqs1) + self.assertEqual(seqs1, seqs2) + self.assertEqual(cmp(seqs1, seqs2), 0) + self.assertTrue(foo in seqs1) + if hasattr(seqs1, 'count'): + self.assertTrue(seqs1.count(foo), 1) + if hasattr(seqs1, 'index'): + self.assertEqual(seqs1.index(foo), 1) + + +def test_main(): + test_support.run_unittest(SeqTestCase) + + +if __name__ == "__main__": + test_main() Modified: trunk/jython/src/org/python/core/PyList.java =================================================================== --- trunk/jython/src/org/python/core/PyList.java 2009-05-03 21:39:08 UTC (rev 6290) +++ trunk/jython/src/org/python/core/PyList.java 2009-05-04 06:07:19 UTC (rev 6291) @@ -946,13 +946,16 @@ } @Override - public synchronized boolean equals(Object o) { - if (o instanceof PyList) { - return (((PyList) o).list.equals(list)); - } else if (o instanceof List && !(o instanceof PyTuple)) { - List oList = (List) o; - return oList.equals(list); + public synchronized boolean equals(Object other) { + if (this == other) { + return true; } + if (other instanceof PyList) { + return _eq((PyList)other).__nonzero__(); + } else if (other instanceof List && !(other instanceof PyTuple)) { + List otherList = (List)other; + return list.equals(otherList); + } return false; } Modified: trunk/jython/src/org/python/core/PyObject.java =================================================================== --- trunk/jython/src/org/python/core/PyObject.java 2009-05-03 21:39:08 UTC (rev 6290) +++ trunk/jython/src/org/python/core/PyObject.java 2009-05-04 06:07:19 UTC (rev 6291) @@ -1676,7 +1676,7 @@ final boolean object___contains__(PyObject o) { for (PyObject item : asIterable()) { - if (o._eq(item).__nonzero__()) { + if (o.equals(item)) { return true; } } Modified: trunk/jython/src/org/python/core/PySequence.java =================================================================== --- trunk/jython/src/org/python/core/PySequence.java 2009-05-03 21:39:08 UTC (rev 6290) +++ trunk/jython/src/org/python/core/PySequence.java 2009-05-04 06:07:19 UTC (rev 6291) @@ -219,7 +219,7 @@ ol2 = o2.__len__(); } for (int i = 0; i < ol1 && i < ol2; i++) { - if (!o1.__getitem__(i)._eq(o2.__getitem__(i)).__nonzero__()) { + if (!o1.__getitem__(i).equals(o2.__getitem__(i))) { return i; } } Modified: trunk/jython/src/org/python/core/PyTuple.java =================================================================== --- trunk/jython/src/org/python/core/PyTuple.java 2009-05-03 21:39:08 UTC (rev 6290) +++ trunk/jython/src/org/python/core/PyTuple.java 2009-05-04 06:07:19 UTC (rev 6291) @@ -470,12 +470,15 @@ } @Override - public boolean equals(Object o) { - if (o instanceof PyTuple) { - return Arrays.equals(array, ((PyTuple) o).array); - } else if (o instanceof List && !(o instanceof PyList)) { - return o.equals(this); + public boolean equals(Object other) { + if (this == other) { + return true; } + if (other instanceof PyTuple) { + return _eq((PyTuple)other).__nonzero__(); + } else if (other instanceof List && !(other instanceof PyList)) { + return other.equals(this); + } return false; } Modified: trunk/jython/src/org/python/modules/_collections/PyDeque.java =================================================================== --- trunk/jython/src/org/python/modules/_collections/PyDeque.java 2009-05-03 21:39:08 UTC (rev 6290) +++ trunk/jython/src/org/python/modules/_collections/PyDeque.java 2009-05-04 06:07:19 UTC (rev 6291) @@ -443,7 +443,7 @@ ol2 = o2.__len__(); } for (int i = 0 ; i < ol1 && i < ol2; i++) { - if (!o1.__getitem__(i)._eq(o2.__getitem__(i)).__nonzero__()) { + if (!o1.__getitem__(i).equals(o2.__getitem__(i))) { return i; } } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <pj...@us...> - 2009-05-06 05:25:24
|
Revision: 6302 http://jython.svn.sourceforge.net/jython/?rev=6302&view=rev Author: pjenvey Date: 2009-05-06 05:25:18 +0000 (Wed, 06 May 2009) Log Message: ----------- o have API methods call into final exposed methods, simplify issuperset, coding standards o enable set's test_weakref Modified Paths: -------------- trunk/jython/Lib/test/test_set.py trunk/jython/src/org/python/core/BaseSet.java Modified: trunk/jython/Lib/test/test_set.py =================================================================== --- trunk/jython/Lib/test/test_set.py 2009-05-06 05:20:34 UTC (rev 6301) +++ trunk/jython/Lib/test/test_set.py 2009-05-06 05:25:18 UTC (rev 6302) @@ -1,5 +1,6 @@ import unittest from test import test_support +from test_weakref import extra_collect from weakref import proxy import operator import copy @@ -227,7 +228,7 @@ # Create a nest of cycles to exercise overall ref count check class A: pass - s = set([A() for i in xrange(1000)]) + s = set(A() for i in xrange(1000)) for elem in s: elem.cycle = s elem.sub = elem @@ -278,25 +279,25 @@ fo.close() os.remove(test_support.TESTFN) -# XXX: tests cpython internals (caches key hashes) -# def test_do_not_rehash_dict_keys(self): -# n = 10 -# d = dict.fromkeys(map(HashCountingInt, xrange(n))) -# self.assertEqual(sum([elem.hash_count for elem in d]), n) -# s = self.thetype(d) -# self.assertEqual(sum([elem.hash_count for elem in d]), n) -# s.difference(d) -# self.assertEqual(sum([elem.hash_count for elem in d]), n) -# if hasattr(s, 'symmetric_difference_update'): -# s.symmetric_difference_update(d) -# self.assertEqual(sum([elem.hash_count for elem in d]), n) -# d2 = dict.fromkeys(set(d)) -# self.assertEqual(sum([elem.hash_count for elem in d]), n) -# d3 = dict.fromkeys(frozenset(d)) -# self.assertEqual(sum([elem.hash_count for elem in d]), n) -# d3 = dict.fromkeys(frozenset(d), 123) -# self.assertEqual(sum([elem.hash_count for elem in d]), n) -# self.assertEqual(d3, dict.fromkeys(d, 123)) + # XXX: Tests CPython internals (caches key hashes) + def _test_do_not_rehash_dict_keys(self): + n = 10 + d = dict.fromkeys(map(HashCountingInt, xrange(n))) + self.assertEqual(sum(elem.hash_count for elem in d), n) + s = self.thetype(d) + self.assertEqual(sum(elem.hash_count for elem in d), n) + s.difference(d) + self.assertEqual(sum(elem.hash_count for elem in d), n) + if hasattr(s, 'symmetric_difference_update'): + s.symmetric_difference_update(d) + self.assertEqual(sum(elem.hash_count for elem in d), n) + d2 = dict.fromkeys(set(d)) + self.assertEqual(sum(elem.hash_count for elem in d), n) + d3 = dict.fromkeys(frozenset(d)) + self.assertEqual(sum(elem.hash_count for elem in d), n) + d3 = dict.fromkeys(frozenset(d), 123) + self.assertEqual(sum(elem.hash_count for elem in d), n) + self.assertEqual(d3, dict.fromkeys(d, 123)) class TestSet(TestJointOps): thetype = set @@ -478,13 +479,13 @@ t ^= t self.assertEqual(t, self.thetype()) -# XXX: CPython gc-specific -# def test_weakref(self): -# s = self.thetype('gallahad') -# p = proxy(s) -# self.assertEqual(str(p), str(s)) -# s = None -# self.assertRaises(ReferenceError, str, p) + def test_weakref(self): + s = self.thetype('gallahad') + p = proxy(s) + self.assertEqual(str(p), str(s)) + s = None + extra_collect() + self.assertRaises(ReferenceError, str, p) # C API test only available in a debug build if hasattr(set, "test_c_api"): @@ -560,15 +561,15 @@ f = self.thetype('abcdcda') self.assertEqual(hash(f), hash(f)) -# XXX: tied to cpython's hash implementation -# def test_hash_effectiveness(self): -# n = 13 -# hashvalues = set() -# addhashvalue = hashvalues.add -# elemmasks = [(i+1, 1<<i) for i in range(n)] -# for i in xrange(2**n): -# addhashvalue(hash(frozenset([e for e, m in elemmasks if m&i]))) -# self.assertEqual(len(hashvalues), 2**n) + # XXX: tied to CPython's hash implementation + def _test_hash_effectiveness(self): + n = 13 + hashvalues = set() + addhashvalue = hashvalues.add + elemmasks = [(i+1, 1<<i) for i in range(n)] + for i in xrange(2**n): + addhashvalue(hash(frozenset([e for e, m in elemmasks if m&i]))) + self.assertEqual(len(hashvalues), 2**n) class FrozenSetSubclass(frozenset): pass @@ -683,11 +684,12 @@ def test_iteration(self): for v in self.set: self.assert_(v in self.values) -# XXX: jython does not use length_hint -# setiter = iter(self.set) -# # note: __length_hint__ is an internal undocumented API, -# # don't rely on it in your own programs -# self.assertEqual(setiter.__length_hint__(), len(self.set)) + # XXX: jython does not use length_hint + if not test_support.is_jython: + setiter = iter(self.set) + # note: __length_hint__ is an internal undocumented API, + # don't rely on it in your own programs + self.assertEqual(setiter.__length_hint__(), len(self.set)) def test_pickling(self): p = pickle.dumps(self.set) Modified: trunk/jython/src/org/python/core/BaseSet.java =================================================================== --- trunk/jython/src/org/python/core/BaseSet.java 2009-05-06 05:20:34 UTC (rev 6301) +++ trunk/jython/src/org/python/core/BaseSet.java 2009-05-06 05:25:18 UTC (rev 6302) @@ -1,3 +1,4 @@ +/* Copyright (c) Jython Developers */ package org.python.core; import java.lang.reflect.Array; @@ -48,8 +49,7 @@ * The union of <code>this</code> with <code>other</code>. <p/> <br/> (I.e. all elements * that are in either set) * - * @param other - * A <code>BaseSet</code> instance. + * @param other A <code>BaseSet</code> instance. * @return The union of the two sets as a new set. */ public PyObject __or__(PyObject other) { @@ -100,7 +100,7 @@ if (!(other instanceof BaseSet)) { throw Py.TypeError("Not Implemented"); } - return difference(other); + return baseset_difference(other); } public PyObject difference(PyObject other) { @@ -108,15 +108,15 @@ } final PyObject baseset_difference(PyObject other) { - BaseSet bs = (other instanceof BaseSet) ? (BaseSet)other : new PySet(other); + BaseSet bs = other instanceof BaseSet ? (BaseSet)other : new PySet(other); Set<PyObject> set = bs._set; BaseSet o = BaseSet.makeNewSet(getType()); + for (PyObject p : _set) { if (!set.contains(p)) { o._set.add(p); } } - return o; } @@ -137,7 +137,7 @@ if (!(other instanceof BaseSet)) { throw Py.TypeError("Not Implemented"); } - return symmetric_difference(other); + return baseset_symmetric_difference(other); } public PyObject symmetric_difference(PyObject other) { @@ -145,7 +145,7 @@ } final PyObject baseset_symmetric_difference(PyObject other) { - BaseSet bs = (other instanceof BaseSet) ? (BaseSet)other : new PySet(other); + BaseSet bs = other instanceof BaseSet ? (BaseSet)other : new PySet(other); BaseSet o = BaseSet.makeNewSet(getType()); for (PyObject p : _set) { if (!bs._set.contains(p)) { @@ -201,13 +201,13 @@ final PyObject baseset___iter__() { return new PyIterator() { - private int size = _set.size(); + private int size = size(); private Iterator<PyObject> iterator = _set.iterator(); @Override public PyObject __iternext__() { - if (_set.size() != size) { + if (size != size()) { throw Py.RuntimeError("set changed size during iteration"); } if (iterator.hasNext()) { @@ -255,7 +255,7 @@ } final PyObject baseset___ne__(PyObject other) { - if(other instanceof BaseSet) { + if (other instanceof BaseSet) { return Py.newBoolean(!_set.equals(((BaseSet)other)._set)); } return Py.True; @@ -285,8 +285,7 @@ final PyObject baseset___lt__(PyObject other) { BaseSet bs = _binary_sanity_check(other); - return Py.newBoolean(__len__() < bs.__len__() - && baseset_issubset(other).__nonzero__()); + return Py.newBoolean(size() < bs.size() && baseset_issubset(other).__nonzero__()); } public PyObject __gt__(PyObject other) { @@ -295,8 +294,7 @@ final PyObject baseset___gt__(PyObject other) { BaseSet bs = _binary_sanity_check(other); - return Py.newBoolean(__len__() > bs.__len__() - && baseset_issuperset(other).__nonzero__()); + return Py.newBoolean(size() > bs.size() && baseset_issuperset(other).__nonzero__()); } /** @@ -326,11 +324,11 @@ final PyObject baseset_intersection(PyObject other) { PyObject little, big; - if(!(other instanceof BaseSet)) { + if (!(other instanceof BaseSet)) { other = new PySet(other); } - if (__len__() <= __builtin__.len(other)) { + if (size() <= __builtin__.len(other)) { little = this; big = other; } else { @@ -348,8 +346,8 @@ } final PyObject baseset_issubset(PyObject other) { - BaseSet bs = (other instanceof BaseSet) ? (BaseSet)other : new PySet(other); - if (__len__() > bs.__len__()) { + BaseSet bs = other instanceof BaseSet ? (BaseSet)other : new PySet(other); + if (size() > bs.size()) { return Py.False; } for (Object p : _set) { @@ -361,16 +359,8 @@ } final PyObject baseset_issuperset(PyObject other) { - BaseSet bs = (other instanceof BaseSet) ? (BaseSet)other : new PySet(other); - if (__len__() < bs.__len__()) { - return Py.False; - } - for (Object p : bs._set) { - if (!_set.contains(p)) { - return Py.False; - } - } - return Py.True; + BaseSet bs = other instanceof BaseSet ? (BaseSet)other : new PySet(other); + return bs.baseset_issubset(this); } public String toString() { @@ -414,10 +404,8 @@ * can override, say, __hash__ and all of a sudden you can't assume that a non-PyFrozenSet is * unhashable anymore. * - * @param pye - * The exception thrown from a hashable operation. - * @param value - * The object which was unhashable. + * @param pye The exception thrown from a hashable operation. + * @param value The object which was unhashable. * @return A PyFrozenSet if appropriate, otherwise the pye is rethrown */ protected final PyFrozenSet asFrozen(PyException pye, PyObject value) { This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <pj...@us...> - 2009-05-06 05:46:17
|
Revision: 6303 http://jython.svn.sourceforge.net/jython/?rev=6303&view=rev Author: pjenvey Date: 2009-05-06 05:46:00 +0000 (Wed, 06 May 2009) Log Message: ----------- fix binops disallowing right side binop attempts (throwing their own TypeErrors), cleanup _binary_sanity_check Modified Paths: -------------- trunk/jython/Lib/test/test_set_jy.py trunk/jython/src/org/python/core/BaseSet.java Modified: trunk/jython/Lib/test/test_set_jy.py =================================================================== --- trunk/jython/Lib/test/test_set_jy.py 2009-05-06 05:25:18 UTC (rev 6302) +++ trunk/jython/Lib/test/test_set_jy.py 2009-05-06 05:46:00 UTC (rev 6303) @@ -1,11 +1,30 @@ +import unittest from test import test_support -import unittest -from java.util import Random -from javatests import PySetInJavaTest +if test_support.is_jython: + from java.util import Random + from javatests import PySetInJavaTest -class SetInJavaTest(unittest.TestCase): - "Tests for derived dict behaviour" +class SetTestCase(unittest.TestCase): + + def test_binops(self): + class Foo(object): + __rsub__ = lambda self, other: 'rsub' + __ror__ = lambda self, other: 'ror' + __rand__ = lambda self, other: 'rand' + __rxor__ = lambda self, other: 'rxor' + foo = Foo() + s = set() + self.assertEqual(s - foo, 'rsub') + self.assertEqual(s | foo, 'ror') + self.assertEqual(s & foo, 'rand') + self.assertEqual(s ^ foo, 'rxor') + + +class SetInJavaTestCase(unittest.TestCase): + + """Tests for derived dict behaviour""" + def test_using_PySet_as_Java_Set(self): PySetInJavaTest.testPySetAsJavaSet() @@ -16,20 +35,26 @@ if isinstance(v, unicode): self.assertEquals("value", v) else: - v.nextInt()#Should be a java.util.Random; ensure we can call it + # Should be a java.util.Random; ensure we can call it + v.nextInt() def test_java_accessing_items_added_in_python(self): - # Test a type that should be coerced into a Java type, a Java instance - # that should be wrapped, and a Python instance that should pass - # through as itself with str, Random and tuple respectively. + # Test a type that should be coerced into a Java type, a Java + # instance that should be wrapped, and a Python instance that + # should pass through as itself with str, Random and tuple + # respectively. s = set(["value", Random(), ("tuple", "of", "stuff")]) PySetInJavaTest.accessAndRemovePySetItems(s) - self.assertEquals(0, len(s))# Check that the Java removal affected the underlying set - + # Check that the Java removal affected the underlying set + self.assertEquals(0, len(s)) def test_main(): - test_support.run_unittest(SetInJavaTest) + tests = [SetTestCase] + if test_support.is_jython: + tests.append(SetInJavaTestCase) + test_support.run_unittest(*tests) + if __name__ == '__main__': test_main() Modified: trunk/jython/src/org/python/core/BaseSet.java =================================================================== --- trunk/jython/src/org/python/core/BaseSet.java 2009-05-06 05:25:18 UTC (rev 6302) +++ trunk/jython/src/org/python/core/BaseSet.java 2009-05-06 05:46:00 UTC (rev 6303) @@ -58,7 +58,7 @@ final PyObject baseset___or__(PyObject other) { if (!(other instanceof BaseSet)) { - throw Py.TypeError("Not Implemented"); + return null; } return baseset_union(other); } @@ -78,7 +78,7 @@ final PyObject baseset___and__(PyObject other) { if (!(other instanceof BaseSet)) { - throw Py.TypeError("Not Implemented"); + return null; } return baseset_intersection(other); } @@ -98,7 +98,7 @@ final PyObject baseset___sub__(PyObject other) { if (!(other instanceof BaseSet)) { - throw Py.TypeError("Not Implemented"); + return null; } return baseset_difference(other); } @@ -135,7 +135,7 @@ final PyObject baseset___xor__(PyObject other) { if (!(other instanceof BaseSet)) { - throw Py.TypeError("Not Implemented"); + return null; } return baseset_symmetric_difference(other); } @@ -266,8 +266,7 @@ } final PyObject baseset___le__(PyObject other) { - _binary_sanity_check(other); - return baseset_issubset(other); + return baseset_issubset(asBaseSet(other)); } public PyObject __ge__(PyObject other) { @@ -275,8 +274,7 @@ } final PyObject baseset___ge__(PyObject other) { - _binary_sanity_check(other); - return baseset_issuperset(other); + return baseset_issuperset(asBaseSet(other)); } public PyObject __lt__(PyObject other) { @@ -284,7 +282,7 @@ } final PyObject baseset___lt__(PyObject other) { - BaseSet bs = _binary_sanity_check(other); + BaseSet bs = asBaseSet(other); return Py.newBoolean(size() < bs.size() && baseset_issubset(other).__nonzero__()); } @@ -293,7 +291,7 @@ } final PyObject baseset___gt__(PyObject other) { - BaseSet bs = _binary_sanity_check(other); + BaseSet bs = asBaseSet(other); return Py.newBoolean(size() > bs.size() && baseset_issuperset(other).__nonzero__()); } @@ -385,12 +383,18 @@ return buf.toString(); } - protected final BaseSet _binary_sanity_check(PyObject other) throws PyIgnoreMethodTag { - try { + /** + * Casts other as BaseSet, throwing a TypeError tailored for the rich comparison + * methods when not applicable. + * + * @param other a PyObject + * @return a BaseSet + */ + protected final BaseSet asBaseSet(PyObject other) { + if (other instanceof BaseSet) { return (BaseSet)other; - } catch (ClassCastException e) { - throw Py.TypeError("Binary operation only permitted between sets"); } + throw Py.TypeError("can only compare to a set"); } /** This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <pj...@us...> - 2009-05-06 08:20:26
|
Revision: 6304 http://jython.svn.sourceforge.net/jython/?rev=6304&view=rev Author: pjenvey Date: 2009-05-06 08:20:08 +0000 (Wed, 06 May 2009) Log Message: ----------- Py.matchException -> PyException.match Oh Py.matchException, how I loathe thee Modified Paths: -------------- trunk/jython/Tools/jythonc/SrcGenCompiler.py trunk/jython/bugtests/classes/test292j.java trunk/jython/src/org/python/antlr/ast/AssertDerived.java trunk/jython/src/org/python/antlr/ast/AssignDerived.java trunk/jython/src/org/python/antlr/ast/AttributeDerived.java trunk/jython/src/org/python/antlr/ast/AugAssignDerived.java trunk/jython/src/org/python/antlr/ast/BinOpDerived.java trunk/jython/src/org/python/antlr/ast/BoolOpDerived.java trunk/jython/src/org/python/antlr/ast/BreakDerived.java trunk/jython/src/org/python/antlr/ast/CallDerived.java trunk/jython/src/org/python/antlr/ast/ClassDefDerived.java trunk/jython/src/org/python/antlr/ast/CompareDerived.java trunk/jython/src/org/python/antlr/ast/ContinueDerived.java trunk/jython/src/org/python/antlr/ast/DeleteDerived.java trunk/jython/src/org/python/antlr/ast/DictDerived.java trunk/jython/src/org/python/antlr/ast/EllipsisDerived.java trunk/jython/src/org/python/antlr/ast/ExceptHandlerDerived.java trunk/jython/src/org/python/antlr/ast/ExecDerived.java trunk/jython/src/org/python/antlr/ast/ExprDerived.java trunk/jython/src/org/python/antlr/ast/ExpressionDerived.java trunk/jython/src/org/python/antlr/ast/ExtSliceDerived.java trunk/jython/src/org/python/antlr/ast/ForDerived.java trunk/jython/src/org/python/antlr/ast/FunctionDefDerived.java trunk/jython/src/org/python/antlr/ast/GeneratorExpDerived.java trunk/jython/src/org/python/antlr/ast/GlobalDerived.java trunk/jython/src/org/python/antlr/ast/IfDerived.java trunk/jython/src/org/python/antlr/ast/IfExpDerived.java trunk/jython/src/org/python/antlr/ast/ImportDerived.java trunk/jython/src/org/python/antlr/ast/ImportFromDerived.java trunk/jython/src/org/python/antlr/ast/IndexDerived.java trunk/jython/src/org/python/antlr/ast/InteractiveDerived.java trunk/jython/src/org/python/antlr/ast/LambdaDerived.java trunk/jython/src/org/python/antlr/ast/ListCompDerived.java trunk/jython/src/org/python/antlr/ast/ListDerived.java trunk/jython/src/org/python/antlr/ast/ModuleDerived.java trunk/jython/src/org/python/antlr/ast/NameDerived.java trunk/jython/src/org/python/antlr/ast/NumDerived.java trunk/jython/src/org/python/antlr/ast/PassDerived.java trunk/jython/src/org/python/antlr/ast/PrintDerived.java trunk/jython/src/org/python/antlr/ast/RaiseDerived.java trunk/jython/src/org/python/antlr/ast/ReprDerived.java trunk/jython/src/org/python/antlr/ast/ReturnDerived.java trunk/jython/src/org/python/antlr/ast/SliceDerived.java trunk/jython/src/org/python/antlr/ast/StrDerived.java trunk/jython/src/org/python/antlr/ast/SubscriptDerived.java trunk/jython/src/org/python/antlr/ast/SuiteDerived.java trunk/jython/src/org/python/antlr/ast/TryExceptDerived.java trunk/jython/src/org/python/antlr/ast/TryFinallyDerived.java trunk/jython/src/org/python/antlr/ast/TupleDerived.java trunk/jython/src/org/python/antlr/ast/UnaryOpDerived.java trunk/jython/src/org/python/antlr/ast/WhileDerived.java trunk/jython/src/org/python/antlr/ast/WithDerived.java trunk/jython/src/org/python/antlr/ast/YieldDerived.java trunk/jython/src/org/python/antlr/ast/aliasDerived.java trunk/jython/src/org/python/antlr/ast/argumentsDerived.java trunk/jython/src/org/python/antlr/ast/comprehensionDerived.java trunk/jython/src/org/python/antlr/ast/keywordDerived.java trunk/jython/src/org/python/antlr/op/AddDerived.java trunk/jython/src/org/python/antlr/op/AndDerived.java trunk/jython/src/org/python/antlr/op/AugLoadDerived.java trunk/jython/src/org/python/antlr/op/AugStoreDerived.java trunk/jython/src/org/python/antlr/op/BitAndDerived.java trunk/jython/src/org/python/antlr/op/BitOrDerived.java trunk/jython/src/org/python/antlr/op/BitXorDerived.java trunk/jython/src/org/python/antlr/op/DelDerived.java trunk/jython/src/org/python/antlr/op/DivDerived.java trunk/jython/src/org/python/antlr/op/EqDerived.java trunk/jython/src/org/python/antlr/op/FloorDivDerived.java trunk/jython/src/org/python/antlr/op/GtDerived.java trunk/jython/src/org/python/antlr/op/GtEDerived.java trunk/jython/src/org/python/antlr/op/InDerived.java trunk/jython/src/org/python/antlr/op/InvertDerived.java trunk/jython/src/org/python/antlr/op/IsDerived.java trunk/jython/src/org/python/antlr/op/IsNotDerived.java trunk/jython/src/org/python/antlr/op/LShiftDerived.java trunk/jython/src/org/python/antlr/op/LoadDerived.java trunk/jython/src/org/python/antlr/op/LtDerived.java trunk/jython/src/org/python/antlr/op/LtEDerived.java trunk/jython/src/org/python/antlr/op/ModDerived.java trunk/jython/src/org/python/antlr/op/MultDerived.java trunk/jython/src/org/python/antlr/op/NotDerived.java trunk/jython/src/org/python/antlr/op/NotEqDerived.java trunk/jython/src/org/python/antlr/op/NotInDerived.java trunk/jython/src/org/python/antlr/op/OrDerived.java trunk/jython/src/org/python/antlr/op/ParamDerived.java trunk/jython/src/org/python/antlr/op/PowDerived.java trunk/jython/src/org/python/antlr/op/RShiftDerived.java trunk/jython/src/org/python/antlr/op/StoreDerived.java trunk/jython/src/org/python/antlr/op/SubDerived.java trunk/jython/src/org/python/antlr/op/UAddDerived.java trunk/jython/src/org/python/antlr/op/USubDerived.java trunk/jython/src/org/python/compiler/CodeCompiler.java trunk/jython/src/org/python/compiler/Module.java trunk/jython/src/org/python/compiler/pbc/BytecodeCompiler.java trunk/jython/src/org/python/core/AstList.java trunk/jython/src/org/python/core/BaseSet.java trunk/jython/src/org/python/core/ClasspathPyImporterDerived.java trunk/jython/src/org/python/core/FunctionThread.java trunk/jython/src/org/python/core/Py.java trunk/jython/src/org/python/core/PyArrayDerived.java trunk/jython/src/org/python/core/PyBaseExceptionDerived.java trunk/jython/src/org/python/core/PyBooleanDerived.java trunk/jython/src/org/python/core/PyBytecode.java trunk/jython/src/org/python/core/PyCallIter.java trunk/jython/src/org/python/core/PyClassMethodDerived.java trunk/jython/src/org/python/core/PyComplex.java trunk/jython/src/org/python/core/PyComplexDerived.java trunk/jython/src/org/python/core/PyDictionary.java trunk/jython/src/org/python/core/PyDictionaryDerived.java trunk/jython/src/org/python/core/PyEnumerateDerived.java trunk/jython/src/org/python/core/PyException.java trunk/jython/src/org/python/core/PyFastSequenceIter.java trunk/jython/src/org/python/core/PyFileDerived.java trunk/jython/src/org/python/core/PyFloat.java trunk/jython/src/org/python/core/PyFloatDerived.java trunk/jython/src/org/python/core/PyFrame.java trunk/jython/src/org/python/core/PyFrozenSetDerived.java trunk/jython/src/org/python/core/PyInstance.java trunk/jython/src/org/python/core/PyInteger.java trunk/jython/src/org/python/core/PyIntegerDerived.java trunk/jython/src/org/python/core/PyList.java trunk/jython/src/org/python/core/PyListDerived.java trunk/jython/src/org/python/core/PyLong.java trunk/jython/src/org/python/core/PyLongDerived.java trunk/jython/src/org/python/core/PyModuleDerived.java trunk/jython/src/org/python/core/PyObject.java trunk/jython/src/org/python/core/PyObjectDerived.java trunk/jython/src/org/python/core/PyPropertyDerived.java trunk/jython/src/org/python/core/PySequenceIter.java trunk/jython/src/org/python/core/PySetDerived.java trunk/jython/src/org/python/core/PySlice.java trunk/jython/src/org/python/core/PySliceDerived.java trunk/jython/src/org/python/core/PyString.java trunk/jython/src/org/python/core/PyStringDerived.java trunk/jython/src/org/python/core/PyStringMap.java trunk/jython/src/org/python/core/PySuperDerived.java trunk/jython/src/org/python/core/PySystemState.java trunk/jython/src/org/python/core/PyTupleDerived.java trunk/jython/src/org/python/core/PyTypeDerived.java trunk/jython/src/org/python/core/PyUnicodeDerived.java trunk/jython/src/org/python/core/__builtin__.java trunk/jython/src/org/python/core/imp.java trunk/jython/src/org/python/core/io/BufferedIOMixin.java trunk/jython/src/org/python/core/io/IOBase.java trunk/jython/src/org/python/modules/PyTeeIterator.java trunk/jython/src/org/python/modules/_collections/PyDefaultDictDerived.java trunk/jython/src/org/python/modules/_collections/PyDeque.java trunk/jython/src/org/python/modules/_collections/PyDequeDerived.java trunk/jython/src/org/python/modules/_csv/PyDialectDerived.java trunk/jython/src/org/python/modules/_functools/PyPartialDerived.java trunk/jython/src/org/python/modules/_weakref/ReferenceTypeDerived.java trunk/jython/src/org/python/modules/binascii.java trunk/jython/src/org/python/modules/itertools.java trunk/jython/src/org/python/modules/random/PyRandomDerived.java trunk/jython/src/org/python/modules/thread/PyLocalDerived.java trunk/jython/src/org/python/modules/zipimport/zipimporterDerived.java trunk/jython/src/org/python/util/InteractiveConsole.java trunk/jython/src/org/python/util/InteractiveInterpreter.java trunk/jython/src/org/python/util/jython.java trunk/jython/src/templates/object.derived trunk/jython/tests/java/org/python/expose/generate/MethodExposerTest.java trunk/jython/tests/java/org/python/tests/CustomizableMapHolder.java Modified: trunk/jython/Tools/jythonc/SrcGenCompiler.py =================================================================== --- trunk/jython/Tools/jythonc/SrcGenCompiler.py 2009-05-06 05:46:00 UTC (rev 6303) +++ trunk/jython/Tools/jythonc/SrcGenCompiler.py 2009-05-06 08:20:08 UTC (rev 6304) @@ -969,8 +969,7 @@ continue type = self.visit(exchandler.type) - t = jast.InvokeStatic("Py", "matchException", - [exctmp, type.asAny()]) + t = jast.Invoke(exctmp, "match", [type.asAny()]) newbody = [] if exchandler.name is not None: Modified: trunk/jython/bugtests/classes/test292j.java =================================================================== --- trunk/jython/bugtests/classes/test292j.java 2009-05-06 05:46:00 UTC (rev 6303) +++ trunk/jython/bugtests/classes/test292j.java 2009-05-06 08:20:08 UTC (rev 6304) @@ -10,7 +10,7 @@ try { __builtin__.__import__("test292j1"); } catch (PyException exc) { - if (!Py.matchException(exc, Py.ImportError)) + if (!exc.match(Py.ImportError)) throw exc; } } Modified: trunk/jython/src/org/python/antlr/ast/AssertDerived.java =================================================================== --- trunk/jython/src/org/python/antlr/ast/AssertDerived.java 2009-05-06 05:46:00 UTC (rev 6303) +++ trunk/jython/src/org/python/antlr/ast/AssertDerived.java 2009-05-06 08:20:08 UTC (rev 6304) @@ -840,7 +840,7 @@ try { return impl.__get__(this,self_type).__call__(); } catch (PyException exc) { - if (Py.matchException(exc,Py.StopIteration)) + if (exc.match(Py.StopIteration)) return null; throw exc; } @@ -855,7 +855,7 @@ try { return impl.__get__(this,self_type).__call__(key); } catch (PyException exc) { - if (Py.matchException(exc,Py.LookupError)) + if (exc.match(Py.LookupError)) return null; throw exc; } @@ -869,7 +869,7 @@ try { return impl.__get__(this,self_type).__call__(new PyInteger(key)); } catch (PyException exc) { - if (Py.matchException(exc,Py.LookupError)) + if (exc.match(Py.LookupError)) return null; throw exc; } @@ -1000,7 +1000,7 @@ } // else: pass through to __getitem__ invocation } } catch (PyException e) { - if (!Py.matchException(e,Py.AttributeError)) { + if (!e.match(Py.AttributeError)) { throw e; } else { firstAttributeError=e; // saved to avoid swallowing custom AttributeErrors Modified: trunk/jython/src/org/python/antlr/ast/AssignDerived.java =================================================================== --- trunk/jython/src/org/python/antlr/ast/AssignDerived.java 2009-05-06 05:46:00 UTC (rev 6303) +++ trunk/jython/src/org/python/antlr/ast/AssignDerived.java 2009-05-06 08:20:08 UTC (rev 6304) @@ -840,7 +840,7 @@ try { return impl.__get__(this,self_type).__call__(); } catch (PyException exc) { - if (Py.matchException(exc,Py.StopIteration)) + if (exc.match(Py.StopIteration)) return null; throw exc; } @@ -855,7 +855,7 @@ try { return impl.__get__(this,self_type).__call__(key); } catch (PyException exc) { - if (Py.matchException(exc,Py.LookupError)) + if (exc.match(Py.LookupError)) return null; throw exc; } @@ -869,7 +869,7 @@ try { return impl.__get__(this,self_type).__call__(new PyInteger(key)); } catch (PyException exc) { - if (Py.matchException(exc,Py.LookupError)) + if (exc.match(Py.LookupError)) return null; throw exc; } @@ -1000,7 +1000,7 @@ } // else: pass through to __getitem__ invocation } } catch (PyException e) { - if (!Py.matchException(e,Py.AttributeError)) { + if (!e.match(Py.AttributeError)) { throw e; } else { firstAttributeError=e; // saved to avoid swallowing custom AttributeErrors Modified: trunk/jython/src/org/python/antlr/ast/AttributeDerived.java =================================================================== --- trunk/jython/src/org/python/antlr/ast/AttributeDerived.java 2009-05-06 05:46:00 UTC (rev 6303) +++ trunk/jython/src/org/python/antlr/ast/AttributeDerived.java 2009-05-06 08:20:08 UTC (rev 6304) @@ -840,7 +840,7 @@ try { return impl.__get__(this,self_type).__call__(); } catch (PyException exc) { - if (Py.matchException(exc,Py.StopIteration)) + if (exc.match(Py.StopIteration)) return null; throw exc; } @@ -855,7 +855,7 @@ try { return impl.__get__(this,self_type).__call__(key); } catch (PyException exc) { - if (Py.matchException(exc,Py.LookupError)) + if (exc.match(Py.LookupError)) return null; throw exc; } @@ -869,7 +869,7 @@ try { return impl.__get__(this,self_type).__call__(new PyInteger(key)); } catch (PyException exc) { - if (Py.matchException(exc,Py.LookupError)) + if (exc.match(Py.LookupError)) return null; throw exc; } @@ -1000,7 +1000,7 @@ } // else: pass through to __getitem__ invocation } } catch (PyException e) { - if (!Py.matchException(e,Py.AttributeError)) { + if (!e.match(Py.AttributeError)) { throw e; } else { firstAttributeError=e; // saved to avoid swallowing custom AttributeErrors Modified: trunk/jython/src/org/python/antlr/ast/AugAssignDerived.java =================================================================== --- trunk/jython/src/org/python/antlr/ast/AugAssignDerived.java 2009-05-06 05:46:00 UTC (rev 6303) +++ trunk/jython/src/org/python/antlr/ast/AugAssignDerived.java 2009-05-06 08:20:08 UTC (rev 6304) @@ -840,7 +840,7 @@ try { return impl.__get__(this,self_type).__call__(); } catch (PyException exc) { - if (Py.matchException(exc,Py.StopIteration)) + if (exc.match(Py.StopIteration)) return null; throw exc; } @@ -855,7 +855,7 @@ try { return impl.__get__(this,self_type).__call__(key); } catch (PyException exc) { - if (Py.matchException(exc,Py.LookupError)) + if (exc.match(Py.LookupError)) return null; throw exc; } @@ -869,7 +869,7 @@ try { return impl.__get__(this,self_type).__call__(new PyInteger(key)); } catch (PyException exc) { - if (Py.matchException(exc,Py.LookupError)) + if (exc.match(Py.LookupError)) return null; throw exc; } @@ -1000,7 +1000,7 @@ } // else: pass through to __getitem__ invocation } } catch (PyException e) { - if (!Py.matchException(e,Py.AttributeError)) { + if (!e.match(Py.AttributeError)) { throw e; } else { firstAttributeError=e; // saved to avoid swallowing custom AttributeErrors Modified: trunk/jython/src/org/python/antlr/ast/BinOpDerived.java =================================================================== --- trunk/jython/src/org/python/antlr/ast/BinOpDerived.java 2009-05-06 05:46:00 UTC (rev 6303) +++ trunk/jython/src/org/python/antlr/ast/BinOpDerived.java 2009-05-06 08:20:08 UTC (rev 6304) @@ -840,7 +840,7 @@ try { return impl.__get__(this,self_type).__call__(); } catch (PyException exc) { - if (Py.matchException(exc,Py.StopIteration)) + if (exc.match(Py.StopIteration)) return null; throw exc; } @@ -855,7 +855,7 @@ try { return impl.__get__(this,self_type).__call__(key); } catch (PyException exc) { - if (Py.matchException(exc,Py.LookupError)) + if (exc.match(Py.LookupError)) return null; throw exc; } @@ -869,7 +869,7 @@ try { return impl.__get__(this,self_type).__call__(new PyInteger(key)); } catch (PyException exc) { - if (Py.matchException(exc,Py.LookupError)) + if (exc.match(Py.LookupError)) return null; throw exc; } @@ -1000,7 +1000,7 @@ } // else: pass through to __getitem__ invocation } } catch (PyException e) { - if (!Py.matchException(e,Py.AttributeError)) { + if (!e.match(Py.AttributeError)) { throw e; } else { firstAttributeError=e; // saved to avoid swallowing custom AttributeErrors Modified: trunk/jython/src/org/python/antlr/ast/BoolOpDerived.java =================================================================== --- trunk/jython/src/org/python/antlr/ast/BoolOpDerived.java 2009-05-06 05:46:00 UTC (rev 6303) +++ trunk/jython/src/org/python/antlr/ast/BoolOpDerived.java 2009-05-06 08:20:08 UTC (rev 6304) @@ -840,7 +840,7 @@ try { return impl.__get__(this,self_type).__call__(); } catch (PyException exc) { - if (Py.matchException(exc,Py.StopIteration)) + if (exc.match(Py.StopIteration)) return null; throw exc; } @@ -855,7 +855,7 @@ try { return impl.__get__(this,self_type).__call__(key); } catch (PyException exc) { - if (Py.matchException(exc,Py.LookupError)) + if (exc.match(Py.LookupError)) return null; throw exc; } @@ -869,7 +869,7 @@ try { return impl.__get__(this,self_type).__call__(new PyInteger(key)); } catch (PyException exc) { - if (Py.matchException(exc,Py.LookupError)) + if (exc.match(Py.LookupError)) return null; throw exc; } @@ -1000,7 +1000,7 @@ } // else: pass through to __getitem__ invocation } } catch (PyException e) { - if (!Py.matchException(e,Py.AttributeError)) { + if (!e.match(Py.AttributeError)) { throw e; } else { firstAttributeError=e; // saved to avoid swallowing custom AttributeErrors Modified: trunk/jython/src/org/python/antlr/ast/BreakDerived.java =================================================================== --- trunk/jython/src/org/python/antlr/ast/BreakDerived.java 2009-05-06 05:46:00 UTC (rev 6303) +++ trunk/jython/src/org/python/antlr/ast/BreakDerived.java 2009-05-06 08:20:08 UTC (rev 6304) @@ -840,7 +840,7 @@ try { return impl.__get__(this,self_type).__call__(); } catch (PyException exc) { - if (Py.matchException(exc,Py.StopIteration)) + if (exc.match(Py.StopIteration)) return null; throw exc; } @@ -855,7 +855,7 @@ try { return impl.__get__(this,self_type).__call__(key); } catch (PyException exc) { - if (Py.matchException(exc,Py.LookupError)) + if (exc.match(Py.LookupError)) return null; throw exc; } @@ -869,7 +869,7 @@ try { return impl.__get__(this,self_type).__call__(new PyInteger(key)); } catch (PyException exc) { - if (Py.matchException(exc,Py.LookupError)) + if (exc.match(Py.LookupError)) return null; throw exc; } @@ -1000,7 +1000,7 @@ } // else: pass through to __getitem__ invocation } } catch (PyException e) { - if (!Py.matchException(e,Py.AttributeError)) { + if (!e.match(Py.AttributeError)) { throw e; } else { firstAttributeError=e; // saved to avoid swallowing custom AttributeErrors Modified: trunk/jython/src/org/python/antlr/ast/CallDerived.java =================================================================== --- trunk/jython/src/org/python/antlr/ast/CallDerived.java 2009-05-06 05:46:00 UTC (rev 6303) +++ trunk/jython/src/org/python/antlr/ast/CallDerived.java 2009-05-06 08:20:08 UTC (rev 6304) @@ -840,7 +840,7 @@ try { return impl.__get__(this,self_type).__call__(); } catch (PyException exc) { - if (Py.matchException(exc,Py.StopIteration)) + if (exc.match(Py.StopIteration)) return null; throw exc; } @@ -855,7 +855,7 @@ try { return impl.__get__(this,self_type).__call__(key); } catch (PyException exc) { - if (Py.matchException(exc,Py.LookupError)) + if (exc.match(Py.LookupError)) return null; throw exc; } @@ -869,7 +869,7 @@ try { return impl.__get__(this,self_type).__call__(new PyInteger(key)); } catch (PyException exc) { - if (Py.matchException(exc,Py.LookupError)) + if (exc.match(Py.LookupError)) return null; throw exc; } @@ -1000,7 +1000,7 @@ } // else: pass through to __getitem__ invocation } } catch (PyException e) { - if (!Py.matchException(e,Py.AttributeError)) { + if (!e.match(Py.AttributeError)) { throw e; } else { firstAttributeError=e; // saved to avoid swallowing custom AttributeErrors Modified: trunk/jython/src/org/python/antlr/ast/ClassDefDerived.java =================================================================== --- trunk/jython/src/org/python/antlr/ast/ClassDefDerived.java 2009-05-06 05:46:00 UTC (rev 6303) +++ trunk/jython/src/org/python/antlr/ast/ClassDefDerived.java 2009-05-06 08:20:08 UTC (rev 6304) @@ -840,7 +840,7 @@ try { return impl.__get__(this,self_type).__call__(); } catch (PyException exc) { - if (Py.matchException(exc,Py.StopIteration)) + if (exc.match(Py.StopIteration)) return null; throw exc; } @@ -855,7 +855,7 @@ try { return impl.__get__(this,self_type).__call__(key); } catch (PyException exc) { - if (Py.matchException(exc,Py.LookupError)) + if (exc.match(Py.LookupError)) return null; throw exc; } @@ -869,7 +869,7 @@ try { return impl.__get__(this,self_type).__call__(new PyInteger(key)); } catch (PyException exc) { - if (Py.matchException(exc,Py.LookupError)) + if (exc.match(Py.LookupError)) return null; throw exc; } @@ -1000,7 +1000,7 @@ } // else: pass through to __getitem__ invocation } } catch (PyException e) { - if (!Py.matchException(e,Py.AttributeError)) { + if (!e.match(Py.AttributeError)) { throw e; } else { firstAttributeError=e; // saved to avoid swallowing custom AttributeErrors Modified: trunk/jython/src/org/python/antlr/ast/CompareDerived.java =================================================================== --- trunk/jython/src/org/python/antlr/ast/CompareDerived.java 2009-05-06 05:46:00 UTC (rev 6303) +++ trunk/jython/src/org/python/antlr/ast/CompareDerived.java 2009-05-06 08:20:08 UTC (rev 6304) @@ -840,7 +840,7 @@ try { return impl.__get__(this,self_type).__call__(); } catch (PyException exc) { - if (Py.matchException(exc,Py.StopIteration)) + if (exc.match(Py.StopIteration)) return null; throw exc; } @@ -855,7 +855,7 @@ try { return impl.__get__(this,self_type).__call__(key); } catch (PyException exc) { - if (Py.matchException(exc,Py.LookupError)) + if (exc.match(Py.LookupError)) return null; throw exc; } @@ -869,7 +869,7 @@ try { return impl.__get__(this,self_type).__call__(new PyInteger(key)); } catch (PyException exc) { - if (Py.matchException(exc,Py.LookupError)) + if (exc.match(Py.LookupError)) return null; throw exc; } @@ -1000,7 +1000,7 @@ } // else: pass through to __getitem__ invocation } } catch (PyException e) { - if (!Py.matchException(e,Py.AttributeError)) { + if (!e.match(Py.AttributeError)) { throw e; } else { firstAttributeError=e; // saved to avoid swallowing custom AttributeErrors Modified: trunk/jython/src/org/python/antlr/ast/ContinueDerived.java =================================================================== --- trunk/jython/src/org/python/antlr/ast/ContinueDerived.java 2009-05-06 05:46:00 UTC (rev 6303) +++ trunk/jython/src/org/python/antlr/ast/ContinueDerived.java 2009-05-06 08:20:08 UTC (rev 6304) @@ -840,7 +840,7 @@ try { return impl.__get__(this,self_type).__call__(); } catch (PyException exc) { - if (Py.matchException(exc,Py.StopIteration)) + if (exc.match(Py.StopIteration)) return null; throw exc; } @@ -855,7 +855,7 @@ try { return impl.__get__(this,self_type).__call__(key); } catch (PyException exc) { - if (Py.matchException(exc,Py.LookupError)) + if (exc.match(Py.LookupError)) return null; throw exc; } @@ -869,7 +869,7 @@ try { return impl.__get__(this,self_type).__call__(new PyInteger(key)); } catch (PyException exc) { - if (Py.matchException(exc,Py.LookupError)) + if (exc.match(Py.LookupError)) return null; throw exc; } @@ -1000,7 +1000,7 @@ } // else: pass through to __getitem__ invocation } } catch (PyException e) { - if (!Py.matchException(e,Py.AttributeError)) { + if (!e.match(Py.AttributeError)) { throw e; } else { firstAttributeError=e; // saved to avoid swallowing custom AttributeErrors Modified: trunk/jython/src/org/python/antlr/ast/DeleteDerived.java =================================================================== --- trunk/jython/src/org/python/antlr/ast/DeleteDerived.java 2009-05-06 05:46:00 UTC (rev 6303) +++ trunk/jython/src/org/python/antlr/ast/DeleteDerived.java 2009-05-06 08:20:08 UTC (rev 6304) @@ -840,7 +840,7 @@ try { return impl.__get__(this,self_type).__call__(); } catch (PyException exc) { - if (Py.matchException(exc,Py.StopIteration)) + if (exc.match(Py.StopIteration)) return null; throw exc; } @@ -855,7 +855,7 @@ try { return impl.__get__(this,self_type).__call__(key); } catch (PyException exc) { - if (Py.matchException(exc,Py.LookupError)) + if (exc.match(Py.LookupError)) return null; throw exc; } @@ -869,7 +869,7 @@ try { return impl.__get__(this,self_type).__call__(new PyInteger(key)); } catch (PyException exc) { - if (Py.matchException(exc,Py.LookupError)) + if (exc.match(Py.LookupError)) return null; throw exc; } @@ -1000,7 +1000,7 @@ } // else: pass through to __getitem__ invocation } } catch (PyException e) { - if (!Py.matchException(e,Py.AttributeError)) { + if (!e.match(Py.AttributeError)) { throw e; } else { firstAttributeError=e; // saved to avoid swallowing custom AttributeErrors Modified: trunk/jython/src/org/python/antlr/ast/DictDerived.java =================================================================== --- trunk/jython/src/org/python/antlr/ast/DictDerived.java 2009-05-06 05:46:00 UTC (rev 6303) +++ trunk/jython/src/org/python/antlr/ast/DictDerived.java 2009-05-06 08:20:08 UTC (rev 6304) @@ -840,7 +840,7 @@ try { return impl.__get__(this,self_type).__call__(); } catch (PyException exc) { - if (Py.matchException(exc,Py.StopIteration)) + if (exc.match(Py.StopIteration)) return null; throw exc; } @@ -855,7 +855,7 @@ try { return impl.__get__(this,self_type).__call__(key); } catch (PyException exc) { - if (Py.matchException(exc,Py.LookupError)) + if (exc.match(Py.LookupError)) return null; throw exc; } @@ -869,7 +869,7 @@ try { return impl.__get__(this,self_type).__call__(new PyInteger(key)); } catch (PyException exc) { - if (Py.matchException(exc,Py.LookupError)) + if (exc.match(Py.LookupError)) return null; throw exc; } @@ -1000,7 +1000,7 @@ } // else: pass through to __getitem__ invocation } } catch (PyException e) { - if (!Py.matchException(e,Py.AttributeError)) { + if (!e.match(Py.AttributeError)) { throw e; } else { firstAttributeError=e; // saved to avoid swallowing custom AttributeErrors Modified: trunk/jython/src/org/python/antlr/ast/EllipsisDerived.java =================================================================== --- trunk/jython/src/org/python/antlr/ast/EllipsisDerived.java 2009-05-06 05:46:00 UTC (rev 6303) +++ trunk/jython/src/org/python/antlr/ast/EllipsisDerived.java 2009-05-06 08:20:08 UTC (rev 6304) @@ -840,7 +840,7 @@ try { return impl.__get__(this,self_type).__call__(); } catch (PyException exc) { - if (Py.matchException(exc,Py.StopIteration)) + if (exc.match(Py.StopIteration)) return null; throw exc; } @@ -855,7 +855,7 @@ try { return impl.__get__(this,self_type).__call__(key); } catch (PyException exc) { - if (Py.matchException(exc,Py.LookupError)) + if (exc.match(Py.LookupError)) return null; throw exc; } @@ -869,7 +869,7 @@ try { return impl.__get__(this,self_type).__call__(new PyInteger(key)); } catch (PyException exc) { - if (Py.matchException(exc,Py.LookupError)) + if (exc.match(Py.LookupError)) return null; throw exc; } @@ -1000,7 +1000,7 @@ } // else: pass through to __getitem__ invocation } } catch (PyException e) { - if (!Py.matchException(e,Py.AttributeError)) { + if (!e.match(Py.AttributeError)) { throw e; } else { firstAttributeError=e; // saved to avoid swallowing custom AttributeErrors Modified: trunk/jython/src/org/python/antlr/ast/ExceptHandlerDerived.java =================================================================== --- trunk/jython/src/org/python/antlr/ast/ExceptHandlerDerived.java 2009-05-06 05:46:00 UTC (rev 6303) +++ trunk/jython/src/org/python/antlr/ast/ExceptHandlerDerived.java 2009-05-06 08:20:08 UTC (rev 6304) @@ -840,7 +840,7 @@ try { return impl.__get__(this,self_type).__call__(); } catch (PyException exc) { - if (Py.matchException(exc,Py.StopIteration)) + if (exc.match(Py.StopIteration)) return null; throw exc; } @@ -855,7 +855,7 @@ try { return impl.__get__(this,self_type).__call__(key); } catch (PyException exc) { - if (Py.matchException(exc,Py.LookupError)) + if (exc.match(Py.LookupError)) return null; throw exc; } @@ -869,7 +869,7 @@ try { return impl.__get__(this,self_type).__call__(new PyInteger(key)); } catch (PyException exc) { - if (Py.matchException(exc,Py.LookupError)) + if (exc.match(Py.LookupError)) return null; throw exc; } @@ -1000,7 +1000,7 @@ } // else: pass through to __getitem__ invocation } } catch (PyException e) { - if (!Py.matchException(e,Py.AttributeError)) { + if (!e.match(Py.AttributeError)) { throw e; } else { firstAttributeError=e; // saved to avoid swallowing custom AttributeErrors Modified: trunk/jython/src/org/python/antlr/ast/ExecDerived.java =================================================================== --- trunk/jython/src/org/python/antlr/ast/ExecDerived.java 2009-05-06 05:46:00 UTC (rev 6303) +++ trunk/jython/src/org/python/antlr/ast/ExecDerived.java 2009-05-06 08:20:08 UTC (rev 6304) @@ -840,7 +840,7 @@ try { return impl.__get__(this,self_type).__call__(); } catch (PyException exc) { - if (Py.matchException(exc,Py.StopIteration)) + if (exc.match(Py.StopIteration)) return null; throw exc; } @@ -855,7 +855,7 @@ try { return impl.__get__(this,self_type).__call__(key); } catch (PyException exc) { - if (Py.matchException(exc,Py.LookupError)) + if (exc.match(Py.LookupError)) return null; throw exc; } @@ -869,7 +869,7 @@ try { return impl.__get__(this,self_type).__call__(new PyInteger(key)); } catch (PyException exc) { - if (Py.matchException(exc,Py.LookupError)) + if (exc.match(Py.LookupError)) return null; throw exc; } @@ -1000,7 +1000,7 @@ } // else: pass through to __getitem__ invocation } } catch (PyException e) { - if (!Py.matchException(e,Py.AttributeError)) { + if (!e.match(Py.AttributeError)) { throw e; } else { firstAttributeError=e; // saved to avoid swallowing custom AttributeErrors Modified: trunk/jython/src/org/python/antlr/ast/ExprDerived.java =================================================================== --- trunk/jython/src/org/python/antlr/ast/ExprDerived.java 2009-05-06 05:46:00 UTC (rev 6303) +++ trunk/jython/src/org/python/antlr/ast/ExprDerived.java 2009-05-06 08:20:08 UTC (rev 6304) @@ -840,7 +840,7 @@ try { return impl.__get__(this,self_type).__call__(); } catch (PyException exc) { - if (Py.matchException(exc,Py.StopIteration)) + if (exc.match(Py.StopIteration)) return null; throw exc; } @@ -855,7 +855,7 @@ try { return impl.__get__(this,self_type).__call__(key); } catch (PyException exc) { - if (Py.matchException(exc,Py.LookupError)) + if (exc.match(Py.LookupError)) return null; throw exc; } @@ -869,7 +869,7 @@ try { return impl.__get__(this,self_type).__call__(new PyInteger(key)); } catch (PyException exc) { - if (Py.matchException(exc,Py.LookupError)) + if (exc.match(Py.LookupError)) return null; throw exc; } @@ -1000,7 +1000,7 @@ } // else: pass through to __getitem__ invocation } } catch (PyException e) { - if (!Py.matchException(e,Py.AttributeError)) { + if (!e.match(Py.AttributeError)) { throw e; } else { firstAttributeError=e; // saved to avoid swallowing custom AttributeErrors Modified: trunk/jython/src/org/python/antlr/ast/ExpressionDerived.java =================================================================== --- trunk/jython/src/org/python/antlr/ast/ExpressionDerived.java 2009-05-06 05:46:00 UTC (rev 6303) +++ trunk/jython/src/org/python/antlr/ast/ExpressionDerived.java 2009-05-06 08:20:08 UTC (rev 6304) @@ -840,7 +840,7 @@ try { return impl.__get__(this,self_type).__call__(); } catch (PyException exc) { - if (Py.matchException(exc,Py.StopIteration)) + if (exc.match(Py.StopIteration)) return null; throw exc; } @@ -855,7 +855,7 @@ try { return impl.__get__(this,self_type).__call__(key); } catch (PyException exc) { - if (Py.matchException(exc,Py.LookupError)) + if (exc.match(Py.LookupError)) return null; throw exc; } @@ -869,7 +869,7 @@ try { return impl.__get__(this,self_type).__call__(new PyInteger(key)); } catch (PyException exc) { - if (Py.matchException(exc,Py.LookupError)) + if (exc.match(Py.LookupError)) return null; throw exc; } @@ -1000,7 +1000,7 @@ } // else: pass through to __getitem__ invocation } } catch (PyException e) { - if (!Py.matchException(e,Py.AttributeError)) { + if (!e.match(Py.AttributeError)) { throw e; } else { firstAttributeError=e; // saved to avoid swallowing custom AttributeErrors Modified: trunk/jython/src/org/python/antlr/ast/ExtSliceDerived.java =================================================================== --- trunk/jython/src/org/python/antlr/ast/ExtSliceDerived.java 2009-05-06 05:46:00 UTC (rev 6303) +++ trunk/jython/src/org/python/antlr/ast/ExtSliceDerived.java 2009-05-06 08:20:08 UTC (rev 6304) @@ -840,7 +840,7 @@ try { return impl.__get__(this,self_type).__call__(); } catch (PyException exc) { - if (Py.matchException(exc,Py.StopIteration)) + if (exc.match(Py.StopIteration)) return null; throw exc; } @@ -855,7 +855,7 @@ try { return impl.__get__(this,self_type).__call__(key); } catch (PyException exc) { - if (Py.matchException(exc,Py.LookupError)) + if (exc.match(Py.LookupError)) return null; throw exc; } @@ -869,7 +869,7 @@ try { return impl.__get__(this,self_type).__call__(new PyInteger(key)); } catch (PyException exc) { - if (Py.matchException(exc,Py.LookupError)) + if (exc.match(Py.LookupError)) return null; throw exc; } @@ -1000,7 +1000,7 @@ } // else: pass through to __getitem__ invocation } } catch (PyException e) { - if (!Py.matchException(e,Py.AttributeError)) { + if (!e.match(Py.AttributeError)) { throw e; } else { firstAttributeError=e; // saved to avoid swallowing custom AttributeErrors Modified: trunk/jython/src/org/python/antlr/ast/ForDerived.java =================================================================== --- trunk/jython/src/org/python/antlr/ast/ForDerived.java 2009-05-06 05:46:00 UTC (rev 6303) +++ trunk/jython/src/org/python/antlr/ast/ForDerived.java 2009-05-06 08:20:08 UTC (rev 6304) @@ -840,7 +840,7 @@ try { return impl.__get__(this,self_type).__call__(); } catch (PyException exc) { - if (Py.matchException(exc,Py.StopIteration)) + if (exc.match(Py.StopIteration)) return null; throw exc; } @@ -855,7 +855,7 @@ try { return impl.__get__(this,self_type).__call__(key); } catch (PyException exc) { - if (Py.matchException(exc,Py.LookupError)) + if (exc.match(Py.LookupError)) return null; throw exc; } @@ -869,7 +869,7 @@ try { return impl.__get__(this,self_type).__call__(new PyInteger(key)); } catch (PyException exc) { - if (Py.matchException(exc,Py.LookupError)) + if (exc.match(Py.LookupError)) return null; throw exc; } @@ -1000,7 +1000,7 @@ } // else: pass through to __getitem__ invocation } } catch (PyException e) { - if (!Py.matchException(e,Py.AttributeError)) { + if (!e.match(Py.AttributeError)) { throw e; } else { firstAttributeError=e; // saved to avoid swallowing custom AttributeErrors Modified: trunk/jython/src/org/python/antlr/ast/FunctionDefDerived.java =================================================================== --- trunk/jython/src/org/python/antlr/ast/FunctionDefDerived.java 2009-05-06 05:46:00 UTC (rev 6303) +++ trunk/jython/src/org/python/antlr/ast/FunctionDefDerived.java 2009-05-06 08:20:08 UTC (rev 6304) @@ -840,7 +840,7 @@ try { return impl.__get__(this,self_type).__call__(); } catch (PyException exc) { - if (Py.matchException(exc,Py.StopIteration)) + if (exc.match(Py.StopIteration)) return null; throw exc; } @@ -855,7 +855,7 @@ try { return impl.__get__(this,self_type).__call__(key); } catch (PyException exc) { - if (Py.matchException(exc,Py.LookupError)) + if (exc.match(Py.LookupError)) return null; throw exc; } @@ -869,7 +869,7 @@ try { return impl.__get__(this,self_type).__call__(new PyInteger(key)); } catch (PyException exc) { - if (Py.matchException(exc,Py.LookupError)) + if (exc.match(Py.LookupError)) return null; throw exc; } @@ -1000,7 +1000,7 @@ } // else: pass through to __getitem__ invocation } } catch (PyException e) { - if (!Py.matchException(e,Py.AttributeError)) { + if (!e.match(Py.AttributeError)) { throw e; } else { firstAttributeError=e; // saved to avoid swallowing custom AttributeErrors Modified: trunk/jython/src/org/python/antlr/ast/GeneratorExpDerived.java =================================================================== --- trunk/jython/src/org/python/antlr/ast/GeneratorExpDerived.java 2009-05-06 05:46:00 UTC (rev 6303) +++ trunk/jython/src/org/python/antlr/ast/GeneratorExpDerived.java 2009-05-06 08:20:08 UTC (rev 6304) @@ -840,7 +840,7 @@ try { return impl.__get__(this,self_type).__call__(); } catch (PyException exc) { - if (Py.matchException(exc,Py.StopIteration)) + if (exc.match(Py.StopIteration)) return null; throw exc; } @@ -855,7 +855,7 @@ try { return impl.__get__(this,self_type).__call__(key); } catch (PyException exc) { - if (Py.matchException(exc,Py.LookupError)) + if (exc.match(Py.LookupError)) return null; throw exc; } @@ -869,7 +869,7 @@ try { return impl.__get__(this,self_type).__call__(new PyInteger(key)); } catch (PyException exc) { - if (Py.matchException(exc,Py.LookupError)) + if (exc.match(Py.LookupError)) return null; throw exc; } @@ -1000,7 +1000,7 @@ } // else: pass through to __getitem__ invocation } } catch (PyException e) { - if (!Py.matchException(e,Py.AttributeError)) { + if (!e.match(Py.AttributeError)) { throw e; } else { firstAttributeError=e; // saved to avoid swallowing custom AttributeErrors Modified: trunk/jython/src/org/python/antlr/ast/GlobalDerived.java =================================================================== --- trunk/jython/src/org/python/antlr/ast/GlobalDerived.java 2009-05-06 05:46:00 UTC (rev 6303) +++ trunk/jython/src/org/python/antlr/ast/GlobalDerived.java 2009-05-06 08:20:08 UTC (rev 6304) @@ -840,7 +840,7 @@ try { return impl.__get__(this,self_type).__call__(); } catch (PyException exc) { - if (Py.matchException(exc,Py.StopIteration)) + if (exc.match(Py.StopIteration)) return null; throw exc; } @@ -855,7 +855,7 @@ try { return impl.__get__(this,self_type).__call__(key); } catch (PyException exc) { - if (Py.matchException(exc,Py.LookupError)) + if (exc.match(Py.LookupError)) return null; throw exc; } @@ -869,7 +869,7 @@ try { return impl.__get__(this,self_type).__call__(new PyInteger(key)); } catch (PyException exc) { - if (Py.matchException(exc,Py.LookupError)) + if (exc.match(Py.LookupError)) return null; throw exc; } @@ -1000,7 +1000,7 @@ } // else: pass through to __getitem__ invocation } } catch (PyException e) { - if (!Py.matchException(e,Py.AttributeError)) { + if (!e.match(Py.AttributeError)) { throw e; } else { firstAttributeError=e; // saved to avoid swallowing custom AttributeErrors Modified: trunk/jython/src/org/python/antlr/ast/IfDerived.java =================================================================== --- trunk/jython/src/org/python/antlr/ast/IfDerived.java 2009-05-06 05:46:00 UTC (rev 6303) +++ trunk/jython/src/org/python/antlr/ast/IfDerived.java 2009-05-06 08:20:08 UTC (rev 6304) @@ -840,7 +840,7 @@ try { return impl.__get__(this,self_type).__call__(); } catch (PyException exc) { - if (Py.matchException(exc,Py.StopIteration)) + if (exc.match(Py.StopIteration)) return null; throw exc; } @@ -855,7 +855,7 @@ try { return impl.__get__(this,self_type).__call__(key); } catch (PyException exc) { - if (Py.matchException(exc,Py.LookupError)) + if (exc.match(Py.LookupError)) return null; throw exc; } @@ -869,7 +869,7 @@ try { return impl.__get__(this,self_type).__call__(new PyInteger(key)); } catch (PyException exc) { - if (Py.matchException(exc,Py.LookupError)) + if (exc.match(Py.LookupError)) return null; throw exc; } @@ -1000,7 +1000,7 @@ } // else: pass through to __getitem__ invocation } } catch (PyException e) { - if (!Py.matchException(e,Py.AttributeError)) { + if (!e.match(Py.AttributeError)) { throw e; } else { firstAttributeError=e; // saved to avoid swallowing custom AttributeErrors Modified: trunk/jython/src/org/python/antlr/ast/IfExpDerived.java =================================================================== --- trunk/jython/src/org/python/antlr/ast/IfExpDerived.java 2009-05-06 05:46:00 UTC (rev 6303) +++ trunk/jython/src/org/python/antlr/ast/IfExpDerived.java 2009-05-06 08:20:08 UTC (rev 6304) @@ -840,7 +840,7 @@ try { return impl.__get__(this,self_type).__call__(); } catch (PyException exc) { - if (Py.matchException(exc,Py.StopIteration)) + if (exc.match(Py.StopIteration)) return null; throw exc; } @@ -855,7 +855,7 @@ try { return impl.__get__(this,self_type).__call__(key); } catch (PyException exc) { - if (Py.matchException(exc,Py.LookupError)) + if (exc.match(Py.LookupError)) return null; throw exc; } @@ -869,7 +869,7 @@ try { return impl.__get__(this,self_type).__call__(new PyInteger(key)); } catch (PyException exc) { - if (Py.matchException(exc,Py.LookupError)) + if (exc.match(Py.LookupError)) return null; throw exc; } @@ -1000,7 +1000,7 @@ } // else: pass through to __getitem__ invocation } } catch (PyException e) { - if (!Py.matchException(e,Py.AttributeError)) { + if (!e.match(Py.AttributeError)) { throw e; } else { firstAttributeError=e; // saved to avoid swallowing custom AttributeErrors Modified: trunk/jython/src/org/python/antlr/ast/ImportDerived.java =================================================================== --- trunk/jython/src/org/python/antlr/ast/ImportDerived.java 2009-05-06 05:46:00 UTC (rev 6303) +++ trunk/jython/src/org/python/antlr/ast/ImportDerived.java 2009-05-06 08:20:08 UTC (rev 6304) @@ -840,7 +840,7 @@ try { return impl.__get__(this,self_type).__call__(); } catch (PyException exc) { - if (Py.matchException(exc,Py.StopIteration)) + if (exc.match(Py.StopIteration)) return null; throw exc; } @@ -855,7 +855,7 @@ try { return impl.__get__(this,self_type).__call__(key); } catch (PyException exc) { - if (Py.matchException(exc,Py.LookupError)) + if (exc.match(Py.LookupError)) return null; throw exc; } @@ -869,7 +869,7 @@ try { return impl.__get__(this,self_type).__call__(new PyInteger(key)); } catch (PyException exc) { - if (Py.matchException(exc,Py.LookupError)) + if (exc.match(Py.LookupError)) return null; throw exc; } @@ -1000,7 +1000,7 @@ } // else: pass through to __getitem__ invocation } } catch (PyException e) { - if (!Py.matchException(e,Py.AttributeError)) { + if (!e.match(Py.AttributeError)) { throw e; } else { firstAttributeError=e; // saved to avoid swallowing custom AttributeErrors Modified: trunk/jython/src/org/python/antlr/ast/ImportFromDerived.java =================================================================== --- trunk/jython/src/org/python/antlr/ast/ImportFromDerived.java 2009-05-06 05:46:00 UTC (rev 6303) +++ trunk/jython/src/org/python/antlr/ast/ImportFromDerived.java 2009-05-06 08:20:08 UTC (rev 6304) @@ -840,7 +840,7 @@ try { return impl.__get__(this,self_type).__call__(); } catch (PyException exc) { - if (Py.matchException(exc,Py.StopIteration)) + if (exc.match(Py.StopIteration)) return null; throw exc; } @@ -855,7 +855,7 @@ try { return impl.__get__(this,self_type).__call__(key); } catch (PyException exc) { - if (Py.matchException(exc,Py.LookupError)) + if (exc.match(Py.LookupError)) return null; throw exc; } @@ -869,7 +869,7 @@ try { return impl.__get__(this,self_type).__call__(new PyInteger(key)); } catch (PyException exc) { - if (Py.matchException(exc,Py.LookupError)) + if (exc.match(Py.LookupError)) return null; throw exc; } @@ -1000,7 +1000,7 @@ } // else: pass through to __getitem__ invocation } } catch (PyException e) { - if (!Py.matchException(e,Py.AttributeError)) { + if (!e.match(Py.AttributeError)) { throw e; } else { firstAttributeError=e; // saved to avoid swallowing custom AttributeErrors Modified: trunk/jython/src/org/python/antlr/ast/IndexDerived.java =================================================================== --- trunk/jython/src/org/python/antlr/ast/IndexDerived.java 2009-05-06 05:46:00 UTC (rev 6303) +++ trunk/jython/src/org/python/antlr/ast/IndexDerived.java 2009-05-06 08:20:08 UTC (rev 6304) @@ -840,7 +840,7 @@ try { return impl.__get__(this,self_type).__call__(); } catch (PyException exc) { - if (Py.matchException(exc,Py.StopIteration)) + if (exc.match(Py.StopIteration)) return null; throw exc; } @@ -855,7 +855,7 @@ try { return impl.__get__(this,self_type).__call__(key); } catch (PyException exc) { - if (Py.matchException(exc,Py.LookupError)) + if (exc.match(Py.LookupError)) return null; throw exc; } @@ -869,7 +869,7 @@ try { return impl.__get__(this,self_type).__call__(new PyInteger(key)); } catch (PyException exc) { - if (Py.matchException(exc,Py.LookupError)) + if (exc.match(Py.LookupError)) return null; throw exc; } @@ -1000,7 +1000,7 @@ } // else: pass through to __getitem__ invocation } } catch (PyException e) { - if (!Py.matchException(e,Py.AttributeError)) { + if (!e.match(Py.AttributeError)) { throw e; } else { firstAttributeError=e; // saved to avoid swallowing custom AttributeErrors Modified: trunk/jython/src/org/python/antlr/ast/InteractiveDerived.java =================================================================== --- trunk/jython/src/org/python/antlr/ast/InteractiveDerived.java 2009-05-06 05:46:00 UTC (rev 6303) +++ trunk/jython/src/org/python/antlr/ast/InteractiveDerived.java 2009-05-06 08:20:08 UTC (rev 6304) @@ -840,7 +840,7 @@ try { return impl.__get__(this,self_type).__call__(); } catch (PyException exc) { - if (Py.matchException(exc,Py.StopIteration)) + if (exc.match(Py.StopIteration)) return null; throw exc; } @@ -855,7 +855,7 @@ try { return impl.__get__(this,self_type).__call__(key); } catch (PyException exc) { - if (Py.matchException(exc,Py.LookupError)) + if (exc.match(Py.LookupError)) return null; throw exc; } @@ -869,7 +869,7 @@ try { return impl.__get__(this,self_type).__call__(new PyInteger... [truncated message content] |
From: <pj...@us...> - 2009-05-07 02:14:34
|
Revision: 6311 http://jython.svn.sourceforge.net/jython/?rev=6311&view=rev Author: pjenvey Date: 2009-05-07 01:41:35 +0000 (Thu, 07 May 2009) Log Message: ----------- o enable javac Xlint warnings, minus serial and unchecked for now as we're violating those all over the place. plus fixes for most violations o un-deprecate Py.FixedFileWrapper and PyObject._callextra -- they may have been mistakenly deprecated as they're pretty important Modified Paths: -------------- trunk/jython/build.xml trunk/jython/src/com/ziclix/python/sql/JDBC20DataHandler.java trunk/jython/src/org/python/compiler/Code.java trunk/jython/src/org/python/core/InitModule.java trunk/jython/src/org/python/core/Py.java trunk/jython/src/org/python/core/PyObject.java trunk/jython/src/org/python/core/PyString.java trunk/jython/src/org/python/core/PySystemState.java trunk/jython/src/org/python/core/imp.java trunk/jython/src/org/python/core/util/StringUtil.java trunk/jython/src/org/python/modules/_csv/PyReader.java trunk/jython/src/org/python/modules/zipimport/zipimporter.java trunk/jython/src/org/python/util/JythoncAntTask.java trunk/jython/src/org/python/util/PythonInterpreter.java Modified: trunk/jython/build.xml =================================================================== --- trunk/jython/build.xml 2009-05-07 00:58:52 UTC (rev 6310) +++ trunk/jython/build.xml 2009-05-07 01:41:35 UTC (rev 6311) @@ -117,9 +117,10 @@ <property name="build.compiler" value="modern" /> <property name="jdk.target.version" value="1.5" /> <property name="jdk.source.version" value="1.5" /> - <property name="deprecation" value="off" /> + <property name="deprecation" value="true" /> <property name="debug" value="true" /> <property name="nowarn" value="false" /> + <property name="javac.args" value="-Xlint -Xlint:-serial -Xlint:-unchecked"/> <!-- properties work.dir and jython.base.dir are also defined in full-preinit --> <property name="work.dir" value="${basedir}" /> @@ -413,6 +414,7 @@ deprecation="${deprecation}" nowarn="${nowarn}"> <include name="org/python/util/TemplateAntTask.java" /> + <compilerarg line="${javac.args}"/> </javac> </target> @@ -456,6 +458,7 @@ nowarn="${nowarn}" memoryMaximumSize="192m" fork="true"> + <compilerarg line="${javac.args}"/> <src path="${source.dir}"/> <src path="${gensrc.dir}"/> @@ -471,7 +474,9 @@ source="${jdk.source.version}" debug="${debug}" deprecation="${deprecation}" - nowarn="${nowarn}"/> + nowarn="${nowarn}"> + <compilerarg line="${javac.args}"/> + </javac> <!-- java files used by tests --> <javac srcdir="${test.source.dir}" @@ -480,7 +485,8 @@ source="${jdk.source.version}" debug="${debug}" deprecation="${deprecation}" - nowarn="${nowarn}"> + nowarn="${nowarn}"> + <compilerarg line="${javac.args}"/> <classpath refid="test.classpath" /> </javac> <javac srcdir="tests/data/initializer" @@ -490,6 +496,7 @@ debug="${debug}" deprecation="${deprecation}" nowarn="${nowarn}"> + <compilerarg line="${javac.args}"/> <classpath refid="test.classpath" /> </javac> <copy file="${source.dir}/org/python/modules/ucnhash.dat" Modified: trunk/jython/src/com/ziclix/python/sql/JDBC20DataHandler.java =================================================================== --- trunk/jython/src/com/ziclix/python/sql/JDBC20DataHandler.java 2009-05-07 00:58:52 UTC (rev 6310) +++ trunk/jython/src/com/ziclix/python/sql/JDBC20DataHandler.java 2009-05-07 01:41:35 UTC (rev 6311) @@ -52,6 +52,7 @@ * @param type * @throws SQLException */ + @SuppressWarnings("fallthrough") public void setJDBCObject(PreparedStatement stmt, int index, PyObject object, int type) throws SQLException { if (DataHandler.checkNull(stmt, index, object, type)) { Modified: trunk/jython/src/org/python/compiler/Code.java =================================================================== --- trunk/jython/src/org/python/compiler/Code.java 2009-05-07 00:58:52 UTC (rev 6310) +++ trunk/jython/src/org/python/compiler/Code.java 2009-05-07 01:41:35 UTC (rev 6311) @@ -179,6 +179,7 @@ mv.visitVarInsn(arg0, arg1); } + @SuppressWarnings("fallthrough") private int sigSize(String sig, boolean includeReturn) { int stack = 0; int i = 0; Modified: trunk/jython/src/org/python/core/InitModule.java =================================================================== --- trunk/jython/src/org/python/core/InitModule.java 2009-05-07 00:58:52 UTC (rev 6310) +++ trunk/jython/src/org/python/core/InitModule.java 2009-05-07 01:41:35 UTC (rev 6311) @@ -9,7 +9,7 @@ * @deprecated This class is deprecated. See ClassDictInit for a replacement. * @see ClassDictInit */ - +@Deprecated public interface InitModule { public abstract void initModule(PyObject dict); } Modified: trunk/jython/src/org/python/core/Py.java =================================================================== --- trunk/jython/src/org/python/core/Py.java 2009-05-07 00:58:52 UTC (rev 6310) +++ trunk/jython/src/org/python/core/Py.java 2009-05-07 01:41:35 UTC (rev 6311) @@ -1915,7 +1915,7 @@ return (objs.toArray(dest)); } } -/** @deprecated */ + class FixedFileWrapper extends StdoutWrapper { private PyObject file; Modified: trunk/jython/src/org/python/core/PyObject.java =================================================================== --- trunk/jython/src/org/python/core/PyObject.java 2009-05-07 00:58:52 UTC (rev 6310) +++ trunk/jython/src/org/python/core/PyObject.java 2009-05-07 01:41:35 UTC (rev 6311) @@ -451,7 +451,6 @@ return __call__(arg0, arg1, arg2, arg3); } - /** @deprecated **/ public PyObject _callextra(PyObject[] args, String[] keywords, PyObject starargs, Modified: trunk/jython/src/org/python/core/PyString.java =================================================================== --- trunk/jython/src/org/python/core/PyString.java 2009-05-07 00:58:52 UTC (rev 6310) +++ trunk/jython/src/org/python/core/PyString.java 2009-05-07 01:41:35 UTC (rev 6311) @@ -765,6 +765,7 @@ throw Py.TypeError("bad operand type for unary ~"); } + @SuppressWarnings("fallthrough") public PyComplex __complex__() { boolean got_re = false; boolean got_im = false; @@ -2795,6 +2796,7 @@ return buf.toString(); } + @SuppressWarnings("fallthrough") public PyString format(PyObject args) { PyObject dict = null; this.args = args; Modified: trunk/jython/src/org/python/core/PySystemState.java =================================================================== --- trunk/jython/src/org/python/core/PySystemState.java 2009-05-07 00:58:52 UTC (rev 6310) +++ trunk/jython/src/org/python/core/PySystemState.java 2009-05-07 01:41:35 UTC (rev 6311) @@ -1038,7 +1038,8 @@ // we expect an URL like jar:file:/install_dir/jython.jar!/org/python/core/PySystemState.class if (url != null) { try { - String urlString = URLDecoder.decode(url.toString()); + String urlString = URLDecoder.decode(url.toString(), + Charset.defaultCharset().name()); int jarSeparatorIndex = urlString.lastIndexOf(JAR_SEPARATOR); if (urlString.startsWith(JAR_URL_PREFIX) && jarSeparatorIndex > 0) { jarFileName = urlString.substring(JAR_URL_PREFIX.length(), jarSeparatorIndex); Modified: trunk/jython/src/org/python/core/imp.java =================================================================== --- trunk/jython/src/org/python/core/imp.java 2009-05-07 00:58:52 UTC (rev 6310) +++ trunk/jython/src/org/python/core/imp.java 2009-05-07 01:41:35 UTC (rev 6311) @@ -827,6 +827,7 @@ * replaced by importFrom with level param. Kept for backwards compatibility. * @deprecated use importFrom with level param. */ + @Deprecated public static PyObject[] importFrom(String mod, String[] names, PyFrame frame) { return importFromAs(mod, names, null, frame, DEFAULT_LEVEL); @@ -845,6 +846,7 @@ * replaced by importFromAs with level param. Kept for backwards compatibility. * @deprecated use importFromAs with level param. */ + @Deprecated public static PyObject[] importFromAs(String mod, String[] names, PyFrame frame) { return importFromAs(mod, names, null, frame, DEFAULT_LEVEL); Modified: trunk/jython/src/org/python/core/util/StringUtil.java =================================================================== --- trunk/jython/src/org/python/core/util/StringUtil.java 2009-05-07 00:58:52 UTC (rev 6310) +++ trunk/jython/src/org/python/core/util/StringUtil.java 2009-05-07 01:41:35 UTC (rev 6311) @@ -37,6 +37,7 @@ * @param len the length * @return a new String corresponding to the bytes in buf */ + @SuppressWarnings("deprecation") public static String fromBytes(byte[] buf, int off, int len) { // Yes, I known the method is deprecated, but it is the fastest // way of converting between between byte[] and String Modified: trunk/jython/src/org/python/modules/_csv/PyReader.java =================================================================== --- trunk/jython/src/org/python/modules/_csv/PyReader.java 2009-05-07 00:58:52 UTC (rev 6310) +++ trunk/jython/src/org/python/modules/_csv/PyReader.java 2009-05-07 01:41:35 UTC (rev 6311) @@ -96,6 +96,7 @@ return fields; } + @SuppressWarnings("fallthrough") private void parse_process_char(char c) { switch (state) { case START_RECORD: Modified: trunk/jython/src/org/python/modules/zipimport/zipimporter.java =================================================================== --- trunk/jython/src/org/python/modules/zipimport/zipimporter.java 2009-05-07 00:58:52 UTC (rev 6310) +++ trunk/jython/src/org/python/modules/zipimport/zipimporter.java 2009-05-07 01:41:35 UTC (rev 6311) @@ -454,7 +454,10 @@ * @param time in milliseconds, a long value * @return an int, dos style date value */ + @SuppressWarnings("deprecation") private int epochToDosDate(long time) { + // This and the other conversion methods are cut and pasted from + // java.util.zip.ZipEntry: hence the use deprecated Date APIs Date d = new Date(time); int year = d.getYear() + 1900; if (year < 1980) { @@ -469,6 +472,7 @@ * @param time in milliseconds, a long value * @return an int, dos style time value */ + @SuppressWarnings("deprecation") private int epochToDosTime(long time) { Date d = new Date(time); return d.getHours() << 11 | d.getMinutes() << 5 | d.getSeconds() >> 1; @@ -482,6 +486,7 @@ * @param dosdate a dos style date integer * @return a long time (in milliseconds) value */ + @SuppressWarnings("deprecation") private long dosTimeToEpoch(int dosTime, int dosDate) { Date d = new Date(((dosDate >> 9) & 0x7f) + 80, ((dosDate >> 5) & 0x0f) - 1, Modified: trunk/jython/src/org/python/util/JythoncAntTask.java =================================================================== --- trunk/jython/src/org/python/util/JythoncAntTask.java 2009-05-07 00:58:52 UTC (rev 6310) +++ trunk/jython/src/org/python/util/JythoncAntTask.java 2009-05-07 01:41:35 UTC (rev 6311) @@ -496,7 +496,7 @@ //get dependencies list. if( srcDir == null ) { - srcDir = project.resolveFile("."); + srcDir = getProject().resolveFile("."); } DirectoryScanner scanner = super.getDirectoryScanner(srcDir); String[] dependencies = scanner.getIncludedFiles(); Modified: trunk/jython/src/org/python/util/PythonInterpreter.java =================================================================== --- trunk/jython/src/org/python/util/PythonInterpreter.java 2009-05-07 00:58:52 UTC (rev 6310) +++ trunk/jython/src/org/python/util/PythonInterpreter.java 2009-05-07 01:41:35 UTC (rev 6311) @@ -94,6 +94,7 @@ } /** @deprecated */ + @Deprecated public void setOut(java.io.Writer outStream) { setOut(new PyFileWriter(outStream)); } @@ -113,6 +114,7 @@ } /** @deprecated */ + @Deprecated public void setErr(java.io.Writer outStream) { setErr(new PyFileWriter(outStream)); } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <pj...@us...> - 2009-05-07 03:48:45
|
Revision: 6312 http://jython.svn.sourceforge.net/jython/?rev=6312&view=rev Author: pjenvey Date: 2009-05-07 03:48:35 +0000 (Thu, 07 May 2009) Log Message: ----------- remove unnecessary casts Modified Paths: -------------- trunk/jython/src/org/python/core/Py.java trunk/jython/src/org/python/core/__builtin__.java trunk/jython/src/org/python/util/PythonInterpreter.java trunk/jython/src/org/python/util/jython.java trunk/jython/tests/java/org/python/antlr/PythonTreeTester.java Modified: trunk/jython/src/org/python/core/Py.java =================================================================== --- trunk/jython/src/org/python/core/Py.java 2009-05-07 01:41:35 UTC (rev 6311) +++ trunk/jython/src/org/python/core/Py.java 2009-05-07 03:48:35 UTC (rev 6312) @@ -1230,8 +1230,8 @@ throw Py.TypeError( "exec: argument 1 must be string, code or file object"); } - code = (PyCode)Py.compile_flags(contents, "<string>", CompileMode.exec, - getCompilerFlags(flags, false)); + code = Py.compile_flags(contents, "<string>", CompileMode.exec, + getCompilerFlags(flags, false)); } Py.runCode(code, locals, globals); } Modified: trunk/jython/src/org/python/core/__builtin__.java =================================================================== --- trunk/jython/src/org/python/core/__builtin__.java 2009-05-07 01:41:35 UTC (rev 6311) +++ trunk/jython/src/org/python/core/__builtin__.java 2009-05-07 03:48:35 UTC (rev 6312) @@ -527,7 +527,7 @@ PyCode code; try { - code = (PyCode)Py.compile_flags(file, name, CompileMode.exec, cflags); + code = Py.compile_flags(file, name, CompileMode.exec, cflags); } finally { try { file.close(); Modified: trunk/jython/src/org/python/util/PythonInterpreter.java =================================================================== --- trunk/jython/src/org/python/util/PythonInterpreter.java 2009-05-07 01:41:35 UTC (rev 6311) +++ trunk/jython/src/org/python/util/PythonInterpreter.java 2009-05-07 03:48:35 UTC (rev 6312) @@ -5,7 +5,6 @@ import org.python.core.CompileMode; import org.python.core.CompilerFlags; import org.python.core.Py; -import org.python.core.PyCode; import org.python.core.PyException; import org.python.core.PyFile; import org.python.core.PyFileWriter; @@ -164,7 +163,7 @@ public void execfile(java.io.InputStream s, String name) { setState(); - Py.runCode((PyCode)Py.compile_flags(s, name, CompileMode.exec, cflags), locals, locals); + Py.runCode(Py.compile_flags(s, name, CompileMode.exec, cflags), locals, locals); Py.flushLine(); } Modified: trunk/jython/src/org/python/util/jython.java =================================================================== --- trunk/jython/src/org/python/util/jython.java 2009-05-07 01:41:35 UTC (rev 6311) +++ trunk/jython/src/org/python/util/jython.java 2009-05-07 03:48:35 UTC (rev 6312) @@ -101,7 +101,7 @@ InputStream file = zip.getInputStream(runit); PyCode code; try { - code = (PyCode)Py.compile(file, "__run__", CompileMode.exec); + code = Py.compile(file, "__run__", CompileMode.exec); } finally { file.close(); } Modified: trunk/jython/tests/java/org/python/antlr/PythonTreeTester.java =================================================================== --- trunk/jython/tests/java/org/python/antlr/PythonTreeTester.java 2009-05-07 01:41:35 UTC (rev 6311) +++ trunk/jython/tests/java/org/python/antlr/PythonTreeTester.java 2009-05-07 03:48:35 UTC (rev 6312) @@ -41,13 +41,13 @@ PythonTree r = null; switch (_block) { case MODULE : - r = (PythonTree)parser.file_input().tree; + r = parser.file_input().tree; break; case INTERACTIVE : - r = (PythonTree)parser.single_input().tree; + r = parser.single_input().tree; break; case EXPRESSION : - r = (PythonTree)parser.eval_input().tree; + r = parser.eval_input().tree; break; } if (args.length > 1) { This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <pj...@us...> - 2009-05-10 06:43:50
|
Revision: 6326 http://jython.svn.sourceforge.net/jython/?rev=6326&view=rev Author: pjenvey Date: 2009-05-10 06:43:49 +0000 (Sun, 10 May 2009) Log Message: ----------- enable jline by default, with: o a custom build that fixes its term settings on BSD platforms o its unicode handling disabled since we expect raw bytes o our own keybindings disabling tab completion o it or any custom python.console disabled when not interactive refs #1293 Modified Paths: -------------- trunk/jython/build.xml trunk/jython/registry trunk/jython/src/org/python/util/JLineConsole.java trunk/jython/src/org/python/util/jline-keybindings.properties trunk/jython/src/org/python/util/jython.java Added Paths: ----------- trunk/jython/extlibs/jline-0.9.95-SNAPSHOT.jar Removed Paths: ------------- trunk/jython/extlibs/jline-0.9.94.jar Modified: trunk/jython/build.xml =================================================================== --- trunk/jython/build.xml 2009-05-10 06:42:35 UTC (rev 6325) +++ trunk/jython/build.xml 2009-05-10 06:43:49 UTC (rev 6326) @@ -145,7 +145,7 @@ <!-- classpaths --> <path id="main.classpath"> <pathelement path="${extlibs.dir}/libreadline-java-0.8.jar" /> - <pathelement path="${extlibs.dir}/jline-0.9.94.jar" /> + <pathelement path="${extlibs.dir}/jline-0.9.95-SNAPSHOT.jar" /> <pathelement path="${extlibs.dir}/servlet-api-2.5.jar" /> <pathelement path="${informix.jar}" /> <pathelement path="${oracle.jar}" /> @@ -503,8 +503,8 @@ todir="${compile.dir}/org/python/modules" preservelastmodified="true" /> - <copy todir="${compile.dir}/com" preservelastmodified="true"> - <fileset dir="${source.dir}/com"> + <copy todir="${compile.dir}" preservelastmodified="true"> + <fileset dir="${source.dir}"> <include name="**/*.properties" /> </fileset> </copy> @@ -562,6 +562,8 @@ <rule pattern="org.apache.xerces.**" result="org.python.apache.xerces.@1"/> <rule pattern="org.apache.wml.**" result="org.python.apache.wml.@1"/> <rule pattern="org.apache.html.**" result="org.python.apache.html.@1"/> + <zipfileset src="extlibs/jline-0.9.95-SNAPSHOT.jar"/> + <rule pattern="jline.**" result="org.python.jline.@1"/> <manifest> <attribute name="Main-Class" value="org.python.util.jython" /> <attribute name="Built-By" value="${user.name}" /> Deleted: trunk/jython/extlibs/jline-0.9.94.jar =================================================================== (Binary files differ) Added: trunk/jython/extlibs/jline-0.9.95-SNAPSHOT.jar =================================================================== (Binary files differ) Property changes on: trunk/jython/extlibs/jline-0.9.95-SNAPSHOT.jar ___________________________________________________________________ Added: svn:mime-type + application/octet-stream Modified: trunk/jython/registry =================================================================== --- trunk/jython/registry 2009-05-10 06:42:35 UTC (rev 6325) +++ trunk/jython/registry 2009-05-10 06:43:49 UTC (rev 6326) @@ -30,11 +30,14 @@ # this option is set from the command line. #python.verbose = message -# Setting this to the name of different console class, new console -# features can be enabled. Readline support is such an example -#python.console=org.python.util.JLineConsole +# Jython ships with a JLine console (http://jline.sourceforge.net/) +# out of the box. Setting this to the name of different console class, +# new console features can be enabled. Readline support is such an +# example: #python.console=org.python.util.ReadlineConsole #python.console.readlinelib=JavaReadline +# To activate the legacy Jython console: +#python.console=org.python.util.InteractiveConsole # Setting this to a valid codec name will cause the console to use a # different encoding when reading commands from the console. Modified: trunk/jython/src/org/python/util/JLineConsole.java =================================================================== --- trunk/jython/src/org/python/util/JLineConsole.java 2009-05-10 06:42:35 UTC (rev 6325) +++ trunk/jython/src/org/python/util/JLineConsole.java 2009-05-10 06:43:49 UTC (rev 6326) @@ -1,9 +1,18 @@ package org.python.util; import java.io.File; +import java.io.FileDescriptor; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStreamWriter; +import java.io.Writer; + import jline.ConsoleReader; import jline.Terminal; + import org.python.core.Py; import org.python.core.PyObject; @@ -14,6 +23,8 @@ */ public class JLineConsole extends InteractiveConsole { + protected ConsoleReader reader; + public JLineConsole() { this(null); } @@ -21,36 +32,71 @@ public JLineConsole(PyObject locals) { this(locals, CONSOLE_FILENAME); try { - File historyFile = new File(System.getProperty("user.home"), - ".jline-jython.history"); + File historyFile = new File(System.getProperty("user.home"), ".jline-jython.history"); reader.getHistory().setHistoryFile(historyFile); - } catch(IOException e) { - // oh well, no history from file + } catch (IOException e) { + // oh well, no history from file } } public JLineConsole(PyObject locals, String filename) { super(locals, filename, true); + + // Disable JLine's unicode handling so it yields raw bytes + System.setProperty("jline.UnixTerminal.input.encoding", "ISO-8859-1"); + System.setProperty("jline.WindowsTerminal.input.encoding", "ISO-8859-1"); + Terminal.setupTerminal(); try { - reader = new ConsoleReader(); - } catch(IOException e) { + InputStream input = new FileInputStream(FileDescriptor.in); + // Raw bytes in, so raw bytes out + Writer output = new OutputStreamWriter(new FileOutputStream(FileDescriptor.out), + "ISO-8859-1"); + reader = new ConsoleReader(input, output, getBindings()); + } catch (IOException e) { throw new RuntimeException(e); } } + /** + * Return the JLine bindings file. + * + * This handles loading the user's custom keybindings (normally JLine does) so it can + * fallback to Jython's (which disable tab completition) when the user's are not + * available. + * + * @return an InputStream of the JLine bindings file. + */ + protected InputStream getBindings() { + String userBindings = new File(System.getProperty("user.home"), + ".jlinebindings.properties").getAbsolutePath(); + File bindingsFile = new File(System.getProperty("jline.keybindings", userBindings)); + + try { + if (bindingsFile.isFile()) { + try { + return new FileInputStream(bindingsFile); + } catch (FileNotFoundException fnfe) { + // Shouldn't really ever happen + fnfe.printStackTrace(); + } + } + } catch (SecurityException se) { + // continue + } + return getClass().getResourceAsStream("jline-keybindings.properties"); + } + public String raw_input(PyObject prompt) { String line = null; try { line = reader.readLine(prompt.toString()); - } catch(IOException io) { + } catch (IOException io) { throw Py.IOError(io); } - if(line == null) { + if (line == null) { throw Py.EOFError("Ctrl-D exit"); } return line.endsWith("\n") ? line.substring(0, line.length() - 1) : line; } - - protected ConsoleReader reader; } Modified: trunk/jython/src/org/python/util/jline-keybindings.properties =================================================================== --- trunk/jython/src/org/python/util/jline-keybindings.properties 2009-05-10 06:42:35 UTC (rev 6325) +++ trunk/jython/src/org/python/util/jline-keybindings.properties 2009-05-10 06:43:49 UTC (rev 6326) @@ -24,8 +24,10 @@ # deleting the previous character 8: DELETE_PREV_CHAR -# TAB, CTRL-I: signal that console completion should be attempted -9: COMPLETE +## TAB, CTRL-I: signal that console completion should be attempted +#9: COMPLETE +# Jython needs a real TAB, disable completion +9: UNKNOWN # CTRL-J, CTRL-M: newline 10: NEWLINE Modified: trunk/jython/src/org/python/util/jython.java =================================================================== --- trunk/jython/src/org/python/util/jython.java 2009-05-10 06:42:35 UTC (rev 6325) +++ trunk/jython/src/org/python/util/jython.java 2009-05-10 06:43:49 UTC (rev 6326) @@ -137,9 +137,6 @@ // Setup the basic python system state from these options PySystemState.initialize(PySystemState.getBaseProperties(), opts.properties, opts.argv); - // Now create an interpreter - InteractiveConsole interp = newInterpreter(); - PyList warnoptions = new PyList(); for (String wopt : opts.warnoptions) { warnoptions.append(new PyString(wopt)); @@ -155,6 +152,9 @@ } } + // Now create an interpreter + InteractiveConsole interp = newInterpreter(opts.interactive); + // Print banner and copyright information (or not) if (opts.interactive && opts.notice && !opts.runModule) { System.err.println(InteractiveConsole.getDefaultBanner()); @@ -306,16 +306,25 @@ /** * Returns a new python interpreter using the InteractiveConsole subclass from the * <tt>python.console</tt> registry key. + * <p> + + * When stdin is interactive the default is {@link JLineConsole}. Otherwise the + * featureless {@link InteractiveConsole} is always used as alternative consoles cause + * unexpected behavior with the std file streams. */ - private static InteractiveConsole newInterpreter() { - try { - String interpClass = - PySystemState.registry.getProperty("python.console", - "org.python.util.InteractiveConsole"); - return (InteractiveConsole)Class.forName(interpClass).newInstance(); - } catch (Throwable t) { - return new InteractiveConsole(); + private static InteractiveConsole newInterpreter(boolean interactiveStdin) { + if (interactiveStdin) { + String interpClass = PySystemState.registry.getProperty("python.console", ""); + if (interpClass.length() > 0) { + try { + return (InteractiveConsole)Class.forName(interpClass).newInstance(); + } catch (Throwable t) { + // fall through + } + } + return new JLineConsole(); } + return new InteractiveConsole(); } /** This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <otm...@us...> - 2009-05-10 08:23:51
|
Revision: 6327 http://jython.svn.sourceforge.net/jython/?rev=6327&view=rev Author: otmarhumbel Date: 2009-05-10 08:23:48 +0000 (Sun, 10 May 2009) Log Message: ----------- small cleanup Modified Paths: -------------- trunk/jython/registry trunk/jython/src/org/python/core/PySystemState.java Modified: trunk/jython/registry =================================================================== --- trunk/jython/registry 2009-05-10 06:43:49 UTC (rev 6326) +++ trunk/jython/registry 2009-05-10 08:23:48 UTC (rev 6327) @@ -31,7 +31,7 @@ #python.verbose = message # Jython ships with a JLine console (http://jline.sourceforge.net/) -# out of the box. Setting this to the name of different console class, +# out of the box. Setting this to the name of a different console class, # new console features can be enabled. Readline support is such an # example: #python.console=org.python.util.ReadlineConsole Modified: trunk/jython/src/org/python/core/PySystemState.java =================================================================== --- trunk/jython/src/org/python/core/PySystemState.java 2009-05-10 06:43:49 UTC (rev 6326) +++ trunk/jython/src/org/python/core/PySystemState.java 2009-05-10 08:23:48 UTC (rev 6327) @@ -217,7 +217,7 @@ } private void initEncoding() { - String encoding = registry.getProperty("python.console.encoding"); + String encoding = registry.getProperty(PYTHON_CONSOLE_ENCODING); if (encoding == null) { return; } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <fwi...@us...> - 2009-05-11 15:27:01
|
Revision: 6338 http://jython.svn.sourceforge.net/jython/?rev=6338&view=rev Author: fwierzbicki Date: 2009-05-11 15:26:58 +0000 (Mon, 11 May 2009) Log Message: ----------- Increment release numbers, update NEWS and README. Modified Paths: -------------- trunk/jython/NEWS trunk/jython/README.txt trunk/jython/build.xml Modified: trunk/jython/NEWS =================================================================== --- trunk/jython/NEWS 2009-05-11 14:45:39 UTC (rev 6337) +++ trunk/jython/NEWS 2009-05-11 15:26:58 UTC (rev 6338) @@ -1,6 +1,6 @@ Jython NEWS -Jython 2.5.0 rc 1 +Jython 2.5.0 a0 - rc1 Bugs fixed (new numbering due to move to Roundup) - [ 1188 ] Patch against trunk to handle SecurityExceptions - [ 1271 ] Bean property accessors in derived class overide methods in base class @@ -9,9 +9,6 @@ - [ 1272 ] ASTList ClassCastException - [ 1261 ] jython -c "import sys; sys.exit(1)" not giving correct exit code. - [ 1215 ] extra spaces in import statement break importing - -Jython 2.5.0 a0 - b3 - Bugs fixed (new numbering due to move to Roundup) - [ 1126 ] ImportError raised for Java subpackages import - [ 1111 ] keyword arguments not supported on __import__ - [ 1567212 ] Jython $py.class bytecode doesn't include the .py's mtime Modified: trunk/jython/README.txt =================================================================== --- trunk/jython/README.txt 2009-05-11 14:45:39 UTC (rev 6337) +++ trunk/jython/README.txt 2009-05-11 15:26:58 UTC (rev 6338) @@ -1,15 +1,12 @@ -Welcome to Jython 2.5b4 -======================= +Welcome to Jython 2.5rc1 +======================== -This is the fifth beta of the 2.5 version of Jython. It contains a new -implementation of List and Tuple, as well as a patch which helps Jython run in -an envrironment without file write access (specifically for use on Google App -Engine) There are also a number of smaller bug fixes. This beta contains all -of the new features for the eventual 2.5 release continues the feature freeze. -We are very close, once this beta has been tested in the wild for a bit and we -close a few more high priority bugs, we will start release candidates. +This is the first release candidate of the 2.5 version of Jython. It contains +bug fixes and polish since the last beta. One especially nice bit of polish is +that jline is enabled by default now, and so using up and down arrows should +work out of the box. If no major bugs are found this release will get +re-labled and released as the production version of 2.5.0. The release was compiled on Mac OS X with JDK 5 and requires JDK 5 to run. -As a beta release, this release is incomplete and contains bugs. Do not -use in a production environment. +Please try this out and report any bugs at http://bugs.jython.org. Modified: trunk/jython/build.xml =================================================================== --- trunk/jython/build.xml 2009-05-11 14:45:39 UTC (rev 6337) +++ trunk/jython/build.xml 2009-05-11 15:26:58 UTC (rev 6338) @@ -186,13 +186,13 @@ <property name="PY_RELEASE_LEVEL_SNAPSHOT" value="170"/> <!-- 0xAA --> <!-- The current version info --> - <property name="jython.version" value="2.5b4+"/> - <property name="jython.version.noplus" value="2.5b4"/> + <property name="jython.version" value="2.5rc1+"/> + <property name="jython.version.noplus" value="2.5rc1"/> <property name="jython.major_version" value="2"/> <property name="jython.minor_version" value="5"/> <property name="jython.micro_version" value="0"/> - <property name="jython.release_level" value="${PY_RELEASE_LEVEL_BETA}"/> - <property name="jython.release_serial" value="4"/> + <property name="jython.release_level" value="${PY_RELEASE_LEVEL_GAMMA}"/> + <property name="jython.release_serial" value="1"/> <condition property="do.snapshot.build"> <isset property="snapshot.revision" /> This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <fwi...@us...> - 2009-05-11 21:03:32
|
Revision: 6341 http://jython.svn.sourceforge.net/jython/?rev=6341&view=rev Author: fwierzbicki Date: 2009-05-11 21:03:27 +0000 (Mon, 11 May 2009) Log Message: ----------- Changes for rc2. Modified Paths: -------------- trunk/jython/README.txt trunk/jython/build.xml Modified: trunk/jython/README.txt =================================================================== --- trunk/jython/README.txt 2009-05-11 21:00:49 UTC (rev 6340) +++ trunk/jython/README.txt 2009-05-11 21:03:27 UTC (rev 6341) @@ -1,12 +1,15 @@ -Welcome to Jython 2.5rc1 +Welcome to Jython 2.5rc2 ======================== -This is the first release candidate of the 2.5 version of Jython. It contains -bug fixes and polish since the last beta. One especially nice bit of polish is -that jline is enabled by default now, and so using up and down arrows should -work out of the box. If no major bugs are found this release will get -re-labled and released as the production version of 2.5.0. +This is the second release candidate of the 2.5 version of Jython (about 10 +minutes after the first). It fixes a windows bug with our jline support on +windows. Below is the RC1 notes: +It contains bug fixes and polish since the last beta. One especially nice bit +of polish is that jline is enabled by default now, and so using up and down +arrows should work out of the box. If no major bugs are found this release +will get re-labled and released as the production version of 2.5.0. + The release was compiled on Mac OS X with JDK 5 and requires JDK 5 to run. Please try this out and report any bugs at http://bugs.jython.org. Modified: trunk/jython/build.xml =================================================================== --- trunk/jython/build.xml 2009-05-11 21:00:49 UTC (rev 6340) +++ trunk/jython/build.xml 2009-05-11 21:03:27 UTC (rev 6341) @@ -186,13 +186,13 @@ <property name="PY_RELEASE_LEVEL_SNAPSHOT" value="170"/> <!-- 0xAA --> <!-- The current version info --> - <property name="jython.version" value="2.5rc1+"/> - <property name="jython.version.noplus" value="2.5rc1"/> + <property name="jython.version" value="2.5rc2+"/> + <property name="jython.version.noplus" value="2.5rc2"/> <property name="jython.major_version" value="2"/> <property name="jython.minor_version" value="5"/> <property name="jython.micro_version" value="0"/> <property name="jython.release_level" value="${PY_RELEASE_LEVEL_GAMMA}"/> - <property name="jython.release_serial" value="1"/> + <property name="jython.release_serial" value="2"/> <condition property="do.snapshot.build"> <isset property="snapshot.revision" /> This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <pj...@us...> - 2009-05-12 02:22:27
|
Revision: 6344 http://jython.svn.sourceforge.net/jython/?rev=6344&view=rev Author: pjenvey Date: 2009-05-12 01:51:08 +0000 (Tue, 12 May 2009) Log Message: ----------- quiet some warnings and small cleanup Modified Paths: -------------- trunk/jython/src/org/python/modules/itertools.java trunk/jython/src/org/python/util/JLineConsole.java trunk/jython/tests/java/javatests/Dict2JavaTest.java Modified: trunk/jython/src/org/python/modules/itertools.java =================================================================== --- trunk/jython/src/org/python/modules/itertools.java 2009-05-12 01:35:11 UTC (rev 6343) +++ trunk/jython/src/org/python/modules/itertools.java 2009-05-12 01:51:08 UTC (rev 6344) @@ -1,3 +1,4 @@ +/* Copyright (c) Jython Developers */ package org.python.modules; import java.util.ArrayList; @@ -134,7 +135,7 @@ // start over again counter = 0; } - return (PyObject)saved.get(counter++); + return saved.get(counter++); } }; Modified: trunk/jython/src/org/python/util/JLineConsole.java =================================================================== --- trunk/jython/src/org/python/util/JLineConsole.java 2009-05-12 01:35:11 UTC (rev 6343) +++ trunk/jython/src/org/python/util/JLineConsole.java 2009-05-12 01:51:08 UTC (rev 6344) @@ -1,3 +1,4 @@ +/* Copyright (c) Jython Developers */ package org.python.util; import java.io.File; @@ -87,6 +88,7 @@ return getClass().getResourceAsStream("jline-keybindings.properties"); } + @Override public String raw_input(PyObject prompt) { String line = null; try { Modified: trunk/jython/tests/java/javatests/Dict2JavaTest.java =================================================================== --- trunk/jython/tests/java/javatests/Dict2JavaTest.java 2009-05-12 01:35:11 UTC (rev 6343) +++ trunk/jython/tests/java/javatests/Dict2JavaTest.java 2009-05-12 01:51:08 UTC (rev 6344) @@ -1,9 +1,10 @@ +/* Copyright (c) Jython Developers */ package javatests; + import java.util.Map; import java.util.Set; import java.util.Collection; import java.util.HashMap; -import java.util.Iterator; /** * This class is used by the test_dict2java.py test script for testing @@ -13,21 +14,21 @@ */ public class Dict2JavaTest { - private Map map = null; + private Map<Object, Object> map; - public Dict2JavaTest(Map map) { + public Dict2JavaTest(Map<Object, Object> map) { this.map = map; } - - public Set entrySet() { + + public Set<Map.Entry<Object, Object>> entrySet() { return map.entrySet(); } - public Set keySet() { + public Set<Object> keySet() { return map.keySet(); } - public Collection values() { + public Collection<Object> values() { return map.values(); } @@ -41,7 +42,7 @@ } public boolean test_putAll_efg() { - HashMap hmap = new HashMap(); + HashMap<String, String> hmap = new HashMap<String, String>(); hmap.put("e", "1"); hmap.put("f", null); hmap.put("g", "2"); @@ -70,21 +71,21 @@ public boolean test_java_mapentry() { // created outside of Jython with non PyOjects - HashMap hmap = new HashMap(); + HashMap<String, Object> hmap = new HashMap<String, Object>(); hmap.put("b", "y"); - Map.Entry entry = (Map.Entry)hmap.entrySet().iterator().next(); + Map.Entry<String, Object> entry = hmap.entrySet().iterator().next(); if (!map.entrySet().contains(entry)) return false; // Test a number - hmap = new HashMap(); + hmap = new HashMap<String, Object>(); hmap.put("i", new Integer(3)); - entry = (Map.Entry)hmap.entrySet().iterator().next(); + entry = hmap.entrySet().iterator().next(); if (!map.entrySet().contains(entry)) return false; // test Null - hmap = new HashMap(); + hmap = new HashMap<String, Object>(); hmap.put("f", null); - entry = (Map.Entry)hmap.entrySet().iterator().next(); + entry = hmap.entrySet().iterator().next(); if (!map.entrySet().contains(entry)) return false; return true; } @@ -92,7 +93,7 @@ // make sure nulls are handled and other object types, nulls // should never match anything in the entry set. public boolean test_entry_set_nulls() { - Set set = map.entrySet(); + Set<Map.Entry<Object, Object>> set = map.entrySet(); return set.contains(null) == false && set.remove(null) == false && set.contains(new Boolean(true)) == false && set.remove(new String("")) == false; } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <otm...@us...> - 2009-05-18 21:53:02
|
Revision: 6357 http://jython.svn.sourceforge.net/jython/?rev=6357&view=rev Author: otmarhumbel Date: 2009-05-18 21:52:55 +0000 (Mon, 18 May 2009) Log Message: ----------- re-enable setting a different console in the registry Modified Paths: -------------- trunk/jython/src/org/python/util/jython.java Added Paths: ----------- trunk/jython/tests/java/org/python/util/jythonTest.java Modified: trunk/jython/src/org/python/util/jython.java =================================================================== --- trunk/jython/src/org/python/util/jython.java 2009-05-18 05:02:53 UTC (rev 6356) +++ trunk/jython/src/org/python/util/jython.java 2009-05-18 21:52:55 UTC (rev 6357) @@ -322,7 +322,7 @@ } String interpClass = PySystemState.registry.getProperty("python.console", ""); - if (interpClass.length() == 0) { + if (interpClass.length() > 0) { try { return (InteractiveConsole)Class.forName(interpClass).newInstance(); } catch (Throwable t) { Added: trunk/jython/tests/java/org/python/util/jythonTest.java =================================================================== --- trunk/jython/tests/java/org/python/util/jythonTest.java (rev 0) +++ trunk/jython/tests/java/org/python/util/jythonTest.java 2009-05-18 21:52:55 UTC (rev 6357) @@ -0,0 +1,88 @@ +package org.python.util; + +import java.lang.reflect.Method; +import java.util.Properties; + +import org.python.core.PySystemState; + +import junit.framework.TestCase; + +/** + * Tests for creating the right interactive console. + */ +public class jythonTest extends TestCase { + + private static final String PYTHON_CONSOLE = "python.console"; + + private Properties _originalRegistry; + + @Override + protected void setUp() throws Exception { + _originalRegistry = PySystemState.registry; + Properties registry; + if (_originalRegistry != null) { + registry = new Properties(_originalRegistry); + } else { + registry = new Properties(); + } + PySystemState.registry = registry; + } + + @Override + protected void tearDown() throws Exception { + PySystemState.registry = _originalRegistry; + } + + /** + * test the default behavior + * + * @throws Exception + */ + public void testNewInterpreter() throws Exception { + assertEquals(JLineConsole.class, invokeNewInterpreter(true).getClass()); + } + + /** + * test registry override + * + * @throws Exception + */ + public void testNewInterpreter_registry() throws Exception { + PySystemState.registry.setProperty(PYTHON_CONSOLE, "org.python.util.InteractiveConsole"); + assertEquals(InteractiveConsole.class, invokeNewInterpreter(true).getClass()); + } + + /** + * test fallback in case of an invalid registry value + * + * @throws Exception + */ + public void testNewInterpreter_unknown() throws Exception { + PySystemState.registry.setProperty(PYTHON_CONSOLE, "foo.bar.NoConsole"); + assertEquals(JLineConsole.class, invokeNewInterpreter(true).getClass()); + } + + /** + * test non-interactive fallback to legacy console + * + * @throws Exception + */ + public void testNewInterpreter_NonInteractive() throws Exception { + assertEquals(InteractiveConsole.class, invokeNewInterpreter(false).getClass()); + } + + /** + * Invoke the private static method 'newInterpreter(boolean)' on jython.class + * + * @throws Exception + */ + private InteractiveConsole invokeNewInterpreter(boolean interactiveStdin) throws Exception { + Method method = jython.class.getDeclaredMethod("newInterpreter", Boolean.TYPE); + assertNotNull(method); + method.setAccessible(true); + Object result = method.invoke(null, interactiveStdin); + assertNotNull(result); + assertTrue(result instanceof InteractiveConsole); + return (InteractiveConsole)result; + } +} This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |