From: <pj...@us...> - 2009-04-05 03:19:00
|
Revision: 6163 http://jython.svn.sourceforge.net/jython/?rev=6163&view=rev Author: pjenvey Date: 2009-04-05 03:18:39 +0000 (Sun, 05 Apr 2009) Log Message: ----------- remove stop_at_java cruft -- remnants of old Java integration Modified Paths: -------------- trunk/jython/src/org/python/core/PyClass.java trunk/jython/src/org/python/core/PyInstance.java Modified: trunk/jython/src/org/python/core/PyClass.java =================================================================== --- trunk/jython/src/org/python/core/PyClass.java 2009-04-05 02:32:50 UTC (rev 6162) +++ trunk/jython/src/org/python/core/PyClass.java 2009-04-05 03:18:39 UTC (rev 6163) @@ -86,12 +86,12 @@ * Setup cached references to methods where performance really counts */ private void cacheDescriptors() { - __getattr__ = lookup("__getattr__", false); - __setattr__ = lookup("__setattr__", false); - __delattr__ = lookup("__delattr__", false); - __tojava__ = lookup("__tojava__", false); - __del__ = lookup("__del__", false); - __contains__ = lookup("__contains__", false); + __getattr__ = lookup("__getattr__"); + __setattr__ = lookup("__setattr__"); + __delattr__ = lookup("__delattr__"); + __tojava__ = lookup("__tojava__"); + __del__ = lookup("__del__"); + __contains__ = lookup("__contains__"); } private static void findModule(PyObject dict) { @@ -107,28 +107,19 @@ } } - // returns [PyObject, PyClass] - PyObject[] lookupGivingClass(String name, boolean stop_at_java) { + PyObject lookup(String name) { PyObject result = __dict__.__finditem__(name); - PyClass resolvedClass = this; if (result == null && __bases__ != null) { - int n = __bases__.__len__(); - for (int i = 0; i < n; i++) { - resolvedClass = (PyClass)(__bases__.__getitem__(i)); - PyObject[] res = resolvedClass.lookupGivingClass(name, stop_at_java); - if (res[0] != null) { - return res; + for (PyObject base : __bases__.getArray()) { + result = ((PyClass)base).lookup(name); + if (result != null) { + break; } } } - return new PyObject[] { result, resolvedClass }; + return result; } - PyObject lookup(String name, boolean stop_at_java) { - PyObject[] result = lookupGivingClass(name, stop_at_java); - return result[0]; - } - @Override public PyObject fastGetDict() { return __dict__; @@ -136,12 +127,11 @@ @Override public PyObject __findattr_ex__(String name) { - PyObject[] result = lookupGivingClass(name, false); - if (result[0] == null) { + PyObject result = lookup(name); + if (result == null) { return super.__findattr_ex__(name); } - // XXX: do we need to use result[1] (wherefound) for java cases for backw comp? - return result[0].__get__(null, this); + return result.__get__(null, this); } @Override Modified: trunk/jython/src/org/python/core/PyInstance.java =================================================================== --- trunk/jython/src/org/python/core/PyInstance.java 2009-04-05 02:32:50 UTC (rev 6162) +++ trunk/jython/src/org/python/core/PyInstance.java 2009-04-05 03:18:39 UTC (rev 6163) @@ -97,14 +97,14 @@ public void __init__(PyObject[] args, String[] keywords) { // Invoke our own init function - PyObject init = instclass.lookup("__init__", true); + PyObject init = instclass.lookup("__init__"); PyObject ret = null; if (init != null) { ret = init.__call__(this, args, keywords); } if (ret == null) { if (args.length != 0) { - init = instclass.lookup("__init__", false); + init = instclass.lookup("__init__"); if (init != null) { ret = init.__call__(this, args, keywords); } else { @@ -117,34 +117,16 @@ } } - public PyObject __jfindattr__(String name) { - //System.err.println("jfinding: "+name); - return __findattr__(name, true); - } - public PyObject __findattr_ex__(String name) { - return __findattr_ex__(name, false); - } - - public PyObject __findattr__(String name, boolean stopAtJava) { - try { - return __findattr_ex__(name, stopAtJava); - } catch (PyException exc) { - if (Py.matchException(exc, Py.AttributeError)) return null; - throw exc; - } - } - - protected PyObject __findattr_ex__(String name, boolean stopAtJava) { PyObject result = ifindlocal(name); - if (result != null) + if (result != null) { return result; + } // it wasn't found in the instance, try the class - PyObject[] result2 = instclass.lookupGivingClass(name, stopAtJava); - if (result2[0] != null) - // xxx do we need to use result2[1] (wherefound) for java cases for backw comp? - return result2[0].__get__(this, instclass); - // xxx do we need to use + result = instclass.lookup(name); + if (result != null) { + return result.__get__(this, instclass); + } return ifindfunction(name); } @@ -156,8 +138,8 @@ return __dict__.__finditem__(name); } - protected PyObject ifindclass(String name, boolean stopAtJava) { - return instclass.lookup(name, stopAtJava); + protected PyObject ifindclass(String name) { + return instclass.lookup(name); } protected PyObject ifindfunction(String name) { @@ -180,7 +162,7 @@ public PyObject invoke(String name) { PyObject f = ifindlocal(name); if (f == null) { - f = ifindclass(name, false); + f = ifindclass(name); if (f != null) { if (f instanceof PyFunction) { return f.__call__(this); @@ -197,7 +179,7 @@ public PyObject invoke(String name, PyObject arg1) { PyObject f = ifindlocal(name); if (f == null) { - f = ifindclass(name, false); + f = ifindclass(name); if (f != null) { if (f instanceof PyFunction) { return f.__call__(this, arg1); @@ -214,7 +196,7 @@ public PyObject invoke(String name, PyObject arg1, PyObject arg2) { PyObject f = ifindlocal(name); if (f == null) { - f = ifindclass(name, false); + f = ifindclass(name); if (f != null) { if (f instanceof PyFunction) { return f.__call__(this, arg1, arg2); This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <pj...@us...> - 2009-04-06 01:03:49
|
Revision: 6171 http://jython.svn.sourceforge.net/jython/?rev=6171&view=rev Author: pjenvey Date: 2009-04-06 01:03:47 +0000 (Mon, 06 Apr 2009) Log Message: ----------- make exposed methods final Modified Paths: -------------- trunk/jython/src/org/python/core/PyClass.java trunk/jython/src/org/python/core/PyType.java Modified: trunk/jython/src/org/python/core/PyClass.java =================================================================== --- trunk/jython/src/org/python/core/PyClass.java 2009-04-05 23:21:56 UTC (rev 6170) +++ trunk/jython/src/org/python/core/PyClass.java 2009-04-06 01:03:47 UTC (rev 6171) @@ -149,8 +149,12 @@ } @Override + public PyObject __call__(PyObject[] args, String[] keywords) { + return classobj___call__(args, keywords); + } + @ExposedMethod - public PyObject __call__(PyObject[] args, String[] keywords) { + final PyObject classobj___call__(PyObject[] args, String[] keywords) { PyInstance inst; if (__del__ == null) { inst = new PyInstance(this); Modified: trunk/jython/src/org/python/core/PyType.java =================================================================== --- trunk/jython/src/org/python/core/PyType.java 2009-04-05 23:21:56 UTC (rev 6170) +++ trunk/jython/src/org/python/core/PyType.java 2009-04-06 01:03:47 UTC (rev 6171) @@ -1313,7 +1313,7 @@ } @ExposedMethod(names = "__repr__", doc = BuiltinDocs.type___repr___doc) - public String type_toString() { + final String type_toString() { String kind; if (!builtin) { kind = "class"; This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <pj...@us...> - 2009-04-07 01:53:11
|
Revision: 6181 http://jython.svn.sourceforge.net/jython/?rev=6181&view=rev Author: pjenvey Date: 2009-04-07 01:52:46 +0000 (Tue, 07 Apr 2009) Log Message: ----------- str/unicode don't need __unicode__, and having it actually confuses some code Modified Paths: -------------- trunk/jython/src/org/python/core/PyString.java trunk/jython/src/org/python/core/PyUnicode.java Modified: trunk/jython/src/org/python/core/PyString.java =================================================================== --- trunk/jython/src/org/python/core/PyString.java 2009-04-07 01:49:15 UTC (rev 6180) +++ trunk/jython/src/org/python/core/PyString.java 2009-04-07 01:52:46 UTC (rev 6181) @@ -101,12 +101,6 @@ } public PyUnicode __unicode__() { - return str___unicode__(); - } - - //XXX: need doc - @ExposedMethod - final PyUnicode str___unicode__() { return new PyUnicode(this); } Modified: trunk/jython/src/org/python/core/PyUnicode.java =================================================================== --- trunk/jython/src/org/python/core/PyUnicode.java 2009-04-07 01:49:15 UTC (rev 6180) +++ trunk/jython/src/org/python/core/PyUnicode.java 2009-04-07 01:52:46 UTC (rev 6181) @@ -213,10 +213,8 @@ return fmt.format(other); } - //XXX: needs doc - @ExposedMethod/*(doc = BuiltinDocs.unicode___unicode___doc)*/ - final PyUnicode unicode___unicode__() { - return str___unicode__(); + public PyUnicode __unicode__() { + return this; } @Override This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <pj...@us...> - 2009-04-21 03:14:09
|
Revision: 6249 http://jython.svn.sourceforge.net/jython/?rev=6249&view=rev Author: pjenvey Date: 2009-04-21 03:13:55 +0000 (Tue, 21 Apr 2009) Log Message: ----------- recycle numerics in some obvious places Modified Paths: -------------- trunk/jython/src/org/python/core/PyComplex.java trunk/jython/src/org/python/core/PyFloat.java trunk/jython/src/org/python/core/PyInteger.java trunk/jython/src/org/python/core/PyLong.java Modified: trunk/jython/src/org/python/core/PyComplex.java =================================================================== --- trunk/jython/src/org/python/core/PyComplex.java 2009-04-21 02:37:28 UTC (rev 6248) +++ trunk/jython/src/org/python/core/PyComplex.java 2009-04-21 03:13:55 UTC (rev 6249) @@ -639,6 +639,9 @@ @ExposedMethod(doc = BuiltinDocs.complex___pos___doc) final PyObject complex___pos__() { + if (getType() == TYPE) { + return this; + } return new PyComplex(real, imag); } Modified: trunk/jython/src/org/python/core/PyFloat.java =================================================================== --- trunk/jython/src/org/python/core/PyFloat.java 2009-04-21 02:37:28 UTC (rev 6248) +++ trunk/jython/src/org/python/core/PyFloat.java 2009-04-21 03:13:55 UTC (rev 6249) @@ -560,7 +560,7 @@ @ExposedMethod(doc = BuiltinDocs.float___pos___doc) final PyObject float___pos__() { - return Py.newFloat(value); + return float___float__(); } public PyObject __invert__() { @@ -573,10 +573,10 @@ @ExposedMethod(doc = BuiltinDocs.float___abs___doc) final PyObject float___abs__() { - if (value >= 0) - return Py.newFloat(value); - else - return __neg__(); + if (value < 0) { + return float___neg__(); + } + return float___float__(); } public PyObject __int__() { @@ -606,6 +606,9 @@ @ExposedMethod(doc = BuiltinDocs.float___float___doc) final PyFloat float___float__() { + if (getType() == TYPE) { + return this; + } return Py.newFloat(value); } public PyComplex __complex__() { Modified: trunk/jython/src/org/python/core/PyInteger.java =================================================================== --- trunk/jython/src/org/python/core/PyInteger.java 2009-04-21 02:37:28 UTC (rev 6248) +++ trunk/jython/src/org/python/core/PyInteger.java 2009-04-21 03:13:55 UTC (rev 6249) @@ -722,7 +722,7 @@ @ExposedMethod(doc = BuiltinDocs.int___pos___doc) final PyObject int___pos__() { - return Py.newInteger(getValue()); + return int___int__(); } public PyObject __abs__() { @@ -731,10 +731,10 @@ @ExposedMethod(doc = BuiltinDocs.int___abs___doc) final PyObject int___abs__() { - if (getValue() >= 0) - return Py.newInteger(getValue()); - else - return __neg__(); + if (getValue() < 0) { + return int___neg__(); + } + return int___int__(); } public PyObject __invert__() { @@ -752,6 +752,9 @@ @ExposedMethod(doc = BuiltinDocs.int___int___doc) final PyInteger int___int__() { + if (getType() == TYPE) { + return this; + } return Py.newInteger(getValue()); } Modified: trunk/jython/src/org/python/core/PyLong.java =================================================================== --- trunk/jython/src/org/python/core/PyLong.java 2009-04-21 02:37:28 UTC (rev 6248) +++ trunk/jython/src/org/python/core/PyLong.java 2009-04-21 03:13:55 UTC (rev 6249) @@ -741,7 +741,7 @@ @ExposedMethod(doc = BuiltinDocs.long___pos___doc) final PyObject long___pos__() { - return Py.newLong(value); + return long___long__(); } public PyObject __abs__() { @@ -750,7 +750,10 @@ @ExposedMethod(doc = BuiltinDocs.long___abs___doc) final PyObject long___abs__() { - return Py.newLong(value.abs()); + if (value.signum() == -1) { + return long___neg__(); + } + return long___long__(); } public PyObject __invert__() { @@ -771,7 +774,7 @@ if (value.compareTo(PyInteger.maxInt) <= 0 && value.compareTo(PyInteger.minInt) >= 0) { return Py.newInteger(value.intValue()); } - return Py.newLong(value); + return long___long__(); } @@ -781,6 +784,9 @@ @ExposedMethod(doc = BuiltinDocs.long___long___doc) final PyObject long___long__() { + if (getType() == TYPE) { + return this; + } return Py.newLong(value); } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <zy...@us...> - 2009-04-23 07:38:55
|
Revision: 6257 http://jython.svn.sourceforge.net/jython/?rev=6257&view=rev Author: zyasoft Date: 2009-04-23 07:38:49 +0000 (Thu, 23 Apr 2009) Log Message: ----------- Fixed PyList#toArray(Object[]), which in turn fixes initializing a Vector from a list on Java 5. This change resolves the test_java_list_delegate. Also fixed PyList#iterator, resolving #1323 (still need to put in a test). Modified Paths: -------------- trunk/jython/src/org/python/core/PyList.java trunk/jython/src/org/python/core/PyTuple.java Modified: trunk/jython/src/org/python/core/PyList.java =================================================================== --- trunk/jython/src/org/python/core/PyList.java 2009-04-23 05:46:39 UTC (rev 6256) +++ trunk/jython/src/org/python/core/PyList.java 2009-04-23 07:38:49 UTC (rev 6257) @@ -772,8 +772,10 @@ @Override public boolean containsAll(Collection c) { - if (c instanceof PySequenceList) { - return list.containsAll(c); + if (c instanceof PyList) { + return list.containsAll(((PyList) c).list); + } else if (c instanceof PyTuple) { + return list.containsAll(((PyTuple) c).getList()); } else { return list.containsAll(new PyList(c)); } @@ -783,8 +785,9 @@ 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? + } else if (o instanceof List && !(o instanceof PyTuple)) { + List oList = (List) o; + return oList.equals(list); } return false; } @@ -813,7 +816,23 @@ @Override public Iterator iterator() { - return list.iterator(); + return new Iterator() { + + private final Iterator<PyObject> iter = list.iterator(); + + public boolean hasNext() { + return iter.hasNext(); + } + + public Object next() { + return iter.next().__tojava__(Object.class); + } + + public void remove() { + iter.remove(); + } + }; + } @Override @@ -945,14 +964,14 @@ @Override public Object[] toArray(Object[] a) { Object copy[] = list.toArray(); - if (a.length != copy.length) { + 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; + if (a.length > copy.length) { + a[copy.length] = null; } return a; } Modified: trunk/jython/src/org/python/core/PyTuple.java =================================================================== --- trunk/jython/src/org/python/core/PyTuple.java 2009-04-23 05:46:39 UTC (rev 6256) +++ trunk/jython/src/org/python/core/PyTuple.java 2009-04-23 07:38:49 UTC (rev 6257) @@ -460,7 +460,13 @@ @Override public boolean containsAll(Collection c) { - return getList().containsAll(new PyList(c)); + if (c instanceof PyList) { + return getList().containsAll(((PyList)c).list); + } else if (c instanceof PyTuple) { + return getList().containsAll(((PyTuple)c).getList()); + } else { + return getList().containsAll(new PyList(c)); + } } @Override This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <zy...@us...> - 2009-04-30 05:00:03
|
Revision: 6279 http://jython.svn.sourceforge.net/jython/?rev=6279&view=rev Author: zyasoft Date: 2009-04-30 05:00:01 +0000 (Thu, 30 Apr 2009) Log Message: ----------- Synchronized methods in PyList, and removed synchronization in PySequence (not necessary for immutable types like xrange, string, tuple). Modified Paths: -------------- trunk/jython/src/org/python/core/PyList.java trunk/jython/src/org/python/core/PySequence.java Modified: trunk/jython/src/org/python/core/PyList.java =================================================================== --- trunk/jython/src/org/python/core/PyList.java 2009-04-29 08:36:15 UTC (rev 6278) +++ trunk/jython/src/org/python/core/PyList.java 2009-04-30 05:00:01 UTC (rev 6279) @@ -21,6 +21,7 @@ public static final PyType TYPE = PyType.fromClass(PyList.class); protected final List<PyObject> list; + public volatile int gListAllocatedStatus = -1; public PyList() { this(TYPE); @@ -113,7 +114,7 @@ } @ExposedMethod(doc = BuiltinDocs.list___len___doc) - final int list___len__() { + final synchronized int list___len__() { return size(); } @@ -150,7 +151,7 @@ } } - protected void setsliceList(int start, int stop, int step, List value) { + final private 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); @@ -161,7 +162,7 @@ } } - protected void setsliceIterator(int start, int stop, int step, Iterator<PyObject> iter) { + final private void setsliceIterator(int start, int stop, int step, Iterator<PyObject> iter) { if (step == 1) { List<PyObject> insertion = new ArrayList<PyObject>(); if (iter != null) { @@ -184,7 +185,7 @@ } } - protected void setslicePyList(int start, int stop, int step, PyList other) { + final private void setslicePyList(int start, int stop, int step, PyList other) { if (step == 1) { list.subList(start, stop).clear(); list.addAll(start, other.list); @@ -203,7 +204,7 @@ } @Override - protected PyObject repeat(int count) { + protected synchronized PyObject repeat(int count) { if (count < 0) { count = 0; } @@ -221,32 +222,32 @@ } @ExposedMethod(type = MethodType.BINARY, doc = BuiltinDocs.list___ne___doc) - final PyObject list___ne__(PyObject o) { + final synchronized PyObject list___ne__(PyObject o) { return seq___ne__(o); } @ExposedMethod(type = MethodType.BINARY, doc = BuiltinDocs.list___eq___doc) - final PyObject list___eq__(PyObject o) { + final synchronized PyObject list___eq__(PyObject o) { return seq___eq__(o); } @ExposedMethod(type = MethodType.BINARY, doc = BuiltinDocs.list___lt___doc) - final PyObject list___lt__(PyObject o) { + final synchronized PyObject list___lt__(PyObject o) { return seq___lt__(o); } @ExposedMethod(type = MethodType.BINARY, doc = BuiltinDocs.list___le___doc) - final PyObject list___le__(PyObject o) { + final synchronized PyObject list___le__(PyObject o) { return seq___le__(o); } @ExposedMethod(type = MethodType.BINARY, doc = BuiltinDocs.list___gt___doc) - final PyObject list___gt__(PyObject o) { + final synchronized PyObject list___gt__(PyObject o) { return seq___gt__(o); } @ExposedMethod(type = MethodType.BINARY, doc = BuiltinDocs.list___ge___doc) - final PyObject list___ge__(PyObject o) { + final synchronized PyObject list___ge__(PyObject o) { return seq___ge__(o); } @@ -256,7 +257,7 @@ } @ExposedMethod(type = MethodType.BINARY, doc = BuiltinDocs.list___imul___doc) - final PyObject list___imul__(PyObject o) { + final synchronized PyObject list___imul__(PyObject o) { if (!o.isIndex()) { return null; } @@ -294,7 +295,7 @@ } @ExposedMethod(type = MethodType.BINARY, doc = BuiltinDocs.list___mul___doc) - final PyObject list___mul__(PyObject o) { + final synchronized PyObject list___mul__(PyObject o) { if (!o.isIndex()) { return null; } @@ -307,7 +308,7 @@ } @ExposedMethod(type = MethodType.BINARY, doc = BuiltinDocs.list___rmul___doc) - final PyObject list___rmul__(PyObject o) { + final synchronized PyObject list___rmul__(PyObject o) { if (!o.isIndex()) { return null; } @@ -320,7 +321,7 @@ } @ExposedMethod(type = MethodType.BINARY, doc = BuiltinDocs.list___add___doc) - final PyObject list___add__(PyObject o) { + final synchronized PyObject list___add__(PyObject o) { PyList sum = null; if (o instanceof PySequenceList && !(o instanceof PyTuple)) { if (o instanceof PyList) { @@ -352,7 +353,7 @@ //XXX: needs __doc__ @ExposedMethod(type = MethodType.BINARY) - final PyObject list___radd__(PyObject o) { + final synchronized PyObject list___radd__(PyObject o) { // Support adding java.util.List, but prevent adding PyTuple. // 'o' should never be a PyNewList since __add__ is defined. PyList sum = null; @@ -369,22 +370,22 @@ } @ExposedMethod(doc = BuiltinDocs.list___contains___doc) - final boolean list___contains__(PyObject o) { + final synchronized boolean list___contains__(PyObject o) { return object___contains__(o); } @ExposedMethod(doc = BuiltinDocs.list___delitem___doc) - final void list___delitem__(PyObject index) { + final synchronized void list___delitem__(PyObject index) { seq___delitem__(index); } @ExposedMethod(doc = BuiltinDocs.list___setitem___doc) - final void list___setitem__(PyObject o, PyObject def) { + final synchronized void list___setitem__(PyObject o, PyObject def) { seq___setitem__(o, def); } @ExposedMethod(doc = BuiltinDocs.list___getitem___doc) - final PyObject list___getitem__(PyObject o) { + final synchronized PyObject list___getitem__(PyObject o) { PyObject ret = seq___finditem__(o); if (ret == null) { throw Py.IndexError("index out of range: " + o); @@ -398,22 +399,22 @@ } @ExposedMethod(doc = BuiltinDocs.list___iter___doc) - public PyObject list___iter__() { + public synchronized PyObject list___iter__() { return new PyFastSequenceIter(this); } @ExposedMethod(defaults = "null", doc = BuiltinDocs.list___getslice___doc) - final PyObject list___getslice__(PyObject start, PyObject stop, PyObject step) { + final synchronized PyObject list___getslice__(PyObject start, PyObject stop, PyObject step) { return seq___getslice__(start, stop, step); } @ExposedMethod(defaults = "null", doc = BuiltinDocs.list___setslice___doc) - final void list___setslice__(PyObject start, PyObject stop, PyObject step, PyObject value) { + final synchronized void list___setslice__(PyObject start, PyObject stop, PyObject step, PyObject value) { seq___setslice__(start, stop, step, value); } @ExposedMethod(defaults = "null", doc = BuiltinDocs.list___delslice___doc) - final void list___delslice__(PyObject start, PyObject stop, PyObject step) { + final synchronized void list___delslice__(PyObject start, PyObject stop, PyObject step) { seq___delslice__(start, stop, step); } @@ -431,7 +432,7 @@ //XXX: needs __doc__ @ExposedMethod(names = "__repr__") - final String list_toString() { + final synchronized String list_toString() { ThreadState ts = Py.getThreadState(); if (!ts.enterRepr(this)) { return "[...]"; @@ -462,7 +463,7 @@ } @ExposedMethod(doc = BuiltinDocs.list_append_doc) - final void list_append(PyObject o) { + final synchronized void list_append(PyObject o) { pyadd(o); gListAllocatedStatus = __len__(); } @@ -478,7 +479,7 @@ } @ExposedMethod(doc = BuiltinDocs.list_count_doc) - final int list_count(PyObject o) { + final synchronized int list_count(PyObject o) { int count = 0; for (PyObject item : list) { if (item.equals(o)) { @@ -507,21 +508,21 @@ } @ExposedMethod(defaults = {"null", "null"}, doc = BuiltinDocs.list_index_doc) - final int list_index(PyObject o, PyObject start, PyObject stop) { + final synchronized int list_index(PyObject o, PyObject start, PyObject stop) { int startInt = start == null ? 0 : PySlice.calculateSliceIndex(start); int stopInt = stop == null ? size() : PySlice.calculateSliceIndex(stop); return list_index(o, startInt, stopInt); } - final int list_index(PyObject o, int start, int stop) { + final synchronized int list_index(PyObject o, int start, int stop) { return _index(o, "list.index(x): x not in list", start, stop); } - final int list_index(PyObject o, int start) { + final synchronized int list_index(PyObject o, int start) { return _index(o, "list.index(x): x not in list", start, size()); } - final int list_index(PyObject o) { + final synchronized int list_index(PyObject o) { return _index(o, "list.index(x): x not in list", 0, size()); } @@ -559,7 +560,7 @@ } @ExposedMethod(doc = BuiltinDocs.list_insert_doc) - final void list_insert(int index, PyObject o) { + final synchronized void list_insert(int index, PyObject o) { if (index < 0) { index = Math.max(0, size() + index); } @@ -583,7 +584,7 @@ } @ExposedMethod(doc = BuiltinDocs.list_remove_doc) - final void list_remove(PyObject o) { + final synchronized void list_remove(PyObject o) { del(_index(o, "list.remove(x): x not in list", 0, size())); gListAllocatedStatus = __len__(); } @@ -598,7 +599,7 @@ } @ExposedMethod(doc = BuiltinDocs.list_reverse_doc) - final void list_reverse() { + final synchronized void list_reverse() { Collections.reverse(list); gListAllocatedStatus = __len__(); } @@ -621,7 +622,7 @@ } @ExposedMethod(defaults = "-1", doc = BuiltinDocs.list_pop_doc) - final PyObject list_pop(int n) { + final synchronized PyObject list_pop(int n) { int length = size(); if (length == 0) { throw Py.IndexError("pop from empty list"); @@ -648,7 +649,7 @@ } @ExposedMethod(doc = BuiltinDocs.list_extend_doc) - final void list_extend(PyObject o) { + final synchronized void list_extend(PyObject o) { if (o instanceof PyList) { list.addAll(((PyList) o).list); } else { @@ -665,7 +666,7 @@ } @ExposedMethod(type = MethodType.BINARY, doc = BuiltinDocs.list___iadd___doc) - final PyObject list___iadd__(PyObject o) { + final synchronized PyObject list___iadd__(PyObject o) { PyType oType = o.getType(); if (oType == TYPE || oType == PyTuple.TYPE || this == o) { extend(fastSequence(o, "argument must be iterable")); @@ -701,7 +702,7 @@ * operators. */ @ExposedMethod(doc = BuiltinDocs.list_sort_doc) - final void list_sort(PyObject[] args, String[] kwds) { + final synchronized void list_sort(PyObject[] args, String[] kwds) { ArgParser ap = new ArgParser("list", args, kwds, new String[]{"cmp", "key", "reverse"}, 0); PyObject cmp = ap.getPyObject(0, Py.None); PyObject key = ap.getPyObject(1, Py.None); @@ -729,7 +730,7 @@ } @ExposedMethod(doc = BuiltinDocs.list___hash___doc) - final int list___hash__() { + final synchronized int list___hash__() { throw Py.TypeError(String.format("unhashable type: '%.200s'", getType().fastGetName())); } @@ -750,7 +751,7 @@ } @Override - public boolean addAll(int index, Collection c) { + public synchronized boolean addAll(int index, Collection c) { PyList elements = new PyList(c); return list.addAll(index, elements.list); } @@ -761,17 +762,17 @@ } @Override - public void clear() { + public synchronized void clear() { list.clear(); } @Override - public boolean contains(Object o) { + public synchronized boolean contains(Object o) { return list.contains(Py.java2py(o)); } @Override - public boolean containsAll(Collection c) { + public synchronized boolean containsAll(Collection c) { if (c instanceof PyList) { return list.containsAll(((PyList) c).list); } else if (c instanceof PyTuple) { @@ -782,7 +783,7 @@ } @Override - public boolean equals(Object o) { + public synchronized boolean equals(Object o) { if (o instanceof PyList) { return (((PyList) o).list.equals(list)); } else if (o instanceof List && !(o instanceof PyTuple)) { @@ -793,24 +794,23 @@ } @Override - public Object get(int index) { + public synchronized Object get(int index) { return list.get(index).__tojava__(Object.class); } - /** @deprecated */ @Override - public PyObject[] getArray() { - PyObject a[] = null; // = new PyObject[list.size()]; + public synchronized PyObject[] getArray() { + PyObject a[] = null; return list.toArray(a); } @Override - public int indexOf(Object o) { + public synchronized int indexOf(Object o) { return list.indexOf(o); } @Override - public boolean isEmpty() { + public synchronized boolean isEmpty() { return list.isEmpty(); } @@ -836,7 +836,7 @@ } @Override - public int lastIndexOf(Object o) { + public synchronized int lastIndexOf(Object o) { return list.lastIndexOf(Py.java2py(o)); } @@ -890,37 +890,37 @@ } @Override - public void pyadd(int index, PyObject element) { + public synchronized void pyadd(int index, PyObject element) { list.add(index, element); } @Override - public boolean pyadd(PyObject o) { + public synchronized boolean pyadd(PyObject o) { list.add(o); return true; } @Override - public PyObject pyget(int index) { + public synchronized PyObject pyget(int index) { return list.get(index); } - public void pyset(int index, PyObject element) { + public synchronized void pyset(int index, PyObject element) { list.set(index, element); } @Override - public Object remove(int index) { + public synchronized Object remove(int index) { return list.remove(index); } @Override - public void remove(int start, int stop) { + public synchronized void remove(int start, int stop) { list.subList(start, stop).clear(); } @Override - public boolean removeAll(Collection c) { + public synchronized boolean removeAll(Collection c) { if (c instanceof PySequenceList) { return list.removeAll(c); } else { @@ -929,7 +929,7 @@ } @Override - public boolean retainAll(Collection c) { + public synchronized boolean retainAll(Collection c) { if (c instanceof PySequenceList) { return list.retainAll(c); } else { @@ -938,22 +938,22 @@ } @Override - public Object set(int index, Object element) { + public synchronized Object set(int index, Object element) { return list.set(index, Py.java2py(element)).__tojava__(Object.class); } @Override - public int size() { + public synchronized int size() { return list.size(); } @Override - public List subList(int fromIndex, int toIndex) { + public synchronized List subList(int fromIndex, int toIndex) { return fromList(list.subList(fromIndex, toIndex)); } @Override - public Object[] toArray() { + public synchronized Object[] toArray() { Object copy[] = list.toArray(); for (int i = 0; i < copy.length; i++) { copy[i] = ((PyObject) copy[i]).__tojava__(Object.class); @@ -962,7 +962,7 @@ } @Override - public Object[] toArray(Object[] a) { + public synchronized Object[] toArray(Object[] a) { Object copy[] = list.toArray(); if (a.length < copy.length) { a = copy; @@ -994,7 +994,7 @@ } @Override - public boolean remove(Object o) { + public synchronized boolean remove(Object o) { return list.remove(Py.java2py(o)); } } Modified: trunk/jython/src/org/python/core/PySequence.java =================================================================== --- trunk/jython/src/org/python/core/PySequence.java 2009-04-29 08:36:15 UTC (rev 6278) +++ trunk/jython/src/org/python/core/PySequence.java 2009-04-30 05:00:01 UTC (rev 6279) @@ -15,7 +15,6 @@ public abstract class PySequence extends PyObject { public PySequence() {} - public int gListAllocatedStatus = -1; protected PySequence(PyType type) { super(type); @@ -99,11 +98,11 @@ return new PySequenceIter(this); } - public synchronized PyObject __eq__(PyObject o) { + public PyObject __eq__(PyObject o) { return seq___eq__(o); } - final synchronized PyObject seq___eq__(PyObject o) { + final PyObject seq___eq__(PyObject o) { if(!(getType() == o.getType()) && !(getType().isSubType(o.getType()))) { return null; } @@ -116,11 +115,11 @@ return (i < 0) ? Py.True : Py.False; } - public synchronized PyObject __ne__(PyObject o) { + public PyObject __ne__(PyObject o) { return seq___ne__(o); } - final synchronized PyObject seq___ne__(PyObject o) { + final PyObject seq___ne__(PyObject o) { if(!(getType() == o.getType()) && !(getType().isSubType(o.getType()))) { return null; } @@ -133,11 +132,11 @@ return (i < 0) ? Py.False : Py.True; } - public synchronized PyObject __lt__(PyObject o) { + public PyObject __lt__(PyObject o) { return seq___lt__(o); } - final synchronized PyObject seq___lt__(PyObject o) { + final PyObject seq___lt__(PyObject o) { if(!(getType() == o.getType()) && !(getType().isSubType(o.getType()))) { return null; } @@ -148,11 +147,11 @@ return __finditem__(i)._lt(o.__finditem__(i)); } - public synchronized PyObject __le__(PyObject o) { + public PyObject __le__(PyObject o) { return seq___le__(o); } - final synchronized PyObject seq___le__(PyObject o) { + final PyObject seq___le__(PyObject o) { if(!(getType() == o.getType()) && !(getType().isSubType(o.getType()))) { return null; } @@ -163,11 +162,11 @@ return __finditem__(i)._le(o.__finditem__(i)); } - public synchronized PyObject __gt__(PyObject o) { + public PyObject __gt__(PyObject o) { return seq___gt__(o); } - final synchronized PyObject seq___gt__(PyObject o) { + final PyObject seq___gt__(PyObject o) { if(!(getType() == o.getType()) && !(getType().isSubType(o.getType()))) { return null; } @@ -177,11 +176,11 @@ return __finditem__(i)._gt(o.__finditem__(i)); } - public synchronized PyObject __ge__(PyObject o) { + public PyObject __ge__(PyObject o) { return seq___ge__(o); } - final synchronized PyObject seq___ge__(PyObject o) { + final PyObject seq___ge__(PyObject o) { if(!(getType() == o.getType()) && !(getType().isSubType(o.getType()))) { return null; } @@ -263,7 +262,7 @@ return seq___finditem__(index); } - final synchronized PyObject seq___finditem__(int index) { + final PyObject seq___finditem__(int index) { return delegator.checkIdxAndFindItem(index); } @@ -291,22 +290,22 @@ return false; } - public synchronized PyObject __getslice__(PyObject start, PyObject stop, PyObject step) { + public PyObject __getslice__(PyObject start, PyObject stop, PyObject step) { return seq___getslice__(start, stop, step); } - final synchronized PyObject seq___getslice__(PyObject start, PyObject stop, PyObject step) { + final PyObject seq___getslice__(PyObject start, PyObject stop, PyObject step) { return delegator.getSlice(new PySlice(start, stop, step)); } - public synchronized void __setslice__(PyObject start, + public void __setslice__(PyObject start, PyObject stop, PyObject step, PyObject value) { seq___setslice__(start, stop, step, value); } - final synchronized void seq___setslice__(PyObject start, + final void seq___setslice__(PyObject start, PyObject stop, PyObject step, PyObject value) { @@ -317,15 +316,15 @@ delegator.checkIdxAndSetSlice(new PySlice(start, stop, step), value); } - public synchronized void __delslice__(PyObject start, PyObject stop, PyObject step) { + public void __delslice__(PyObject start, PyObject stop, PyObject step) { seq___delslice__(start, stop, step); } - final synchronized void seq___delslice__(PyObject start, PyObject stop, PyObject step) { + final void seq___delslice__(PyObject start, PyObject stop, PyObject step) { delegator.checkIdxAndDelItem(new PySlice(start, stop, step)); } - public synchronized void __setitem__(int index, PyObject value) { + public void __setitem__(int index, PyObject value) { delegator.checkIdxAndSetItem(index, value); } @@ -337,11 +336,11 @@ delegator.checkIdxAndSetItem(index, value); } - public synchronized void __delitem__(PyObject index) { + public void __delitem__(PyObject index) { seq___delitem__(index); } - final synchronized void seq___delitem__(PyObject index) { + final void seq___delitem__(PyObject index) { delegator.checkIdxAndDelItem(index); } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <zy...@us...> - 2009-04-30 06:25:42
|
Revision: 6280 http://jython.svn.sourceforge.net/jython/?rev=6280&view=rev Author: zyasoft Date: 2009-04-30 06:25:36 +0000 (Thu, 30 Apr 2009) Log Message: ----------- Fixed PyList#sort so that reversed sorts are stable and keyed sorts are keyed only once. Modified Paths: -------------- trunk/jython/src/org/python/core/PyList.java Removed Paths: ------------- trunk/jython/src/org/python/core/PyComparator.java Deleted: trunk/jython/src/org/python/core/PyComparator.java =================================================================== --- trunk/jython/src/org/python/core/PyComparator.java 2009-04-30 05:00:01 UTC (rev 6279) +++ trunk/jython/src/org/python/core/PyComparator.java 2009-04-30 06:25:36 UTC (rev 6280) @@ -1,53 +0,0 @@ -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-30 05:00:01 UTC (rev 6279) +++ trunk/jython/src/org/python/core/PyList.java 2009-04-30 06:25:36 UTC (rev 6280) @@ -11,6 +11,7 @@ import java.util.Collection; import java.util.Collections; +import java.util.Comparator; import java.util.ConcurrentModificationException; import java.util.Iterator; import java.util.List; @@ -710,21 +711,183 @@ sort(cmp, key, reverse); } - public void sort(PyObject compare) { - sort(compare, Py.None, Py.False); + public void sort(PyObject cmp, PyObject key, PyObject reverse) { + boolean bReverse = reverse.__nonzero__(); + if (key == Py.None || key == null) { + if (cmp == Py.None || cmp == null) { + sort(bReverse); + } else { + sort(cmp, bReverse); + } + } else { + sort(cmp, key, bReverse); + } } + // a bunch of optimized paths for sort to avoid unnecessary work, such as DSU or checking compare functions for null + public void sort() { - sort(Py.None, Py.None, Py.False); + sort(false); } - public synchronized void sort(PyObject cmp, PyObject key, PyObject reverse) { + private synchronized void sort(boolean reverse) { gListAllocatedStatus = -1; - PyComparator c = new PyComparator(this, cmp, key, reverse.__nonzero__()); + if (reverse) { + Collections.reverse(list); // maintain stability of sort by reversing first + } + Collections.sort(list, new PyObjectDefaultComparator(this)); + if (reverse) { + Collections.reverse(list); // maintain stability of sort by reversing first + } + gListAllocatedStatus = __len__(); + } + + private static class PyObjectDefaultComparator implements Comparator<PyObject> { + + private final PyList list; + + PyObjectDefaultComparator(PyList list) { + this.list = list; + } + + public int compare(PyObject o1, PyObject o2) { + int result = o1._cmp(o2); + 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 PyObjectDefaultComparator) { + return true; + } + return false; + } + } + + public void sort(PyObject compare) { + sort(compare, false); + } + + private synchronized void sort(PyObject compare, boolean reverse) { + gListAllocatedStatus = -1; + if (reverse) { + Collections.reverse(list); // maintain stability of sort by reversing first + } + PyObjectComparator c = new PyObjectComparator(this, compare); Collections.sort(list, c); + if (reverse) { + Collections.reverse(list); + } gListAllocatedStatus = __len__(); } + private static class PyObjectComparator implements Comparator<PyObject> { + + private final PyList list; + private final PyObject cmp; + + PyObjectComparator(PyList list, PyObject cmp) { + this.list = list; + this.cmp = cmp; + } + + public int compare(PyObject o1, PyObject o2) { + int result = cmp.__call__(o1, o2).asInt(); + 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 PyObjectComparator) { + return cmp.equals(((PyComparator) o).cmp); + } + return false; + } + } + + private static class KV { + + private final PyObject key; + private final PyObject value; + + KV(PyObject key, PyObject value) { + this.key = key; + this.value = value; + } + } + + private static class KVComparator implements Comparator<KV> { + + private final PyList list; + private final PyObject cmp; + + KVComparator(PyList list, PyObject cmp) { + this.list = list; + this.cmp = cmp; + } + + public int compare(KV o1, KV o2) { + int result; + if (cmp != null && cmp != Py.None) { + result = cmp.__call__(o1.key, o2.key).asInt(); + } else { + result = o1.key._cmp(o2.key); + } + 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 PyObjectComparator) { + return cmp.equals(((PyComparator) o).cmp); + } + return false; + } + } + + private synchronized void sort(PyObject cmp, PyObject key, boolean reverse) { + gListAllocatedStatus = -1; + + int size = list.size(); + final ArrayList<KV> decorated = new ArrayList<KV>(size); + for (PyObject value : list) { + decorated.add(new KV(key.__call__(value), value)); + } + list.clear(); + KVComparator c = new KVComparator(this, cmp); + if (reverse) { + Collections.reverse(decorated); // maintain stability of sort by reversing first + } + Collections.sort(decorated, c); + if (reverse) { + Collections.reverse(decorated); + } + if (list instanceof ArrayList) { + ((ArrayList) list).ensureCapacity(size); + } + for (KV kv : decorated) { + list.add(kv.value); + } + gListAllocatedStatus = __len__(); + } + public int hashCode() { return list___hash__(); } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <pj...@us...> - 2009-05-03 07:37:22
|
Revision: 6288 http://jython.svn.sourceforge.net/jython/?rev=6288&view=rev Author: pjenvey Date: 2009-05-03 07:37:09 +0000 (Sun, 03 May 2009) Log Message: ----------- cleanup/coding standards Modified Paths: -------------- trunk/jython/src/org/python/core/PyBaseString.java trunk/jython/src/org/python/core/PySequence.java trunk/jython/src/org/python/core/PySequenceList.java trunk/jython/src/org/python/core/PyXRange.java trunk/jython/src/org/python/core/io/FileIO.java trunk/jython/src/org/python/core/io/StreamIO.java Modified: trunk/jython/src/org/python/core/PyBaseString.java =================================================================== --- trunk/jython/src/org/python/core/PyBaseString.java 2009-05-03 06:09:20 UTC (rev 6287) +++ trunk/jython/src/org/python/core/PyBaseString.java 2009-05-03 07:37:09 UTC (rev 6288) @@ -10,10 +10,6 @@ public static final PyType TYPE = PyType.fromClass(PyBaseString.class); - public PyBaseString() { - super(); - } - protected PyBaseString(PyType type) { super(type); } Modified: trunk/jython/src/org/python/core/PySequence.java =================================================================== --- trunk/jython/src/org/python/core/PySequence.java 2009-05-03 06:09:20 UTC (rev 6287) +++ trunk/jython/src/org/python/core/PySequence.java 2009-05-03 07:37:09 UTC (rev 6288) @@ -2,8 +2,8 @@ package org.python.core; /** - * The abstract superclass of PyObjects that implements a Sequence. Minimize the work in creating - * such objects. + * The abstract superclass of PyObjects that implements a Sequence. Minimize the work in + * creating such objects. * * Method names are designed to make it possible for subclasses of PySequence to implement * java.util.List. @@ -14,50 +14,41 @@ */ public abstract class PySequence extends PyObject { - public PySequence() {} - protected PySequence(PyType type) { super(type); } // These methods must be defined for any sequence /** - * @param index - * index of element to return. + * @param index index of element to return. * @return the element at the given position in the list. */ - abstract protected PyObject pyget(int index); + protected abstract PyObject pyget(int index); /** * Returns a range of elements from the sequence. * - * @param start - * the position of the first element. - * @param stop - * one more than the position of the last element. - * @param step - * the step size. + * @param start the position of the first element. + * @param stop one more than the position of the last element. + * @param step the step size. * @return a sequence corresponding the the given range of elements. */ - abstract protected PyObject getslice(int start, int stop, int step); + protected abstract PyObject getslice(int start, int stop, int step); /** * Repeats the given sequence. * - * @param count - * the number of times to repeat the sequence. + * @param count the number of times to repeat the sequence. * @return this sequence repeated count times. */ - abstract protected PyObject repeat(int count); + protected abstract PyObject repeat(int count); // These methods only apply to mutable sequences /** * Sets the given element of the sequence. * - * @param index - * index of the element to set. - * @param value - * the value to set this element to. + * @param index index of the element to set. + * @param value the value to set this element to. */ protected void pyset(int index, PyObject value) { throw Py.TypeError("can't assign to immutable object"); @@ -71,7 +62,7 @@ getType().fastGetName())); } - protected void del(int i) throws PyException { + protected void del(int i) { throw Py.TypeError(String.format("'%s' object does not support item deletion", getType().fastGetName())); } @@ -82,6 +73,7 @@ } + @Override public boolean __nonzero__() { return seq___nonzero__(); } @@ -90,6 +82,7 @@ return __len__() != 0; } + @Override public PyObject __iter__() { return seq___iter__(); } @@ -98,166 +91,182 @@ return new PySequenceIter(this); } + @Override public PyObject __eq__(PyObject o) { return seq___eq__(o); } final PyObject seq___eq__(PyObject o) { - if(!(getType() == o.getType()) && !(getType().isSubType(o.getType()))) { + if (getType() != o.getType() && !getType().isSubType(o.getType())) { return null; } int tl = __len__(); int ol = o.__len__(); - if(tl != ol) { + if (tl != ol) { return Py.False; } int i = cmp(this, tl, o, ol); - return (i < 0) ? Py.True : Py.False; + return i < 0 ? Py.True : Py.False; } + @Override public PyObject __ne__(PyObject o) { return seq___ne__(o); } final PyObject seq___ne__(PyObject o) { - if(!(getType() == o.getType()) && !(getType().isSubType(o.getType()))) { + if (getType() != o.getType() && !getType().isSubType(o.getType())) { return null; } int tl = __len__(); int ol = o.__len__(); - if(tl != ol) { + if (tl != ol) { return Py.True; } int i = cmp(this, tl, o, ol); - return (i < 0) ? Py.False : Py.True; + return i < 0 ? Py.False : Py.True; } + @Override public PyObject __lt__(PyObject o) { return seq___lt__(o); } final PyObject seq___lt__(PyObject o) { - if(!(getType() == o.getType()) && !(getType().isSubType(o.getType()))) { + if (getType() != o.getType() && !getType().isSubType(o.getType())) { return null; } int i = cmp(this, -1, o, -1); - if(i < 0) { - return (i == -1) ? Py.True : Py.False; + if (i < 0) { + return i == -1 ? Py.True : Py.False; } return __finditem__(i)._lt(o.__finditem__(i)); } + @Override public PyObject __le__(PyObject o) { return seq___le__(o); } final PyObject seq___le__(PyObject o) { - if(!(getType() == o.getType()) && !(getType().isSubType(o.getType()))) { + if (getType() != o.getType() && !getType().isSubType(o.getType())) { return null; } int i = cmp(this, -1, o, -1); - if(i < 0) { - return (i == -1 || i == -2) ? Py.True : Py.False; + if (i < 0) { + return i == -1 || i == -2 ? Py.True : Py.False; } return __finditem__(i)._le(o.__finditem__(i)); } + @Override public PyObject __gt__(PyObject o) { return seq___gt__(o); } final PyObject seq___gt__(PyObject o) { - if(!(getType() == o.getType()) && !(getType().isSubType(o.getType()))) { + if (getType() != o.getType() && !getType().isSubType(o.getType())) { return null; } int i = cmp(this, -1, o, -1); - if(i < 0) - return (i == -3) ? Py.True : Py.False; + if (i < 0) { + return i == -3 ? Py.True : Py.False; + } return __finditem__(i)._gt(o.__finditem__(i)); } + @Override public PyObject __ge__(PyObject o) { return seq___ge__(o); } final PyObject seq___ge__(PyObject o) { - if(!(getType() == o.getType()) && !(getType().isSubType(o.getType()))) { + if (getType() != o.getType() && !getType().isSubType(o.getType())) { return null; } int i = cmp(this, -1, o, -1); - if(i < 0) { - return (i == -3 || i == -2) ? Py.True : Py.False; + if (i < 0) { + return i == -3 || i == -2 ? Py.True : Py.False; } return __finditem__(i)._ge(o.__finditem__(i)); } - // Return value >= 0 is the index where the sequences differs. - // -1: reached the end of o1 without a difference - // -2: reached the end of both seqeunces without a difference - // -3: reached the end of o2 without a difference + /** + * Compare the specified object/length pairs. + * + * @return value >= 0 is the index where the sequences differs. + * -1: reached the end of o1 without a difference + * -2: reached the end of both seqeunces without a difference + * -3: reached the end of o2 without a difference + */ protected static int cmp(PyObject o1, int ol1, PyObject o2, int ol2) { - if(ol1 < 0) { + if (ol1 < 0) { ol1 = o1.__len__(); } - if(ol2 < 0) { + if (ol2 < 0) { ol2 = o2.__len__(); } - for(int i = 0; i < ol1 && i < ol2; i++) { - if(!o1.__getitem__(i)._eq(o2.__getitem__(i)).__nonzero__()) { + for (int i = 0; i < ol1 && i < ol2; i++) { + if (!o1.__getitem__(i)._eq(o2.__getitem__(i)).__nonzero__()) { return i; } } - if(ol1 == ol2) { + if (ol1 == ol2) { return -2; } - return (ol1 < ol2) ? -1 : -3; + return ol1 < ol2 ? -1 : -3; } - // Return a copy of a sequence where the __len__() method is - // telling the truth. + /** + * Return a copy of a sequence where the __len__() method is telling the truth. + */ protected static PySequence fastSequence(PyObject seq, String msg) { if (seq instanceof PySequence) { return (PySequence)seq; } PyList list = new PyList(); PyObject iter = Py.iter(seq, msg); - for(PyObject item = null; (item = iter.__iternext__()) != null;) { + for (PyObject item = null; (item = iter.__iternext__()) != null;) { list.append(item); } return list; } - // make step a long in case adding the start, stop and step together overflows an int + /** + * Make step a long in case adding the start, stop and step together overflows an int. + */ protected static final int sliceLength(int start, int stop, long step) { int ret; - if(step > 0) { + if (step > 0) { ret = (int)((stop - start + step - 1) / step); } else { ret = (int)((stop - start + step + 1) / step); } - if(ret < 0) { + if (ret < 0) { return 0; } return ret; } /** - * Adjusts <code>index</code> such that it's >= 0 and <= __len__. If <code>index</code> starts - * off negative, it's treated as an index from the end of the sequence going back to the start. + * Adjusts <code>index</code> such that it's >= 0 and <= __len__. If + * <code>index</code> starts off negative, it's treated as an index from the end of + * the sequence going back to the start. */ protected int boundToSequence(int index) { int length = __len__(); - if(index < 0) { + if (index < 0) { index += length; - if(index < 0) { + if (index < 0) { index = 0; } - } else if(index > length) { + } else if (index > length) { index = length; } return index; } + @Override public PyObject __finditem__(int index) { return seq___finditem__(index); } @@ -266,6 +275,7 @@ return delegator.checkIdxAndFindItem(index); } + @Override public PyObject __finditem__(PyObject index) { return seq___finditem__(index); } @@ -274,6 +284,7 @@ return delegator.checkIdxAndFindItem(index); } + @Override public PyObject __getitem__(PyObject index) { return seq___getitem__(index); } @@ -282,14 +293,17 @@ return delegator.checkIdxAndGetItem(index); } + @Override public boolean isMappingType() throws PyIgnoreMethodTag { return false; } + @Override public boolean isNumberType() throws PyIgnoreMethodTag { return false; } + @Override public PyObject __getslice__(PyObject start, PyObject stop, PyObject step) { return seq___getslice__(start, stop, step); } @@ -298,17 +312,12 @@ return delegator.getSlice(new PySlice(start, stop, step)); } - public void __setslice__(PyObject start, - PyObject stop, - PyObject step, - PyObject value) { + @Override + public void __setslice__(PyObject start, PyObject stop, PyObject step, PyObject value) { seq___setslice__(start, stop, step, value); } - final void seq___setslice__(PyObject start, - PyObject stop, - PyObject step, - PyObject value) { + final void seq___setslice__(PyObject start, PyObject stop, PyObject step, PyObject value) { if (value == null) { value = step; step = null; @@ -316,6 +325,7 @@ delegator.checkIdxAndSetSlice(new PySlice(start, stop, step), value); } + @Override public void __delslice__(PyObject start, PyObject stop, PyObject step) { seq___delslice__(start, stop, step); } @@ -324,10 +334,12 @@ delegator.checkIdxAndDelItem(new PySlice(start, stop, step)); } + @Override public void __setitem__(int index, PyObject value) { delegator.checkIdxAndSetItem(index, value); } + @Override public void __setitem__(PyObject index, PyObject value) { seq___setitem__(index, value); } @@ -336,6 +348,7 @@ delegator.checkIdxAndSetItem(index, value); } + @Override public void __delitem__(PyObject index) { seq___delitem__(index); } @@ -344,18 +357,19 @@ delegator.checkIdxAndDelItem(index); } - public synchronized Object __tojava__(Class c) throws PyIgnoreMethodTag { - if(c.isArray()) { - Class component = c.getComponentType(); + @Override + public synchronized Object __tojava__(Class<?> c) throws PyIgnoreMethodTag { + if (c.isArray()) { + Class<?> component = c.getComponentType(); try { int n = __len__(); PyArray array = new PyArray(component, n); - for(int i = 0; i < n; i++) { + for (int i = 0; i < n; i++) { PyObject o = pyget(i); array.set(i, o); } return array.getArray(); - } catch(Throwable t) { + } catch (Throwable t) { // ok } } @@ -367,8 +381,9 @@ * * {0} is the op name. {1} is the left operand type. {2} is the right operand type. */ + @Override protected String unsupportedopMessage(String op, PyObject o2) { - if(op.equals("*")) { + if (op.equals("*")) { return "can''t multiply sequence by non-int of type ''{2}''"; } return null; @@ -379,8 +394,9 @@ * * {0} is the op name. {1} is the left operand type. {2} is the right operand type. */ + @Override protected String runsupportedopMessage(String op, PyObject o2) { - if(op.equals("*")) { + if (op.equals("*")) { return "can''t multiply sequence by non-int of type ''{1}''"; } return null; Modified: trunk/jython/src/org/python/core/PySequenceList.java =================================================================== --- trunk/jython/src/org/python/core/PySequenceList.java 2009-05-03 06:09:20 UTC (rev 6287) +++ trunk/jython/src/org/python/core/PySequenceList.java 2009-05-03 07:37:09 UTC (rev 6288) @@ -7,9 +7,6 @@ public abstract class PySequenceList extends PySequence { - public PySequenceList() { - } - protected PySequenceList(PyType type) { super(type); } Modified: trunk/jython/src/org/python/core/PyXRange.java =================================================================== --- trunk/jython/src/org/python/core/PyXRange.java 2009-05-03 06:09:20 UTC (rev 6287) +++ trunk/jython/src/org/python/core/PyXRange.java 2009-05-03 07:37:09 UTC (rev 6288) @@ -28,6 +28,8 @@ } public PyXRange(int ilow, int ihigh, int istep) { + super(TYPE); + if (istep == 0) { throw Py.ValueError("xrange() arg 3 must not be zero"); } Modified: trunk/jython/src/org/python/core/io/FileIO.java =================================================================== --- trunk/jython/src/org/python/core/io/FileIO.java 2009-05-03 06:09:20 UTC (rev 6287) +++ trunk/jython/src/org/python/core/io/FileIO.java 2009-05-03 07:37:09 UTC (rev 6288) @@ -13,7 +13,6 @@ import java.nio.channels.FileChannel; import com.kenai.constantine.platform.Errno; -import org.python.core.imp; import org.python.core.Py; import org.python.core.util.FileUtil; import org.python.core.util.RelativeFile; @@ -168,8 +167,9 @@ // open("/dev/null", "w") works fine. Because we have // to simulate the "w" mode in Java, we suppress the // exception. - if (ioe.getMessage().equals("Invalid argument")) + if (ioe.getMessage().equals("Invalid argument")) { return; + } throw Py.IOError(ioe); } } Modified: trunk/jython/src/org/python/core/io/StreamIO.java =================================================================== --- trunk/jython/src/org/python/core/io/StreamIO.java 2009-05-03 06:09:20 UTC (rev 6287) +++ trunk/jython/src/org/python/core/io/StreamIO.java 2009-05-03 07:37:09 UTC (rev 6288) @@ -173,8 +173,9 @@ } catch (Exception e) { // XXX: masking other exceptions } finally { - if (inField != null && inField.isAccessible()) + if (inField != null && inField.isAccessible()) { inField.setAccessible(false); + } } } return null; @@ -197,8 +198,9 @@ } catch (Exception e) { // XXX: masking other exceptions } finally { - if (outField != null && outField.isAccessible()) + if (outField != null && outField.isAccessible()) { outField.setAccessible(false); + } } } return null; This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <pj...@us...> - 2009-05-30 06:03:09
|
Revision: 6425 http://jython.svn.sourceforge.net/jython/?rev=6425&view=rev Author: pjenvey Date: 2009-05-30 06:00:25 +0000 (Sat, 30 May 2009) Log Message: ----------- quiet some warnings and remove a couple unused things Modified Paths: -------------- trunk/jython/src/org/python/core/JavaImportHelper.java trunk/jython/src/org/python/core/Py.java trunk/jython/src/org/python/core/PyArray.java trunk/jython/src/org/python/core/ReflectedArgs.java trunk/jython/src/org/python/core/codecs.java Modified: trunk/jython/src/org/python/core/JavaImportHelper.java =================================================================== --- trunk/jython/src/org/python/core/JavaImportHelper.java 2009-05-30 02:08:23 UTC (rev 6424) +++ trunk/jython/src/org/python/core/JavaImportHelper.java 2009-05-30 06:00:25 UTC (rev 6425) @@ -36,10 +36,8 @@ // check explicit imports first (performance optimization) // handle 'from java.net import URL' like explicit imports - List stringFromlist = getFromListAsStrings(fromlist); - Iterator fromlistIterator = stringFromlist.iterator(); - while (fromlistIterator.hasNext()) { - String fromName = (String) fromlistIterator.next(); + List<String> stringFromlist = getFromListAsStrings(fromlist); + for (String fromName : stringFromlist) { if (isJavaClass(packageName, fromName)) { packageAdded = addPackage(packageName, packageAdded); @@ -59,7 +57,7 @@ // if all else fails, check already loaded packages if (!packageAdded) { // build the actual map with the packages known to the VM - Map packages = buildLoadedPackages(); + Map<String, String> packages = buildLoadedPackages(); // add known packages String parentPackageName = packageName; @@ -78,9 +76,7 @@ } while (dotPos > 0); // handle package imports like 'from java import math' - fromlistIterator = stringFromlist.iterator(); - while (fromlistIterator.hasNext()) { - String fromName = (String) fromlistIterator.next(); + for (String fromName : stringFromlist) { String fromPackageName = packageName + DOT + fromName; if (isLoadedPackage(fromPackageName, packages)) { packageAdded = addPackage(fromPackageName, packageAdded); @@ -113,8 +109,8 @@ * @param fromlist * @return a list containing java.lang.String entries */ - private static final List getFromListAsStrings(PyObject fromlist) { - List stringFromlist = new ArrayList(); + private static final List<String> getFromListAsStrings(PyObject fromlist) { + List<String> stringFromlist = new ArrayList<String>(); if (fromlist != null && fromlist != Py.EmptyTuple && fromlist instanceof PyTuple) { Iterator iterator = ((PyTuple) fromlist).iterator(); @@ -146,7 +142,7 @@ * @return <code>true</code> if the package with the given name is already loaded by the VM, <code>false</code> * otherwise. */ - private static boolean isLoadedPackage(String javaPackageName, Map packages) { + private static boolean isLoadedPackage(String javaPackageName, Map<String, String> packages) { boolean isLoaded = false; if (javaPackageName != null) { isLoaded = packages.containsKey(javaPackageName); @@ -160,8 +156,8 @@ * All parent packages appear as single entries like python modules, e.g. <code>java</code>, * <code>java.lang</code>, <code>java.lang.reflect</code>, */ - private static Map buildLoadedPackages() { - TreeMap packageMap = new TreeMap(); + private static Map<String, String> buildLoadedPackages() { + TreeMap<String, String> packageMap = new TreeMap<String, String>(); Package[] packages = Package.getPackages(); for (int i = 0; i < packages.length; i++) { String packageName = packages[i].getName(); Modified: trunk/jython/src/org/python/core/Py.java =================================================================== --- trunk/jython/src/org/python/core/Py.java 2009-05-30 02:08:23 UTC (rev 6424) +++ trunk/jython/src/org/python/core/Py.java 2009-05-30 06:00:25 UTC (rev 6425) @@ -13,6 +13,7 @@ import java.io.Serializable; import java.io.StreamCorruptedException; import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; import java.sql.Date; import java.sql.Time; import java.sql.Timestamp; @@ -23,7 +24,6 @@ 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; import org.python.util.Generic; @@ -481,7 +481,7 @@ // ??pending: was @deprecated but is actually used by proxie code. // Can get rid of it? public static Object tojava(PyObject o, String s) { - Class c = findClass(s); + Class<?> c = findClass(s); if (c == null) { throw Py.TypeError("can't convert to: " + s); } @@ -663,15 +663,13 @@ funcs, func_id); } - public static PyCode newJavaCode(Class cls, String name) { + public static PyCode newJavaCode(Class<?> cls, String name) { return new JavaCode(newJavaFunc(cls, name)); } - public static PyObject newJavaFunc(Class cls, String name) { + public static PyObject newJavaFunc(Class<?> cls, String name) { try { - java.lang.reflect.Method m = cls.getMethod(name, new Class[]{ - PyObject[].class, String[].class - }); + Method m = cls.getMethod(name, new Class<?>[]{PyObject[].class, String[].class}); return new JavaFunc(m); } catch (NoSuchMethodException e) { throw Py.JavaError(e); @@ -1510,10 +1508,6 @@ */ private static ExtensiblePyObjectAdapter adapter; - private static Class[] pyClassCtrSignature = { - String.class, PyTuple.class, PyObject.class, Class.class - }; - // XXX: The following two makeClass overrides are *only* for the // old compiler, they should be removed when the newcompiler hits public static PyObject makeClass(String name, PyObject[] bases, @@ -1939,6 +1933,7 @@ } } + @Override protected PyObject myFile() { return file; } @@ -1958,6 +1953,7 @@ } } + @Override public PyObject call(ThreadState state, PyFrame frame, PyObject closure) { //XXX: what the heck is this? Looks like debug code, but it's // been here a long time... @@ -1965,39 +1961,46 @@ return Py.None; } + @Override public PyObject call(ThreadState state, PyObject args[], String keywords[], PyObject globals, PyObject[] defaults, PyObject closure) { return func.__call__(args, keywords); } + @Override public PyObject call(ThreadState state, PyObject self, PyObject args[], String keywords[], PyObject globals, PyObject[] defaults, PyObject closure) { return func.__call__(self, args, keywords); } + @Override public PyObject call(ThreadState state, PyObject globals, PyObject[] defaults, PyObject closure) { return func.__call__(); } + @Override public PyObject call(ThreadState state, PyObject arg1, PyObject globals, PyObject[] defaults, PyObject closure) { return func.__call__(arg1); } + @Override public PyObject call(ThreadState state, PyObject arg1, PyObject arg2, PyObject globals, PyObject[] defaults, PyObject closure) { return func.__call__(arg1, arg2); } + @Override public PyObject call(ThreadState state, PyObject arg1, PyObject arg2, PyObject arg3, PyObject globals, PyObject[] defaults, PyObject closure) { return func.__call__(arg1, arg2, arg3); } + @Override public PyObject call(ThreadState state, PyObject arg1, PyObject arg2, PyObject arg3, PyObject arg4, PyObject globals, PyObject[] defaults, PyObject closure) { @@ -2011,12 +2014,13 @@ */ class JavaFunc extends PyObject { - java.lang.reflect.Method method; + Method method; - public JavaFunc(java.lang.reflect.Method method) { + public JavaFunc(Method method) { this.method = method; } + @Override public PyObject __call__(PyObject[] args, String[] kws) { Object[] margs = new Object[]{args, kws}; try { @@ -2026,10 +2030,12 @@ } } + @Override public PyObject _doget(PyObject container) { return _doget(container, null); } + @Override public PyObject _doget(PyObject container, PyObject wherefound) { if (container == null) { return this; Modified: trunk/jython/src/org/python/core/PyArray.java =================================================================== --- trunk/jython/src/org/python/core/PyArray.java 2009-05-30 02:08:23 UTC (rev 6424) +++ trunk/jython/src/org/python/core/PyArray.java 2009-05-30 06:00:25 UTC (rev 6425) @@ -36,7 +36,7 @@ private Object data; /** The Java array class. */ - private Class type; + private Class<?> type; /** The Python style typecode of the array. */ private String typecode; @@ -47,12 +47,12 @@ super(type); } - public PyArray(Class type, Object data) { + public PyArray(Class<?> type, Object data) { this(TYPE); setup(type, data); } - public PyArray(Class type, int n) { + public PyArray(Class<?> type, int n) { this(type, Array.newInstance(type, n)); } @@ -61,7 +61,7 @@ typecode = toCopy.typecode; } - private void setup(Class type, Object data) { + private void setup(Class<?> type, Object data) { this.type = type; typecode = class2char(type); if (data == null) { @@ -87,7 +87,7 @@ PyObject obj = ap.getPyObject(0); PyObject initial = ap.getPyObject(1, null); - Class type; + Class<?> type; String typecode; if (obj instanceof PyString && !(obj instanceof PyUnicode)) { if (obj.__len__() != 1) { @@ -138,7 +138,7 @@ return array; } - public static PyArray zeros(int n, Class ctype) { + public static PyArray zeros(int n, Class<?> ctype) { PyArray array = new PyArray(ctype, n); array.typecode = ctype.getName(); return array; @@ -161,7 +161,7 @@ * <code>Class</code> type of the elements stored in the array. * @return a new PyArray */ - public static PyArray array(PyObject init, Class ctype) { + public static PyArray array(PyObject init, Class<?> ctype) { PyArray array = new PyArray(ctype, 0); array.typecode = ctype.getName(); array.extendInternal(init); @@ -248,6 +248,7 @@ seq___delslice__(start, stop, step); } + @Override public PyObject __imul__(PyObject o) { return array___imul__(o); } @@ -272,6 +273,7 @@ return this; } + @Override public PyObject __mul__(PyObject o) { return array___mul__(o); } @@ -284,6 +286,7 @@ return repeat(o.asIndex(Py.OverflowError)); } + @Override public PyObject __rmul__(PyObject o) { return array___rmul__(o); } @@ -296,6 +299,7 @@ return repeat(o.asIndex(Py.OverflowError)); } + @Override public PyObject __iadd__(PyObject other) { return array___iadd__(other); } @@ -316,6 +320,7 @@ return this; } + @Override public PyObject __add__(PyObject other) { return array___add__(other); } @@ -348,6 +353,7 @@ * * @return number of elements in the array */ + @Override public int __len__() { return array___len__(); } @@ -357,6 +363,7 @@ return delegate.getSize(); } + @Override public PyObject __reduce__() { return array___reduce__(); } @@ -402,7 +409,8 @@ * target <em>Class</em> for the conversion * @return Java object converted to required class type if possible. */ - public Object __tojava__(Class c) { + @Override + public Object __tojava__(Class<?> c) { if(c == Object.class || (c.isArray() && c.getComponentType().isAssignableFrom(type))) { return data; @@ -502,6 +510,7 @@ * * @return copy of current PyArray */ + @Override public Object clone() { return new PyArray(this); } @@ -558,7 +567,7 @@ */ // promote B, H, I (unsigned int) to next larger size - public static Class char2class(char type) throws PyIgnoreMethodTag { + public static Class<?> char2class(char type) throws PyIgnoreMethodTag { switch(type){ case 'z': return Boolean.TYPE; @@ -591,40 +600,7 @@ } } - private static Class char2storageClass(char type) throws PyIgnoreMethodTag { - switch(type){ - case 'z': - return Boolean.TYPE; - case 'b': - return Byte.TYPE; - case 'B': - return Byte.TYPE; - case 'u': - return Integer.TYPE; - case 'c': - return Character.TYPE; - case 'h': - return Short.TYPE; - case 'H': - return Short.TYPE; - case 'i': - return Integer.TYPE; - case 'I': - return Integer.TYPE; - case 'l': - return Long.TYPE; - case 'L': - return Long.TYPE; - case 'f': - return Float.TYPE; - case 'd': - return Double.TYPE; - default: - throw Py.ValueError("bad typecode (must be c, b, B, u, h, H, i, I, l, L, f or d)"); - } - } - - private static String class2char(Class cls) { + private static String class2char(Class<?> cls) { if(cls.equals(Boolean.TYPE)) return "z"; else if(cls.equals(Character.TYPE)) @@ -684,6 +660,7 @@ * @param i * index of the item to be deleted from the array */ + @Override protected void del(int i) { // Now the AbstractArray can support this: // throw Py.TypeError("can't remove from array"); @@ -698,6 +675,7 @@ * @param stop * finishing index of slice */ + @Override protected void delRange(int start, int stop) { delegate.remove(start, stop); } @@ -1054,6 +1032,7 @@ * @param i * index of the item to be retrieved from the array */ + @Override protected PyObject pyget(int i) { if ("u".equals(typecode)) { return new PyUnicode(Array.getInt(data, i)); @@ -1199,6 +1178,7 @@ * stepping increment of the slice * @return A new PyArray object containing the described slice */ + @Override protected PyObject getslice(int start, int stop, int step) { if (step > 0 && stop < start) { stop = start; @@ -1376,6 +1356,7 @@ * @return A new PyArray object containing the source object repeated * <em>count</em> times. */ + @Override protected PyObject repeat(int count) { Object arraycopy = delegate.copyArray(); PyArray ret = new PyArray(type, 0); @@ -1425,6 +1406,7 @@ pyset(i, value); } + @Override protected void pyset(int i, PyObject value) { if ("u".equals(typecode)) { Array.setInt(data, i, getCodePoint(value)); @@ -1528,6 +1510,7 @@ * @param step * stepping increment of the slice */ + @Override protected void setslice(int start, int stop, int step, PyObject value) { if (stop < start) { stop = start; @@ -1819,17 +1802,19 @@ super(data == null ? 0 : Array.getLength(data)); } + @Override protected Object getArray() { return data; } + @Override protected void setArray(Object array) { data = array; } @Override protected Object createArray(int size) { - Class baseType = data.getClass().getComponentType(); + Class<?> baseType = data.getClass().getComponentType(); return Array.newInstance(baseType, size); } } Modified: trunk/jython/src/org/python/core/ReflectedArgs.java =================================================================== --- trunk/jython/src/org/python/core/ReflectedArgs.java 2009-05-30 02:08:23 UTC (rev 6424) +++ trunk/jython/src/org/python/core/ReflectedArgs.java 2009-05-30 06:00:25 UTC (rev 6425) @@ -2,11 +2,11 @@ package org.python.core; public class ReflectedArgs { - public Class[] args; + public Class<?>[] args; public Object data; - public Class declaringClass; + public Class<?> declaringClass; public boolean isStatic; @@ -18,8 +18,7 @@ public static final int PyArgsKeywordsCall = 2; - public ReflectedArgs(Object data, Class[] args, Class declaringClass, - boolean isStatic) { + public ReflectedArgs(Object data, Class<?>[] args, Class<?> declaringClass, boolean isStatic) { this.data = data; this.args = args; this.declaringClass = declaringClass; @@ -129,7 +128,7 @@ return true; } - public static int precedence(Class arg) { + public static int precedence(Class<?> arg) { if (arg == Object.class) { return 3000; } @@ -166,7 +165,7 @@ } if (arg.isArray()) { - Class componentType = arg.getComponentType(); + Class<?> componentType = arg.getComponentType(); if (componentType == Object.class) { return 2500; } @@ -180,7 +179,7 @@ * unimportantly different Returns +/-2 iff arg1 and arg2 are significantly * different */ - public static int compare(Class arg1, Class arg2) { + public static int compare(Class<?> arg1, Class<?> arg2) { int p1 = precedence(arg1); int p2 = precedence(arg2); // Special code if they are both nonprimitives @@ -207,7 +206,7 @@ public static final int REPLACE = 1998; public int compareTo(ReflectedArgs other) { - Class[] oargs = other.args; + Class<?>[] oargs = other.args; // First decision based on flags if (other.flags != this.flags) { @@ -258,6 +257,7 @@ return replace ? REPLACE : 0; } + @Override public String toString() { String s = declaringClass + ", " + isStatic + ", " + flags + ", " + data + "\n"; s = s + "\t("; Modified: trunk/jython/src/org/python/core/codecs.java =================================================================== --- trunk/jython/src/org/python/core/codecs.java 2009-05-30 02:08:23 UTC (rev 6424) +++ trunk/jython/src/org/python/core/codecs.java 2009-05-30 06:00:25 UTC (rev 6425) @@ -1116,7 +1116,7 @@ int input_size = input.length(); int output_size = 0; - ArrayList<Integer> ucs4 = new ArrayList(input_size); + ArrayList<Integer> ucs4 = new ArrayList<Integer>(input_size); int j = 0; for (; j < input_size; j++) { int c = input.charAt(j); This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <pj...@us...> - 2009-06-07 23:36:25
|
Revision: 6466 http://jython.svn.sourceforge.net/jython/?rev=6466&view=rev Author: pjenvey Date: 2009-06-07 23:36:06 +0000 (Sun, 07 Jun 2009) Log Message: ----------- javadoc corrections Modified Paths: -------------- trunk/jython/src/org/python/core/Py.java trunk/jython/src/org/python/core/PyException.java trunk/jython/src/org/python/core/PyFile.java trunk/jython/src/org/python/core/PyObject.java Modified: trunk/jython/src/org/python/core/Py.java =================================================================== --- trunk/jython/src/org/python/core/Py.java 2009-06-07 23:13:56 UTC (rev 6465) +++ trunk/jython/src/org/python/core/Py.java 2009-06-07 23:36:06 UTC (rev 6466) @@ -866,7 +866,7 @@ * Initializes a default PythonInterpreter and runs the code from * {@link PyRunnable#getMain} as __main__ * - * Called by the code generated in {@link Module#addMain()} + * Called by the code generated in {@link org.python.compiler.Module#addMain()} */ public static void runMain(PyRunnable main, String[] args) throws Exception { runMain(new PyRunnableBootstrap(main), args); @@ -875,7 +875,7 @@ /** * Initializes a default PythonInterpreter and runs the code loaded from the * {@link CodeBootstrap} as __main__ Called by the code generated in - * {@link Module#addMain()} + * {@link org.python.compiler.Module#addMain()} */ public static void runMain(CodeBootstrap main, String[] args) throws Exception { @@ -1628,18 +1628,6 @@ boolean linenumbers, boolean printResults, CompilerFlags cflags) { return CompilerFacade.compile(node, name, filename, linenumbers, printResults, cflags); - /* - try { - ByteArrayOutputStream ostream = new ByteArrayOutputStream(); - Module.compile(node, ostream, name, filename, linenumbers, printResults, cflags); - - saveClassFile(name, ostream); - - return BytecodeLoader.makeCode(name, ostream.toByteArray(), filename); - } catch (Throwable t) { - throw ParserFacade.fixParseError(null, t, filename); - } - */ } public static PyCode compile_flags(mod node, String filename, @@ -1658,10 +1646,10 @@ } /** - * Compiles python source code coming from decoded Strings. + * Compiles python source code coming from String (raw bytes) data. * - * DO NOT use this for PyString input. Use - * {@link #compile_flags(byte[], String, String, CompilerFlags)} instead. + * If the String is properly decoded (from PyUnicode) the PyCF_SOURCE_IS_UTF8 flag + * should be specified. */ public static PyCode compile_flags(String data, String filename, CompileMode kind, CompilerFlags cflags) { Modified: trunk/jython/src/org/python/core/PyException.java =================================================================== --- trunk/jython/src/org/python/core/PyException.java 2009-06-07 23:13:56 UTC (rev 6465) +++ trunk/jython/src/org/python/core/PyException.java 2009-06-07 23:36:06 UTC (rev 6466) @@ -166,9 +166,9 @@ * Logic for the raise statement * * @param type the first arg to raise, a type or an instance - * @param value the second arg, the instance of the class or - * arguments to its constructor - * @param tb a traceback object + * @param value the second arg, the instance of the class or arguments to its + * constructor + * @param traceback a traceback object * @return a PyException wrapper */ public static PyException doRaise(PyObject type, PyObject value, PyObject traceback) { Modified: trunk/jython/src/org/python/core/PyFile.java =================================================================== --- trunk/jython/src/org/python/core/PyFile.java 2009-06-07 23:13:56 UTC (rev 6465) +++ trunk/jython/src/org/python/core/PyFile.java 2009-06-07 23:36:06 UTC (rev 6466) @@ -103,8 +103,8 @@ * method <code>file</code> doesn't expose this functionality (<code>open</code> does * albeit deprecated) as it isn't available to regular Python code. To wrap an * InputStream in a file from Python, use - * {@link FileUtil#wrap(InputStream, int)} - * {@link FileUtil#wrap(InputStream)} + * {@link util.FileUtil#wrap(InputStream, int)} + * {@link util.FileUtil#wrap(InputStream)} */ public PyFile(InputStream istream, int bufsize) { this(istream, "<Java InputStream '" + istream + "' as file>", "r", bufsize, true); @@ -124,8 +124,8 @@ * method <code>file</code> doesn't expose this functionality (<code>open</code> does * albeit deprecated) as it isn't available to regular Python code. To wrap an * OutputStream in a file from Python, use - * {@link FileUtil#wrap(OutputStream, int)} - * {@link FileUtil#wrap(OutputStream)} + * {@link util.FileUtil#wrap(OutputStream, int)} + * {@link util.FileUtil#wrap(OutputStream)} */ public PyFile(OutputStream ostream, int bufsize) { this(ostream, "<Java OutputStream '" + ostream + "' as file>", "w", bufsize, true); Modified: trunk/jython/src/org/python/core/PyObject.java =================================================================== --- trunk/jython/src/org/python/core/PyObject.java 2009-06-07 23:13:56 UTC (rev 6465) +++ trunk/jython/src/org/python/core/PyObject.java 2009-06-07 23:36:06 UTC (rev 6466) @@ -904,7 +904,7 @@ * @return the value corresponding to name * @exception Py.AttributeError if the name is not found. * - * @see #__findattr_ex__(PyString) + * @see #__findattr_ex__(String) **/ public final PyObject __getattr__(PyString name) { return __getattr__(name.internedString()); This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <cg...@us...> - 2009-06-23 06:51:14
|
Revision: 6498 http://jython.svn.sourceforge.net/jython/?rev=6498&view=rev Author: cgroves Date: 2009-06-23 06:51:07 +0000 (Tue, 23 Jun 2009) Log Message: ----------- Don't extend PyReflectedField in PyBeanEventProperty. Fixes Issue1377 by keeping PyJavaType from accessing field spuriously on PyBeanEventProperties. Modified Paths: -------------- trunk/jython/src/org/python/core/PyBeanEventProperty.java trunk/jython/src/org/python/core/PyBeanProperty.java trunk/jython/src/org/python/core/PyJavaType.java trunk/jython/src/org/python/core/PyReflectedField.java Modified: trunk/jython/src/org/python/core/PyBeanEventProperty.java =================================================================== --- trunk/jython/src/org/python/core/PyBeanEventProperty.java 2009-06-23 06:21:59 UTC (rev 6497) +++ trunk/jython/src/org/python/core/PyBeanEventProperty.java 2009-06-23 06:51:07 UTC (rev 6498) @@ -9,7 +9,7 @@ import org.python.util.Generic; -public class PyBeanEventProperty extends PyReflectedField { +public class PyBeanEventProperty extends PyObject { private static Map<String, Class<?>> adapterClasses = Generic.map(); @@ -38,6 +38,7 @@ this.eventClass = eventClass; } + @Override public PyObject _doget(PyObject self) { if (self == null) { return this; @@ -65,6 +66,7 @@ return func; } + @Override public boolean _doset(PyObject self, PyObject value) { Object jself = Py.tojava(self, addMethod.getDeclaringClass()); if (!(value instanceof PyCompoundCallable)) { @@ -77,6 +79,7 @@ return true; } + @Override public String toString() { return "<beanEventProperty " + __name__ + " for event " + eventClass.toString() + " " + Py.idstr(this) + ">"; Modified: trunk/jython/src/org/python/core/PyBeanProperty.java =================================================================== --- trunk/jython/src/org/python/core/PyBeanProperty.java 2009-06-23 06:21:59 UTC (rev 6497) +++ trunk/jython/src/org/python/core/PyBeanProperty.java 2009-06-23 06:51:07 UTC (rev 6498) @@ -14,6 +14,7 @@ this.myType = myType; } + @Override public PyObject _doget(PyObject self) { if (self == null) { if (field != null) { @@ -36,6 +37,7 @@ } } + @Override public boolean _doset(PyObject self, PyObject value) { if (self == null) { if (field != null) { @@ -72,6 +74,7 @@ return new PyBeanProperty(__name__, myType, getMethod, setMethod); } + @Override public String toString() { String typeName = "unknown"; if (myType != null) { Modified: trunk/jython/src/org/python/core/PyJavaType.java =================================================================== --- trunk/jython/src/org/python/core/PyJavaType.java 2009-06-23 06:21:59 UTC (rev 6497) +++ trunk/jython/src/org/python/core/PyJavaType.java 2009-06-23 06:51:07 UTC (rev 6498) @@ -56,8 +56,10 @@ super(TYPE == null ? fromClass(PyType.class) : TYPE); } + @Override protected boolean useMetatypeFirst(PyObject attr) { - return !(attr instanceof PyReflectedField || attr instanceof PyReflectedFunction); + return !(attr instanceof PyReflectedField || attr instanceof PyReflectedFunction || + attr instanceof PyBeanEventProperty); } // Java types are ok with things being added and removed from their dicts as long as there isn't Modified: trunk/jython/src/org/python/core/PyReflectedField.java =================================================================== --- trunk/jython/src/org/python/core/PyReflectedField.java 2009-06-23 06:21:59 UTC (rev 6497) +++ trunk/jython/src/org/python/core/PyReflectedField.java 2009-06-23 06:51:07 UTC (rev 6498) @@ -4,7 +4,6 @@ import java.lang.reflect.Field; import java.lang.reflect.Modifier; - public class PyReflectedField extends PyObject { public Field field; @@ -14,6 +13,7 @@ this.field = field; } + @Override public PyObject _doget(PyObject self) { Object iself = null; if (!Modifier.isStatic(field.getModifiers())) { @@ -32,6 +32,7 @@ return Py.java2py(value); } + @Override public boolean _doset(PyObject self, PyObject value) { Object iself = null; if (!Modifier.isStatic(field.getModifiers())) { @@ -51,6 +52,7 @@ return true; } + @Override public String toString() { return "<reflected field "+field.toString()+" "+Py.idstr(this)+">"; } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <th...@us...> - 2009-07-15 02:31:49
|
Revision: 6537 http://jython.svn.sourceforge.net/jython/?rev=6537&view=rev Author: thobes Date: 2009-07-15 02:31:42 +0000 (Wed, 15 Jul 2009) Log Message: ----------- Performance improvements for list multiplication. Modified Paths: -------------- trunk/jython/src/org/python/core/PyList.java trunk/jython/src/org/python/core/PyTuple.java Modified: trunk/jython/src/org/python/core/PyList.java =================================================================== --- trunk/jython/src/org/python/core/PyList.java 2009-07-13 16:32:44 UTC (rev 6536) +++ trunk/jython/src/org/python/core/PyList.java 2009-07-15 02:31:42 UTC (rev 6537) @@ -21,7 +21,7 @@ public class PyList extends PySequenceList implements List { public static final PyType TYPE = PyType.fromClass(PyList.class); - protected final List<PyObject> list; + private final List<PyObject> list; public volatile int gListAllocatedStatus = -1; public PyList() { @@ -77,6 +77,10 @@ return new PyList(list, false); } + List<PyObject> getList() { + return Collections.unmodifiableList(list); + } + private static List<PyObject> listify(Iterator<PyObject> iter) { List<PyObject> list = Generic.list(); while (iter.hasNext()) { @@ -215,11 +219,12 @@ throw Py.MemoryError(""); } - PyList newList = new PyList(); + PyObject[] elements = list.toArray(new PyObject[size]); + PyObject[] newList = new PyObject[newSize]; for (int i = 0; i < count; i++) { - newList.addAll(list); + System.arraycopy(elements, 0, newList, i * size, size); } - return newList; + return new PyList(newList); } @ExposedMethod(type = MethodType.BINARY, doc = BuiltinDocs.list___ne___doc) Modified: trunk/jython/src/org/python/core/PyTuple.java =================================================================== --- trunk/jython/src/org/python/core/PyTuple.java 2009-07-13 16:32:44 UTC (rev 6536) +++ trunk/jython/src/org/python/core/PyTuple.java 2009-07-15 02:31:42 UTC (rev 6537) @@ -461,7 +461,7 @@ @Override public boolean containsAll(Collection c) { if (c instanceof PyList) { - return getList().containsAll(((PyList)c).list); + return getList().containsAll(((PyList)c).getList()); } else if (c instanceof PyTuple) { return getList().containsAll(((PyTuple)c).getList()); } else { This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <nr...@us...> - 2009-07-23 06:31:58
|
Revision: 6570 http://jython.svn.sourceforge.net/jython/?rev=6570&view=rev Author: nriley Date: 2009-07-23 06:31:56 +0000 (Thu, 23 Jul 2009) Log Message: ----------- Restore some accidentally-reverted changes from the JSR 223 merge. Modified Paths: -------------- trunk/jython/src/org/python/core/Py.java trunk/jython/src/org/python/core/PyFinalizableInstance.java Modified: trunk/jython/src/org/python/core/Py.java =================================================================== --- trunk/jython/src/org/python/core/Py.java 2009-07-23 05:16:14 UTC (rev 6569) +++ trunk/jython/src/org/python/core/Py.java 2009-07-23 06:31:56 UTC (rev 6570) @@ -1027,7 +1027,7 @@ stderr.println(getStackTrace((Throwable) javaError)); } } - stderr.println(formatException(type, value, tb)); + stderr.println(formatException(type, value)); } /** @@ -1080,7 +1080,7 @@ out.print("^\n"); } - static String formatException(PyObject type, PyObject value, PyObject tb) { + public static String formatException(PyObject type, PyObject value) { StringBuilder buf = new StringBuilder(); if (PyException.isExceptionClass(type)) { @@ -1106,7 +1106,7 @@ } else { buf.append(type.__str__()); } - if (value != Py.None) { + if (value != null && value != Py.None) { // only print colon if the str() of the object is not the empty string PyObject s = value.__str__(); if (!(s instanceof PyString) || s.__len__() != 0) { Modified: trunk/jython/src/org/python/core/PyFinalizableInstance.java =================================================================== --- trunk/jython/src/org/python/core/PyFinalizableInstance.java 2009-07-23 05:16:14 UTC (rev 6569) +++ trunk/jython/src/org/python/core/PyFinalizableInstance.java 2009-07-23 06:31:56 UTC (rev 6570) @@ -31,7 +31,7 @@ } catch (PyException e) { ; } Py.stderr.println("Exception " + - Py.formatException(exc.type, exc.value, exc.traceback) + + Py.formatException(exc.type, exc.value) + " in " + method + " ignored"); } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <pj...@us...> - 2009-10-04 21:25:59
|
Revision: 6837 http://jython.svn.sourceforge.net/jython/?rev=6837&view=rev Author: pjenvey Date: 2009-10-04 21:25:41 +0000 (Sun, 04 Oct 2009) Log Message: ----------- hack around PyReflectedFunction's assumption of how instancemethod calls into it so instancemethod's ThreadState pass through optimization can be enabled Modified Paths: -------------- trunk/jython/src/org/python/core/PyMethod.java trunk/jython/src/org/python/core/PyReflectedConstructor.java trunk/jython/src/org/python/core/PyReflectedFunction.java trunk/jython/src/org/python/core/ReflectedArgs.java Modified: trunk/jython/src/org/python/core/PyMethod.java =================================================================== --- trunk/jython/src/org/python/core/PyMethod.java 2009-10-04 20:16:12 UTC (rev 6836) +++ trunk/jython/src/org/python/core/PyMethod.java 2009-10-04 21:25:41 UTC (rev 6837) @@ -94,7 +94,7 @@ return this; } } - /*// This has been disabled since JavaFunc expects to be called with self + boxed args + @Override public PyObject __call__() { return __call__(Py.getThreadState()); @@ -146,8 +146,7 @@ } @Override - public PyObject __call__(ThreadState state, PyObject arg0, PyObject arg1, - PyObject arg2) { + public PyObject __call__(ThreadState state, PyObject arg0, PyObject arg1, PyObject arg2) { PyObject self = checkSelf(arg0, null); if (self == null) { return im_func.__call__(state, arg0, arg1, arg2); @@ -162,17 +161,17 @@ } @Override - public PyObject __call__(ThreadState state, PyObject arg0, PyObject arg1, - PyObject arg2, PyObject arg3) { + public PyObject __call__(ThreadState state, PyObject arg0, PyObject arg1, PyObject arg2, + PyObject arg3) { PyObject self = checkSelf(arg0, null); if (self == null) { return im_func.__call__(state, arg0, arg1, arg2, arg3); } else { - return im_func.__call__(state, self, new PyObject[]{arg0, arg1, arg2, arg3}, Py.NoKeywords); + return im_func.__call__(state, self, new PyObject[]{arg0, arg1, arg2, arg3}, + Py.NoKeywords); } } - @Override public PyObject __call__(PyObject arg1, PyObject[] args, String[] keywords) { return __call__(Py.getThreadState(), arg1, args, keywords); @@ -180,15 +179,15 @@ @Override public PyObject __call__(ThreadState state, PyObject arg1, PyObject[] args, - String[] keywords) { + String[] keywords) { PyObject self = checkSelf(arg1, args); if (self == null) { return im_func.__call__(state, arg1, args, keywords); } else { - PyObject[] new_args = new PyObject[args.length+1]; - System.arraycopy(args, 0, new_args, 1, args.length); - new_args[0] = arg1; - return im_func.__call__(state, self, new_args, keywords); + PyObject[] newArgs = new PyObject[args.length + 1]; + System.arraycopy(args, 0, newArgs, 1, args.length); + newArgs[0] = arg1; + return im_func.__call__(state, self, newArgs, keywords); } } @@ -201,14 +200,19 @@ public PyObject __call__(ThreadState state, PyObject[] args) { return __call__(state, args, Py.NoKeywords); } - */ + @Override public PyObject __call__(PyObject[] args, String[] keywords) { - return instancemethod___call__(args, keywords); + return __call__(Py.getThreadState(), args, keywords); } @Override public PyObject __call__(ThreadState state, PyObject[] args, String[] keywords) { + return instancemethod___call__(state, args, keywords); + } + + @ExposedMethod(doc = BuiltinDocs.instancemethod___call___doc) + final PyObject instancemethod___call__(ThreadState state, PyObject[] args, String[] keywords) { PyObject self = checkSelf(null, args); if (self == null) { return im_func.__call__(state, args, keywords); @@ -216,11 +220,6 @@ return im_func.__call__(state, self, args, keywords); } } - - @ExposedMethod(doc = BuiltinDocs.instancemethod___call___doc) - final PyObject instancemethod___call__(PyObject[] args, String[] keywords) { - return __call__(Py.getThreadState(), args, keywords); - } private PyObject checkSelf(PyObject arg, PyObject[] args) { PyObject self = im_self; Modified: trunk/jython/src/org/python/core/PyReflectedConstructor.java =================================================================== --- trunk/jython/src/org/python/core/PyReflectedConstructor.java 2009-10-04 20:16:12 UTC (rev 6836) +++ trunk/jython/src/org/python/core/PyReflectedConstructor.java 2009-10-04 21:25:41 UTC (rev 6837) @@ -77,6 +77,7 @@ return obj; } + @Override public PyObject __call__(PyObject self, PyObject[] args, String[] keywords) { if (self == null) { throw Py.TypeError("invalid self argument to constructor"); @@ -144,6 +145,7 @@ return Py.None; } + @Override public PyObject __call__(PyObject[] args, String[] keywords) { if (args.length < 1) { throw Py.TypeError("constructor requires self argument"); @@ -180,6 +182,15 @@ obj.javaProxy = jself; } + @Override + public PyObject _doget(PyObject container, PyObject wherefound) { + if (container == null) { + return this; + } + return new PyMethod(this, container, wherefound); + } + + @Override public String toString() { // printArgs(); return "<java constructor " + __name__ + " " + Py.idstr(this) + ">"; Modified: trunk/jython/src/org/python/core/PyReflectedFunction.java =================================================================== --- trunk/jython/src/org/python/core/PyReflectedFunction.java 2009-10-04 20:16:12 UTC (rev 6836) +++ trunk/jython/src/org/python/core/PyReflectedFunction.java 2009-10-04 21:25:41 UTC (rev 6837) @@ -17,6 +17,9 @@ public int nargs; + /** Whether __call__ should act as if this is called as a static method. */ + private boolean calledStatically; + protected PyReflectedFunction(String name) { __name__ = name; } @@ -35,17 +38,22 @@ } } + @Override public PyObject _doget(PyObject container) { return _doget(container, null); } + @Override public PyObject _doget(PyObject container, PyObject wherefound) { + // NOTE: this calledStatically business is pretty hacky if (container == null) { - return this; + return calledStatically ? this : copyWithCalledStatically(true); } - return new PyMethod(this, container, wherefound); + return new PyMethod(calledStatically ? copyWithCalledStatically(false) : this, + container, wherefound); } + @Override public PyObject getDoc() { return __doc__; } @@ -66,6 +74,12 @@ return func; } + private PyReflectedFunction copyWithCalledStatically(boolean calledStatically) { + PyReflectedFunction copy = copy(); + copy.calledStatically = calledStatically; + return copy; + } + public boolean handles(Method method) { return handles(makeArgs(method)); } @@ -143,6 +157,7 @@ nargs = nn; } + @Override public PyObject __call__(PyObject self, PyObject[] args, String[] keywords) { ReflectedCallData callData = new ReflectedCallData(); ReflectedArgs match = null; @@ -179,14 +194,17 @@ return Py.java2py(o); } + @Override public PyObject __call__(PyObject[] args, String[] keywords) { - PyObject self = null; - /* - PyObject[] new_args = new PyObject[args.length - 1]; - System.arraycopy(args, 1, new_args, 0, new_args.length); - self = args[0]; - args = new_args; - */ + PyObject self; + if (calledStatically) { + self = null; + } else { + PyObject[] unboundArgs = new PyObject[args.length - 1]; + System.arraycopy(args, 1, unboundArgs, 0, unboundArgs.length); + self = args[0]; + args = unboundArgs; + } return __call__(self, args, keywords); } @@ -317,8 +335,8 @@ } } + @Override public String toString() { - // printArgs(); return "<java function " + __name__ + " " + Py.idstr(this) + ">"; } } Modified: trunk/jython/src/org/python/core/ReflectedArgs.java =================================================================== --- trunk/jython/src/org/python/core/ReflectedArgs.java 2009-10-04 20:16:12 UTC (rev 6836) +++ trunk/jython/src/org/python/core/ReflectedArgs.java 2009-10-04 21:25:41 UTC (rev 6837) @@ -50,12 +50,6 @@ */ if (this.isStatic) { if (self != null) { - /* - PyObject[] newArgs = new PyObject[pyArgs.length+1]; - System.arraycopy(pyArgs, 0, newArgs, 1, pyArgs.length); - newArgs[0] = self; - pyArgs = newArgs; - //*/ self = null; } } else { This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <pj...@us...> - 2009-10-12 05:04:59
|
Revision: 6853 http://jython.svn.sourceforge.net/jython/?rev=6853&view=rev Author: pjenvey Date: 2009-10-12 05:04:37 +0000 (Mon, 12 Oct 2009) Log Message: ----------- port Armin Rigo's global mro cache optimization from PyPy/CPython 2.6. unlike their's this version is thread safe (non-blocking). being global, it may become less optimal when shared by many PythonInterpreters/PySystemStates this provides a nice attribute lookup speedup but it can slow down silly things like class attribute counters (maybe due to our extra allocation around the cache invalidation) refs http://bugs.python.org/issue1700288 Modified Paths: -------------- trunk/jython/src/org/python/core/PyJavaType.java trunk/jython/src/org/python/core/PyType.java Modified: trunk/jython/src/org/python/core/PyJavaType.java =================================================================== --- trunk/jython/src/org/python/core/PyJavaType.java 2009-10-10 06:05:26 UTC (rev 6852) +++ trunk/jython/src/org/python/core/PyJavaType.java 2009-10-12 05:04:37 UTC (rev 6853) @@ -421,7 +421,7 @@ // 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 fromType[] = new PyObject[] { null }; - PyObject superForName = lookup_where(prop.__name__, fromType); + PyObject superForName = lookup_where_mro(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 @@ -608,7 +608,7 @@ } String nmethname = normalize(meth.getName()); PyObject[] where = new PyObject[1]; - PyObject obj = lookup_where(nmethname, where); + PyObject obj = lookup_where_mro(nmethname, where); if (obj == null) { // Nothing in our supertype hierarchy defines something with this name, so it // must not be visible there. Modified: trunk/jython/src/org/python/core/PyType.java =================================================================== --- trunk/jython/src/org/python/core/PyType.java 2009-10-10 06:05:26 UTC (rev 6852) +++ trunk/jython/src/org/python/core/PyType.java 2009-10-12 05:04:37 UTC (rev 6853) @@ -9,6 +9,7 @@ import java.util.List; import java.util.Map; import java.util.Set; +import java.util.concurrent.atomic.AtomicReferenceArray; import org.python.expose.ExposeAsSuperclass; import org.python.expose.ExposedDelete; @@ -81,12 +82,18 @@ /** Whether this type's __getattribute__ is object.__getattribute__. */ private volatile boolean usesObjectGetattribute; + /** MethodCacheEntry version tag. */ + private volatile Object versionTag = new Object(); + /** The number of __slots__ defined. */ private int numSlots; private ReferenceQueue<PyType> subclasses_refq = new ReferenceQueue<PyType>(); private Set<WeakReference<PyType>> subclasses = Generic.set(); + /** Global mro cache. */ + private static final MethodCache methodCache = new MethodCache(); + /** Mapping of Java classes to their PyTypes. */ private static Map<Class<?>, PyType> class_to_type; @@ -185,6 +192,7 @@ type.createAllSlots(!base.needs_userdict, !base.needs_weakref); type.ensureAttributes(); + type.invalidateMethodCache(); for (PyObject cur : type.bases) { if (cur instanceof PyType) @@ -277,7 +285,7 @@ if (wantWeak) { createWeakrefSlot(); } - needs_finalizer = lookup("__del__") != null; + needs_finalizer = lookup_mro("__del__") != null; } /** @@ -494,8 +502,8 @@ } private void fillHasSetAndDelete() { - has_set = lookup("__set__") != null; - has_delete = lookup("__delete__") != null; + has_set = lookup_mro("__set__") != null; + has_delete = lookup_mro("__delete__") != null; } public PyObject getStatic() { @@ -1042,17 +1050,50 @@ } /** - * INTERNAL lookup for name through mro objects' dicts + * Attribute lookup for name through mro objects' dicts. Lookups are cached. * - * @param name - * attribute name (must be interned) + * @param name attribute name (must be interned) * @return found object or null */ public PyObject lookup(String name) { return lookup_where(name, null); } + /** + * Attribute lookup for name directly through mro objects' dicts. This isn't cached, + * and should generally only be used during the bootstrapping of a type. + * + * @param name attribute name (must be interned) + * @return found object or null + */ + protected PyObject lookup_mro(String name) { + return lookup_where_mro(name, null); + } + + /** + * Attribute lookup for name through mro objects' dicts. Lookups are cached. + * + * Returns where in the mro the attribute was found at where[0]. + * + * @param name attribute name (must be interned) + * @param where Where in the mro the attribute was found is written to index 0 + * @return found object or null + */ public PyObject lookup_where(String name, PyObject[] where) { + return methodCache.lookup_where(this, name, where); + } + + /** + * Attribute lookup for name through mro objects' dicts. This isn't cached, and should + * generally only be used during the bootstrapping of a type. + * + * Returns where in the mro the attribute was found at where[0]. + * + * @param name attribute name (must be interned) + * @param where Where in the mro the attribute was found is written to index 0 + * @return found object or null + */ + protected PyObject lookup_where_mro(String name, PyObject[] where) { PyObject[] mro = this.mro; if (mro == null) { return null; @@ -1176,7 +1217,8 @@ class_to_type.put(c, newtype); newtype.builtin = true; - newtype.init(c,needsInners); + newtype.init(c, needsInners); + newtype.invalidateMethodCache(); return newtype; } @@ -1313,6 +1355,7 @@ } void postSetattr(String name) { + invalidateMethodCache(); if (name == "__set__") { if (!has_set && lookup("__set__") != null) { traverse_hierarchy(false, new OnType() { @@ -1363,8 +1406,8 @@ postDelattr(name); } - void postDelattr(String name) { + invalidateMethodCache(); if (name == "__set__") { if (has_set && lookup("__set__") == null) { traverse_hierarchy(false, new OnType() { @@ -1400,6 +1443,19 @@ } } + /** + * Invalidate this type's MethodCache entries. *Must* be called after any modification + * to __dict__ (or anything else affecting attribute lookups). + */ + protected void invalidateMethodCache() { + traverse_hierarchy(false, new OnType() { + public boolean onType(PyType type) { + type.versionTag = new Object(); + return false; + } + }); + } + public PyObject __call__(PyObject[] args, String[] keywords) { return type___call__(args, keywords); } @@ -1449,6 +1505,7 @@ throw Py.ValueError("__name__ must not contain null bytes"); } setName(nameStr); + invalidateMethodCache(); } public void setName(String name) { @@ -1701,4 +1758,107 @@ mro = newMro.toArray(new PyObject[newMro.size()]); } } + + /** + * A thead safe, non-blocking version of Armin Rigo's mro cache. + */ + static class MethodCache { + + /** The fixed size cache. */ + private final AtomicReferenceArray<MethodCacheEntry> table; + + /** Size of the cache exponent (2 ** SIZE_EXP). */ + public static final int SIZE_EXP = 11; + + public MethodCache() { + table = new AtomicReferenceArray<MethodCacheEntry>(1 << SIZE_EXP); + clear(); + } + + public void clear() { + int length = table.length(); + for (int i = 0; i < length; i++) { + table.set(i, MethodCacheEntry.EMPTY); + } + } + + public PyObject lookup_where(PyType type, String name, PyObject where[]) { + Object versionTag = type.versionTag; + int index = indexFor(versionTag, name); + MethodCacheEntry entry = table.get(index); + + if (entry.isValid(versionTag, name)) { + return entry.get(where); + } + + // Always cache where + if (where == null) { + where = new PyObject[1]; + } + PyObject value = type.lookup_where_mro(name, where); + if (isCacheableName(name)) { + // CAS isn't totally necessary here but is possibly more correct. Cache by + // the original version before the lookup, if it's changed since then + // we'll cache a bad entry. Bad entries and CAS failures aren't a concern + // as subsequent lookups will sort themselves out + table.compareAndSet(index, entry, new MethodCacheEntry(versionTag, name, where[0], + value)); + } + return value; + } + + /** + * Return the table index for type version/name. + */ + private static int indexFor(Object version, String name) { + long hash = version.hashCode() * name.hashCode(); + return (int)hash >>> (Integer.SIZE - SIZE_EXP); + } + + /** + * Determine if name is cacheable. + * + * Since the cache can keep references to names alive longer than usual, it avoids + * caching unusually large strings. + */ + private static boolean isCacheableName(String name) { + return name.length() <= 100; + } + + static class MethodCacheEntry extends WeakReference<PyObject> { + + /** Version of the entry, a PyType.versionTag. */ + private final Object version; + + /** The name of the attribute. */ + private final String name; + + /** Where in the mro the value was found. */ + private final WeakReference<PyObject> where; + + static final MethodCacheEntry EMPTY = new MethodCacheEntry(); + + private MethodCacheEntry() { + this(null, null, null, null); + } + + public MethodCacheEntry(Object version, String name, PyObject where, PyObject value) { + super(value); + this.version = version; + this.name = name; + this.where = new WeakReference<PyObject>(where); + } + + public boolean isValid(Object version, String name) { + return this.version == version && this.name == name; + } + + public PyObject get(PyObject[] where) { + if (where != null) { + where[0] = this.where.get(); + } + return get(); + } + } + } } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <pj...@us...> - 2009-10-13 02:32:07
|
Revision: 6854 http://jython.svn.sourceforge.net/jython/?rev=6854&view=rev Author: pjenvey Date: 2009-10-13 02:31:45 +0000 (Tue, 13 Oct 2009) Log Message: ----------- move the cached objectGetattribute out of PyObject to ease bootstrapping Modified Paths: -------------- trunk/jython/src/org/python/core/Deriveds.java trunk/jython/src/org/python/core/PyObject.java Modified: trunk/jython/src/org/python/core/Deriveds.java =================================================================== --- trunk/jython/src/org/python/core/Deriveds.java 2009-10-12 05:04:37 UTC (rev 6853) +++ trunk/jython/src/org/python/core/Deriveds.java 2009-10-13 02:31:45 UTC (rev 6854) @@ -6,8 +6,12 @@ */ public class Deriveds { + /** object.__getattribute__ descriptor, cached for use by __findattr_ex__. */ + private static final PyObject objectGetattribute = + PyObject.TYPE.__findattr__("__getattribute__"); + /** - * Derived's __findattr_ex__ implementation. + * Deriveds' __findattr_ex__ implementation. * * This resides here (in org.python.core) because it manipulates PyType, and doesn't * call any of the Derived classes' superclass methods. @@ -34,7 +38,7 @@ type.getName())); } - if (getattribute == PyObject.objectGetattribute) { + if (getattribute == objectGetattribute) { type.setUsesObjectGetattribute(true); } pyName = PyString.fromInterned(name); Modified: trunk/jython/src/org/python/core/PyObject.java =================================================================== --- trunk/jython/src/org/python/core/PyObject.java 2009-10-12 05:04:37 UTC (rev 6853) +++ trunk/jython/src/org/python/core/PyObject.java 2009-10-13 02:31:45 UTC (rev 6854) @@ -38,9 +38,6 @@ /** Primitives classes their wrapper classes. */ private static final Map<Class<?>, Class<?>> primitiveMap = Generic.map(); - /** object.__getattribute__ descriptor, cached for use by Deriveds.__findattr_ex__. */ - static final PyObject objectGetattribute; - static { primitiveMap.put(Character.TYPE, Character.class); primitiveMap.put(Boolean.TYPE, Boolean.class); @@ -55,8 +52,6 @@ Py.writeWarning("init", "Bootstrap types weren't encountered in bootstrapping: " + Py.BOOTSTRAP_TYPES); } - - objectGetattribute = TYPE.__findattr__("__getattribute__"); } public PyObject(PyType objtype) { This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <pj...@us...> - 2009-10-28 06:52:41
|
Revision: 6924 http://jython.svn.sourceforge.net/jython/?rev=6924&view=rev Author: pjenvey Date: 2009-10-28 06:52:33 +0000 (Wed, 28 Oct 2009) Log Message: ----------- o further cleanup delattr/setattr handling of names o replace PyMapping_check with isMappingType o PyObject.__len__ can now safely throw TypeErrors instead of AttributeErrors, for the benefit of builtin len Modified Paths: -------------- trunk/jython/src/org/python/core/PyObject.java trunk/jython/src/org/python/core/PySlice.java trunk/jython/src/org/python/core/__builtin__.java Modified: trunk/jython/src/org/python/core/PyObject.java =================================================================== --- trunk/jython/src/org/python/core/PyObject.java 2009-10-28 03:04:56 UTC (rev 6923) +++ trunk/jython/src/org/python/core/PyObject.java 2009-10-28 06:52:33 UTC (rev 6924) @@ -561,7 +561,8 @@ * @return the length of the object **/ public int __len__() { - throw Py.AttributeError("__len__"); + throw Py.TypeError(String.format("object of type '%.200s' has no len()", + getType().fastGetName())); } /** Modified: trunk/jython/src/org/python/core/PySlice.java =================================================================== --- trunk/jython/src/org/python/core/PySlice.java 2009-10-28 03:04:56 UTC (rev 6923) +++ trunk/jython/src/org/python/core/PySlice.java 2009-10-28 06:52:33 UTC (rev 6924) @@ -192,7 +192,7 @@ istop += len; } } catch (PyException pye) { - if (!pye.match(Py.AttributeError)) { + if (!pye.match(Py.TypeError)) { throw pye; } } Modified: trunk/jython/src/org/python/core/__builtin__.java =================================================================== --- trunk/jython/src/org/python/core/__builtin__.java 2009-10-28 03:04:56 UTC (rev 6923) +++ trunk/jython/src/org/python/core/__builtin__.java 2009-10-28 06:52:33 UTC (rev 6924) @@ -86,11 +86,7 @@ case 18: return __builtin__.eval(arg1); case 19: - try { - __builtin__.execfile(arg1.asString(0)); - } catch (ConversionException e) { - throw Py.TypeError("execfile's first argument must be str"); - } + __builtin__.execfile(arg1.asString()); return Py.None; case 23: return __builtin__.hex(arg1); @@ -149,19 +145,14 @@ case 13: return __builtin__.coerce(arg1, arg2); case 15: - __builtin__.delattr(arg1, asString(arg2, - "delattr(): attribute name must be string")); + __builtin__.delattr(arg1, arg2); return Py.None; case 17: return __builtin__.divmod(arg1, arg2); case 18: return __builtin__.eval(arg1, arg2); case 19: - try { - __builtin__.execfile(arg1.asString(0), arg2); - } catch (ConversionException e) { - throw Py.TypeError("execfile's first argument must be str"); - } + __builtin__.execfile(arg1.asString(), arg2); return Py.None; case 20: return __builtin__.filter(arg1, arg2); @@ -202,9 +193,6 @@ d.update(arg3); arg3 = d; } - // this catches both casts of arg3 to a PyDictionary, and - // all casts of keys in the dictionary to PyStrings inside - // apply(PyObject, PyObject, PyDictionary) PyDictionary d = (PyDictionary) arg3; return __builtin__.apply(arg1, arg2, d); } catch (ClassCastException e) { @@ -214,8 +202,7 @@ case 18: return __builtin__.eval(arg1, arg2, arg3); case 19: - __builtin__.execfile(asString(arg1, "execfile's first argument must be str", - false), arg2, arg3); + __builtin__.execfile(arg1.asString(), arg2, arg3); return Py.None; case 21: return __builtin__.getattr(arg1, arg2, arg3); @@ -224,9 +211,7 @@ case 35: return __builtin__.reduce(arg1, arg2, arg3); case 39: - __builtin__.setattr(arg1, asString(arg2, - "setattr(): attribute name must be string"), - arg3); + __builtin__.setattr(arg1, arg2, arg3); return Py.None; case 44: return fancyCall(new PyObject[] {arg1, arg2, arg3}); @@ -243,28 +228,6 @@ } } - /** - * @return arg as an interned String, or throws TypeError with mesage if asString - * throws a ConversionException - */ - private String asString(PyObject arg, String message) { - return asString(arg, message, true); - } - - /** - * @param intern - should the resulting string be interned - * @return arg as a String, or throws TypeError with message if asString throws a - * ConversionException. - */ - private String asString(PyObject arg, String message, boolean intern) { - - try { - return intern ? arg.asString(0).intern() : arg.asString(0); - } catch (ConversionException e) { - throw Py.TypeError(message); - } - } - @Override public PyObject __call__(PyObject arg1, PyObject arg2, PyObject arg3, PyObject arg4) { switch (this.index) { @@ -465,8 +428,8 @@ throw Py.TypeError("number coercion failed"); } - public static void delattr(PyObject o, String n) { - o.__delattr__(n); + public static void delattr(PyObject obj, PyObject name) { + obj.__delattr__(asName(name, "delattr")); } public static PyObject dir(PyObject o) { @@ -493,25 +456,21 @@ return x._divmod(y); } - private static boolean PyMapping_check(PyObject o, boolean rw) { - return o == null || - o == Py.None || - (o instanceof PyDictionary) || - (o.__findattr__("__getitem__") != null && - (!rw || o.__findattr__("__setitem__") != null)); + private static boolean isMappingType(PyObject o) { + return o == null || o == Py.None || o.isMappingType(); } - private static void verify_mappings(PyObject globals, PyObject locals, boolean rw) { - if (!PyMapping_check(globals, rw)) { + private static void verify_mappings(PyObject globals, PyObject locals) { + if (!isMappingType(globals)) { throw Py.TypeError("globals must be a mapping"); } - if (!PyMapping_check(locals, rw)) { + if (!isMappingType(locals)) { throw Py.TypeError("locals must be a mapping"); } } public static PyObject eval(PyObject o, PyObject globals, PyObject locals) { - verify_mappings(globals, locals, false); + verify_mappings(globals, locals); PyCode code; if (o instanceof PyCode) { code = (PyCode) o; @@ -542,7 +501,7 @@ public static void execfile_flags(String name, PyObject globals, PyObject locals, CompilerFlags cflags) { - verify_mappings(globals, locals, true); + verify_mappings(globals, locals); FileInputStream file; try { file = new FileInputStream(new RelativeFile(name)); @@ -652,17 +611,9 @@ return getattr(obj, name, null); } - public static PyObject getattr(PyObject obj, PyObject name, PyObject def) { - String nameStr; - if (name instanceof PyUnicode) { - nameStr = ((PyUnicode)name).encode().intern(); - } else if (name instanceof PyString) { - nameStr = ((PyString)name).internedString(); - } else { - throw Py.TypeError("getattr(): attribute name must be string"); - } - - PyObject result = obj.__findattr__(nameStr); + public static PyObject getattr(PyObject obj, PyObject nameObj, PyObject def) { + String name = asName(nameObj, "getattr"); + PyObject result = obj.__findattr__(name); if (result != null) { return result; } @@ -670,7 +621,7 @@ return def; } // throws AttributeError - obj.noAttributeError(nameStr); + obj.noAttributeError(name); return null; } @@ -678,18 +629,10 @@ return Py.getFrame().f_globals; } - public static boolean hasattr(PyObject obj, PyObject name) { - String nameStr; - if (name instanceof PyUnicode) { - nameStr = ((PyUnicode)name).encode().intern(); - } else if (name instanceof PyString) { - nameStr = ((PyString)name).internedString(); - } else { - throw Py.TypeError("hasattr(): attribute name must be string"); - } - + public static boolean hasattr(PyObject obj, PyObject nameObj) { + String name = asName(nameObj, "hasattr"); try { - return obj.__findattr__(nameStr) != null; + return obj.__findattr__(name) != null; } catch (PyException pye) { // swallow } @@ -753,24 +696,8 @@ return new PyCallIter(callable, sentinel); } - public static int len(PyObject o) { - try { - return o.__len__(); - } catch (PyException e) { - // Make this work like CPython where - // - // a = 7; len(a) raises a TypeError, - // a.__len__() raises an AttributeError - // and - // class F: pass - // f = F(); len(f) also raises an AttributeError - // - // Testing the type of o feels unclean though - if (e.type == Py.AttributeError && !(o instanceof PyInstance)) { - throw Py.TypeError("len() of unsized object"); - } - throw e; - } + public static int len(PyObject obj) { + return obj.__len__(); } public static PyObject locals() { @@ -1094,8 +1021,8 @@ return o.__repr__(); } - public static void setattr(PyObject o, String n, PyObject v) { - o.__setattr__(n, v); + public static void setattr(PyObject obj, PyObject name, PyObject value) { + obj.__setattr__(asName(name, "setattr"), value); } public static PyObject sum(PyObject seq, PyObject result) { @@ -1225,6 +1152,22 @@ fromlist, Py.newInteger(level)}); return module; } + + /** + * Return an interned String from name, raising a TypeError when conversion fails. + * + * @param name a PyObject + * @param function name of the python function caller + * @return an interned String + */ + private static String asName(PyObject name, String function) { + if (name instanceof PyUnicode) { + return ((PyUnicode)name).encode().intern(); + } else if (name instanceof PyString) { + return ((PyString)name).internedString(); + } + throw Py.TypeError(function + "(): attribute name must be string"); + } } class ImportFunction extends PyBuiltinFunction { This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <pj...@us...> - 2009-10-29 06:59:18
|
Revision: 6931 http://jython.svn.sourceforge.net/jython/?rev=6931&view=rev Author: pjenvey Date: 2009-10-29 06:58:50 +0000 (Thu, 29 Oct 2009) Log Message: ----------- base the initial CHM capacity off the passed in Map Modified Paths: -------------- trunk/jython/src/org/python/core/PyDictionary.java trunk/jython/src/org/python/core/PyStringMap.java Modified: trunk/jython/src/org/python/core/PyDictionary.java =================================================================== --- trunk/jython/src/org/python/core/PyDictionary.java 2009-10-29 04:57:43 UTC (rev 6930) +++ trunk/jython/src/org/python/core/PyDictionary.java 2009-10-29 06:58:50 UTC (rev 6931) @@ -13,6 +13,7 @@ import java.util.Map.Entry; import java.util.Set; import java.util.concurrent.ConcurrentMap; +import java.util.concurrent.ConcurrentHashMap; import org.python.expose.ExposedClassMethod; import org.python.expose.ExposedMethod; @@ -36,34 +37,40 @@ * Create an empty dictionary. */ public PyDictionary() { - super(TYPE); - table = Generic.concurrentMap(); + this(TYPE); } /** + * Create a dictionary of type with the specified initial capacity. + */ + public PyDictionary(PyType type, int capacity) { + super(type); + table = new ConcurrentHashMap<PyObject, PyObject>(capacity, Generic.CHM_LOAD_FACTOR, + Generic.CHM_CONCURRENCY_LEVEL); + } + + /** * For derived types */ - public PyDictionary(PyType subtype) { - super(subtype); + public PyDictionary(PyType type) { + super(type); table = Generic.concurrentMap(); } /** * Create a new dictionary which is based on given map. */ - public PyDictionary(Map<PyObject, PyObject> t) { - super(TYPE); - table = Generic.concurrentMap(); - table.putAll(t); + public PyDictionary(Map<PyObject, PyObject> map) { + this(TYPE, map); } /** * Create a new derived dictionary which is based on the given map. */ - public PyDictionary(PyType subtype, Map<PyObject, PyObject> t) { - super(subtype); - table = Generic.concurrentMap(); - table.putAll(t); + public PyDictionary(PyType type, Map<PyObject, PyObject> map) { + this(type, Math.max((int) (map.size() / Generic.CHM_LOAD_FACTOR) + 1, + Generic.CHM_INITIAL_CAPACITY)); + table.putAll(map); } Modified: trunk/jython/src/org/python/core/PyStringMap.java =================================================================== --- trunk/jython/src/org/python/core/PyStringMap.java 2009-10-29 04:57:43 UTC (rev 6930) +++ trunk/jython/src/org/python/core/PyStringMap.java 2009-10-29 06:58:50 UTC (rev 6931) @@ -44,8 +44,8 @@ } public PyStringMap(Map<Object, PyObject> map) { - super(getLazyType()); - table = Generic.concurrentMap(); + this(Math.max((int) (map.size() / Generic.CHM_LOAD_FACTOR) + 1, + Generic.CHM_INITIAL_CAPACITY)); table.putAll(map); } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <pj...@us...> - 2009-10-30 23:53:43
|
Revision: 6934 http://jython.svn.sourceforge.net/jython/?rev=6934&view=rev Author: pjenvey Date: 2009-10-30 23:53:24 +0000 (Fri, 30 Oct 2009) Log Message: ----------- remove the unneeded Generics workaround and always specify the cached TYPE to BaseSet Modified Paths: -------------- trunk/jython/src/org/python/core/BaseSet.java trunk/jython/src/org/python/core/PyFrozenSet.java trunk/jython/src/org/python/core/PySet.java Modified: trunk/jython/src/org/python/core/BaseSet.java =================================================================== --- trunk/jython/src/org/python/core/BaseSet.java 2009-10-30 01:34:16 UTC (rev 6933) +++ trunk/jython/src/org/python/core/BaseSet.java 2009-10-30 23:53:24 UTC (rev 6934) @@ -12,12 +12,8 @@ protected Set<PyObject> _set; /** - * Create a new Python set instance from the specified Set object. + * Create a new Python set of type from the specified Set object. */ - protected BaseSet(Set<PyObject> set) { - _set = set; - } - protected BaseSet(PyType type, Set<PyObject> set) { super(type); _set = set; Modified: trunk/jython/src/org/python/core/PyFrozenSet.java =================================================================== --- trunk/jython/src/org/python/core/PyFrozenSet.java 2009-10-30 01:34:16 UTC (rev 6933) +++ trunk/jython/src/org/python/core/PyFrozenSet.java 2009-10-30 23:53:24 UTC (rev 6934) @@ -15,11 +15,11 @@ public static final PyType TYPE = PyType.fromClass(PyFrozenSet.class); public PyFrozenSet() { - super(new HashSet<PyObject>()); + super(TYPE, new HashSet<PyObject>()); } public PyFrozenSet(PyObject data) { - super(_update(new HashSet<PyObject>(), data)); + this(TYPE, data); } public PyFrozenSet(PyType type, PyObject data) { Modified: trunk/jython/src/org/python/core/PySet.java =================================================================== --- trunk/jython/src/org/python/core/PySet.java 2009-10-30 01:34:16 UTC (rev 6933) +++ trunk/jython/src/org/python/core/PySet.java 2009-10-30 23:53:24 UTC (rev 6934) @@ -2,7 +2,6 @@ import java.util.Iterator; import java.util.NoSuchElementException; -import java.util.Set; import org.python.expose.ExposedMethod; import org.python.expose.ExposedNew; @@ -16,22 +15,17 @@ public static final PyType TYPE = PyType.fromClass(PySet.class); public PySet() { - super(concurrentSet()); + this(TYPE); } public PySet(PyType type) { - super(type, concurrentSet()); + super(type, Generic.<PyObject>concurrentSet()); } public PySet(PyObject data) { - super(_update(concurrentSet(), data)); + super(TYPE, _update(Generic.<PyObject>concurrentSet(), data)); } - /** Contextualize the needed Set<PyObject> type paramaters (generics workaround). */ - private static Set<PyObject> concurrentSet() { - return Generic.concurrentSet(); - } - @ExposedNew @ExposedMethod(doc = BuiltinDocs.set___init___doc) final void set___init__(PyObject[] args, String[] kwds) { This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <le...@us...> - 2010-01-30 16:07:07
|
Revision: 6970 http://jython.svn.sourceforge.net/jython/?rev=6970&view=rev Author: leosoto Date: 2010-01-30 16:06:59 +0000 (Sat, 30 Jan 2010) Log Message: ----------- Cleanup of class-loading strategy SyspathJavaLoader is now a delegating classloader. Its parent is the context class loader, for backwards compatibility. And when sys.classLoader is set, it willdelegate to it, WITHOUT searching on sys.path, but after the regular parent delegation. The parent of SyspathJavaLoader is determined by imp.getParentClassLoader, to allow other class loading components to use a consistent parent. Refactored findClass/findClassEx to eliminate code duplications and to use: - only sys.classLoader if it is set - SyspathJavaLoader if it can be used - SyspathJavaLoader's parent if SyspathJavaLoader can't be used - Class.forName(String) as a last resort Refactored ClassPathImporter to use SyspathJavaLoader's parent if sys.classLoader is not set. Modified Paths: -------------- trunk/jython/src/org/python/core/ClasspathPyImporter.java trunk/jython/src/org/python/core/Py.java trunk/jython/src/org/python/core/SyspathJavaLoader.java trunk/jython/src/org/python/core/imp.java Modified: trunk/jython/src/org/python/core/ClasspathPyImporter.java =================================================================== --- trunk/jython/src/org/python/core/ClasspathPyImporter.java 2010-01-30 10:14:30 UTC (rev 6969) +++ trunk/jython/src/org/python/core/ClasspathPyImporter.java 2010-01-30 16:06:59 UTC (rev 6970) @@ -89,13 +89,12 @@ if (entries.containsKey(filename)) { return filename; } - InputStream is = tryClassLoader(filename, Py.getSystemState().getClassLoader(), "sys"); - if (is == null) { - is = tryClassLoader(filename, Thread.currentThread().getContextClassLoader(), "context"); + InputStream is; + if (Py.getSystemState().getClassLoader() != null) { + is = tryClassLoader(filename, Py.getSystemState().getClassLoader(), "sys"); + } else { + is = tryClassLoader(filename, imp.getParentClassLoader(), "parent"); } - if (is == null) { - is = tryClassLoader(filename, ClasspathPyImporter.class.getClassLoader(), "current"); - } if (is != null) { entries.put(filename, is); return filename; Modified: trunk/jython/src/org/python/core/Py.java =================================================================== --- trunk/jython/src/org/python/core/Py.java 2010-01-30 10:14:30 UTC (rev 6969) +++ trunk/jython/src/org/python/core/Py.java 2010-01-30 16:06:59 UTC (rev 6970) @@ -780,35 +780,68 @@ return true; } - private static boolean secEnv = false; + private static boolean syspathJavaLoaderRestricted = false; - public static Class<?> findClass(String name) { - try { - ClassLoader classLoader = Py.getSystemState().getClassLoader(); + /** + * Common code for findClass and findClassEx + * @param name Name of the Java class to load and initialize + * @param reason Reason for loading it, used for debugging. No debug output + * is generated if it is null + * @return the loaded class, or null if no class loader is accessible + * @throws ClassNotFoundException if the class wasn't found by the class loader + */ + private static Class<?> findClassInternal(String name, String reason) throws ClassNotFoundException { + ClassLoader classLoader = Py.getSystemState().getClassLoader(); + if (classLoader != null) { + if (reason != null) { + writeDebug("import", "trying " + name + " as " + reason + + " in sys.classLoader"); + } + return loadAndInitClass(name, classLoader); + } + + if (!syspathJavaLoaderRestricted) { + try { + classLoader = imp.getSyspathJavaLoader(); + } catch (SecurityException e) { + syspathJavaLoaderRestricted = true; + } if (classLoader != null) { - return classLoader.loadClass(name); - } - - if (!secEnv) { + if (reason != null) { + writeDebug("import", "trying " + name + " as " + reason + + " in SysPathJavaLoader"); + } try { - classLoader = imp.getSyspathJavaLoader(); - } catch (SecurityException e) { - secEnv = true; + return loadAndInitClass(name, classLoader); + } catch (ClassNotFoundException cnfe) { + // let the default classloader try } - if (classLoader != null) { - try { - return classLoader.loadClass(name); - } catch (ClassNotFoundException cnfe) { - // let the context classloader try - } - } } - - classLoader = Thread.currentThread().getContextClassLoader(); - if (classLoader != null) { - return classLoader.loadClass(name); - } - return null; + } + if (reason != null) { + writeDebug("import", "trying " + name + " as " + reason + + " in Jython's parent class loader"); + } + classLoader = imp.getParentClassLoader(); + if (classLoader != null) { + return loadAndInitClass(name, classLoader); + } + + if (reason != null) { + writeDebug("import", "trying " + name + " as " + reason + + " in Class.forName"); + } + return Class.forName(name); + } + + /** + * Tries to find a Java class. + * @param name Name of the Java class. + * @return The class, or null if it wasn't found + */ + public static Class<?> findClass(String name) { + try { + return findClassInternal(name, null); } catch (ClassNotFoundException e) { // e.printStackTrace(); return null; @@ -821,39 +854,20 @@ } } + /** + * Tries to find a Java class. + * + * Unless {@link #findClass(String)}, it raises a JavaError + * if the class was found but there were problems loading it. + * @param name Name of the Java class. + * @param reason Reason for finding the class. Used for debugging messages. + * @return The class, or null if it wasn't found + * @throws JavaError wrapping LinkageErrors/IllegalArgumentExceptions + * occurred when the class is found but can't be loaded. + */ public static Class<?> findClassEx(String name, String reason) { - try { - ClassLoader classLoader = Py.getSystemState().getClassLoader(); - if (classLoader != null) { - writeDebug("import", "trying " + name + " as " + reason + - " in classLoader"); - return classLoader.loadClass(name); - } - - if (!secEnv) { - try { - classLoader = imp.getSyspathJavaLoader(); - } catch (SecurityException e) { - secEnv = true; - } - if (classLoader != null) { - writeDebug("import", "trying " + name + " as " + reason + - " in syspath loader"); - try { - return classLoader.loadClass(name); - } catch (ClassNotFoundException cnfe) { - // let the context classloader try - } - } - } - - writeDebug("import", "trying " + name + " as " + reason + - " in Class.forName"); - classLoader = Thread.currentThread().getContextClassLoader(); - if (classLoader != null) { - return classLoader.loadClass(name); - } - return null; + try { + return findClassInternal(name, reason); } catch (ClassNotFoundException e) { return null; } catch (IllegalArgumentException e) { @@ -863,6 +877,14 @@ } } + // An alias to express intent (since boolean flags aren't exactly obvious). + // We *need* to initialize classes on findClass/findClassEx, so that import + // statements can trigger static initializers + private static Class<?> loadAndInitClass(String name, ClassLoader loader) throws ClassNotFoundException { + return Class.forName(name, true, loader); + } + + public static void initProxy(PyProxy proxy, String module, String pyclass, Object[] args) { if (proxy._getPyInstance() != null) Modified: trunk/jython/src/org/python/core/SyspathJavaLoader.java =================================================================== --- trunk/jython/src/org/python/core/SyspathJavaLoader.java 2010-01-30 10:14:30 UTC (rev 6969) +++ trunk/jython/src/org/python/core/SyspathJavaLoader.java 2010-01-30 16:06:59 UTC (rev 6970) @@ -9,40 +9,118 @@ import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; +import java.net.MalformedURLException; +import java.net.URL; import java.util.StringTokenizer; import java.util.zip.ZipEntry; +import javax.management.RuntimeErrorException; + import org.python.core.util.RelativeFile; public class SyspathJavaLoader extends ClassLoader { private static final char SLASH_CHAR = '/'; - public InputStream getResourceAsStream(String res) { - Py.writeDebug("resource", "trying resource: " + res); - PySystemState sys = Py.getSystemState(); - ClassLoader classLoader = sys.getClassLoader(); - if (classLoader != null) { - return classLoader.getResourceAsStream(res); + public SyspathJavaLoader(ClassLoader parent) { + super(parent); + } + + + /** + * Returns a byte[] with the contents read from an InputStream. + * + * The stream is closed after reading the bytes. + * + * @param input The input stream + * @param size The number of bytes to read + * + * @return an array of byte[size] with the contents read + * */ + private byte[] getBytesFromInputStream(InputStream input, int size) { + try { + byte[] buffer = new byte[size]; + int nread = 0; + while(nread < size) { + nread += input.read(buffer, nread, size - nread); + } + return buffer; + } catch (IOException exc) { + return null; + } finally { + try { + input.close(); + } catch (IOException e) { + // Nothing to do + } + } + } + + private byte[] getBytesFromDir(String dir, String name) { + try { + File file = getFile(dir, name); + if (file == null) { + return null; + } + return getBytesFromInputStream(new FileInputStream(file), (int)file.length()); + } catch (FileNotFoundException e) { + return null; + } catch(SecurityException e) { + return null; } - classLoader = Thread.currentThread().getContextClassLoader(); - - InputStream ret; - - if (classLoader != null) { - ret = classLoader.getResourceAsStream(res); - } else { - ret = ClassLoader.getSystemResourceAsStream(res); + } + + private byte[] getBytesFromArchive(SyspathArchive archive, String name) { + String entryname = name.replace('.', SLASH_CHAR) + ".class"; + ZipEntry ze = archive.getEntry(entryname); + if (ze == null) { + return null; } - if (ret != null) { - return ret; + try { + return getBytesFromInputStream(archive.getInputStream(ze), + (int)ze.getSize()); + } catch (IOException e) { + return null; + } + } + + @Override + protected Class<?> findClass(String name) throws ClassNotFoundException { + PySystemState sys = Py.getSystemState(); + ClassLoader sysClassLoader = sys.getClassLoader(); + if (sysClassLoader != null) { + // sys.classLoader overrides this class loader! + return sysClassLoader.loadClass(name); + } + // Search the sys.path for a .class file matching the named class. + PyList path = sys.path; + for (int i = 0; i < path.__len__(); i++) { + byte[] buffer; + PyObject entry = replacePathItem(sys, i, path); + if (entry instanceof SyspathArchive) { + SyspathArchive archive = (SyspathArchive)entry; + buffer = getBytesFromArchive(archive, name); + } else { + String dir = entry.__str__().toString(); + buffer = getBytesFromDir(dir, name); + } + if (buffer != null) { + return defineClass(name, buffer, 0, buffer.length); + } } - - if (res.charAt(0) == SLASH_CHAR) { + // couldn't find the .class file on sys.path + throw new ClassNotFoundException(name); + } + + @Override + protected URL findResource(String res) { + PySystemState sys = Py.getSystemState(); + + if (res.charAt(0) == SLASH_CHAR) { res = res.substring(1); } - String entryRes = res; + String entryRes = res; if (File.separatorChar != SLASH_CHAR) { res = res.replace(SLASH_CHAR, File.separatorChar); entryRes = entryRes.replace(File.separatorChar, SLASH_CHAR); @@ -55,25 +133,25 @@ SyspathArchive archive = (SyspathArchive) entry; ZipEntry ze = archive.getEntry(entryRes); if (ze != null) { - try { - return archive.getInputStream(ze); - } catch (IOException e) { - ; - } + try { + return new URL("jar:" + entry.__str__().toString() + "!/" + entryRes); + } catch (MalformedURLException e) { + throw new RuntimeException(e); + } } continue; } String dir = sys.getPath(entry.__str__().toString()); try { - return new BufferedInputStream(new FileInputStream(new File(dir, res))); - } catch (IOException e) { - continue; - } + return new File(dir, res).toURI().toURL(); + } catch (MalformedURLException e) { + throw new RuntimeException(e); + } } - return null; } + static PyObject replacePathItem(PySystemState sys, int idx, PyList paths) { PyObject path = paths.__getitem__(idx); if (path instanceof SyspathArchive) { @@ -92,91 +170,6 @@ return path; } - // override from abstract base class - protected Class<?> loadClass(String name, boolean resolve) - throws ClassNotFoundException { - // First, if the Python runtime system has a default class loader, defer to it. - PySystemState sys = Py.getSystemState(); - ClassLoader classLoader = sys.getClassLoader(); - if (classLoader != null) { - return classLoader.loadClass(name); - } - - // Search the sys.path for a .class file matching the named class. - try { - return Class.forName(name); - } 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 (SecurityException se) { - } - - Class<?> c = findLoadedClass(name); - if(c != null) { - return c; - } - - PyList path = sys.path; - for(int i = 0; i < path.__len__(); i++) { - - InputStream fis; - int size; - PyObject entry = replacePathItem(sys, i, path); - if(entry instanceof SyspathArchive) { - SyspathArchive archive = (SyspathArchive)entry; - String entryname = name.replace('.', SLASH_CHAR) + ".class"; - ZipEntry ze = archive.getEntry(entryname); - if(ze == null) { - continue; - } - try { - fis = archive.getInputStream(ze); - size = (int)ze.getSize(); - } catch (IOException exc) { - continue; - } - } else { - String dir = entry.__str__().toString(); - File file = getFile(dir, name); - if (file == null) { - continue; - } - try { - size = (int)file.length(); - fis = new FileInputStream(file); - } catch (FileNotFoundException e) { - continue; - } catch(SecurityException e) { - continue; - } - } - try { - byte[] buffer = new byte[size]; - int nread = 0; - while(nread < size) { - nread += fis.read(buffer, nread, size - nread); - } - fis.close(); - return loadClassFromBytes(name, buffer); - } catch (IOException e) { - - } finally { - try { - fis.close(); - } catch (IOException e) { - } - } - } - - // couldn't find the .class file on sys.path - throw new ClassNotFoundException(name); - } - private File getFile(String dir, String name) { String accum = ""; boolean first = true; @@ -192,12 +185,5 @@ return new RelativeFile(dir, accum + ".class"); } - private Class<?> loadClassFromBytes(String name, byte[] data) { - // System.err.println("loadClassFromBytes("+name+", byte[])"); - Class<?> c = defineClass(name, data, 0, data.length); - resolveClass(c); - Compiler.compileClass(c); - return c; - } } Modified: trunk/jython/src/org/python/core/imp.java =================================================================== --- trunk/jython/src/org/python/core/imp.java 2010-01-30 10:14:30 UTC (rev 6969) +++ trunk/jython/src/org/python/core/imp.java 2010-01-30 16:06:59 UTC (rev 6970) @@ -41,11 +41,41 @@ public static ClassLoader getSyspathJavaLoader() { synchronized (syspathJavaLoaderLock) { if (syspathJavaLoader == null) { - syspathJavaLoader = new SyspathJavaLoader(); - } + syspathJavaLoader = new SyspathJavaLoader(getParentClassLoader()); + } } return syspathJavaLoader; } + + /** + * Returns the parent class loader for Jython. In most environments + * is just the class loader that loaded this class (imp.class). However, + * when that class loader is null (e.g., when Jython has been + * loaded using the boot loader) we return the Thread's context class + * loader (which can also be null, but in such case we return null anyway). + * + * @return the parent class loader for Jython + */ + public static ClassLoader getParentClassLoader() { + ClassLoader parent = null; + // XXX: While trying the current class loader before using the context class + // loader seems like the saner approach, there may be legacy code + // expecting Jython to use the context class loader, + // + // Se we should uncomment the following line when we feel like + // doing backwards-incompatible changes (3.0?) + // + // parent = imp.class.getClassLoader(); + if (parent == null) { + // Try the context class loader + try { + parent = Thread.currentThread().getContextClassLoader(); + } catch (SecurityException e) { + // We just give up + } + } + return parent; + } private imp() { } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <le...@us...> - 2010-01-31 06:16:27
|
Revision: 6973 http://jython.svn.sourceforge.net/jython/?rev=6973&view=rev Author: leosoto Date: 2010-01-31 06:16:21 +0000 (Sun, 31 Jan 2010) Log Message: ----------- Fixed problems introduced with the recent class loading refactor. Note that we still do not have a stable/consistent classloading hierarchy in place. But we are closer. Modified Paths: -------------- trunk/jython/src/org/python/core/Py.java trunk/jython/src/org/python/core/imp.java Modified: trunk/jython/src/org/python/core/Py.java =================================================================== --- trunk/jython/src/org/python/core/Py.java 2010-01-30 16:36:46 UTC (rev 6972) +++ trunk/jython/src/org/python/core/Py.java 2010-01-31 06:16:21 UTC (rev 6973) @@ -787,7 +787,7 @@ * @param name Name of the Java class to load and initialize * @param reason Reason for loading it, used for debugging. No debug output * is generated if it is null - * @return the loaded class, or null if no class loader is accessible + * @return the loaded class * @throws ClassNotFoundException if the class wasn't found by the class loader */ private static Class<?> findClassInternal(String name, String reason) throws ClassNotFoundException { @@ -799,39 +799,42 @@ } return loadAndInitClass(name, classLoader); } - if (!syspathJavaLoaderRestricted) { try { classLoader = imp.getSyspathJavaLoader(); + if (classLoader != null && reason != null) { + writeDebug("import", "trying " + name + " as " + reason + + " in SysPathJavaLoader"); + } } catch (SecurityException e) { syspathJavaLoaderRestricted = true; } - if (classLoader != null) { - if (reason != null) { - writeDebug("import", "trying " + name + " as " + reason + - " in SysPathJavaLoader"); - } - try { - return loadAndInitClass(name, classLoader); - } catch (ClassNotFoundException cnfe) { - // let the default classloader try - } + } + if (syspathJavaLoaderRestricted) { + classLoader = imp.getParentClassLoader(); + if (classLoader != null && reason != null) { + writeDebug("import", "trying " + name + " as " + reason + + " in Jython's parent class loader"); } + } + if (classLoader != null) { + try { + return loadAndInitClass(name, classLoader); + } catch (ClassNotFoundException cnfe) { + // let the default classloader try + // XXX: by trying another classloader that may not be on a + // parent/child relationship with the Jython's parent + // classsloader we are risking some nasty class loading + // problems (such as having two incompatible copies for + // the same class that is itself a dependency of two + // classes loaded from these two different class loaders) + } } if (reason != null) { writeDebug("import", "trying " + name + " as " + reason + - " in Jython's parent class loader"); + " in context class loader, for backwards compatibility"); } - classLoader = imp.getParentClassLoader(); - if (classLoader != null) { - return loadAndInitClass(name, classLoader); - } - - if (reason != null) { - writeDebug("import", "trying " + name + " as " + reason + - " in Class.forName"); - } - return Class.forName(name); + return loadAndInitClass(name, Thread.currentThread().getContextClassLoader()); } /** Modified: trunk/jython/src/org/python/core/imp.java =================================================================== --- trunk/jython/src/org/python/core/imp.java 2010-01-30 16:36:46 UTC (rev 6972) +++ trunk/jython/src/org/python/core/imp.java 2010-01-31 06:16:21 UTC (rev 6973) @@ -48,36 +48,63 @@ } /** - * Returns the parent class loader for Jython. In most environments - * is just the class loader that loaded this class (imp.class). However, - * when that class loader is null (e.g., when Jython has been - * loaded using the boot loader) we return the Thread's context class - * loader (which can also be null, but in such case we return null anyway). + * <p> + * Selects the parent class loader for Jython, used for dinamically load classes and resources * - * @return the parent class loader for Jython + * <p> + * The current implementation chooses between the current and context + * classloader based on the following criteria:<ul> + * + * <li>If both are the same, that one is returned. + * <li>If either is null, the non-null one is selected. + * <li>If both are not null, and a parent/child relationship can be determined, + * the child is selected. + * <li>If both are not null and not on a parent/child relationship, the + * current class loader is returned (since it is likely for the + * context class loader to <b>not</b> see the Jython classes) + * + * @return the parent class loader for Jython or null if both the current and context classloaders are null; */ public static ClassLoader getParentClassLoader() { - ClassLoader parent = null; - // XXX: While trying the current class loader before using the context class - // loader seems like the saner approach, there may be legacy code - // expecting Jython to use the context class loader, - // - // Se we should uncomment the following line when we feel like - // doing backwards-incompatible changes (3.0?) - // - // parent = imp.class.getClassLoader(); - if (parent == null) { - // Try the context class loader - try { - parent = Thread.currentThread().getContextClassLoader(); - } catch (SecurityException e) { - // We just give up - } - } - return parent; - } + ClassLoader current = imp.class.getClassLoader(); + ClassLoader context = Thread.currentThread().getContextClassLoader(); + if (context == current) { + return current; + } + if (context == null) { + return current; + } + if (current == null) { + return context; + } + if (isParentClassLoader(context, current)) { + return current; + } + if (isParentClassLoader(current, context)) { + return context; + } + return current; + } - private imp() { + private static boolean isParentClassLoader( + ClassLoader suspectedParent, ClassLoader child) { + try { + ClassLoader parent = child.getParent(); + if (suspectedParent == parent) { + return true; + } + if (parent == null || parent == child) { + // We reached the boot class loader + return false; + } + return isParentClassLoader(suspectedParent, parent); + + } catch (SecurityException e) { + return false; + } + } + + private imp() { } /** This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <pj...@us...> - 2010-03-14 21:40:07
|
Revision: 6985 http://jython.svn.sourceforge.net/jython/?rev=6985&view=rev Author: pjenvey Date: 2010-03-14 21:39:57 +0000 (Sun, 14 Mar 2010) Log Message: ----------- coding standards/cleanup Modified Paths: -------------- trunk/jython/src/org/python/core/PyComplex.java trunk/jython/src/org/python/core/PyFloat.java trunk/jython/src/org/python/core/PyInteger.java trunk/jython/src/org/python/core/PyLong.java Modified: trunk/jython/src/org/python/core/PyComplex.java =================================================================== --- trunk/jython/src/org/python/core/PyComplex.java 2010-03-13 17:33:14 UTC (rev 6984) +++ trunk/jython/src/org/python/core/PyComplex.java 2010-03-14 21:39:57 UTC (rev 6985) @@ -1,4 +1,7 @@ -// Copyright (c) Corporation for National Research Initiatives +/* + * Copyright (c) Corporation for National Research Initiatives + * Copyright (c) Jython Developers + */ package org.python.core; import org.python.expose.ExposedGet; @@ -15,14 +18,28 @@ public static final PyType TYPE = PyType.fromClass(PyComplex.class); + static PyComplex J = new PyComplex(0, 1.); + @ExposedGet(doc = BuiltinDocs.complex_real_doc) public double real; @ExposedGet(doc = BuiltinDocs.complex_imag_doc) public double imag; - static PyComplex J = new PyComplex(0, 1.); + public PyComplex(PyType subtype, double r, double i) { + super(subtype); + real = r; + imag = i; + } + public PyComplex(double r, double i) { + this(TYPE, r, i); + } + + public PyComplex(double r) { + this(r, 0.0); + } + @ExposedNew public static PyObject complex_new(PyNewWrapper new_, boolean init, PyType subtype, PyObject[] args, String[] keywords) { @@ -58,7 +75,7 @@ PyComplex complexImag; PyFloat toFloat = null; if (real instanceof PyComplex) { - complexReal = (PyComplex)real; + complexReal = (PyComplex) real; } else { try { toFloat = real.__float__(); @@ -75,7 +92,7 @@ if (imag == null) { complexImag = new PyComplex(0.0); } else if (imag instanceof PyComplex) { - complexImag = (PyComplex)imag; + complexImag = (PyComplex) imag; } else { toFloat = null; try { @@ -98,20 +115,6 @@ return complexReal; } - public PyComplex(PyType subtype, double r, double i) { - super(subtype); - real = r; - imag = i; - } - - public PyComplex(double r, double i) { - this(TYPE, r, i); - } - - public PyComplex(double r) { - this(r, 0.0); - } - public final PyFloat getReal() { return Py.newFloat(real); } @@ -121,14 +124,14 @@ } public static String toString(double value) { - if (value == Math.floor(value) && - value <= Long.MAX_VALUE && value >= Long.MIN_VALUE) { - return Long.toString((long)value); + if (value == Math.floor(value) && value <= Long.MAX_VALUE && value >= Long.MIN_VALUE) { + return Long.toString((long) value); } else { return Double.toString(value); } } + @Override public String toString() { return complex_toString(); } @@ -136,16 +139,17 @@ @ExposedMethod(names = {"__repr__", "__str__"}, doc = BuiltinDocs.complex___str___doc) final String complex_toString() { if (real == 0.) { - return toString(imag)+"j"; + return toString(imag) + "j"; } else { if (imag >= 0) { - return "("+toString(real)+"+"+toString(imag)+"j)"; + return String.format("(%s+%sj)", toString(real), toString(imag)); } else { - return "("+toString(real)+"-"+toString(-imag)+"j)"; + return String.format("(%s-%sj)", toString(real), toString(-imag)); } } } + @Override public int hashCode() { return complex___hash__(); } @@ -155,12 +159,12 @@ if (imag == 0) { return new PyFloat(real).hashCode(); } else { - long v = Double.doubleToLongBits(real) ^ - Double.doubleToLongBits(imag); - return (int)v ^ (int)(v >> 32); + long v = Double.doubleToLongBits(real) ^ Double.doubleToLongBits(imag); + return (int) v ^ (int) (v >> 32); } } + @Override public boolean __nonzero__() { return complex___nonzero__(); } @@ -170,18 +174,17 @@ return real != 0 || imag != 0; } - /*public Object __tojava__(Class c) { - return super.__tojava__(c); - }*/ - + @Override public int __cmp__(PyObject other) { - if (!canCoerce(other)) + if (!canCoerce(other)) { return -2; + } PyComplex c = coerce(other); double oreal = c.real; double oimag = c.imag; - if (real == oreal && imag == oimag) + if (real == oreal && imag == oimag) { return 0; + } if (real != oreal) { return real < oreal ? -1 : 1; } else { @@ -189,42 +192,42 @@ } } - /* - * @see org.python.core.PyObject#__eq__(org.python.core.PyObject) - */ + @Override public PyObject __eq__(PyObject other) { return complex___eq__(other); } @ExposedMethod(type = MethodType.BINARY, doc = BuiltinDocs.complex___eq___doc) final PyObject complex___eq__(PyObject other) { - if (!canCoerce(other)) + if (!canCoerce(other)) { return null; + } PyComplex c = coerce(other); return Py.newBoolean(real == c.real && imag == c.imag); } - /* - * @see org.python.core.PyObject#__ne__(org.python.core.PyObject) - */ + @Override public PyObject __ne__(PyObject other) { return complex___ne__(other); } @ExposedMethod(type = MethodType.BINARY, doc = BuiltinDocs.complex___ne___doc) final PyObject complex___ne__(PyObject other) { - if (!canCoerce(other)) + if (!canCoerce(other)) { return null; + } PyComplex c = coerce(other); return Py.newBoolean(real != c.real || imag != c.imag); } private PyObject unsupported_comparison(PyObject other) { - if (!canCoerce(other)) + if (!canCoerce(other)) { return null; + } throw Py.TypeError("cannot compare complex numbers using <, <=, >, >="); } + @Override public PyObject __ge__(PyObject other) { return complex___ge__(other); } @@ -234,6 +237,7 @@ return unsupported_comparison(other); } + @Override public PyObject __gt__(PyObject other) { return complex___gt__(other); } @@ -243,6 +247,7 @@ return unsupported_comparison(other); } + @Override public PyObject __le__(PyObject other) { return complex___le__(other); } @@ -252,6 +257,7 @@ return unsupported_comparison(other); } + @Override public PyObject __lt__(PyObject other) { return complex___lt__(other); } @@ -261,62 +267,72 @@ return unsupported_comparison(other); } + @Override public Object __coerce_ex__(PyObject other) { return complex___coerce_ex__(other); } - + @ExposedMethod(doc = BuiltinDocs.complex___coerce___doc) final PyObject complex___coerce__(PyObject other) { return adaptToCoerceTuple(complex___coerce_ex__(other)); } - /** + /** * Coercion logic for complex. Implemented as a final method to avoid - * invocation of virtual methods from the exposed coerce. - */ + * invocation of virtual methods from the exposed coerce. + */ final PyObject complex___coerce_ex__(PyObject other) { - if (other instanceof PyComplex) + if (other instanceof PyComplex) { return other; - if (other instanceof PyFloat) - return new PyComplex(((PyFloat)other).getValue(), 0); - if (other instanceof PyInteger) - return new PyComplex(((PyInteger)other).getValue(), 0); - if (other instanceof PyLong) - return new PyComplex(((PyLong)other).doubleValue(), 0); + } + if (other instanceof PyFloat) { + return new PyComplex(((PyFloat) other).getValue(), 0); + } + if (other instanceof PyInteger) { + return new PyComplex(((PyInteger) other).getValue(), 0); + } + if (other instanceof PyLong) { + return new PyComplex(((PyLong) other).doubleValue(), 0); + } return Py.None; } private final boolean canCoerce(PyObject other) { - return other instanceof PyComplex || - other instanceof PyFloat || - other instanceof PyInteger || - other instanceof PyLong; + return other instanceof PyComplex || other instanceof PyFloat || other instanceof PyInteger + || other instanceof PyLong; } private final PyComplex coerce(PyObject other) { - if (other instanceof PyComplex) + if (other instanceof PyComplex) { return (PyComplex) other; - if (other instanceof PyFloat) - return new PyComplex(((PyFloat)other).getValue(), 0); - if (other instanceof PyInteger) - return new PyComplex(((PyInteger)other).getValue(), 0); - if (other instanceof PyLong) - return new PyComplex(((PyLong)other).doubleValue(), 0); + } + if (other instanceof PyFloat) { + return new PyComplex(((PyFloat) other).getValue(), 0); + } + if (other instanceof PyInteger) { + return new PyComplex(((PyInteger) other).getValue(), 0); + } + if (other instanceof PyLong) { + return new PyComplex(((PyLong) other).doubleValue(), 0); + } throw Py.TypeError("xxx"); } + @Override public PyObject __add__(PyObject right) { return complex___add__(right); } @ExposedMethod(type = MethodType.BINARY, doc = BuiltinDocs.complex___add___doc) final PyObject complex___add__(PyObject right) { - if (!canCoerce(right)) + if (!canCoerce(right)) { return null; + } PyComplex c = coerce(right); - return new PyComplex(real+c.real, imag+c.imag); + return new PyComplex(real + c.real, imag + c.imag); } + @Override public PyObject __radd__(PyObject left) { return complex___radd__(left); } @@ -327,55 +343,63 @@ } private final static PyObject _sub(PyComplex o1, PyComplex o2) { - return new PyComplex(o1.real-o2.real, o1.imag-o2.imag); + return new PyComplex(o1.real - o2.real, o1.imag - o2.imag); } + @Override public PyObject __sub__(PyObject right) { return complex___sub__(right); } @ExposedMethod(type = MethodType.BINARY, doc = BuiltinDocs.complex___sub___doc) final PyObject complex___sub__(PyObject right) { - if (!canCoerce(right)) + if (!canCoerce(right)) { return null; + } return _sub(this, coerce(right)); } + @Override public PyObject __rsub__(PyObject left) { return complex___rsub__(left); } @ExposedMethod(type = MethodType.BINARY, doc = BuiltinDocs.complex___rsub___doc) final PyObject complex___rsub__(PyObject left) { - if (!canCoerce(left)) + if (!canCoerce(left)) { return null; + } return _sub(coerce(left), this); } private final static PyObject _mul(PyComplex o1, PyComplex o2) { - return new PyComplex(o1.real*o2.real-o1.imag*o2.imag, - o1.real*o2.imag+o1.imag*o2.real); + return new PyComplex(o1.real * o2.real - o1.imag * o2.imag, + o1.real * o2.imag + o1.imag * o2.real); } + @Override public PyObject __mul__(PyObject right) { return complex___mul__(right); } @ExposedMethod(type = MethodType.BINARY, doc = BuiltinDocs.complex___mul___doc) final PyObject complex___mul__(PyObject right) { - if (!canCoerce(right)) + if (!canCoerce(right)) { return null; + } return _mul(this, coerce(right)); } + @Override public PyObject __rmul__(PyObject left) { return complex___rmul__(left); } @ExposedMethod(type = MethodType.BINARY, doc = BuiltinDocs.complex___rmul___doc) final PyObject complex___rmul__(PyObject left) { - if (!canCoerce(left)) + if (!canCoerce(left)) { return null; + } return _mul(coerce(left), this); } @@ -400,95 +424,113 @@ } } + @Override public PyObject __div__(PyObject right) { return complex___div__(right); } @ExposedMethod(type = MethodType.BINARY, doc = BuiltinDocs.complex___div___doc) final PyObject complex___div__(PyObject right) { - if (!canCoerce(right)) + if (!canCoerce(right)) { return null; - if (Options.divisionWarning >= 2) + } + if (Options.divisionWarning >= 2) { Py.warning(Py.DeprecationWarning, "classic complex division"); + } return _div(this, coerce(right)); } + @Override public PyObject __rdiv__(PyObject left) { return complex___rdiv__(left); } @ExposedMethod(type = MethodType.BINARY, doc = BuiltinDocs.complex___rdiv___doc) final PyObject complex___rdiv__(PyObject left) { - if (!canCoerce(left)) + if (!canCoerce(left)) { return null; - if (Options.divisionWarning >= 2) + } + if (Options.divisionWarning >= 2) { Py.warning(Py.DeprecationWarning, "classic complex division"); + } return _div(coerce(left), this); } + @Override public PyObject __floordiv__(PyObject right) { return complex___floordiv__(right); } @ExposedMethod(type = MethodType.BINARY, doc = BuiltinDocs.complex___floordiv___doc) final PyObject complex___floordiv__(PyObject right) { - if (!canCoerce(right)) + if (!canCoerce(right)) { return null; + } return _divmod(this, coerce(right)).__finditem__(0); } + @Override public PyObject __rfloordiv__(PyObject left) { return complex___rfloordiv__(left); } @ExposedMethod(type = MethodType.BINARY, doc = BuiltinDocs.complex___rfloordiv___doc) final PyObject complex___rfloordiv__(PyObject left) { - if (!canCoerce(left)) + if (!canCoerce(left)) { return null; + } return _divmod(coerce(left), this).__finditem__(0); } + @Override public PyObject __truediv__(PyObject right) { return complex___truediv__(right); } @ExposedMethod(type = MethodType.BINARY, doc = BuiltinDocs.complex___truediv___doc) final PyObject complex___truediv__(PyObject right) { - if (!canCoerce(right)) + if (!canCoerce(right)) { return null; + } return _div(this, coerce(right)); } + @Override public PyObject __rtruediv__(PyObject left) { return complex___rtruediv__(left); } @ExposedMethod(type = MethodType.BINARY, doc = BuiltinDocs.complex___rtruediv___doc) final PyObject complex___rtruediv__(PyObject left) { - if (!canCoerce(left)) + if (!canCoerce(left)) { return null; + } return _div(coerce(left), this); } + @Override public PyObject __mod__(PyObject right) { return complex___mod__(right); } @ExposedMethod(type = MethodType.BINARY, doc = BuiltinDocs.complex___mod___doc) final PyObject complex___mod__(PyObject right) { - if (!canCoerce(right)) + if (!canCoerce(right)) { return null; + } return _mod(this, coerce(right)); } + @Override public PyObject __rmod__(PyObject left) { return complex___rmod__(left); } @ExposedMethod(type = MethodType.BINARY, doc = BuiltinDocs.complex___rmod___doc) final PyObject complex___rmod__(PyObject left) { - if (!canCoerce(left)) + if (!canCoerce(left)) { return null; + } return _mod(coerce(left), this); } @@ -502,25 +544,29 @@ return value.__sub__(z.__mul__(right)); } + @Override public PyObject __divmod__(PyObject right) { return complex___divmod__(right); } @ExposedMethod(type = MethodType.BINARY, doc = BuiltinDocs.complex___divmod___doc) final PyObject complex___divmod__(PyObject right) { - if (!canCoerce(right)) + if (!canCoerce(right)) { return null; + } return _divmod(this, coerce(right)); } + @Override public PyObject __rdivmod__(PyObject left) { return complex___rdivmod__(left); } @ExposedMethod(type = MethodType.BINARY, doc = BuiltinDocs.complex___rdivmod___doc) final PyObject complex___rdivmod__(PyObject left) { - if (!canCoerce(left)) + if (!canCoerce(left)) { return null; + } return _divmod(coerce(left), this); } @@ -534,10 +580,11 @@ return new PyTuple(z, value.__sub__(z.__mul__(right))); } - private static PyObject ipow(PyComplex value, int iexp) { int pow = iexp; - if (pow < 0) pow = -pow; + if (pow < 0) { + pow = -pow; + } double xr = value.real; double xi = value.imag; @@ -549,25 +596,28 @@ while (pow > 0) { if ((pow & 0x1) != 0) { - tmp = zr*xr - zi*xi; - zi = zi*xr + zr*xi; + tmp = zr * xr - zi * xi; + zi = zi * xr + zr * xi; zr = tmp; } pow >>= 1; - if (pow == 0) + if (pow == 0) { break; - tmp = xr*xr - xi*xi; - xi = xr*xi*2; + } + tmp = xr * xr - xi * xi; + xi = xr * xi * 2; xr = tmp; } PyComplex ret = new PyComplex(zr, zi); - if (iexp < 0) - return new PyComplex(1,0).__div__(ret); + if (iexp < 0) { + return new PyComplex(1, 0).__div__(ret); + } return ret; } + @Override public PyObject __pow__(PyObject right, PyObject modulo) { return complex___pow__(right, modulo); } @@ -577,19 +627,22 @@ if (modulo != null) { throw Py.ValueError("complex modulo"); } - if (!canCoerce(right)) + if (!canCoerce(right)) { return null; + } return _pow(this, coerce(right)); } + @Override public PyObject __rpow__(PyObject left) { return complex___rpow__(left); } @ExposedMethod(type = MethodType.BINARY, doc = BuiltinDocs.complex___rpow___doc) final PyObject complex___rpow__(PyObject left) { - if (!canCoerce(left)) + if (!canCoerce(left)) { return null; + } return _pow(coerce(left), this); } @@ -610,7 +663,7 @@ } // Check for integral powers - int iexp = (int)yr; + int iexp = (int) yr; if (yi == 0 && yr == iexp && iexp >= -128 && iexp <= 128) { return ipow(value, iexp); } @@ -619,14 +672,15 @@ double len = Math.pow(abs, yr); double at = Math.atan2(xi, xr); - double phase = at*yr; + double phase = at * yr; if (yi != 0) { - len /= Math.exp(at*yi); - phase += yi*Math.log(abs); + len /= Math.exp(at * yi); + phase += yi * Math.log(abs); } - return new PyComplex(len*Math.cos(phase), len*Math.sin(phase)); + return new PyComplex(len * Math.cos(phase), len * Math.sin(phase)); } + @Override public PyObject __neg__() { return complex___neg__(); } @@ -636,6 +690,7 @@ return new PyComplex(-real, -imag); } + @Override public PyObject __pos__() { return complex___pos__(); } @@ -648,10 +703,12 @@ return new PyComplex(real, imag); } + @Override public PyObject __invert__() { - throw Py.TypeError("bad operand type for unary ~"); + throw Py.TypeError("bad operand type for unary ~"); } + @Override public PyObject __abs__() { return complex___abs__(); } @@ -661,26 +718,27 @@ return new PyFloat(Math.hypot(real, imag)); } + @Override public PyObject __int__() { return complex___int__(); } @ExposedMethod(doc = BuiltinDocs.complex___int___doc) final PyInteger complex___int__() { - throw Py.TypeError( - "can't convert complex to int; use e.g. int(abs(z))"); + throw Py.TypeError("can't convert complex to int; use e.g. int(abs(z))"); } + @Override public PyObject __long__() { return complex___long__(); } @ExposedMethod(doc = BuiltinDocs.complex___long___doc) final PyObject complex___long__() { - throw Py.TypeError( - "can't convert complex to long; use e.g. long(abs(z))"); + throw Py.TypeError("can't convert complex to long; use e.g. long(abs(z))"); } + @Override public PyFloat __float__() { return complex___float__(); } @@ -690,6 +748,7 @@ throw Py.TypeError("can't convert complex to float; use e.g. abs(z)"); } + @Override public PyComplex __complex__() { return new PyComplex(real, imag); } @@ -708,6 +767,7 @@ return new PyTuple(new PyComplex(real, imag)); } + @Override public PyTuple __getnewargs__() { return complex___getnewargs__(); } Modified: trunk/jython/src/org/python/core/PyFloat.java =================================================================== --- trunk/jython/src/org/python/core/PyFloat.java 2010-03-13 17:33:14 UTC (rev 6984) +++ trunk/jython/src/org/python/core/PyFloat.java 2010-03-14 21:39:57 UTC (rev 6985) @@ -1,4 +1,7 @@ -// Copyright (c) Corporation for National Research Initiatives +/* + * Copyright (c) Corporation for National Research Initiatives + * Copyright (c) Jython Developers + */ package org.python.core; import java.io.Serializable; @@ -14,16 +17,33 @@ * A builtin python float. */ @ExposedType(name = "float", doc = BuiltinDocs.float_doc) -public class PyFloat extends PyObject -{ +public class PyFloat extends PyObject { + + public static final PyType TYPE = PyType.fromClass(PyFloat.class); + /** Precisions used by repr() and str(), respectively. */ private static final int PREC_REPR = 17; private static final int PREC_STR = 12; + private double value; + + public PyFloat(PyType subtype, double v) { + super(subtype); + value = v; + } + + public PyFloat(double v) { + this(TYPE, v); + } + + public PyFloat(float v) { + this((double) v); + } + @ExposedNew public static PyObject float_new(PyNewWrapper new_, boolean init, PyType subtype, - PyObject[] args, String[] keywords) { - ArgParser ap = new ArgParser("float", args, keywords, new String[] { "x" }, 0); + PyObject[] args, String[] keywords) { + ArgParser ap = new ArgParser("float", args, keywords, new String[] {"x"}, 0); PyObject x = ap.getPyObject(0, null); if (x == null) { if (new_.for_type == subtype) { @@ -54,23 +74,6 @@ } } - public static final PyType TYPE = PyType.fromClass(PyFloat.class); - - private double value; - - public PyFloat(PyType subtype, double v) { - super(subtype); - value = v; - } - - public PyFloat(double v) { - this(TYPE, v); - } - - public PyFloat(float v) { - this((double)v); - } - /** * Determine if this float is not infinity, nor NaN. */ @@ -82,10 +85,12 @@ return value; } + @Override public String toString() { return __str__().toString(); } + @Override public PyString __str__() { return float___str__(); } @@ -95,6 +100,7 @@ return Py.newString(formatDouble(PREC_STR)); } + @Override public PyString __repr__() { return float___repr__(); } @@ -108,7 +114,7 @@ if (Double.isNaN(value)) { return "nan"; } - + String result = String.format("%%.%dg", precision); result = Py.newString(result).__mod__(this).toString(); @@ -127,6 +133,7 @@ return result; } + @Override public int hashCode() { return float___hash__(); } @@ -134,19 +141,21 @@ @ExposedMethod(doc = BuiltinDocs.float___hash___doc) final int float___hash__() { double intPart = Math.floor(value); - double fractPart = value-intPart; + double fractPart = value - intPart; if (fractPart == 0) { - if (intPart <= Integer.MAX_VALUE && intPart >= Integer.MIN_VALUE) - return (int)value; - else + if (intPart <= Integer.MAX_VALUE && intPart >= Integer.MIN_VALUE) { + return (int) value; + } else { return __long__().hashCode(); + } } else { long v = Double.doubleToLongBits(value); - return (int)v ^ (int)(v >> 32); + return (int) v ^ (int) (v >> 32); } } + @Override public boolean __nonzero__() { return float___nonzero__(); } @@ -156,10 +165,10 @@ return value != 0; } - public Object __tojava__(Class c) { - if (c == Double.TYPE || c == Number.class || - c == Double.class || c == Object.class || c == Serializable.class) - { + @Override + public Object __tojava__(Class<?> c) { + if (c == Double.TYPE || c == Number.class || c == Double.class || c == Object.class + || c == Serializable.class) { return new Double(value); } if (c == Float.TYPE || c == Float.class) { @@ -168,6 +177,7 @@ return super.__tojava__(c); } + @Override public PyObject __eq__(PyObject other) { // preclude _cmp_unsafe's this == other shortcut because NaN != anything, even // itself @@ -177,6 +187,7 @@ return null; } + @Override public PyObject __ne__(PyObject other) { if (Double.isNaN(value)) { return Py.True; @@ -184,18 +195,19 @@ return null; } + @Override public int __cmp__(PyObject other) { return float___cmp__(other); } - //XXX: needs __doc__ + // XXX: needs __doc__ @ExposedMethod(type = MethodType.CMP) final int float___cmp__(PyObject other) { double i = value; double j; if (other instanceof PyFloat) { - j = ((PyFloat)other).value; + j = ((PyFloat) other).value; } else if (!isFinite()) { // we're infinity: our magnitude exceeds any finite // integer, so it doesn't matter which int we compare i @@ -206,10 +218,10 @@ return -2; } } else if (other instanceof PyInteger) { - j = ((PyInteger)other).getValue(); + j = ((PyInteger) other).getValue(); } else if (other instanceof PyLong) { BigDecimal v = new BigDecimal(value); - BigDecimal w = new BigDecimal(((PyLong)other).getValue()); + BigDecimal w = new BigDecimal(((PyLong) other).getValue()); return v.compareTo(w); } else { return -2; @@ -227,6 +239,7 @@ } } + @Override public Object __coerce_ex__(PyObject other) { return float___coerce_ex__(other); } @@ -236,22 +249,23 @@ return adaptToCoerceTuple(float___coerce_ex__(other)); } - /** + /** * Coercion logic for float. Implemented as a final method to avoid - * invocation of virtual methods from the exposed coerce. - */ + * invocation of virtual methods from the exposed coerce. + */ final Object float___coerce_ex__(PyObject other) { - if (other instanceof PyFloat) + if (other instanceof PyFloat) { return other; - else { - if (other instanceof PyInteger) - return new PyFloat((double)((PyInteger)other).getValue()); - if (other instanceof PyLong) - return new PyFloat(((PyLong)other).doubleValue()); - else + } else { + if (other instanceof PyInteger) { + return new PyFloat((double) ((PyInteger) other).getValue()); + } + if (other instanceof PyLong) { + return new PyFloat(((PyLong) other).doubleValue()); + } else { return Py.None; + } } - } private static final boolean canCoerce(PyObject other) { @@ -259,28 +273,32 @@ } private static final double coerce(PyObject other) { - if (other instanceof PyFloat) + if (other instanceof PyFloat) { return ((PyFloat) other).value; - else if (other instanceof PyInteger) + } else if (other instanceof PyInteger) { return ((PyInteger) other).getValue(); - else if (other instanceof PyLong) + } else if (other instanceof PyLong) { return ((PyLong) other).doubleValue(); - else + } else { throw Py.TypeError("xxx"); + } } + @Override public PyObject __add__(PyObject right) { return float___add__(right); } @ExposedMethod(type = MethodType.BINARY, doc = BuiltinDocs.float___add___doc) final PyObject float___add__(PyObject right) { - if (!canCoerce(right)) + if (!canCoerce(right)) { return null; + } double rightv = coerce(right); return new PyFloat(value + rightv); } + @Override public PyObject __radd__(PyObject left) { return float___radd__(left); } @@ -290,42 +308,49 @@ return __add__(left); } + @Override public PyObject __sub__(PyObject right) { return float___sub__(right); } @ExposedMethod(type = MethodType.BINARY, doc = BuiltinDocs.float___sub___doc) final PyObject float___sub__(PyObject right) { - if (!canCoerce(right)) + if (!canCoerce(right)) { return null; + } double rightv = coerce(right); return new PyFloat(value - rightv); } + @Override public PyObject __rsub__(PyObject left) { return float___rsub__(left); } @ExposedMethod(type = MethodType.BINARY, doc = BuiltinDocs.float___rsub___doc) final PyObject float___rsub__(PyObject left) { - if (!canCoerce(left)) + if (!canCoerce(left)) { return null; + } double leftv = coerce(left); return new PyFloat(leftv - value); } + @Override public PyObject __mul__(PyObject right) { return float___mul__(right); } @ExposedMethod(type = MethodType.BINARY, doc = BuiltinDocs.float___mul___doc) final PyObject float___mul__(PyObject right) { - if (!canCoerce(right)) + if (!canCoerce(right)) { return null; + } double rightv = coerce(right); return new PyFloat(value * rightv); } + @Override public PyObject __rmul__(PyObject left) { return float___rmul__(left); } @@ -335,151 +360,185 @@ return __mul__(left); } + @Override public PyObject __div__(PyObject right) { return float___div__(right); } @ExposedMethod(type = MethodType.BINARY, doc = BuiltinDocs.float___div___doc) final PyObject float___div__(PyObject right) { - if (!canCoerce(right)) + if (!canCoerce(right)) { return null; - if (Options.divisionWarning >= 2) + } + if (Options.divisionWarning >= 2) { Py.warning(Py.DeprecationWarning, "classic float division"); + } + double rightv = coerce(right); - if (rightv == 0) + if (rightv == 0) { throw Py.ZeroDivisionError("float division"); + } return new PyFloat(value / rightv); } + @Override public PyObject __rdiv__(PyObject left) { return float___rdiv__(left); } @ExposedMethod(type = MethodType.BINARY, doc = BuiltinDocs.float___rdiv___doc) final PyObject float___rdiv__(PyObject left) { - if (!canCoerce(left)) + if (!canCoerce(left)) { return null; - if (Options.divisionWarning >= 2) + } + if (Options.divisionWarning >= 2) { Py.warning(Py.DeprecationWarning, "classic float division"); + } + double leftv = coerce(left); - if (value == 0) + if (value == 0) { throw Py.ZeroDivisionError("float division"); + } return new PyFloat(leftv / value); } + @Override public PyObject __floordiv__(PyObject right) { return float___floordiv__(right); } @ExposedMethod(type = MethodType.BINARY, doc = BuiltinDocs.float___floordiv___doc) final PyObject float___floordiv__(PyObject right) { - if (!canCoerce(right)) + if (!canCoerce(right)) { return null; + } double rightv = coerce(right); - if (rightv == 0) + if (rightv == 0) { throw Py.ZeroDivisionError("float division"); + } return new PyFloat(Math.floor(value / rightv)); } + @Override public PyObject __rfloordiv__(PyObject left) { return float___rfloordiv__(left); } @ExposedMethod(type = MethodType.BINARY, doc = BuiltinDocs.float___rfloordiv___doc) final PyObject float___rfloordiv__(PyObject left) { - if (!canCoerce(left)) + if (!canCoerce(left)) { return null; + } double leftv = coerce(left); - if (value == 0) + if (value == 0) { throw Py.ZeroDivisionError("float division"); + } return new PyFloat(Math.floor(leftv / value)); } + @Override public PyObject __truediv__(PyObject right) { return float___truediv__(right); } @ExposedMethod(type = MethodType.BINARY, doc = BuiltinDocs.float___truediv___doc) final PyObject float___truediv__(PyObject right) { - if (!canCoerce(right)) + if (!canCoerce(right)) { return null; + } double rightv = coerce(right); - if (rightv == 0) + if (rightv == 0) { throw Py.ZeroDivisionError("float division"); + } return new PyFloat(value / rightv); } + @Override public PyObject __rtruediv__(PyObject left) { return float___rtruediv__(left); } @ExposedMethod(type = MethodType.BINARY, doc = BuiltinDocs.float___rtruediv___doc) final PyObject float___rtruediv__(PyObject left) { - if (!canCoerce(left)) + if (!canCoerce(left)) { return null; + } double leftv = coerce(left); - if (value == 0) + if (value == 0) { throw Py.ZeroDivisionError("float division"); + } return new PyFloat(leftv / value); } private static double modulo(double x, double y) { - if (y == 0) + if (y == 0) { throw Py.ZeroDivisionError("float modulo"); + } double z = Math.IEEEremainder(x, y); - if (z*y < 0) + if (z * y < 0) { z += y; + } return z; } + @Override public PyObject __mod__(PyObject right) { return float___mod__(right); } @ExposedMethod(type = MethodType.BINARY, doc = BuiltinDocs.float___mod___doc) final PyObject float___mod__(PyObject right) { - if (!canCoerce(right)) + if (!canCoerce(right)) { return null; + } double rightv = coerce(right); return new PyFloat(modulo(value, rightv)); } + @Override public PyObject __rmod__(PyObject left) { return float___rmod__(left); } @ExposedMethod(type = MethodType.BINARY, doc = BuiltinDocs.float___rmod___doc) final PyObject float___rmod__(PyObject left) { - if (!canCoerce(left)) + if (!canCoerce(left)) { return null; + } double leftv = coerce(left); return new PyFloat(modulo(leftv, value)); } + @Override public PyObject __divmod__(PyObject right) { return float___divmod__(right); } @ExposedMethod(type = MethodType.BINARY, doc = BuiltinDocs.float___divmod___doc) final PyObject float___divmod__(PyObject right) { - if (!canCoerce(right)) + if (!canCoerce(right)) { return null; + } double rightv = coerce(right); - if (rightv == 0) + if (rightv == 0) { throw Py.ZeroDivisionError("float division"); + } double z = Math.floor(value / rightv); return new PyTuple(new PyFloat(z), new PyFloat(value - z * rightv)); } + @Override public PyObject __rdivmod__(PyObject left) { - if (!canCoerce(left)) + if (!canCoerce(left)) { return null; + } double leftv = coerce(left); - if (value == 0) + if (value == 0) { throw Py.ZeroDivisionError("float division"); + } double z = Math.floor(leftv / value); return new PyTuple(new PyFloat(z), new PyFloat(leftv - z * value)); @@ -487,22 +546,23 @@ @ExposedMethod(type = MethodType.BINARY, doc = BuiltinDocs.float___rdivmod___doc) final PyObject float___rdivmod__(PyObject left) { - return __rdivmod__(left); + return __rdivmod__(left); } - + @Override public PyObject __pow__(PyObject right, PyObject modulo) { return float___pow__(right, modulo); } - @ExposedMethod(type = MethodType.BINARY, defaults = "null", doc = BuiltinDocs.float___pow___doc) + @ExposedMethod(type = MethodType.BINARY, defaults = "null", + doc = BuiltinDocs.float___pow___doc) final PyObject float___pow__(PyObject right, PyObject modulo) { - if (!canCoerce(right)) + if (!canCoerce(right)) { return null; + } if (modulo != null) { - throw Py.TypeError("pow() 3rd argument not allowed " + - "unless all arguments are integers"); + throw Py.TypeError("pow() 3rd argument not allowed unless all arguments are integers"); } return _pow(value, coerce(right), modulo); @@ -510,12 +570,14 @@ @ExposedMethod(type = MethodType.BINARY, doc = BuiltinDocs.float___rpow___doc) final PyObject float___rpow__(PyObject left) { - return __rpow__(left); + return __rpow__(left); } - + + @Override public PyObject __rpow__(PyObject left) { - if (!canCoerce(left)) + if (!canCoerce(left)) { return null; + } return _pow(coerce(left), value, null); } @@ -523,28 +585,27 @@ private static PyFloat _pow(double value, double iw, PyObject modulo) { // Rely completely on Java's pow function if (iw == 0) { - if (modulo != null) + if (modulo != null) { return new PyFloat(modulo(1.0, coerce(modulo))); + } return new PyFloat(1.0); } if (value == 0.0) { - if (iw < 0.0) - throw Py.ZeroDivisionError("0.0 cannot be raised to a " + - "negative power"); + if (iw < 0.0) { + throw Py.ZeroDivisionError("0.0 cannot be raised to a negative power"); + } return new PyFloat(0); } - if (value < 0 && iw != Math.floor(iw)) + if (value < 0 && iw != Math.floor(iw)) { throw Py.ValueError("negative number cannot be raised to a fractional power"); - + } + double ret = Math.pow(value, iw); - if (modulo == null) { - return new PyFloat(ret); - } else { - return new PyFloat(modulo(ret, coerce(modulo))); - } + return new PyFloat(modulo == null ? ret : modulo(ret, coerce(modulo))); } + @Override public PyObject __neg__() { return float___neg__(); } @@ -554,6 +615,7 @@ return new PyFloat(-value); } + @Override public PyObject __pos__() { return float___pos__(); } @@ -563,10 +625,12 @@ return float___float__(); } + @Override public PyObject __invert__() { throw Py.TypeError("bad operand type for unary ~"); } + @Override public PyObject __abs__() { return float___abs__(); } @@ -579,6 +643,7 @@ return float___float__(); } + @Override public PyObject __int__() { return float___int__(); } @@ -586,11 +651,12 @@ @ExposedMethod(doc = BuiltinDocs.float___int___doc) final PyObject float___int__() { if (value <= Integer.MAX_VALUE && value >= Integer.MIN_VALUE) { - return new PyInteger((int)value); + return new PyInteger((int) value); } return __long__(); } + @Override public PyObject __long__() { return float___long__(); } @@ -600,6 +666,7 @@ return new PyLong(value); } + @Override public PyFloat __float__() { return float___float__(); } @@ -611,6 +678,8 @@ } return Py.newFloat(value); } + + @Override public PyComplex __complex__() { return new PyComplex(value, 0.); } @@ -620,10 +689,12 @@ return new PyTuple(new PyObject[] {new PyFloat(getValue())}); } + @Override public PyTuple __getnewargs__() { return float___getnewargs__(); } + @Override public double asDouble() { return value; } @@ -635,23 +706,26 @@ // standard singleton issues apply here to __getformat__/__setformat__, // but this is what Python demands - public enum Format { - UNKNOWN ("unknown"), - BE ("IEEE, big-endian"), - LE ("IEEE, little-endian"); - + + UNKNOWN("unknown"), + BE("IEEE, big-endian"), + LE("IEEE, little-endian"); + private final String format; + Format(String format) { this.format = format; } - public String format() { return format; } + + public String format() { + return format; + } } - - // subset of IEEE-754, the JVM is big-endian + // subset of IEEE-754, the JVM is big-endian public static volatile Format double_format = Format.BE; public static volatile Format float_format = Format.BE; - + @ExposedClassMethod(doc = BuiltinDocs.float___getformat___doc) public static String float___getformat__(PyType type, String typestr) { if ("double".equals(typestr)) { @@ -662,7 +736,7 @@ throw Py.ValueError("__getformat__() argument 1 must be 'double' or 'float'"); } } - + @ExposedClassMethod(doc = BuiltinDocs.float___setformat___doc) public static void float___setformat__(PyType type, String typestr, String format) { Format new_format = null; @@ -670,13 +744,15 @@ throw Py.ValueError("__setformat__() argument 1 must be 'double' or 'float'"); } if (Format.LE.format().equals(format)) { - throw Py.ValueError(String.format("can only set %s format to 'unknown' or the " + "detected platform value", typestr)); + throw Py.ValueError(String.format("can only set %s format to 'unknown' or the " + + "detected platform value", typestr)); } else if (Format.BE.format().equals(format)) { new_format = Format.BE; } else if (Format.UNKNOWN.format().equals(format)) { new_format = Format.UNKNOWN; } else { - throw Py.ValueError("__setformat__() argument 2 must be 'unknown', " + "'IEEE, little-endian' or 'IEEE, big-endian'"); + throw Py.ValueError("__setformat__() argument 2 must be 'unknown', " + + "'IEEE, little-endian' or 'IEEE, big-endian'"); } if (new_format != null) { if ("double".equals(typestr)) { Modified: trunk/jython/src/org/python/core/PyInteger.java =================================================================== --- trunk/jython/src/org/python/core/PyInteger.java 2010-03-13 17:33:14 UTC (rev 6984) +++ trunk/jython/src/org/python/core/PyInteger.java 2010-03-14 21:39:57 UTC (rev 6985) @@ -1,4 +1,7 @@ -// Copyright (c) Corporation for National Research Initiatives +/* + * Copyright (c) Corporation for National Research Initiatives + * Copyright (c) Jython Developers + */ package org.python.core; import java.io.Serializable; @@ -14,7 +17,7 @@ */ @ExposedType(name = "int", doc = BuiltinDocs.int_doc) public class PyInteger extends PyObject { - + public static final PyType TYPE = PyType.fromClass(PyInteger.class); /** The minimum value of an int represented by a BigInteger */ @@ -23,31 +26,41 @@ /** The maximum value of an int represented by a BigInteger */ public static final BigInteger maxInt = BigInteger.valueOf(Integer.MAX_VALUE); + private int value; + + public PyInteger(PyType subType, int v) { + super(subType); + value = v; + } + + public PyInteger(int v) { + this(TYPE, v); + } + @ExposedNew public static PyObject int_new(PyNewWrapper new_, boolean init, PyType subtype, PyObject[] args, String[] keywords) { - ArgParser ap = new ArgParser("int", args, keywords, new String[] { "x", - "base" }, 0); + ArgParser ap = new ArgParser("int", args, keywords, new String[] {"x", "base"}, 0); PyObject x = ap.getPyObject(0, null); int base = ap.getInt(1, -909); if (new_.for_type == subtype) { if (x == null) { return Py.Zero; } - if (base == -909) { - if (x instanceof PyBoolean) { - return (coerce(x) == 0) ? Py.Zero : Py.One; - } - return asPyInteger(x); - } - if (!(x instanceof PyString)) { - throw Py.TypeError("int: can't convert non-string with explicit base"); - } + if (base == -909) { + if (x instanceof PyBoolean) { + return (coerce(x) == 0) ? Py.Zero : Py.One; + } + return asPyInteger(x); + } + if (!(x instanceof PyString)) { + throw Py.TypeError("int: can't convert non-string with explicit base"); + } try { - return Py.newInteger(((PyString)x).atoi(base)); + return Py.newInteger(((PyString) x).atoi(base)); } catch (PyException pye) { if (pye.match(Py.OverflowError)) { - return ((PyString)x).atol(base); + return ((PyString) x).atol(base); } throw pye; } @@ -56,60 +69,51 @@ return new PyIntegerDerived(subtype, 0); } if (base == -909) { - PyObject intOrLong = asPyInteger(x); - if (intOrLong instanceof PyInteger) { - return new PyIntegerDerived(subtype, ((PyInteger) intOrLong).getValue()); - } else { - throw Py.OverflowError("long int too large to convert to int"); - } + PyObject intOrLong = asPyInteger(x); + if (intOrLong instanceof PyInteger) { + return new PyIntegerDerived(subtype, ((PyInteger) intOrLong).getValue()); + } else { + throw Py.OverflowError("long int too large to convert to int"); + } } if (!(x instanceof PyString)) { - throw Py - .TypeError("int: can't convert non-string with explicit base"); + throw Py.TypeError("int: can't convert non-string with explicit base"); } return new PyIntegerDerived(subtype, ((PyString) x).atoi(base)); } } // xxx /** - * @return the result of x.__int__ + * @return the result of x.__int__ * @throws Py.Type error if x.__int__ throws an Py.AttributeError */ - private static PyObject asPyInteger(PyObject x) { - try { - return x.__int__(); - } catch (PyException pye) { - if (!pye.match(Py.AttributeError)) - throw pye; - throw Py.TypeError("int() argument must be a string or a number"); - } - } - - private int value; - - public PyInteger(PyType subType, int v) { - super(subType); - value = v; + private static PyObject asPyInteger(PyObject x) { + try { + return x.__int__(); + } catch (PyException pye) { + if (!pye.match(Py.AttributeError)) { + throw pye; + } + throw Py.TypeError("int() argument must be a string or a number"); + } } - public PyInteger(int v) { - this(TYPE, v); - } - public int getValue() { return value; } + @Override public String toString() { return int_toString(); } - //XXX: need separate __doc__ for __repr__ + // XXX: need separate __doc__ for __repr__ @ExposedMethod(names = {"__str__", "__repr__"}, doc = BuiltinDocs.int___str___doc) final String int_toString() { return Integer.toString(getValue()); } + @Override public int hashCode() { return int_hashCode(); } @@ -119,6 +123,7 @@ return getValue(); } + @Override public boolean __nonzero__() { return int___nonzero__(); } @@ -128,42 +133,50 @@ return getValue() != 0; } + @Override public Object __tojava__(Class<?> c) { - if (c == Integer.TYPE || c == Number.class || - c == Object.class || c == Integer.class || - c == Serializable.class) - { + if (c == Integer.TYPE || c == Number.class || c == Object.class || c == Integer.class + || c == Serializable.class) { return new Integer(getValue()); } - if (c == Boolean.TYPE || c == Boolean.class) + if (c == Boolean.TYPE || c == Boolean.class) { return new Boolean(getValue() != 0); - if (c == Byte.TYPE || c == Byte.class) - return new Byte((byte)getValue()); - if (c == Short.TYPE || c == Short.class) - return new Short((short)getValue()); + } + if (c == Byte.TYPE || c == Byte.class) { + return new Byte((byte) getValue()); + } + if (c == Short.TYPE || c == Short.class) { + return new Short((short) getValue()); + } - if (c == Long.TYPE || c == Long.class) + if (c == Long.TYPE || c == Long.class) { return new Long(getValue()); - if (c == Float.TYPE || c == Float.class) + } + if (c == Float.TYPE || c == Float.class) { return new Float(getValue()); - if (c == Double.TYPE || c == Double.class) + } + if (c == Double.TYPE || c == Double.class) { return new Double(getValue()); + } return super.__tojava__(c); } + @Override public int __cmp__(PyObject other) { return int___cmp__(other); } @ExposedMethod(type = MethodType.CMP, doc = BuiltinDocs.int___cmp___doc) final int int___cmp__(PyObject other) { - if (!canCoerce(other)) - return -2; + if (!canCoerce(other)) { + return -2; + } int v = coerce(other); return getValue() < v ? -1 : getValue() > v ? 1 : 0; } + @Override public Object __coerce_ex__(PyObject other) { return int___coerce_ex__(other); } @@ -173,15 +186,12 @@ return adaptToCoerceTuple(int___coerce_ex__(other)); } - /** + /** * Coercion logic for int. Implemented as a final method to avoid - * invocation of virtual methods from the exposed coerced. - */ + * invocation of virtual methods from the exposed coerced. + */ final Object int___coerce_ex__(PyObject other) { - if (other instanceof PyInteger) - return other; - else - return Py.None; + return other instanceof PyInteger ? other : Py.None; } private static final boolean canCoerce(PyObject other) { @@ -189,30 +199,33 @@ } private static final int coerce(PyObject other) { - if (other instanceof PyInteger) + if (other instanceof PyInteger) { return ((PyInteger) other).getValue(); - else - throw Py.TypeError("xxx"); + } + throw Py.TypeError("xxx"); } - + @Override public PyObject __add__(PyObject right) { return int___add__(right); } @ExposedMethod(type = MethodType.BINARY, doc = BuiltinDocs.int___add___doc) final PyObject int___add__(PyObject right) { - if (!canCoerce(right)) + if (!canCoerce(right)) { return null; + } int rightv = coerce(right); int a = getValue(); int b = rightv; int x = a + b; - if ((x^a) >= 0 || (x^b) >= 0) + if ((x ^ a) >= 0 || (x ^ b) >= 0) { return Py.newInteger(x); - return new PyLong((long) a + (long)b); + } + return new PyLong((long) a + (long) b); } + @Override public PyObject __radd__(PyObject left) { return int___radd__(left); } @@ -224,57 +237,64 @@ private static PyObject _sub(int a, int b) { int x = a - b; - if ((x^a) >= 0 || (x^~b) >= 0) + if ((x ^ a) >= 0 || (x ^ ~b) >= 0) { return Py.newInteger(x); - return new PyLong((long) a - (long)b); + } + return new PyLong((long) a - (long) b); } + @Override public PyObject __sub__(PyObject right) { return int___sub__(right); } @ExposedMethod(type = MethodType.BINARY, doc = BuiltinDocs.int___sub___doc) final PyObject int___sub__(PyObject right) { - if (!canCoerce(right)) + if (!canCoerce(right)) { return null; + } return _sub(getValue(), coerce(right)); } + @Override public PyObject __rsub__(PyObject left) { return int___rsub__(left); } @ExposedMethod(type = MethodType.BINARY, doc = BuiltinDocs.int___rsub___doc) final PyObject int___rsub__(PyObject left) { - if (!canCoerce(left)) + if (!canCoerce(left)) { return null; + } return _sub(coerce(left), getValue()); } + @Override public PyObject __mul__(PyObject right) { return int___mul__(right); } @ExposedMethod(type = MethodType.BINARY, doc = BuiltinDocs.int___mul___doc) final PyObject int___mul__(PyObject right) { - if (!canCoerce(right)) + if (!canCoerce(right)) { return null; + } int rightv = coerce(right); double x = getValue(); x *= rightv; - //long x = ((long)getValue())*((PyInteger)right).getValue(); - //System.out.println("mul: "+this+" * "+right+" = "+x); - if (x <= Integer.MAX_VALUE && x >= Integer.MIN_VALUE) - return Py.newInteger((int)x); + if (x <= Integer.MAX_VALUE && x >= Integer.MIN_VALUE) { + return Py.newInteger((int) x); + } return __long__().__mul__(right); } + @Override public PyObject __rmul__(PyObject left) { return int___rmul__(left); } - + @ExposedMethod(type = MethodType.BINARY, doc = BuiltinDocs.int___rmul___doc) final PyObject int___rmul__(PyObject left) { return __mul__(left); @@ -288,13 +308,11 @@ } long xdivy = x / y; long xmody = x - xdivy * y; - - /* If the signs of x and y differ, and the remainder is non-0, - * C89 doesn't define whether xdivy is now the floor or the - * ceiling of the infinitely precise quotient. We want the floor, - * and we have it iff the remainder's sign matches y's. - */ - + + // If the signs of x and y differ, and the remainder is non-0, C89 doesn't define + // whether xdivy is now the floor or the ceiling of the infinitely precise + // quotient. We want the floor, and we have it iff the remainder's sign matches + // y's. if (xmody != 0 && ((y < 0 && xmody > 0) || (y > 0 && xmody < 0))) { xmody += y; --xdivy; @@ -307,128 +325,148 @@ public PyObject __div__(PyObject right) { return int___div__(right); } - + @ExposedMethod(type = MethodType.BINARY, doc = BuiltinDocs.int___div___doc) final PyObject int___div__(PyObject right) { - if (!canCoerce(right)) + if (!canCoerce(right)) { return null; - if (Options.divisionWarning > 0) + } + if (Options.divisionWarning > 0) { Py.warning(Py.DeprecationWarning, "classic int division"); + } return Py.newInteger(divide(getValue(), coerce(right))); } + @Override public PyObject __rdiv__(PyObject left) { return int___rdiv__(left); } @ExposedMethod(type = MethodType.BINARY, doc = BuiltinDocs.int___rdiv___doc) final PyObject int___rdiv__(PyObject left) { - if (!canCoerce(left)) + if (!canCoerce(left)) { return null; - if (Options.divisionWarning > 0) + } + if (Options.divisionWarning > 0) { Py.warning(Py.DeprecationWarning, "classic int division"); + } return Py.newInteger(divide(coerce(left), getValue())); } + @Override public PyObject __floordiv__(PyObject right) { return int___floordiv__(right); } @ExposedMethod(type = MethodType.BINARY, doc = BuiltinDocs.int___floordiv___doc) final PyObject int___floordiv__(PyObject right) { - if (!canCoerce(right)) + if (!canCoerce(right)) { return null; + } return Py.newInteger(divide(getValue(), coerce(right))); } + @Override public PyObject __rfloordiv__(PyObject left) { return int___rfloordiv__(left); } @ExposedMethod(type = MethodType.BINARY, doc = BuiltinDocs.int___rfloordiv___doc) final PyObject int___rfloordiv__(PyObject left) { - if (!canCoerce(left)) + if (!canCoerce(left)) { return null; + } return Py.newInteger(divide(coerce(left), getValue())); } + @Override public PyObject __truediv__(PyObject right) { return int___truediv__(right); } @ExposedMethod(type = MethodType.BINARY, doc = BuiltinDocs.int___truediv___doc) final PyObject int___truediv__(PyObject right) { - if (right instanceof PyInteger) + if (right instanceof PyInteger) { return __float__().__truediv__(right); - else if(right instanceof PyLong) + } else if (right instanceof PyLong) { return int___long__().__truediv__(right); - ... [truncated message content] |
From: <pj...@us...> - 2010-04-17 16:51:19
|
Revision: 7031 http://jython.svn.sourceforge.net/jython/?rev=7031&view=rev Author: pjenvey Date: 2010-04-17 16:51:11 +0000 (Sat, 17 Apr 2010) Log Message: ----------- minor cleanup Modified Paths: -------------- trunk/jython/src/org/python/core/PyBuiltinCallable.java trunk/jython/src/org/python/core/PyXRange.java Modified: trunk/jython/src/org/python/core/PyBuiltinCallable.java =================================================================== --- trunk/jython/src/org/python/core/PyBuiltinCallable.java 2010-04-16 18:50:03 UTC (rev 7030) +++ trunk/jython/src/org/python/core/PyBuiltinCallable.java 2010-04-17 16:51:11 UTC (rev 7031) @@ -1,3 +1,4 @@ +/* Copyright (c) Jython Developers */ package org.python.core; import org.python.expose.ExposedGet; @@ -53,6 +54,7 @@ this.info = info; } + @Override public String toString() { PyObject self = getSelf(); if (self == null) { @@ -76,6 +78,10 @@ public static class DefaultInfo implements Info { + private String name; + + private int maxargs, minargs; + public DefaultInfo(String name, int minargs, int maxargs) { this.name = name; this.minargs = minargs; @@ -86,10 +92,6 @@ this(name, -1, -1); } - private String name; - - private int maxargs, minargs; - public String getName() { return name; } @@ -103,39 +105,39 @@ } public static boolean check(int nargs, int minargs, int maxargs) { - if(nargs < minargs) + if (nargs < minargs) { return false; - if(maxargs != -1 && nargs > maxargs) + } + if (maxargs != -1 && nargs > maxargs) { return false; + } return true; } - public static PyException unexpectedCall(int nargs, - boolean keywords, - String name, - int minargs, - int maxargs) { - if(keywords) + public static PyException unexpectedCall(int nargs, boolean keywords, String name, + int minargs, int maxargs) { + if (keywords) { return Py.TypeError(name + "() takes no keyword arguments"); + } + String argsblurb; - if(minargs == maxargs) { - if(minargs == 0) + if (minargs == maxargs) { + if (minargs == 0) { argsblurb = "no arguments"; - else if(minargs == 1) + } else if (minargs == 1) { argsblurb = "exactly one argument"; - else + } else { argsblurb = minargs + " arguments"; - } else if(maxargs == -1) { - return Py.TypeError(name + "() requires at least " + minargs - + " (" + nargs + " given)"); + } + } else if (maxargs == -1) { + return Py.TypeError(String.format("%s() requires at least %d arguments (%d) given", + name, minargs, nargs)); + } else if (minargs <= 0) { + argsblurb = "at most " + maxargs + " arguments"; } else { - if(minargs <= 0) - argsblurb = "at most " + maxargs + " arguments"; - else - argsblurb = minargs + "-" + maxargs + " arguments"; + argsblurb = minargs + "-" + maxargs + " arguments"; } - return Py.TypeError(name + "() takes " + argsblurb + " (" + nargs - + " given)"); + return Py.TypeError(String.format("%s() takes %s (%d given)", name, argsblurb, nargs)); } public PyException unexpectedCall(int nargs, boolean keywords) { Modified: trunk/jython/src/org/python/core/PyXRange.java =================================================================== --- trunk/jython/src/org/python/core/PyXRange.java 2010-04-16 18:50:03 UTC (rev 7030) +++ trunk/jython/src/org/python/core/PyXRange.java 2010-04-17 16:51:11 UTC (rev 7031) @@ -14,11 +14,11 @@ public static final PyType TYPE = PyType.fromClass(PyXRange.class); - private int start; + private final int start; - private int step; + private final int step; - private int len; + private final int len; public PyXRange(int ihigh) { this(0, ihigh, 1); @@ -145,15 +145,13 @@ @Override public String toString() { - String rtn; int stop = start + len * step; if (start == 0 && step == 1) { - rtn = String.format("xrange(%d)", stop); + return String.format("xrange(%d)", stop); } else if (step == 1) { - rtn = String.format("xrange(%d, %d)", start, stop); + return String.format("xrange(%d, %d)", start, stop); } else { - rtn = String.format("xrange(%d, %d, %d)", start, stop, step); + return String.format("xrange(%d, %d, %d)", start, stop, step); } - return rtn; } } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <zy...@us...> - 2010-08-17 19:23:28
|
Revision: 7097 http://jython.svn.sourceforge.net/jython/?rev=7097&view=rev Author: zyasoft Date: 2010-08-17 19:23:22 +0000 (Tue, 17 Aug 2010) Log Message: ----------- Refactored PyBoolean, PyFloat, PyLong so they consistently use getValue instead of accessing the field value directly. Fixes #1645, although we are awaiting more unit tests on how this be used by user types. Modified Paths: -------------- trunk/jython/src/org/python/core/PyBoolean.java trunk/jython/src/org/python/core/PyFloat.java trunk/jython/src/org/python/core/PyLong.java Modified: trunk/jython/src/org/python/core/PyBoolean.java =================================================================== --- trunk/jython/src/org/python/core/PyBoolean.java 2010-08-16 16:45:29 UTC (rev 7096) +++ trunk/jython/src/org/python/core/PyBoolean.java 2010-08-17 19:23:22 UTC (rev 7097) @@ -7,17 +7,27 @@ import org.python.expose.MethodType; /** - * The builtin python bool. + * The builtin python bool. It would be nice if it didn't extend PyInteger, + * but too hard to avoid pre-Python 2.2 semantics here. */ @ExposedType(name = "bool", isBaseType = false, doc = BuiltinDocs.bool_doc) public class PyBoolean extends PyInteger { public static final PyType TYPE = PyType.fromClass(PyBoolean.class); - private boolean value; + private final boolean value; + public boolean getBooleanValue() { + return value; + } + + @Override + public int getValue() { + return getBooleanValue() ? 1 : 0; + } + public PyBoolean(boolean value) { - super(TYPE, value ? 1 : 0); + super(TYPE, value ? 1 : 0); // XXX is this necessary? this.value = value; } @@ -39,7 +49,7 @@ @ExposedMethod(names = {"__str__", "__repr__"}, doc = BuiltinDocs.bool___str___doc) final String bool_toString() { - return value ? "True" : "False"; + return getBooleanValue() ? "True" : "False"; } @Override @@ -49,7 +59,7 @@ @ExposedMethod(doc = BuiltinDocs.bool___hash___doc) final int bool___hash__() { - return value ? 1 : 0; + return getBooleanValue() ? 1 : 0; } @Override @@ -59,31 +69,31 @@ @ExposedMethod(doc = BuiltinDocs.bool___nonzero___doc) final boolean bool___nonzero__() { - return value; + return getBooleanValue(); } @Override public Object __tojava__(Class<?> c) { if (c == Boolean.TYPE || c == Boolean.class || c == Object.class ) { - return Boolean.valueOf(value); + return Boolean.valueOf(getBooleanValue()); } if (c == Integer.TYPE || c == Number.class || c == Integer.class) { - return Integer.valueOf(value ? 1 : 0); + return Integer.valueOf(getValue()); } if (c == Byte.TYPE || c == Byte.class) { - return Byte.valueOf((byte)(value ? 1 : 0)); + return Byte.valueOf((byte)(getValue())); } if (c == Short.TYPE || c == Short.class) { - return Short.valueOf((short)(value ? 1 : 0)); + return Short.valueOf((short)(getValue())); } if (c == Long.TYPE || c == Long.class) { - return Long.valueOf(value ? 1 : 0); + return Long.valueOf(getValue()); } if (c == Float.TYPE || c == Float.class) { - return Float.valueOf(value ? 1 : 0); + return Float.valueOf(getValue()); } if (c == Double.TYPE || c == Double.class) { - return Double.valueOf(value ? 1 : 0); + return Double.valueOf(getValue()); } return super.__tojava__(c); } @@ -96,7 +106,7 @@ @ExposedMethod(type = MethodType.BINARY, doc = BuiltinDocs.bool___and___doc) final PyObject bool___and__(PyObject right) { if (right instanceof PyBoolean) { - return Py.newBoolean(value & ((PyBoolean)right).value); + return Py.newBoolean(getBooleanValue() & ((PyBoolean) right).getBooleanValue()); } else if (right instanceof PyInteger) { return Py.newInteger(getValue() & ((PyInteger)right).getValue()); } else { @@ -112,7 +122,7 @@ @ExposedMethod(type = MethodType.BINARY, doc = BuiltinDocs.bool___xor___doc) final PyObject bool___xor__(PyObject right) { if (right instanceof PyBoolean) { - return Py.newBoolean(value ^ ((PyBoolean)right).value); + return Py.newBoolean(getBooleanValue() ^ ((PyBoolean) right).getBooleanValue()); } else if (right instanceof PyInteger) { return Py.newInteger(getValue() ^ ((PyInteger)right).getValue()); } else { @@ -128,7 +138,7 @@ @ExposedMethod(type = MethodType.BINARY, doc = BuiltinDocs.bool___or___doc) final PyObject bool___or__(PyObject right) { if (right instanceof PyBoolean) { - return Py.newBoolean(value | ((PyBoolean)right).value); + return Py.newBoolean(getBooleanValue() | ((PyBoolean) right).getBooleanValue()); } else if (right instanceof PyInteger) { return Py.newInteger(getValue() | ((PyInteger)right).getValue()); } else { @@ -143,7 +153,7 @@ @ExposedMethod(doc = BuiltinDocs.bool___neg___doc) final PyObject bool___neg__() { - return Py.newInteger(value ? -1 : 0); + return Py.newInteger(getBooleanValue() ? -1 : 0); } @Override @@ -153,7 +163,7 @@ @ExposedMethod(doc = BuiltinDocs.bool___pos___doc) final PyObject bool___pos__() { - return Py.newInteger(value ? 1 : 0); + return Py.newInteger(getValue()); } @Override @@ -163,6 +173,6 @@ @ExposedMethod(doc = BuiltinDocs.bool___abs___doc) final PyObject bool___abs__() { - return Py.newInteger(value ? 1 : 0); + return Py.newInteger(getValue()); } } Modified: trunk/jython/src/org/python/core/PyFloat.java =================================================================== --- trunk/jython/src/org/python/core/PyFloat.java 2010-08-16 16:45:29 UTC (rev 7096) +++ trunk/jython/src/org/python/core/PyFloat.java 2010-08-17 19:23:22 UTC (rev 7097) @@ -25,8 +25,12 @@ private static final int PREC_REPR = 17; private static final int PREC_STR = 12; - private double value; + private final double value; + public double getValue() { + return value; + } + public PyFloat(PyType subtype, double v) { super(subtype); value = v; @@ -81,10 +85,6 @@ return !Double.isInfinite(value) && !Double.isNaN(value); } - public double getValue() { - return value; - } - @Override public String toString() { return __str__().toString(); @@ -111,7 +111,7 @@ } private String formatDouble(int precision) { - if (Double.isNaN(value)) { + if (Double.isNaN(getValue())) { return "nan"; } @@ -140,17 +140,17 @@ @ExposedMethod(doc = BuiltinDocs.float___hash___doc) final int float___hash__() { - double intPart = Math.floor(value); - double fractPart = value - intPart; + double intPart = Math.floor(getValue()); + double fractPart = getValue() - intPart; if (fractPart == 0) { if (intPart <= Integer.MAX_VALUE && intPart >= Integer.MIN_VALUE) { - return (int) value; + return (int) getValue(); } else { return __long__().hashCode(); } } else { - long v = Double.doubleToLongBits(value); + long v = Double.doubleToLongBits(getValue()); return (int) v ^ (int) (v >> 32); } } @@ -162,17 +162,17 @@ @ExposedMethod(doc = BuiltinDocs.float___nonzero___doc) final boolean float___nonzero__() { - return value != 0; + return getValue() != 0; } @Override public Object __tojava__(Class<?> c) { if (c == Double.TYPE || c == Number.class || c == Double.class || c == Object.class || c == Serializable.class) { - return new Double(value); + return new Double(getValue()); } if (c == Float.TYPE || c == Float.class) { - return new Float(value); + return new Float(getValue()); } return super.__tojava__(c); } @@ -181,7 +181,7 @@ public PyObject __eq__(PyObject other) { // preclude _cmp_unsafe's this == other shortcut because NaN != anything, even // itself - if (Double.isNaN(value)) { + if (Double.isNaN(getValue())) { return Py.False; } return null; @@ -189,7 +189,7 @@ @Override public PyObject __ne__(PyObject other) { - if (Double.isNaN(value)) { + if (Double.isNaN(getValue())) { return Py.True; } return null; @@ -203,11 +203,11 @@ // XXX: needs __doc__ @ExposedMethod(type = MethodType.CMP) final int float___cmp__(PyObject other) { - double i = value; + double i = getValue(); double j; if (other instanceof PyFloat) { - j = ((PyFloat) other).value; + j = ((PyFloat) other).getValue(); } else if (!isFinite()) { // we're infinity: our magnitude exceeds any finite // integer, so it doesn't matter which int we compare i @@ -220,7 +220,7 @@ } else if (other instanceof PyInteger) { j = ((PyInteger) other).getValue(); } else if (other instanceof PyLong) { - BigDecimal v = new BigDecimal(value); + BigDecimal v = new BigDecimal(getValue()); BigDecimal w = new BigDecimal(((PyLong) other).getValue()); return v.compareTo(w); } else { @@ -274,7 +274,7 @@ private static final double coerce(PyObject other) { if (other instanceof PyFloat) { - return ((PyFloat) other).value; + return ((PyFloat) other).getValue(); } else if (other instanceof PyInteger) { return ((PyInteger) other).getValue(); } else if (other instanceof PyLong) { @@ -295,7 +295,7 @@ return null; } double rightv = coerce(right); - return new PyFloat(value + rightv); + return new PyFloat(getValue() + rightv); } @Override @@ -319,7 +319,7 @@ return null; } double rightv = coerce(right); - return new PyFloat(value - rightv); + return new PyFloat(getValue() - rightv); } @Override @@ -333,7 +333,7 @@ return null; } double leftv = coerce(left); - return new PyFloat(leftv - value); + return new PyFloat(leftv - getValue()); } @Override @@ -347,7 +347,7 @@ return null; } double rightv = coerce(right); - return new PyFloat(value * rightv); + return new PyFloat(getValue() * rightv); } @Override @@ -378,7 +378,7 @@ if (rightv == 0) { throw Py.ZeroDivisionError("float division"); } - return new PyFloat(value / rightv); + return new PyFloat(getValue() / rightv); } @Override @@ -396,10 +396,10 @@ } double leftv = coerce(left); - if (value == 0) { + if (getValue() == 0) { throw Py.ZeroDivisionError("float division"); } - return new PyFloat(leftv / value); + return new PyFloat(leftv / getValue()); } @Override @@ -416,7 +416,7 @@ if (rightv == 0) { throw Py.ZeroDivisionError("float division"); } - return new PyFloat(Math.floor(value / rightv)); + return new PyFloat(Math.floor(getValue() / rightv)); } @Override @@ -430,10 +430,10 @@ return null; } double leftv = coerce(left); - if (value == 0) { + if (getValue() == 0) { throw Py.ZeroDivisionError("float division"); } - return new PyFloat(Math.floor(leftv / value)); + return new PyFloat(Math.floor(leftv / getValue())); } @Override @@ -450,7 +450,7 @@ if (rightv == 0) { throw Py.ZeroDivisionError("float division"); } - return new PyFloat(value / rightv); + return new PyFloat(getValue() / rightv); } @Override @@ -464,10 +464,10 @@ return null; } double leftv = coerce(left); - if (value == 0) { + if (getValue() == 0) { throw Py.ZeroDivisionError("float division"); } - return new PyFloat(leftv / value); + return new PyFloat(leftv / getValue()); } private static double modulo(double x, double y) { @@ -492,7 +492,7 @@ return null; } double rightv = coerce(right); - return new PyFloat(modulo(value, rightv)); + return new PyFloat(modulo(getValue(),rightv)); } @Override @@ -506,7 +506,7 @@ return null; } double leftv = coerce(left); - return new PyFloat(modulo(leftv, value)); + return new PyFloat(modulo(leftv, getValue())); } @Override @@ -524,9 +524,9 @@ if (rightv == 0) { throw Py.ZeroDivisionError("float division"); } - double z = Math.floor(value / rightv); + double z = Math.floor(getValue() / rightv); - return new PyTuple(new PyFloat(z), new PyFloat(value - z * rightv)); + return new PyTuple(new PyFloat(z), new PyFloat(getValue() - z * rightv)); } @Override @@ -536,12 +536,12 @@ } double leftv = coerce(left); - if (value == 0) { + if (getValue() == 0) { throw Py.ZeroDivisionError("float division"); } - double z = Math.floor(leftv / value); + double z = Math.floor(leftv / getValue()); - return new PyTuple(new PyFloat(z), new PyFloat(leftv - z * value)); + return new PyTuple(new PyFloat(z), new PyFloat(leftv - z * getValue())); } @ExposedMethod(type = MethodType.BINARY, doc = BuiltinDocs.float___rdivmod___doc) @@ -565,7 +565,7 @@ throw Py.TypeError("pow() 3rd argument not allowed unless all arguments are integers"); } - return _pow(value, coerce(right), modulo); + return _pow( getValue(), coerce(right), modulo); } @ExposedMethod(type = MethodType.BINARY, doc = BuiltinDocs.float___rpow___doc) @@ -579,7 +579,7 @@ return null; } - return _pow(coerce(left), value, null); + return _pow(coerce(left), getValue(), null); } private static PyFloat _pow(double value, double iw, PyObject modulo) { @@ -612,7 +612,7 @@ @ExposedMethod(doc = BuiltinDocs.float___neg___doc) final PyObject float___neg__() { - return new PyFloat(-value); + return new PyFloat(-getValue()); } @Override @@ -637,7 +637,7 @@ @ExposedMethod(doc = BuiltinDocs.float___abs___doc) final PyObject float___abs__() { - if (value < 0) { + if (getValue() < 0) { return float___neg__(); } return float___float__(); @@ -650,8 +650,8 @@ @ExposedMethod(doc = BuiltinDocs.float___int___doc) final PyObject float___int__() { - if (value <= Integer.MAX_VALUE && value >= Integer.MIN_VALUE) { - return new PyInteger((int) value); + if (getValue() <= Integer.MAX_VALUE && getValue() >= Integer.MIN_VALUE) { + return new PyInteger((int) getValue()); } return __long__(); } @@ -663,7 +663,7 @@ @ExposedMethod(doc = BuiltinDocs.float___long___doc) final PyObject float___long__() { - return new PyLong(value); + return new PyLong(getValue()); } @Override @@ -676,12 +676,12 @@ if (getType() == TYPE) { return this; } - return Py.newFloat(value); + return Py.newFloat(getValue()); } @Override public PyComplex __complex__() { - return new PyComplex(value, 0.); + return new PyComplex(getValue(), 0.); } @ExposedMethod(doc = BuiltinDocs.float___getnewargs___doc) @@ -696,7 +696,7 @@ @Override public double asDouble() { - return value; + return getValue(); } @Override Modified: trunk/jython/src/org/python/core/PyLong.java =================================================================== --- trunk/jython/src/org/python/core/PyLong.java 2010-08-16 16:45:29 UTC (rev 7096) +++ trunk/jython/src/org/python/core/PyLong.java 2010-08-17 19:23:22 UTC (rev 7097) @@ -36,8 +36,12 @@ @Deprecated public static final BigInteger maxULong = MAX_ULONG; - private BigInteger value; + private final BigInteger value; + public BigInteger getValue() { + return value; + } + public PyLong(PyType subType, BigInteger v) { super(subType); value = v; @@ -107,7 +111,7 @@ int intValue = ((PyInteger) tmp).getValue(); return new PyLongDerived(subtype, BigInteger.valueOf(intValue)); } else { - return new PyLongDerived(subtype, ((PyLong) tmp).value); + return new PyLongDerived(subtype, ((PyLong) tmp).getValue()); } } @@ -125,10 +129,6 @@ return new BigDecimal(value).toBigInteger(); } - public BigInteger getValue() { - return value; - } - @Override public String toString() { return long_toString(); @@ -136,7 +136,7 @@ @ExposedMethod(names = {"__str__", "__repr__"}, doc = BuiltinDocs.long___str___doc) final String long_toString() { - return value.toString() + "L"; + return getValue().toString() + "L"; } @Override @@ -146,7 +146,7 @@ @ExposedMethod(doc = BuiltinDocs.long___hash___doc) final int long___hash__() { - return value.intValue(); + return getValue().intValue(); } @Override @@ -160,7 +160,7 @@ } public double doubleValue() { - double v = value.doubleValue(); + double v = getValue().doubleValue(); if (Double.isInfinite(v)) { throw Py.OverflowError("long int too large to convert to float"); } @@ -196,7 +196,7 @@ } public double scaledDoubleValue(int[] exp) { - return scaledDoubleValue(value, exp); + return scaledDoubleValue(getValue(),exp); } public long getLong(long min, long max) { @@ -204,8 +204,8 @@ } public long getLong(long min, long max, String overflowMsg) { - if (value.compareTo(MAX_LONG) <= 0 && value.compareTo(MIN_LONG) >= 0) { - long v = value.longValue(); + if (getValue().compareTo(MAX_LONG) <= 0 && getValue().compareTo(MIN_LONG) >= 0) { + long v = getValue().longValue(); if (v >= min && v <= max) { return v; } @@ -255,7 +255,7 @@ } if (c == BigInteger.class || c == Number.class || c == Object.class || c == Serializable.class) { - return value; + return getValue(); } } catch (PyException e) { return Py.NoConversion; @@ -273,7 +273,7 @@ if (!canCoerce(other)) { return -2; } - return value.compareTo(coerce(other)); + return getValue().compareTo(coerce(other)); } @Override @@ -306,7 +306,7 @@ private static final BigInteger coerce(PyObject other) { if (other instanceof PyLong) { - return ((PyLong) other).value; + return ((PyLong) other).getValue(); } else if (other instanceof PyInteger) { return BigInteger.valueOf(((PyInteger) other).getValue()); } else { @@ -324,7 +324,7 @@ if (!canCoerce(right)) { return null; } - return Py.newLong(value.add(coerce(right))); + return Py.newLong(getValue().add(coerce(right))); } @Override @@ -347,7 +347,7 @@ if (!canCoerce(right)) { return null; } - return Py.newLong(value.subtract(coerce(right))); + return Py.newLong(getValue().subtract(coerce(right))); } @Override @@ -357,7 +357,7 @@ @ExposedMethod(type = MethodType.BINARY, doc = BuiltinDocs.long___rsub___doc) final PyObject long___rsub__(PyObject left) { - return Py.newLong(coerce(left).subtract(value)); + return Py.newLong(coerce(left).subtract(getValue())); } @Override @@ -374,7 +374,7 @@ if (!canCoerce(right)) { return null; } - return Py.newLong(value.multiply(coerce(right))); + return Py.newLong(getValue().multiply(coerce(right))); } @Override @@ -390,7 +390,7 @@ if (!canCoerce(left)) { return null; } - return Py.newLong(coerce(left).multiply(value)); + return Py.newLong(coerce(left).multiply(getValue())); } // Getting signs correct for integer division @@ -426,7 +426,7 @@ if (Options.divisionWarning > 0) { Py.warning(Py.DeprecationWarning, "classic long division"); } - return Py.newLong(divide(value, coerce(right))); + return Py.newLong(divide( getValue(), coerce(right))); } @Override @@ -442,7 +442,7 @@ if (Options.divisionWarning > 0) { Py.warning(Py.DeprecationWarning, "classic long division"); } - return Py.newLong(divide(coerce(left), value)); + return Py.newLong(divide(coerce(left), getValue())); } @Override @@ -455,7 +455,7 @@ if (!canCoerce(right)) { return null; } - return Py.newLong(divide(value, coerce(right))); + return Py.newLong(divide( getValue(), coerce(right))); } @Override @@ -468,7 +468,7 @@ if (!canCoerce(left)) { return null; } - return Py.newLong(divide(coerce(left), value)); + return Py.newLong(divide(coerce(left), getValue())); } private static final PyFloat true_divide(BigInteger a, BigInteger b) { @@ -511,7 +511,7 @@ if (!canCoerce(right)) { return null; } - return true_divide(this.value, coerce(right)); + return true_divide( this.getValue(), coerce(right)); } @Override @@ -524,7 +524,7 @@ if (!canCoerce(left)) { return null; } - return true_divide(coerce(left), this.value); + return true_divide(coerce(left), this.getValue()); } private BigInteger modulo(BigInteger x, BigInteger y, BigInteger xdivy) { @@ -542,7 +542,7 @@ return null; } BigInteger rightv = coerce(right); - return Py.newLong(modulo(value, rightv, divide(value, rightv))); + return Py.newLong(modulo(getValue(),rightv, divide(getValue(),rightv))); } @Override @@ -556,7 +556,7 @@ return null; } BigInteger leftv = coerce(left); - return Py.newLong(modulo(leftv, value, divide(leftv, value))); + return Py.newLong(modulo(leftv, getValue(), divide(leftv, getValue()))); } @Override @@ -571,8 +571,8 @@ } BigInteger rightv = coerce(right); - BigInteger xdivy = divide(value, rightv); - return new PyTuple(Py.newLong(xdivy), Py.newLong(modulo(value, rightv, xdivy))); + BigInteger xdivy = divide(getValue(),rightv); + return new PyTuple(Py.newLong(xdivy), Py.newLong(modulo(getValue(),rightv, xdivy))); } @Override @@ -587,8 +587,8 @@ } BigInteger leftv = coerce(left); - BigInteger xdivy = divide(leftv, value); - return new PyTuple(Py.newLong(xdivy), Py.newLong(modulo(leftv, value, xdivy))); + BigInteger xdivy = divide(leftv, getValue()); + return new PyTuple(Py.newLong(xdivy), Py.newLong(modulo(leftv, getValue(), xdivy))); } @Override @@ -606,7 +606,7 @@ if (modulo != null && !canCoerce(right)) { return null; } - return _pow(value, coerce(right), modulo, this, right); + return _pow( getValue(), coerce(right), modulo, this, right); } @Override @@ -619,7 +619,7 @@ if (!canCoerce(left)) { return null; } - return _pow(coerce(left), value, null, left, this); + return _pow(coerce(left), getValue(), null, left, this); } public static PyObject _pow(BigInteger value, BigInteger y, PyObject modulo, PyObject left, @@ -693,7 +693,7 @@ if (rightv < 0) { throw Py.ValueError("negative shift count"); } - return Py.newLong(value.shiftLeft(rightv)); + return Py.newLong(getValue().shiftLeft(rightv)); } @ExposedMethod(type = MethodType.BINARY, doc = BuiltinDocs.long___rlshift___doc) @@ -701,7 +701,7 @@ if (!canCoerce(left)) { return null; } - if (value.intValue() < 0) { + if (getValue().intValue() < 0) { throw Py.ValueError("negative shift count"); } return Py.newLong(coerce(left).shiftLeft(coerceInt(this))); @@ -721,7 +721,7 @@ if (rightv < 0) { throw Py.ValueError("negative shift count"); } - return Py.newLong(value.shiftRight(rightv)); + return Py.newLong(getValue().shiftRight(rightv)); } @ExposedMethod(type = MethodType.BINARY, doc = BuiltinDocs.long___rrshift___doc) @@ -729,7 +729,7 @@ if (!canCoerce(left)) { return null; } - if (value.intValue() < 0) { + if (getValue().intValue() < 0) { throw Py.ValueError("negative shift count"); } return Py.newLong(coerce(left).shiftRight(coerceInt(this))); @@ -745,7 +745,7 @@ if (!canCoerce(right)) { return null; } - return Py.newLong(value.and(coerce(right))); + return Py.newLong(getValue().and(coerce(right))); } @Override @@ -758,7 +758,7 @@ if (!canCoerce(left)) { return null; } - return Py.newLong(coerce(left).and(value)); + return Py.newLong(coerce(left).and(getValue())); } @Override @@ -771,7 +771,7 @@ if (!canCoerce(right)) { return null; } - return Py.newLong(value.xor(coerce(right))); + return Py.newLong(getValue().xor(coerce(right))); } @Override @@ -784,7 +784,7 @@ if (!canCoerce(left)) { return null; } - return Py.newLong(coerce(left).xor(value)); + return Py.newLong(coerce(left).xor(getValue())); } @Override @@ -797,7 +797,7 @@ if (!canCoerce(right)) { return null; } - return Py.newLong(value.or(coerce(right))); + return Py.newLong(getValue().or(coerce(right))); } @Override @@ -810,7 +810,7 @@ if (!canCoerce(left)) { return null; } - return Py.newLong(coerce(left).or(value)); + return Py.newLong(coerce(left).or(getValue())); } @Override @@ -820,7 +820,7 @@ @ExposedMethod(doc = BuiltinDocs.long___neg___doc) final PyObject long___neg__() { - return Py.newLong(value.negate()); + return Py.newLong(getValue().negate()); } @Override @@ -840,7 +840,7 @@ @ExposedMethod(doc = BuiltinDocs.long___abs___doc) final PyObject long___abs__() { - if (value.signum() == -1) { + if (getValue().signum() == -1) { return long___neg__(); } return long___long__(); @@ -853,7 +853,7 @@ @ExposedMethod(doc = BuiltinDocs.long___invert___doc) final PyObject long___invert__() { - return Py.newLong(value.not()); + return Py.newLong(getValue().not()); } @Override @@ -863,8 +863,8 @@ @ExposedMethod(doc = BuiltinDocs.long___int___doc) final PyObject long___int__() { - if (value.compareTo(PyInteger.MAX_INT) <= 0 && value.compareTo(PyInteger.MIN_INT) >= 0) { - return Py.newInteger(value.intValue()); + if (getValue().compareTo(PyInteger.MAX_INT) <= 0 && getValue().compareTo(PyInteger.MIN_INT) >= 0) { + return Py.newInteger(getValue().intValue()); } return long___long__(); } @@ -879,7 +879,7 @@ if (getType() == TYPE) { return this; } - return Py.newLong(value); + return Py.newLong(getValue()); } @Override @@ -908,7 +908,7 @@ @ExposedMethod(doc = BuiltinDocs.long___oct___doc) final PyString long___oct__() { - String s = value.toString(8); + String s = getValue().toString(8); if (s.startsWith("-")) { return new PyString("-0" + s.substring(1, s.length()) + "L"); } else if (s.startsWith("0")) { @@ -925,7 +925,7 @@ @ExposedMethod(doc = BuiltinDocs.long___hex___doc) final PyString long___hex__() { - String s = value.toString(16); + String s = getValue().toString(16); if (s.startsWith("-")) { return new PyString("-0x" + s.substring(1, s.length()) + "L"); } else { @@ -935,12 +935,12 @@ @Override public PyString __str__() { - return Py.newString(value.toString()); + return Py.newString(getValue().toString()); } @Override public PyUnicode __unicode__() { - return new PyUnicode(value.toString()); + return new PyUnicode(getValue().toString()); } @ExposedMethod(doc = BuiltinDocs.long___getnewargs___doc) @@ -970,15 +970,15 @@ @Override public int asIndex(PyObject err) { - boolean tooLow = value.compareTo(PyInteger.MIN_INT) < 0; - boolean tooHigh = value.compareTo(PyInteger.MAX_INT) > 0; + boolean tooLow = getValue().compareTo(PyInteger.MIN_INT) < 0; + boolean tooHigh = getValue().compareTo(PyInteger.MAX_INT) > 0; if (tooLow || tooHigh) { if (err != null) { throw new PyException(err, "cannot fit 'long' into an index-sized integer"); } return tooLow ? Integer.MIN_VALUE : Integer.MAX_VALUE; } - return (int) value.longValue(); + return (int) getValue().longValue(); } @Override This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <zy...@us...> - 2010-08-28 03:52:49
|
Revision: 7109 http://jython.svn.sourceforge.net/jython/?rev=7109&view=rev Author: zyasoft Date: 2010-08-28 03:52:43 +0000 (Sat, 28 Aug 2010) Log Message: ----------- Use Guava's FinalizableReferenceQueue and a new PySystemStateCloser class to manage the closing of those resources that prevent classloader GC (because they have hard refs to classes) after a PySystemState itself is GCed. This refactoring also moved the closing of user-unclosed files associated with a PyFile to the holding PySystemState, instead of having to wait for JVM shutdown. Now the JVM shutdown hook does this closing of resources through the PySystemStateCloser. Modified Paths: -------------- trunk/jython/src/org/python/core/PyFile.java trunk/jython/src/org/python/core/PySystemState.java trunk/jython/src/org/python/core/PyType.java trunk/jython/src/org/python/core/ThreadStateMapping.java Modified: trunk/jython/src/org/python/core/PyFile.java =================================================================== --- trunk/jython/src/org/python/core/PyFile.java 2010-08-27 13:20:44 UTC (rev 7108) +++ trunk/jython/src/org/python/core/PyFile.java 2010-08-28 03:52:43 UTC (rev 7109) @@ -6,7 +6,7 @@ import java.io.InputStream; import java.io.OutputStream; -import java.util.LinkedList; +import java.util.concurrent.Callable; import org.python.core.io.BinaryIOWrapper; import org.python.core.io.BufferedIOBase; @@ -78,13 +78,6 @@ * shutdown */ private Closer closer; - /** All PyFiles' closers */ - private static LinkedList<Closer> closers = new LinkedList<Closer>(); - - static { - initCloser(); - } - public PyFile() {} public PyFile(PyType subType) { @@ -155,7 +148,7 @@ String mode = ap.getString(1, "r"); int bufsize = ap.getInt(2, -1); file___init__(new FileIO(name.toString(), parseMode(mode)), name, mode, bufsize); - closer = new Closer(file); + closer = new Closer(file, Py.getSystemState()); } private void file___init__(RawIOBase raw, String name, String mode, int bufsize) { @@ -569,16 +562,9 @@ } } - private static void initCloser() { - try { - Runtime.getRuntime().addShutdownHook(new PyFileCloser()); - } catch (SecurityException se) { - Py.writeDebug("PyFile", "Can't register file closer hook"); - } - } - + /** - * A mechanism to make sure PyFiles are closed on exit. On creation Closer adds itself + * XXX update docs - A mechanism to make sure PyFiles are closed on exit. On creation Closer adds itself * to a list of Closers that will be run by PyFileCloser on JVM shutdown. When a * PyFile's close or finalize methods are called, PyFile calls its Closer.close which * clears Closer out of the shutdown queue. @@ -588,55 +574,39 @@ * be called during shutdown, so we can't use it. It's vital that this Closer has no * reference to the PyFile it's closing so the PyFile remains garbage collectable. */ - private static class Closer { + private static class Closer implements Callable { - /** The underlying file */ - private TextIOBase file; + /** + * The underlying file + */ + private final TextIOBase file; + private PySystemState sys; - public Closer(TextIOBase file) { + public Closer(TextIOBase file, PySystemState sys) { this.file = file; - // Add ourselves to the queue of Closers to be run on shutdown - synchronized (closers) { - closers.add(this); - } + this.sys = sys; + sys.registerCloser(this); } + // For closing directly + public void close() { - synchronized (closers) { - if (!closers.remove(this)) { - return; - } + if (sys.unregisterCloser(this)) { + file.close(); } - doClose(); + sys = null; } - public void doClose() { + // For closing as part of a shutdown process + + public Object call() { file.close(); + sys = null; + return null; } + } - private static class PyFileCloser extends Thread { - public PyFileCloser() { - super("Jython Shutdown File Closer"); - } - @Override - public void run() { - if (closers == null) { - // closers can be null in some strange cases - return; - } - synchronized (closers) { - while (closers.size() > 0) { - try { - closers.removeFirst().doClose(); - } catch (PyException e) { - // continue - } - } - } - } - } - } Modified: trunk/jython/src/org/python/core/PySystemState.java =================================================================== --- trunk/jython/src/org/python/core/PySystemState.java 2010-08-27 13:20:44 UTC (rev 7108) +++ trunk/jython/src/org/python/core/PySystemState.java 2010-08-28 03:52:43 UTC (rev 7109) @@ -7,18 +7,25 @@ import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; +import java.lang.ref.WeakReference; import java.net.URL; import java.net.URLDecoder; import java.nio.charset.Charset; import java.nio.charset.UnsupportedCharsetException; import java.security.AccessControlException; +import java.util.concurrent.Callable; +import java.util.ArrayList; +import java.util.LinkedHashSet; import java.util.Map; import java.util.Map.Entry; import java.util.Properties; +import java.util.Set; import java.util.StringTokenizer; import java.util.jar.JarEntry; import java.util.jar.JarFile; +import com.google.common.base.FinalizablePhantomReference; +import com.google.common.base.FinalizableReferenceQueue; import org.jruby.ext.posix.util.Platform; import org.python.Version; import org.python.core.adapter.ClassicPyObjectAdapter; @@ -144,8 +151,14 @@ /** true when a SystemRestart is triggered. */ public boolean _systemRestart = false; + // Automatically close resources associated with a PySystemState when they get GCed + private final PySystemStateCloser closer; + private static final FinalizableReferenceQueue systemStateQueue = new FinalizableReferenceQueue(); + + public PySystemState() { initialize(); + closer = new PySystemStateCloser(this); modules = new PyStringMap(); argv = (PyList)defaultArgv.repeat(1); @@ -1225,8 +1238,118 @@ throw Py.ValueError("call stack is not deep enough"); return f; } + + public void registerThreadState(ThreadState[] threadLocal, ThreadState ts) { + closer.registerThreadState(threadLocal, ts); + } + + public void registerCloser(Callable resourceCloser) { + closer.registerCloser(resourceCloser); + } + + public synchronized boolean unregisterCloser(Callable resourceCloser) { + return closer.unregisterCloser(resourceCloser); + } + + public void shutdown() { + closer.shutdown(); + } + + + private static class PySystemStateCloser { + + private final ArrayList<WeakReference<ThreadState[]>> threadStateList = new ArrayList<WeakReference<ThreadState[]>>(); + private final Set<Callable> resourceClosers = new LinkedHashSet<Callable>(); + private final FinalizablePhantomReference<PySystemState> sys; + private volatile boolean isShutdown = false; + + private PySystemStateCloser(PySystemState sys) { + this.sys = new FinalizablePhantomReference<PySystemState>(sys, systemStateQueue) { + public void finalizeReferent() { + shutdown(); + } + }; + initShutdownCloser(); + } + + private synchronized void registerThreadState(ThreadState[] threadLocal, ThreadState ts) { + if (!isShutdown) { // is this really necessary? + threadLocal[0] = ts; + threadStateList.add(new WeakReference<ThreadState[]>(threadLocal)); + } + } + + private synchronized void registerCloser(Callable closer) { + if (!isShutdown) { + resourceClosers.add(closer); + } + } + + private synchronized boolean unregisterCloser(Callable closer) { + return resourceClosers.remove(closer); + } + + private synchronized void shutdown() { + if (isShutdown) { + return; + } + isShutdown = true; + + // clear out existing ThreadStates so that they can be GCed - this resolves ClassLoader issues + for (WeakReference<ThreadState[]> ref : threadStateList) { + ThreadState[] o = ref.get(); + if (o != null) { + o[0] = null; + } + } + threadStateList.clear(); + + for (Callable callable : resourceClosers) { + try { + callable.call(); + } catch (Exception e) { + // just continue + } + } + resourceClosers.clear(); + } + + // Python scripts expect that files are closed upon an orderly shutdown of the VM. + private void initShutdownCloser() { + try { + Runtime.getRuntime().addShutdownHook(new ShutdownCloser()); + } catch (SecurityException se) { + Py.writeDebug("PySystemState", "Can't register shutdown closer hook"); + } + } + + private class ShutdownCloser extends Thread { + + private ShutdownCloser() { + super("Jython Shutdown Closer"); + } + + @Override + public synchronized void run() { + if (resourceClosers == null) { + // resourceClosers can be null in some strange cases + return; + } + for (Callable callable : resourceClosers) { + try { + callable.call(); // side effect of being removed from this set + } catch (Exception e) { + // continue - nothing we can do now! + } + } + resourceClosers.clear(); + } + } + + } } + class PySystemStateFunctions extends PyBuiltinFunctionSet { PySystemStateFunctions(String name, int index, int minargs, int maxargs) { Modified: trunk/jython/src/org/python/core/PyType.java =================================================================== --- trunk/jython/src/org/python/core/PyType.java 2010-08-27 13:20:44 UTC (rev 7108) +++ trunk/jython/src/org/python/core/PyType.java 2010-08-28 03:52:43 UTC (rev 7109) @@ -91,7 +91,7 @@ /** The number of __slots__ defined. */ private int numSlots; - private ReferenceQueue<PyType> subclasses_refq = new ReferenceQueue<PyType>(); + private transient ReferenceQueue<PyType> subclasses_refq = new ReferenceQueue<PyType>(); private Set<WeakReference<PyType>> subclasses = Generic.set(); /** Global mro cache. */ Modified: trunk/jython/src/org/python/core/ThreadStateMapping.java =================================================================== --- trunk/jython/src/org/python/core/ThreadStateMapping.java 2010-08-27 13:20:44 UTC (rev 7108) +++ trunk/jython/src/org/python/core/ThreadStateMapping.java 2010-08-28 03:52:43 UTC (rev 7109) @@ -1,26 +1,41 @@ package org.python.core; class ThreadStateMapping { - private static final ThreadLocal<ThreadState> cachedThreadState = new ThreadLocal<ThreadState>(); + private static final ThreadLocal<ThreadState[]> cachedThreadState = + new ThreadLocal<ThreadState[]>() { + @Override + protected ThreadState[] initialValue() { + return new ThreadState[1]; + } + }; public ThreadState getThreadState(PySystemState newSystemState) { - ThreadState ts = cachedThreadState.get(); + + // usual double checked locking pattern + ThreadState ts = cachedThreadState.get()[0]; + if (ts != null) { return ts; } + synchronized(this) { + ThreadState[] threadLocal = cachedThreadState.get(); + if(threadLocal[0] != null) + return (ThreadState)threadLocal[0]; - Thread t = Thread.currentThread(); - if (newSystemState == null) { - Py.writeDebug("threadstate", "no current system state"); - if (Py.defaultSystemState == null) { - PySystemState.initialize(); + Thread t = Thread.currentThread(); + if (newSystemState == null) { + Py.writeDebug("threadstate", "no current system state"); + if (Py.defaultSystemState == null) { + PySystemState.initialize(); + } + newSystemState = Py.defaultSystemState; } - newSystemState = Py.defaultSystemState; + + ts = new ThreadState(t, newSystemState); + + newSystemState.registerThreadState(threadLocal, ts); + return ts; } - - ts = new ThreadState(t, newSystemState); - cachedThreadState.set(ts); - return ts; } } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |