From: <pj...@us...> - 2011-02-08 01:17:00
|
Revision: 7195 http://jython.svn.sourceforge.net/jython/?rev=7195&view=rev Author: pjenvey Date: 2011-02-08 01:16:53 +0000 (Tue, 08 Feb 2011) Log Message: ----------- cleanup generics around PySystemStateCloser, PySystemState.unregisterCloser doesn't need synchronization Modified Paths: -------------- trunk/jython/src/org/python/core/PyFile.java trunk/jython/src/org/python/core/PySystemState.java Modified: trunk/jython/src/org/python/core/PyFile.java =================================================================== --- trunk/jython/src/org/python/core/PyFile.java 2011-02-05 01:23:12 UTC (rev 7194) +++ trunk/jython/src/org/python/core/PyFile.java 2011-02-08 01:16:53 UTC (rev 7195) @@ -574,7 +574,7 @@ * 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 implements Callable { + private static class Closer implements Callable<Void> { /** * The underlying file @@ -588,8 +588,7 @@ sys.registerCloser(this); } - // For closing directly - + /** For closing directly */ public void close() { if (sys.unregisterCloser(this)) { file.close(); @@ -597,9 +596,8 @@ sys = null; } - // For closing as part of a shutdown process - - public Object call() { + /** For closing as part of a shutdown process */ + public Void call() { file.close(); sys = null; return null; Modified: trunk/jython/src/org/python/core/PySystemState.java =================================================================== --- trunk/jython/src/org/python/core/PySystemState.java 2011-02-05 01:23:12 UTC (rev 7194) +++ trunk/jython/src/org/python/core/PySystemState.java 2011-02-08 01:16:53 UTC (rev 7195) @@ -155,8 +155,10 @@ // Automatically close resources associated with a PySystemState when they get GCed private final PySystemStateCloser closer; - private static final ReferenceQueue systemStateQueue = new ReferenceQueue<PySystemState>(); - private static final ConcurrentMap<WeakReference<PySystemState>, PySystemStateCloser> sysClosers = Generic.concurrentMap(); + private static final ReferenceQueue<PySystemState> systemStateQueue = + new ReferenceQueue<PySystemState>(); + private static final ConcurrentMap<WeakReference<PySystemState>, + PySystemStateCloser> sysClosers = Generic.concurrentMap(); public PySystemState() { initialize(); @@ -1286,11 +1288,11 @@ return f; } - public void registerCloser(Callable resourceCloser) { + public void registerCloser(Callable<Void> resourceCloser) { closer.registerCloser(resourceCloser); } - public synchronized boolean unregisterCloser(Callable resourceCloser) { + public boolean unregisterCloser(Callable<Void> resourceCloser) { return closer.unregisterCloser(resourceCloser); } @@ -1300,32 +1302,33 @@ private static class PySystemStateCloser { - private final Set<Callable> resourceClosers = new LinkedHashSet<Callable>(); + private final Set<Callable<Void>> resourceClosers = new LinkedHashSet<Callable<Void>>(); private volatile boolean isCleanup = false; private final Thread shutdownHook; private PySystemStateCloser(PySystemState sys) { shutdownHook = initShutdownCloser(); - WeakReference<PySystemState> ref = new WeakReference(sys, systemStateQueue); + WeakReference<PySystemState> ref = + new WeakReference<PySystemState>(sys, systemStateQueue); sysClosers.put(ref, this); cleanupOtherClosers(); } private static void cleanupOtherClosers() { - Reference<PySystemStateCloser> ref; + Reference<? extends PySystemState> ref; while ((ref = systemStateQueue.poll()) != null) { PySystemStateCloser closer = sysClosers.get(ref); closer.cleanup(); } } - private synchronized void registerCloser(Callable closer) { + private synchronized void registerCloser(Callable<Void> closer) { if (!isCleanup) { resourceClosers.add(closer); } } - private synchronized boolean unregisterCloser(Callable closer) { + private synchronized boolean unregisterCloser(Callable<Void> closer) { return resourceClosers.remove(closer); } @@ -1335,7 +1338,8 @@ } isCleanup = true; - // close this thread so we can unload any associated classloaders in cycle with this instance + // close this thread so we can unload any associated classloaders in cycle + // with this instance if (shutdownHook != null) { try { Runtime.getRuntime().removeShutdownHook(shutdownHook); @@ -1344,7 +1348,7 @@ } } - for (Callable callable : resourceClosers) { + for (Callable<Void> callable : resourceClosers) { try { callable.call(); } catch (Exception e) { @@ -1378,7 +1382,7 @@ // resourceClosers can be null in some strange cases return; } - for (Callable callable : resourceClosers) { + for (Callable<Void> callable : resourceClosers) { try { callable.call(); // side effect of being removed from this set } catch (Exception e) { This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <pj...@us...> - 2011-03-18 02:25:23
|
Revision: 7245 http://jython.svn.sourceforge.net/jython/?rev=7245&view=rev Author: pjenvey Date: 2011-03-18 02:25:16 +0000 (Fri, 18 Mar 2011) Log Message: ----------- o add abc support. we differ from CPython in that type lacks the __instance/subclasscheck__ methods as it would slow down isinstance/subclass o somewhat fix our object.__init__/__new__ FIXMEs and disallow arbitrary args to __new__ per 2.6. __init__ doesn't repeat this check yet but this is probably enough Modified Paths: -------------- trunk/jython/src/org/python/core/Py.java trunk/jython/src/org/python/core/PyObject.java trunk/jython/src/org/python/core/PyType.java Modified: trunk/jython/src/org/python/core/Py.java =================================================================== --- trunk/jython/src/org/python/core/Py.java 2011-03-18 01:26:55 UTC (rev 7244) +++ trunk/jython/src/org/python/core/Py.java 2011-03-18 02:25:16 UTC (rev 7245) @@ -86,6 +86,8 @@ public static long TPFLAGS_HEAPTYPE = 1L << 9; /** Set if the type allows subclassing */ public static long TPFLAGS_BASETYPE = 1L << 10; + /** Type is abstract and cannot be instantiated */ + public static long TPFLAGS_IS_ABSTRACT = 1L << 20; /** Builtin types that are used to setup PyObject. */ static final Set<Class<?>> BOOTSTRAP_TYPES = Generic.set(); @@ -1866,104 +1868,183 @@ new File(dir, name.substring(0, index))); } - private static boolean abstract_issubclass(PyObject derived, PyObject cls) { - if (derived == cls) { + public static boolean isInstance(PyObject inst, PyObject cls) { + // Quick test for an exact match + if (inst.getType() == cls) { return true; } - PyObject bases = derived.__findattr__("__bases__"); - if (bases == null) { + + if (cls instanceof PyTuple) { + ThreadState threadState = Py.getThreadState(); + threadState.enterRecursiveCall(" in __subclasscheck__"); + try { + for (PyObject item : cls.asIterable()) { + if (isInstance(inst, item)) { + return true; + } + } + } finally { + threadState.leaveRecursiveCall(); + } return false; } - for (int i = 0; i < bases.__len__(); i++) { - if (abstract_issubclass(bases.__getitem__(i), cls)) { - return true; - } + + PyObject checkerResult; + if ((checkerResult = dispatchToChecker(inst, cls, "__instancecheck__")) != null) { + return checkerResult.__nonzero__(); } - return false; - } - public static boolean isInstance(PyObject inst, PyObject cls) { - return recursiveIsInstance(inst, cls, 0); + return recursiveIsInstance(inst, cls); } - private static boolean recursiveIsInstance(PyObject inst, PyObject cls, int recursionDepth) { + static boolean recursiveIsInstance(PyObject inst, PyObject cls) { if (cls instanceof PyClass && inst instanceof PyInstance) { - PyClass inClass = (PyClass)inst.fastGetClass(); - return inClass.isSubClass((PyClass)cls); - } else if (cls instanceof PyType) { + PyClass inClass = ((PyInstance) inst).fastGetClass(); + return inClass.isSubClass((PyClass) cls); + } + if (cls instanceof PyType) { PyType instType = inst.getType(); - PyType type = (PyType)cls; + PyType type = (PyType) cls; // equiv. to PyObject_TypeCheck if (instType == type || instType.isSubType(type)) { return true; } - PyObject c = inst.__findattr__("__class__"); - if (c != null && c != instType && c instanceof PyType) { - return ((PyType)c).isSubType(type); + PyObject instCls = inst.__findattr__("__class__"); + if (instCls != null && instCls != instType && instCls instanceof PyType) { + return ((PyType) instCls).isSubType(type); } return false; - } else if (cls instanceof PyTuple) { - if (recursionDepth > Py.getSystemState().getrecursionlimit()) { - throw Py.RuntimeError("nest level of tuple too deep"); - } + } + + checkClass(cls, "isinstance() arg 2 must be a class, type, or tuple of classes and types"); + PyObject instCls = inst.__findattr__("__class__"); + if (instCls == null) { + return false; + } + return abstractIsSubClass(instCls, cls); + } - for (PyObject tupleItem : ((PyTuple)cls).getArray()) { - if (recursiveIsInstance(inst, tupleItem, recursionDepth + 1)) { - return true; + public static boolean isSubClass(PyObject derived, PyObject cls) { + if (cls instanceof PyTuple) { + ThreadState threadState = Py.getThreadState(); + threadState.enterRecursiveCall(" in __subclasscheck__"); + try { + for (PyObject item : cls.asIterable()) { + if (isSubClass(derived, item)) { + return true; + } } + } finally { + threadState.leaveRecursiveCall(); } return false; - } else { - if (cls.__findattr__("__bases__") == null) { - throw Py.TypeError("isinstance() arg 2 must be a class, type, or tuple of " - + "classes and types"); - } + } - PyObject icls = inst.__findattr__("__class__"); - if (icls == null) { - return false; - } - return abstract_issubclass(icls, cls); + PyObject checkerResult; + if ((checkerResult = dispatchToChecker(derived, cls, "__subclasscheck__")) != null) { + return checkerResult.__nonzero__(); } - } - public static boolean isSubClass(PyObject derived,PyObject cls) { - return isSubClass(derived, cls, 0); + return recursiveIsSubClass(derived, cls); } - private static boolean isSubClass(PyObject derived, PyObject cls, int recursionDepth) { + static boolean recursiveIsSubClass(PyObject derived, PyObject cls) { if (derived instanceof PyType && cls instanceof PyType) { if (derived == cls) { return true; } return ((PyType) derived).isSubType((PyType) cls); - } else if (cls instanceof PyClass && derived instanceof PyClass) { + } + if (derived instanceof PyClass && cls instanceof PyClass) { return ((PyClass) derived).isSubClass((PyClass) cls); - } else if (cls.getClass() == PyTuple.class) { - if (recursionDepth > Py.getSystemState().getrecursionlimit()) { - throw Py.RuntimeError("nest level of tuple too deep"); + } + + checkClass(derived, "issubclass() arg 1 must be a class"); + checkClass(cls, "issubclass() arg 2 must be a class or tuple of classes"); + return abstractIsSubClass(derived, cls); + } + + private static boolean abstractIsSubClass(PyObject derived, PyObject cls) { + while (true) { + if (derived == cls) { + return true; } - for (int i = 0; i < cls.__len__(); i++) { - if (isSubClass(derived, cls.__getitem__(i), recursionDepth + 1)) { + + PyTuple bases = abstractGetBases(derived); + if (bases == null) { + return false; + } + + int basesSize = bases.size(); + if (basesSize == 0) { + return false; + } + if (basesSize == 1) { + // Avoid recursivity in the single inheritance case + derived = bases.pyget(0); + continue; + } + + for (PyObject base : bases.asIterable()) { + if (abstractIsSubClass(base, cls)) { return true; } } return false; - } else { - if (derived.__findattr__("__bases__") == null) { - throw Py.TypeError( - "issubclass() arg 1 must be a class"); - } - if (cls.__findattr__("__bases__") == null) { - throw Py.TypeError( - "issubclass() arg 2 must be a class, type," + " or tuple of classes and types"); - } - return abstract_issubclass(derived, cls); } } + /** + * Attempt to dispatch an isinstance/issubclass call to cls's associated + * __instance/subclasscheck__. + * + * @param checkerArg the argument to call the checker with + * @param cls a Python class + * @param checkerName the checker name + * @return null if cls provides no checker, otherwise the result of calling the + * checker + */ + private static PyObject dispatchToChecker(PyObject checkerArg, PyObject cls, + String checkerName) { + PyObject checker = cls.__findattr__(checkerName); + if (checker == null) { + return null; + } + + PyObject result; + ThreadState threadState = Py.getThreadState(); + threadState.enterRecursiveCall(" in " + checkerName); + try { + result = checker.__call__(checkerArg); + } finally { + threadState.leaveRecursiveCall(); + } + return result; + } + + /** + * Return the __bases__ of cls. Returns null if no valid __bases__ are found. + */ + private static PyTuple abstractGetBases(PyObject cls) { + PyObject bases = cls.__findattr__("__bases__"); + if (bases instanceof PyTuple) { + return (PyTuple) bases; + } + return null; + } + + /** + * Throw a TypeError with the specified message if cls does not appear to be a Python + * class. + */ + private static void checkClass(PyObject cls, String message) { + if (abstractGetBases(cls) == null) { + throw Py.TypeError(message); + } + } + static PyObject[] make_array(PyObject iterable) { // Special-case the common tuple and list cases, for efficiency if (iterable instanceof PySequenceList) { Modified: trunk/jython/src/org/python/core/PyObject.java =================================================================== --- trunk/jython/src/org/python/core/PyObject.java 2011-03-18 01:26:55 UTC (rev 7244) +++ trunk/jython/src/org/python/core/PyObject.java 2011-03-18 02:25:16 UTC (rev 7245) @@ -8,6 +8,7 @@ import java.util.List; import java.util.Map; +import org.python.expose.ExposedClassMethod; import org.python.expose.ExposedDelete; import org.python.expose.ExposedGet; import org.python.expose.ExposedMethod; @@ -74,17 +75,32 @@ objtype = (PyType)this; } - //XXX: in CPython object.__new__ has a doc string... @ExposedNew + static final PyObject object___new__(PyNewWrapper new_, boolean init, PyType subtype, + PyObject[] args, String[] keywords) { + // don't allow arguments if the default object.__init__() is about to be called + PyObject[] where = new PyObject[1]; + subtype.lookup_where("__init__", where); + if (where[0] == TYPE && args.length > 0) { + throw Py.TypeError("object.__new__() takes no parameters"); + } + + if (subtype.isAbstract()) { + // Compute ", ".join(sorted(type.__abstractmethods__)) into methods + PyObject sorted = + Py.getSystemState().getBuiltins().__getitem__(Py.newString("sorted")); + PyString methods = + Py.newString(", ") + .join(sorted.__call__(subtype.getAbstractmethods())); + throw Py.TypeError(String.format("Can't instantiate abstract class %s with abstract " + + "methods %s", subtype.fastGetName(), methods)); + } + + return new_.for_type == subtype ? new PyObject() : new PyObjectDerived(subtype); + } + @ExposedMethod(doc = BuiltinDocs.object___init___doc) final void object___init__(PyObject[] args, String[] keywords) { - // XXX: attempted fix for object(foo=1), etc - // XXX: this doesn't work for metaclasses, for some reason - /* - if (args.length > 0) { - throw Py.TypeError("default __new__ takes no parameters"); - } - */ } @ExposedGet(name = "__class__") @@ -3974,10 +3990,15 @@ } public PyTuple __getnewargs__() { - //default is empty tuple + // default is empty tuple return new PyTuple(); } + @ExposedClassMethod(doc = BuiltinDocs.object___subclasshook___doc) + public static PyObject object___subclasshook__(PyType type, PyObject subclass) { + return Py.NotImplemented; + } + /* arguments' conversion helpers */ public static class ConversionException extends Exception { Modified: trunk/jython/src/org/python/core/PyType.java =================================================================== --- trunk/jython/src/org/python/core/PyType.java 2011-03-18 01:26:55 UTC (rev 7244) +++ trunk/jython/src/org/python/core/PyType.java 2011-03-18 02:25:16 UTC (rev 7245) @@ -120,7 +120,7 @@ } @ExposedNew - public static PyObject type___new__(PyNewWrapper new_, boolean init, PyType subtype, + static final PyObject type___new__(PyNewWrapper new_, boolean init, PyType subtype, PyObject[] args, String[] keywords) { // Special case: type(x) should return x.getType() if (args.length == 1 && keywords.length == 0) { @@ -150,6 +150,18 @@ return newType(new_, subtype, name, bases, dict); } + @ExposedMethod(doc = BuiltinDocs.type___init___doc) + final void type___init__(PyObject[] args, String[] kwds) { + if (kwds.length > 0) { + throw Py.TypeError("type.__init__() takes no keyword arguments"); + } + + if (args.length != 1 && args.length != 3) { + throw Py.TypeError("type.__init__() takes 1 or 3 arguments"); + } + object___init__(Py.EmptyObjects, Py.NoKeywords); + } + public static PyObject newType(PyNewWrapper new_, PyType metatype, String name, PyTuple bases, PyObject dict) { PyObject[] tmpBases = bases.getArray(); @@ -741,6 +753,10 @@ tp_flags = isBaseType ? tp_flags | Py.TPFLAGS_BASETYPE : tp_flags & ~Py.TPFLAGS_BASETYPE; } + boolean isAbstract() { + return (tp_flags & Py.TPFLAGS_IS_ABSTRACT) != 0; + } + private void mro_internal() { if (getType() == TYPE) { mro = computeMro(); @@ -1684,6 +1700,26 @@ throw Py.TypeError(String.format("can't delete %s.__module__", name)); } + @ExposedGet(name = "__abstractmethods__") + public PyObject getAbstractmethods() { + PyObject result = dict.__finditem__("__abstractmethods__"); + if (result == null) { + noAttributeError("__abstractmethods__"); + } + return result; + } + + @ExposedSet(name = "__abstractmethods__") + public void setAbstractmethods(PyObject value) { + // __abstractmethods__ should only be set once on a type, in abc.ABCMeta.__new__, + // so this function doesn't do anything special to update subclasses + dict.__setitem__("__abstractmethods__", value); + postSetattr("__abstractmethods__"); + tp_flags = value.__nonzero__() + ? tp_flags | Py.TPFLAGS_IS_ABSTRACT + : tp_flags & ~Py.TPFLAGS_IS_ABSTRACT; + } + public int getNumSlots() { return numSlots; } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <pj...@us...> - 2011-03-19 20:47:27
|
Revision: 7248 http://jython.svn.sourceforge.net/jython/?rev=7248&view=rev Author: pjenvey Date: 2011-03-19 20:47:21 +0000 (Sat, 19 Mar 2011) Log Message: ----------- add real/imag/numerator/denominator where applicable to the numbers 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 2011-03-19 20:39:47 UTC (rev 7247) +++ trunk/jython/src/org/python/core/PyComplex.java 2011-03-19 20:47:21 UTC (rev 7248) @@ -707,10 +707,7 @@ @ExposedMethod(doc = BuiltinDocs.complex___pos___doc) final PyObject complex___pos__() { - if (getType() == TYPE) { - return this; - } - return new PyComplex(real, imag); + return getType() == TYPE ? this : new PyComplex(real, imag); } @Override Modified: trunk/jython/src/org/python/core/PyFloat.java =================================================================== --- trunk/jython/src/org/python/core/PyFloat.java 2011-03-19 20:39:47 UTC (rev 7247) +++ trunk/jython/src/org/python/core/PyFloat.java 2011-03-19 20:47:21 UTC (rev 7248) @@ -8,6 +8,7 @@ import java.math.BigDecimal; import org.python.expose.ExposedClassMethod; +import org.python.expose.ExposedGet; import org.python.expose.ExposedMethod; import org.python.expose.ExposedNew; import org.python.expose.ExposedType; @@ -78,6 +79,16 @@ } } + @ExposedGet(name = "real", doc = BuiltinDocs.float_real_doc) + public PyObject getReal() { + return getType() == TYPE ? this : new PyFloat(value); + } + + @ExposedGet(name = "imag", doc = BuiltinDocs.float_imag_doc) + public PyObject getImag() { + return Py.newFloat(0.0); + } + /** * Determine if this float is not infinity, nor NaN. */ Modified: trunk/jython/src/org/python/core/PyInteger.java =================================================================== --- trunk/jython/src/org/python/core/PyInteger.java 2011-03-19 20:39:47 UTC (rev 7247) +++ trunk/jython/src/org/python/core/PyInteger.java 2011-03-19 20:47:21 UTC (rev 7248) @@ -7,6 +7,7 @@ import java.io.Serializable; import java.math.BigInteger; +import org.python.expose.ExposedGet; import org.python.expose.ExposedMethod; import org.python.expose.ExposedNew; import org.python.expose.ExposedType; @@ -105,6 +106,26 @@ } } + @ExposedGet(name = "real", doc = BuiltinDocs.int_real_doc) + public PyObject getReal() { + return int___int__(); + } + + @ExposedGet(name = "imag", doc = BuiltinDocs.int_imag_doc) + public PyObject getImag() { + return Py.newInteger(0); + } + + @ExposedGet(name = "numerator", doc = BuiltinDocs.int_numerator_doc) + public PyObject getNumerator() { + return int___int__(); + } + + @ExposedGet(name = "denominator", doc = BuiltinDocs.int_denominator_doc) + public PyObject getDenominator() { + return Py.newInteger(1); + } + public int getValue() { return value; } @@ -814,10 +835,7 @@ @ExposedMethod(doc = BuiltinDocs.int___int___doc) final PyInteger int___int__() { - if (getType() == TYPE) { - return this; - } - return Py.newInteger(getValue()); + return getType() == TYPE ? this : Py.newInteger(getValue()); } @Override Modified: trunk/jython/src/org/python/core/PyLong.java =================================================================== --- trunk/jython/src/org/python/core/PyLong.java 2011-03-19 20:39:47 UTC (rev 7247) +++ trunk/jython/src/org/python/core/PyLong.java 2011-03-19 20:47:21 UTC (rev 7248) @@ -8,6 +8,7 @@ import java.math.BigDecimal; import java.math.BigInteger; +import org.python.expose.ExposedGet; import org.python.expose.ExposedMethod; import org.python.expose.ExposedNew; import org.python.expose.ExposedType; @@ -129,6 +130,26 @@ return new BigDecimal(value).toBigInteger(); } + @ExposedGet(name = "real", doc = BuiltinDocs.long_real_doc) + public PyObject getReal() { + return long___long__(); + } + + @ExposedGet(name = "imag", doc = BuiltinDocs.long_imag_doc) + public PyObject getImag() { + return Py.newLong(0); + } + + @ExposedGet(name = "numerator", doc = BuiltinDocs.long_numerator_doc) + public PyObject getNumerator() { + return long___long__(); + } + + @ExposedGet(name = "denominator", doc = BuiltinDocs.long_denominator_doc) + public PyObject getDenominator() { + return Py.newLong(1); + } + @Override public String toString() { return long_toString(); @@ -876,10 +897,7 @@ @ExposedMethod(doc = BuiltinDocs.long___long___doc) final PyObject long___long__() { - if (getType() == TYPE) { - return this; - } - return Py.newLong(getValue()); + return getType() == TYPE ? this : Py.newLong(getValue()); } @Override This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <pj...@us...> - 2011-03-22 02:38:23
|
Revision: 7261 http://jython.svn.sourceforge.net/jython/?rev=7261&view=rev Author: pjenvey Date: 2011-03-22 02:38:16 +0000 (Tue, 22 Mar 2011) Log Message: ----------- coding standards and other minor changes Modified Paths: -------------- trunk/jython/src/org/python/core/PyInstance.java trunk/jython/src/org/python/core/PyInteger.java trunk/jython/src/org/python/core/PyLong.java trunk/jython/src/org/python/core/PyObject.java trunk/jython/src/org/python/core/PyString.java trunk/jython/src/org/python/core/__builtin__.java trunk/jython/src/org/python/core/stringlib/FieldNameIterator.java trunk/jython/src/org/python/core/stringlib/InternalFormatSpec.java trunk/jython/src/org/python/core/stringlib/InternalFormatSpecParser.java trunk/jython/src/org/python/core/stringlib/MarkupIterator.java Modified: trunk/jython/src/org/python/core/PyInstance.java =================================================================== --- trunk/jython/src/org/python/core/PyInstance.java 2011-03-21 23:11:25 UTC (rev 7260) +++ trunk/jython/src/org/python/core/PyInstance.java 2011-03-22 02:38:16 UTC (rev 7261) @@ -788,16 +788,17 @@ } @Override - public PyObject __format__(PyObject format_spec) { - return instance___format__(format_spec); + public PyObject __format__(PyObject formatSpec) { + return instance___format__(formatSpec); } @ExposedMethod - final PyObject instance___format__(PyObject format_spec) { + final PyObject instance___format__(PyObject formatSpec) { PyObject func = __findattr__("__format__"); - if (func == null) - return super.__format__(format_spec); - return func.__call__(format_spec); + if (func == null) { + return super.__format__(formatSpec); + } + return func.__call__(formatSpec); } // Generated by make_binops.py Modified: trunk/jython/src/org/python/core/PyInteger.java =================================================================== --- trunk/jython/src/org/python/core/PyInteger.java 2011-03-21 23:11:25 UTC (rev 7260) +++ trunk/jython/src/org/python/core/PyInteger.java 2011-03-22 02:38:16 UTC (rev 7261) @@ -914,31 +914,30 @@ } @Override - public PyObject __format__(PyObject format_spec) { - return int___format__(format_spec); + public PyObject __format__(PyObject formatSpec) { + return int___format__(formatSpec); } @ExposedMethod(doc = BuiltinDocs.int___format___doc) - final PyObject int___format__(PyObject format_spec) { - return formatImpl(getValue(), format_spec); + final PyObject int___format__(PyObject formatSpec) { + return formatImpl(getValue(), formatSpec); } - static PyObject formatImpl(Object value, PyObject format_spec) { - if (format_spec instanceof PyString) { - String result; - try { - String specString = ((PyString) format_spec).getString(); - InternalFormatSpec spec = new InternalFormatSpecParser(specString).parse(); - result = formatIntOrLong(value, spec); - } catch (IllegalArgumentException e) { - throw Py.ValueError(e.getMessage()); - } - if (format_spec instanceof PyUnicode) { - return new PyUnicode(result); - } - return new PyString(result); + static PyObject formatImpl(Object value, PyObject formatSpec) { + if (!(formatSpec instanceof PyString)) { + throw Py.TypeError("__format__ requires str or unicode"); } - throw Py.TypeError("__format__ requires str or unicode"); + + PyString formatSpecStr = (PyString) formatSpec; + String result; + try { + String specString = formatSpecStr.getString(); + InternalFormatSpec spec = new InternalFormatSpecParser(specString).parse(); + result = formatIntOrLong(value, spec); + } catch (IllegalArgumentException e) { + throw Py.ValueError(e.getMessage()); + } + return formatSpecStr.createInstance(result); } /** @@ -956,15 +955,14 @@ if (value instanceof Integer) { int intValue = (Integer) value; sign = intValue < 0 ? -1 : intValue == 0 ? 0 : 1; - } - else { + } else { sign = ((BigInteger) value).signum(); } String strValue; if (spec.type == 'c') { if (spec.sign != '\0') { - throw new IllegalArgumentException("Sign not allowed with " + - "integer format specifier 'c'"); + throw new IllegalArgumentException("Sign not allowed with integer format " + + "specifier 'c'"); } if (value instanceof Integer) { int intValue = (Integer) value; @@ -972,8 +970,7 @@ throw new IllegalArgumentException("%c arg not in range(0x10000)"); } strValue = Character.toString((char) intValue); - } - else { + } else { BigInteger bigInt = (BigInteger) value; if (bigInt.intValue() > 0xffff || bigInt.bitCount() > 16) { throw new IllegalArgumentException("%c arg not in range(0x10000)"); @@ -993,18 +990,18 @@ // TODO locale-specific formatting for 'n' if (value instanceof BigInteger) { strValue = ((BigInteger) value).toString(radix); - } - else { + } else { strValue = Integer.toString((Integer) value, radix); } if (spec.alternate) { - if (radix == 2) + if (radix == 2) { strValue = "0b" + strValue; - else if (radix == 8) + } else if (radix == 8) { strValue = "0o" + strValue; - else if (radix == 16) + } else if (radix == 16) { strValue = "0x" + strValue; + } } if (spec.type == 'X') { strValue = strValue.toUpperCase(); Modified: trunk/jython/src/org/python/core/PyLong.java =================================================================== --- trunk/jython/src/org/python/core/PyLong.java 2011-03-21 23:11:25 UTC (rev 7260) +++ trunk/jython/src/org/python/core/PyLong.java 2011-03-22 02:38:16 UTC (rev 7261) @@ -982,13 +982,13 @@ } @Override - public PyObject __format__(PyObject format_spec) { - return long___format__(format_spec); + public PyObject __format__(PyObject formatSpec) { + return long___format__(formatSpec); } @ExposedMethod(doc = BuiltinDocs.long___format___doc) - final PyObject long___format__(PyObject format_spec) { - return PyInteger.formatImpl(getValue(), format_spec); + final PyObject long___format__(PyObject formatSpec) { + return PyInteger.formatImpl(getValue(), formatSpec); } @Override Modified: trunk/jython/src/org/python/core/PyObject.java =================================================================== --- trunk/jython/src/org/python/core/PyObject.java 2011-03-21 23:11:25 UTC (rev 7260) +++ trunk/jython/src/org/python/core/PyObject.java 2011-03-22 02:38:16 UTC (rev 7261) @@ -1710,14 +1710,13 @@ return false; } - public PyObject __format__(PyObject format_spec) { - return object___format__(format_spec); + public PyObject __format__(PyObject formatSpec) { + return object___format__(formatSpec); } @ExposedMethod(doc = BuiltinDocs.object___format___doc) - final PyObject object___format__(PyObject format_spec) { - PyString str = __str__(); - return str.__format__(format_spec); + final PyObject object___format__(PyObject formatSpec) { + return __str__().__format__(formatSpec); } /** Modified: trunk/jython/src/org/python/core/PyString.java =================================================================== --- trunk/jython/src/org/python/core/PyString.java 2011-03-21 23:11:25 UTC (rev 7260) +++ trunk/jython/src/org/python/core/PyString.java 2011-03-22 02:38:16 UTC (rev 7261) @@ -2533,7 +2533,7 @@ final PyObject str_format(PyObject[] args, String[] keywords) { try { return new PyString(buildFormattedString(getString(), args, keywords)); - } catch(IllegalArgumentException e) { + } catch (IllegalArgumentException e) { throw Py.ValueError(e.getMessage()); } } @@ -2562,11 +2562,9 @@ } if ("r".equals(chunk.conversion)) { fieldObj = fieldObj.__repr__(); - } - else if ("s".equals(chunk.conversion)) { + } else if ("s".equals(chunk.conversion)) { fieldObj = fieldObj.__str__(); - } - else if (chunk.conversion != null) { + } else if (chunk.conversion != null) { throw Py.ValueError("Unknown conversion specifier " + chunk.conversion); } String formatSpec = chunk.formatSpec; @@ -2581,17 +2579,17 @@ Object head = iterator.head(); PyObject obj = null; int positionalCount = args.length - keywords.length; + if (head instanceof Integer) { int index = (Integer) head; if (index >= positionalCount) { throw Py.IndexError("tuple index out of range"); } obj = args[index]; - } - else { + } else { for (int i = 0; i < keywords.length; i++) { if (keywords[i].equals(head)) { - obj = args[positionalCount+i]; + obj = args[positionalCount + i]; break; } } @@ -2607,14 +2605,15 @@ } if (chunk.is_attr) { obj = obj.__getattr__((String) chunk.value); - } - else { + } else { PyObject key = chunk.value instanceof String ? new PyString((String) chunk.value) : new PyInteger((Integer) chunk.value); obj = obj.__getitem__(key); } - if (obj == null) break; + if (obj == null) { + break; + } } } return obj; @@ -2626,27 +2625,26 @@ } @Override - public PyObject __format__(PyObject format_spec) { - return str___format__(format_spec); + public PyObject __format__(PyObject formatSpec) { + return str___format__(formatSpec); } @ExposedMethod(doc = BuiltinDocs.str___format___doc) - final PyObject str___format__(PyObject format_spec) { - if (format_spec instanceof PyString) { - String result; - try { - String specString = ((PyString) format_spec).getString(); - InternalFormatSpec spec = new InternalFormatSpecParser(specString).parse(); - result = formatString(getString(), spec); - } catch (IllegalArgumentException e) { - throw Py.ValueError(e.getMessage()); - } - if (format_spec instanceof PyUnicode) { - return new PyUnicode(result); - } - return new PyString(result); + final PyObject str___format__(PyObject formatSpec) { + if (!(formatSpec instanceof PyString)) { + throw Py.TypeError("__format__ requires str or unicode"); } - throw Py.TypeError("__format__ requires str or unicode"); + + PyString formatSpecStr = (PyString) formatSpec; + String result; + try { + String specString = formatSpecStr.getString(); + InternalFormatSpec spec = new InternalFormatSpecParser(specString).parse(); + result = formatString(getString(), spec); + } catch (IllegalArgumentException e) { + throw Py.ValueError(e.getMessage()); + } + return formatSpecStr.createInstance(result); } /** Modified: trunk/jython/src/org/python/core/__builtin__.java =================================================================== --- trunk/jython/src/org/python/core/__builtin__.java 2011-03-21 23:11:25 UTC (rev 7260) +++ trunk/jython/src/org/python/core/__builtin__.java 2011-03-22 02:38:16 UTC (rev 7261) @@ -1314,7 +1314,7 @@ @Override public PyObject __call__(PyObject arg1) { - return __call__(arg1, new PyString("")); + return __call__(arg1, Py.EmptyString); } @Override Modified: trunk/jython/src/org/python/core/stringlib/FieldNameIterator.java =================================================================== --- trunk/jython/src/org/python/core/stringlib/FieldNameIterator.java 2011-03-21 23:11:25 UTC (rev 7260) +++ trunk/jython/src/org/python/core/stringlib/FieldNameIterator.java 2011-03-22 02:38:16 UTC (rev 7261) @@ -1,6 +1,11 @@ package org.python.core.stringlib; -import org.python.core.*; +import org.python.core.PyBoolean; +import org.python.core.PyInteger; +import org.python.core.PyObject; +import org.python.core.PyString; +import org.python.core.PyTuple; +import org.python.core.PyType; import org.python.expose.ExposedMethod; import org.python.expose.ExposedType; @@ -9,6 +14,9 @@ */ @ExposedType(name = "fieldnameiterator", base = PyObject.class, isBaseType = false) public class FieldNameIterator extends PyObject { + + public static final PyType TYPE = PyType.fromClass(FieldNameIterator.class); + private String markup; private Object head; private int index; @@ -26,15 +34,21 @@ @Override public PyObject __iter__() { - return this; + return fieldnameiterator___iter__(); } @ExposedMethod - public PyObject fieldnameiterator___iter__() { + final PyObject fieldnameiterator___iter__() { return this; } + @Override public PyObject __iternext__() { + return fieldnameiterator___iternext__(); + } + + @ExposedMethod + final PyObject fieldnameiterator___iternext__() { Chunk chunk = nextChunk(); if (chunk == null) { return null; @@ -43,23 +57,21 @@ elements [0] = new PyBoolean(chunk.is_attr); if (chunk.value instanceof Integer) { elements [1] = new PyInteger((Integer) chunk.value); - } - else { + } else { elements [1] = new PyString((String) chunk.value); } return new PyTuple(elements); } - @ExposedMethod - public PyObject fieldnameiterator___iternext__() { - return __iternext__(); - } - private int nextDotOrBracket(String markup) { int dotPos = markup.indexOf('.', index); - if (dotPos < 0) dotPos = markup.length(); + if (dotPos < 0) { + dotPos = markup.length(); + } int bracketPos = markup.indexOf('[', index); - if (bracketPos < 0) bracketPos = markup.length(); + if (bracketPos < 0) { + bracketPos = markup.length(); + } return Math.min(dotPos, bracketPos); } @@ -74,8 +86,7 @@ Chunk chunk = new Chunk(); if (markup.charAt(index) == '[') { parseItemChunk(chunk); - } - else if (markup.charAt(index) == '.') { + } else if (markup.charAt(index) == '.') { parseAttrChunk(chunk); } return chunk; @@ -87,7 +98,7 @@ if (endBracket < 0) { throw new IllegalArgumentException("Missing ']' in format string"); } - String itemValue = markup.substring(index+1, endBracket); + String itemValue = markup.substring(index + 1, endBracket); if (itemValue.length() == 0) { throw new IllegalArgumentException("Empty attribute in format string"); } @@ -96,7 +107,7 @@ } catch (NumberFormatException e) { chunk.value = itemValue; } - index = endBracket+1; + index = endBracket + 1; } private void parseAttrChunk(Chunk chunk) { @@ -112,6 +123,7 @@ public static class Chunk { public boolean is_attr; - public Object value; // Integer or String + /** Integer or String. */ + public Object value; } } Modified: trunk/jython/src/org/python/core/stringlib/InternalFormatSpec.java =================================================================== --- trunk/jython/src/org/python/core/stringlib/InternalFormatSpec.java 2011-03-21 23:11:25 UTC (rev 7260) +++ trunk/jython/src/org/python/core/stringlib/InternalFormatSpec.java 2011-03-22 02:38:16 UTC (rev 7261) @@ -25,8 +25,7 @@ } if (useAlign == '^') { leading = remaining/2; - } - else if (useAlign == '<') { + } else if (useAlign == '<') { leading = 0; } char fill = fill_char != 0 ? fill_char : ' '; @@ -34,7 +33,7 @@ result.append(fill); } result.append(value); - for (int i = 0; i < remaining-leading; i++) { + for (int i = 0; i < remaining - leading; i++) { result.append(fill); } return result.toString(); Modified: trunk/jython/src/org/python/core/stringlib/InternalFormatSpecParser.java =================================================================== --- trunk/jython/src/org/python/core/stringlib/InternalFormatSpecParser.java 2011-03-21 23:11:25 UTC (rev 7260) +++ trunk/jython/src/org/python/core/stringlib/InternalFormatSpecParser.java 2011-03-22 02:38:16 UTC (rev 7261) @@ -29,8 +29,7 @@ if (spec.length() >= 1 && isAlign(spec.charAt(0))) { result.align = spec.charAt(index); index++; - } - else if (spec.length() >= 2 && isAlign(spec.charAt(1))) { + } else if (spec.length() >= 2 && isAlign(spec.charAt(1))) { result.fill_char = spec.charAt(0); result.align = spec.charAt(1); index += 2; @@ -73,7 +72,9 @@ index++; empty = false; } - if (empty) return -1; + if (empty) { + return -1; + } return value; } Modified: trunk/jython/src/org/python/core/stringlib/MarkupIterator.java =================================================================== --- trunk/jython/src/org/python/core/stringlib/MarkupIterator.java 2011-03-21 23:11:25 UTC (rev 7260) +++ trunk/jython/src/org/python/core/stringlib/MarkupIterator.java 2011-03-22 02:38:16 UTC (rev 7261) @@ -1,6 +1,10 @@ package org.python.core.stringlib; -import org.python.core.*; +import org.python.core.Py; +import org.python.core.PyObject; +import org.python.core.PyString; +import org.python.core.PyTuple; +import org.python.core.PyType; import org.python.expose.ExposedMethod; import org.python.expose.ExposedType; @@ -9,6 +13,9 @@ */ @ExposedType(name = "formatteriterator", base = PyObject.class, isBaseType = false) public class MarkupIterator extends PyObject { + + public static final PyType TYPE = PyType.fromClass(MarkupIterator.class); + private final String markup; private int index; @@ -18,15 +25,21 @@ @Override public PyObject __iter__() { - return this; + return formatteriterator___iter__(); } @ExposedMethod - public PyObject formatteriterator___iter__() { + final PyObject formatteriterator___iter__() { return this; } + @Override public PyObject __iternext__() { + return formatteriterator___iternext__(); + } + + @ExposedMethod + final PyObject formatteriterator___iternext__() { Chunk chunk; try { chunk = nextChunk(); @@ -40,36 +53,30 @@ elements[0] = new PyString(chunk.literalText); elements[1] = new PyString(chunk.fieldName); if (chunk.fieldName.length() > 0) { - elements[2] = chunk.formatSpec == null ? Py.EmptyString : new PyString(chunk.formatSpec); - } - else { + elements[2] = chunk.formatSpec == null + ? Py.EmptyString : new PyString(chunk.formatSpec); + } else { elements[2] = Py.None; } elements[3] = chunk.conversion == null ? Py.None : new PyString(chunk.conversion); return new PyTuple(elements); } - @ExposedMethod - public PyObject formatteriterator___iternext__() { - return __iternext__(); - } - public Chunk nextChunk() { if (index == markup.length()) { return null; } Chunk result = new Chunk(); int pos = index; - while(true) { + while (true) { pos = indexOfFirst(markup, pos, '{', '}'); - if (pos >= 0 && pos < markup.length()-1 && - markup.charAt(pos+1) == markup.charAt(pos)) { - pos += 2; // skip escaped bracket - } - else if (pos >= 0 && markup.charAt(pos) == '}') { + if (pos >= 0 && pos < markup.length() - 1 + && markup.charAt(pos + 1) == markup.charAt(pos)) { + // skip escaped bracket + pos += 2; + } else if (pos >= 0 && markup.charAt(pos) == '}') { throw new IllegalArgumentException("Single '}' encountered in format string"); - } - else { + } else { break; } } @@ -87,8 +94,7 @@ if (markup.charAt(pos) == '{') { count++; result.formatSpecNeedsExpanding = true; - } - else if (markup.charAt(pos) == '}') { + } else if (markup.charAt(pos) == '}') { count--; if (count == 0) { parseField(result, markup.substring(fieldStart, pos)); @@ -98,8 +104,9 @@ } pos++; } - if (count > 0) + if (count > 0) { throw new IllegalArgumentException("Single '{' encountered in format string"); + } index = pos; } return result; @@ -125,14 +132,12 @@ throw new IllegalArgumentException("expected ':' " + "after conversion specifier"); } - result.formatSpec = fieldMarkup.substring(pos+1); + result.formatSpec = fieldMarkup.substring(pos + 1); } + } else { + result.formatSpec = fieldMarkup.substring(pos + 1); } - else { - result.formatSpec = fieldMarkup.substring(pos+1); - } - } - else { + } else { result.fieldName = fieldMarkup; } } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |