From: <cg...@us...> - 2008-11-10 03:31:58
|
Revision: 5564 http://jython.svn.sourceforge.net/jython/?rev=5564&view=rev Author: cgroves Date: 2008-11-10 03:31:53 +0000 (Mon, 10 Nov 2008) Log Message: ----------- Checkpoint of replacing PyJavaClass with PyJavaType. Works well enough that ProxyMaker creates PyObjects instead of PyJavaInstances and the interpreter starts up, but that's about it Modified Paths: -------------- branches/newstyle-java-types/Lib/test/test_java_visibility.py branches/newstyle-java-types/src/org/python/compiler/ProxyMaker.java branches/newstyle-java-types/src/org/python/core/Options.java branches/newstyle-java-types/src/org/python/core/Py.java branches/newstyle-java-types/src/org/python/core/PyBeanProperty.java branches/newstyle-java-types/src/org/python/core/PyInstance.java branches/newstyle-java-types/src/org/python/core/PyJavaType.java branches/newstyle-java-types/src/org/python/core/PyObject.java branches/newstyle-java-types/src/org/python/core/PyProxy.java branches/newstyle-java-types/src/org/python/core/PyReflectedConstructor.java branches/newstyle-java-types/src/org/python/core/PyReflectedFunction.java branches/newstyle-java-types/src/org/python/core/PyType.java branches/newstyle-java-types/src/org/python/core/ThreadState.java branches/newstyle-java-types/src/org/python/core/adapter/ClassicPyObjectAdapter.java branches/newstyle-java-types/src/org/python/core/adapter/PyObjectAdapter.java Modified: branches/newstyle-java-types/Lib/test/test_java_visibility.py =================================================================== --- branches/newstyle-java-types/Lib/test/test_java_visibility.py 2008-11-10 03:29:23 UTC (rev 5563) +++ branches/newstyle-java-types/Lib/test/test_java_visibility.py 2008-11-10 03:31:53 UTC (rev 5564) @@ -66,8 +66,6 @@ self.failUnless('visibleInstance' in c.__dict__, 'visibleInstance expected in %s __dict__' % c) - - def test_main(): test_support.run_unittest(VisibilityTest) Modified: branches/newstyle-java-types/src/org/python/compiler/ProxyMaker.java =================================================================== --- branches/newstyle-java-types/src/org/python/compiler/ProxyMaker.java 2008-11-10 03:29:23 UTC (rev 5563) +++ branches/newstyle-java-types/src/org/python/compiler/ProxyMaker.java 2008-11-10 03:31:53 UTC (rev 5564) @@ -12,6 +12,9 @@ import java.util.Set; import org.python.core.Py; +import org.python.core.PyJavaType; +import org.python.core.PyObject; +import org.python.core.PyProxy; import org.python.objectweb.asm.Label; import org.python.objectweb.asm.Opcodes; import org.python.util.Generic; @@ -53,13 +56,40 @@ else return ((Integer)i).intValue(); } + /** + * Retrieves <code>name</code> from the PyObject in <code>proxy</code> if it's defined in + * Python. This is a specialized helper function for internal PyProxy use. + */ + public static PyObject findPython(PyProxy proxy, String name) { + PyObject o = proxy._getPyInstance(); + if (o == null) { + proxy.__initProxy__(new Object[0]); + o = proxy._getPyInstance(); + } + PyObject ret = null; + if (o.getDict() != null) { + ret = o.getDict().__finditem__(name); + } + if (ret == null) { + PyObject[] definedOn = new PyObject[1]; + PyObject typeDefined = o.getType().lookup_where(name, definedOn); + if (!(definedOn[0] instanceof PyJavaType)) { + ret = typeDefined; + } + } + if (ret == null) { + return null; + } + Py.setSystemState(proxy._getPySystemState()); + return ret.__get__(o, null); + } + Class<?> superclass; Class<?>[] interfaces; Set<String> names; Set<String> supernames = Generic.set(); public ClassFile classfile; public String myClass; - public boolean isAdapter=false; public ProxyMaker(String classname, Class<?> superclass) { this.myClass = "org.python.proxies."+classname; @@ -432,7 +462,8 @@ if (!isAbstract) { int tmp = code.getLocal("org/python/core/PyObject"); - code.invokestatic("org/python/core/Py", "jfindattr", "(" + $pyProxy + $str + ")" + $pyObj); + code.invokestatic("org/python/compiler/ProxyMaker", "findPython", "(" + $pyProxy + $str + + ")" + $pyObj); code.astore(tmp); code.aload(tmp); @@ -449,20 +480,15 @@ addSuperMethod("super__"+name, name, superClass, parameters, ret, sig, access); } else { - if (!isAdapter) { - code.invokestatic("org/python/core/Py", "jgetattr", "(" + $pyProxy + $str + ")" + $pyObj); - callMethod(code, name, parameters, ret, method.getExceptionTypes()); - } else { - code.invokestatic("org/python/core/Py", "jfindattr", "(" + $pyProxy + $str + ")" + $pyObj); - code.dup(); - Label returnNull = new Label(); - code.ifnull(returnNull); - - callMethod(code, name, parameters, ret, method.getExceptionTypes()); - code.label(returnNull); - code.pop(); - doNullReturn(code, ret); - } + code.invokestatic("org/python/compiler/ProxyMaker", "findPython", "(" + $pyProxy + $str + + ")" + $pyObj); + code.dup(); + Label returnNull = new Label(); + code.ifnull(returnNull); + callMethod(code, name, parameters, ret, method.getExceptionTypes()); + code.label(returnNull); + code.pop(); + doNullReturn(code, ret); } } @@ -600,23 +626,23 @@ public void addProxy() throws Exception { // implement PyProxy interface - classfile.addField("__proxy", "Lorg/python/core/PyInstance;", + classfile.addField("__proxy", "Lorg/python/core/PyObject;", Modifier.PROTECTED); // setProxy methods Code code = classfile.addMethod("_setPyInstance", - "(Lorg/python/core/PyInstance;)V", + "(Lorg/python/core/PyObject;)V", Modifier.PUBLIC); code.aload(0); code.aload(1); - code.putfield(classfile.name, "__proxy", "Lorg/python/core/PyInstance;"); + code.putfield(classfile.name, "__proxy", "Lorg/python/core/PyObject;"); code.return_(); // getProxy method code = classfile.addMethod("_getPyInstance", - "()Lorg/python/core/PyInstance;", + "()Lorg/python/core/PyObject;", Modifier.PUBLIC); code.aload(0); - code.getfield(classfile.name, "__proxy", "Lorg/python/core/PyInstance;"); + code.getfield(classfile.name, "__proxy", "Lorg/python/core/PyObject;"); code.areturn(); // implement PyProxy interface Modified: branches/newstyle-java-types/src/org/python/core/Options.java =================================================================== --- branches/newstyle-java-types/src/org/python/core/Options.java 2008-11-10 03:29:23 UTC (rev 5563) +++ branches/newstyle-java-types/src/org/python/core/Options.java 2008-11-10 03:31:53 UTC (rev 5564) @@ -4,7 +4,7 @@ /** * A class with static fields for each of the settable options. The options from * registry and command line is copied into the fields here and the rest of - * Jyhton checks these fields. + * Jython checks these fields. */ public class Options { // Jython options. Some of these can be set from the command line @@ -24,7 +24,7 @@ public static boolean includeJavaStackInExceptions = false; /** - * When true, python exception raised in overriden methods will be shown on + * When true, python exception raised in overridden methods will be shown on * stderr. This option is remarkably useful when python is used for * implementing CORBA server. Some CORBA servers will turn python exception * (say a NameError) into an anonymous user exception without any Modified: branches/newstyle-java-types/src/org/python/core/Py.java =================================================================== --- branches/newstyle-java-types/src/org/python/core/Py.java 2008-11-10 03:29:23 UTC (rev 5563) +++ branches/newstyle-java-types/src/org/python/core/Py.java 2008-11-10 03:31:53 UTC (rev 5564) @@ -1,7 +1,6 @@ // Copyright (c) Corporation for National Research Initiatives package org.python.core; -import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileOutputStream; @@ -16,7 +15,6 @@ import java.sql.Date; import java.sql.Time; import java.sql.Timestamp; -import java.util.Arrays; import java.util.Calendar; import java.util.HashSet; import java.util.Set; @@ -25,7 +23,6 @@ import org.python.compiler.Module; import org.python.core.adapter.ClassicPyObjectAdapter; import org.python.core.adapter.ExtensiblePyObjectAdapter; -import org.python.core.util.StringUtil; import org.python.modules.errno; public final class Py { @@ -84,7 +81,7 @@ public static long TPFLAGS_HEAPTYPE; /** Builtin types that are used to setup PyObject. */ - static final Set<Class> BOOTSTRAP_TYPES = new HashSet<Class>(4); + static final Set<Class<?>> BOOTSTRAP_TYPES = new HashSet<Class<?>>(4); static { BOOTSTRAP_TYPES.add(PyObject.class); BOOTSTRAP_TYPES.add(PyType.class); @@ -476,35 +473,6 @@ } /* Helper functions for PyProxy's */ - /** @deprecated */ - public static PyObject jfindattr(PyProxy proxy, String name) { - PyObject ret = getInstance(proxy, name); - if (ret == null) - return null; - Py.setSystemState(proxy._getPySystemState()); - return ret; - } - - - /** @deprecated */ - public static PyObject jgetattr(PyProxy proxy, String name) { - PyObject ret = getInstance(proxy, name); - if (ret == null) - throw Py.AttributeError("abstract method '" + name + "' not implemented"); - Py.setSystemState(proxy._getPySystemState()); - return ret; - } - - private static PyObject getInstance(PyProxy proxy, String name) { - PyInstance o = proxy._getPyInstance(); - if (o == null) { - proxy.__initProxy__(new Object[0]); - o = proxy._getPyInstance(); - } - PyObject ret = o.__jfindattr__(name); - return ret; - } - /* Convenience methods to create new constants without using "new" */ private static PyInteger[] integerCache = null; @@ -836,36 +804,20 @@ if (proxy._getPyInstance() != null) return; ThreadState ts = getThreadState(); - PyInstance instance = ts.getInitializingProxy(); + PyObject instance = ts.getInitializingProxy(); if (instance != null) { - if (instance.javaProxy != null) + if (instance.javaProxy != null) { throw Py.TypeError("Proxy instance reused"); + } instance.javaProxy = proxy; proxy._setPyInstance(instance); proxy._setPySystemState(ts.systemState); return; } - PyObject mod; - // ??pending: findClass or should avoid sys.path loading? - Class modClass = Py.findClass(module+"$_PyInner"); - if (modClass != null) { - PyCode code=null; - try { - code = ((PyRunnable)modClass.newInstance()).getMain(); - } catch (Throwable t) { - throw Py.JavaError(t); - } - mod = imp.createFromCode(module, code); - } else { - mod = imp.importName(module.intern(), false); - } - PyClass pyc = (PyClass)mod.__getattr__(pyclass.intern()); + PyObject mod = imp.importName(module.intern(), false); + PyType pyc = (PyType)mod.__getattr__(pyclass.intern()); - instance = new PyInstance(pyc); - instance.javaProxy = proxy; - proxy._setPyInstance(instance); - proxy._setPySystemState(ts.systemState); PyObject[] pargs; if (args == null || args.length == 0) { @@ -875,7 +827,10 @@ for(int i=0; i<args.length; i++) pargs[i] = Py.java2py(args[i]); } - instance.__init__(pargs, Py.NoKeywords); + instance = pyc.__call__(pargs); + instance.javaProxy = proxy; + proxy._setPyInstance(instance); + proxy._setPySystemState(ts.systemState); } /** Modified: branches/newstyle-java-types/src/org/python/core/PyBeanProperty.java =================================================================== --- branches/newstyle-java-types/src/org/python/core/PyBeanProperty.java 2008-11-10 03:29:23 UTC (rev 5563) +++ branches/newstyle-java-types/src/org/python/core/PyBeanProperty.java 2008-11-10 03:31:53 UTC (rev 5564) @@ -4,12 +4,10 @@ public class PyBeanProperty extends PyReflectedField { public Method getMethod, setMethod; - public Class myType; + public Class<?> myType; String __name__; - public PyBeanProperty(String name, Class myType, - Method getMethod, Method setMethod) - { + public PyBeanProperty(String name, Class<?> myType, Method getMethod, Method setMethod) { __name__ = name; this.getMethod = getMethod; this.setMethod = setMethod; @@ -56,7 +54,7 @@ if (value instanceof PyTuple) { try { PyTuple vtup = (PyTuple)value; - value = PyJavaClass.lookup(myType).__call__(vtup.getArray()); // xxx PyObject subclasses + value = Py.java2py(myType).__call__(vtup.getArray()); // xxx PyObject subclasses } catch (Throwable t) { // If something goes wrong ignore it? } Modified: branches/newstyle-java-types/src/org/python/core/PyInstance.java =================================================================== --- branches/newstyle-java-types/src/org/python/core/PyInstance.java 2008-11-10 03:29:23 UTC (rev 5563) +++ branches/newstyle-java-types/src/org/python/core/PyInstance.java 2008-11-10 03:31:53 UTC (rev 5564) @@ -109,7 +109,7 @@ // The javaProxy can be initialized in Py.jfindattr() throw Py.TypeError("Proxy instance already initialized"); } - PyInstance proxyInstance = proxy._getPyInstance(); + PyObject proxyInstance = proxy._getPyInstance(); if (proxyInstance != null && proxyInstance != this) { // The proxy was initialized to another instance!! throw Py.TypeError("Proxy initialization conflict"); Modified: branches/newstyle-java-types/src/org/python/core/PyJavaType.java =================================================================== --- branches/newstyle-java-types/src/org/python/core/PyJavaType.java 2008-11-10 03:29:23 UTC (rev 5563) +++ branches/newstyle-java-types/src/org/python/core/PyJavaType.java 2008-11-10 03:31:53 UTC (rev 5564) @@ -14,11 +14,22 @@ private final static Class<?>[] OO = {PyObject.class, PyObject.class}; + public static PyObject wrapJavaObject(Object o) { + PyObject obj = new PyObject(PyType.fromClass(o.getClass())); + obj.javaProxy = o; + return obj; + } + public PyJavaType() { super(TYPE == null ? fromClass(PyType.class) : TYPE); } @Override + public Class<?> getProxyType() { + return underlying_class; + } + + @Override protected void fillDict() { dict = new PyStringMap(); Map<String, Object> propnames = new HashMap<String, Object>(); @@ -83,10 +94,15 @@ } } } - dict.__setitem__(normalize_name(fldname), new PyReflectedField(field)); + if (dict.__finditem__(normalize_name(fldname)) == null) { + dict.__setitem__(normalize_name(fldname), new PyReflectedField(field)); + } } } for (String propname : propnames.keySet()) { + if(propname.equals("")) { + continue; + } String npropname = normalize_name(StringUtil.decapitalize(propname)); PyObject prev = dict.__finditem__(npropname); if (prev != null && prev instanceof PyReflectedFunction) { Modified: branches/newstyle-java-types/src/org/python/core/PyObject.java =================================================================== --- branches/newstyle-java-types/src/org/python/core/PyObject.java 2008-11-10 03:29:23 UTC (rev 5563) +++ branches/newstyle-java-types/src/org/python/core/PyObject.java 2008-11-10 03:31:53 UTC (rev 5564) @@ -200,8 +200,15 @@ * @param c the Class to convert this <code>PyObject</code> to. **/ public Object __tojava__(Class<?> c) { - if (c.isInstance(this)) + if ((c == Object.class || c == Serializable.class) && javaProxy != null) { + return javaProxy; + } + if (c.isInstance(this)) { return this; + } + if (c.isInstance(javaProxy)) { + return javaProxy; + } return Py.NoConversion; } @@ -3354,19 +3361,15 @@ // Generated by make_binops.py (End) - /* A convenience function for PyProxy's */ - // Possibly add _jcall(), _jcall(Object, ...) as future optimization /** - * A convenience function for PyProxy's. - * @param args call arguments. - * @exception Throwable + * A convenience function for PyProxys. */ public PyObject _jcallexc(Object[] args) throws Throwable { PyObject[] pargs = new PyObject[args.length]; try { - int n = args.length; - for (int i = 0; i < n; i++) + for (int i = 0; i < args.length; i++) { pargs[i] = Py.java2py(args[i]); + } return __call__(pargs); } catch (PyException e) { if (e.value instanceof PyJavaInstance) { @@ -3927,12 +3930,11 @@ } static { - for (Class unbootstrapped : Py.BOOTSTRAP_TYPES) { + for (Class<?> unbootstrapped : Py.BOOTSTRAP_TYPES) { Py.writeWarning("init", "Bootstrap type wasn't encountered in bootstrapping[class=" + unbootstrapped + "]"); } } - } /* Modified: branches/newstyle-java-types/src/org/python/core/PyProxy.java =================================================================== --- branches/newstyle-java-types/src/org/python/core/PyProxy.java 2008-11-10 03:29:23 UTC (rev 5563) +++ branches/newstyle-java-types/src/org/python/core/PyProxy.java 2008-11-10 03:31:53 UTC (rev 5564) @@ -3,7 +3,7 @@ /** * Common methods for all generated proxy classes. - * + * * Proxy classes are created whenever a python class inherits from a java class. Instances of such a * python class consists of two objects: * <ul> @@ -12,24 +12,23 @@ * <li>An instance of PyInstance. The PyInstance.javaProxy contains a reference to the proxy class * instance. * </ul> - * - * All proxy classes, both dynamically generated and statically generated by jythonc implements this - * interface. + * + * All proxy classes implement this interface. */ // This interface should be applicable to ANY class // Choose names that are extremely unlikely to have conflicts public interface PyProxy { /** - * Associate an PyInstance with this proxy instance. This is done during construction and + * Associate a PyObject with this proxy instance. This is done during construction and * initialization of the proxy instance. */ - abstract public void _setPyInstance(PyInstance proxy); + void _setPyInstance(PyObject proxy); /** - * Return the associated PyInstance instance. + * Return the associated PyObject. */ - abstract public PyInstance _getPyInstance(); + PyObject _getPyInstance(); /** * Associate an system state with this proxy instance. This is done during construction and @@ -40,16 +39,16 @@ /** * Return the associated system state. */ - abstract public PySystemState _getPySystemState(); + PySystemState _getPySystemState(); /** - * Initialize the proxy instance. If the proxy have not been initialized already, this call will - * call the python constructor with <code>args</code>. + * Initialize the proxy instance. If the proxy is not initialized, this will call the python + * constructor with <code>args</code>. * <p> * In some situations is it necessary to call the __initProxy__ method from the java superclass - * ctor before the ctor makes call to methods that is overriden in python. + * ctor before the ctor makes call to methods that is overridden in python. * <p> * In most situation the __initProxy__ is called automatically by the jython runtime. */ - public abstract void __initProxy__(Object[] args); + void __initProxy__(Object[] args); } Modified: branches/newstyle-java-types/src/org/python/core/PyReflectedConstructor.java =================================================================== --- branches/newstyle-java-types/src/org/python/core/PyReflectedConstructor.java 2008-11-10 03:29:23 UTC (rev 5563) +++ branches/newstyle-java-types/src/org/python/core/PyReflectedConstructor.java 2008-11-10 03:31:53 UTC (rev 5564) @@ -90,7 +90,7 @@ if (self instanceof PyInstance) { javaClass = ((PyInstance)self).instclass.proxyClass; } else { - javaClass = self.getType().underlying_class; + javaClass = self.getType().getProxyType(); } Class<?> declaringClass = argslist[0].declaringClass; @@ -98,12 +98,6 @@ throw Py.TypeError("self invalid - must implement: " + declaringClass.getName()); } - if (!PyProxy.class.isAssignableFrom(declaringClass) && !(self instanceof PyJavaInstance)) { - PyJavaClass jc = PyJavaClass.lookup(javaClass); - jc.initConstructors(); - return jc.__init__.__call__(self, args, keywords); - } - if (self.javaProxy != null) { Class<?> sup = javaClass; if (PyProxy.class.isAssignableFrom(sup)) { @@ -158,9 +152,7 @@ Object jself = null; ThreadState ts = Py.getThreadState(); try { - if (obj instanceof PyInstance) { - ts.pushInitializingProxy((PyInstance)obj); - } + ts.pushInitializingProxy(obj); try { jself = ctor.newInstance(args); } catch (InvocationTargetException e) { @@ -177,9 +169,7 @@ throw Py.JavaError(t); } } finally { - if (obj instanceof PyInstance) { - ts.popInitializingProxy(); - } + ts.popInitializingProxy(); } obj.javaProxy = jself; } Modified: branches/newstyle-java-types/src/org/python/core/PyReflectedFunction.java =================================================================== --- branches/newstyle-java-types/src/org/python/core/PyReflectedFunction.java 2008-11-10 03:29:23 UTC (rev 5563) +++ branches/newstyle-java-types/src/org/python/core/PyReflectedFunction.java 2008-11-10 03:31:53 UTC (rev 5564) @@ -138,26 +138,6 @@ Object cself = callData.self; Method m = (Method)method; - // Check to see if we should be using a super__ method instead - // This is probably a bit inefficient... - if (self == null && cself != null && cself instanceof PyProxy && - !__name__.startsWith("super__")) { - PyInstance iself = ((PyProxy)cself)._getPyInstance(); - if (argslist[0].declaringClass != iself.instclass.proxyClass) { - String mname = ("super__"+__name__); - // xxx experimental - Method[] super__methods = (Method[])iself.instclass.super__methods.get(mname); - if (super__methods != null) { - Class[] msig = m.getParameterTypes(); - for (Method super__method : super__methods) { - if (java.util.Arrays.equals(msig,super__method.getParameterTypes())) { - m = super__method; - break; - } - } - } - } - } try { Object o = m.invoke(cself, callData.getArgsArray()); Modified: branches/newstyle-java-types/src/org/python/core/PyType.java =================================================================== --- branches/newstyle-java-types/src/org/python/core/PyType.java 2008-11-10 03:29:23 UTC (rev 5563) +++ branches/newstyle-java-types/src/org/python/core/PyType.java 2008-11-10 03:31:53 UTC (rev 5564) @@ -133,6 +133,26 @@ if (bases_list.length == 0) { bases_list = new PyObject[] {object_type}; } + List<Class<?>> interfaces = Generic.list(); + Class<?> baseClass = null; + for (PyObject base : bases_list) { + if (!(base instanceof PyType)) { + continue; + } + Class<?> proxy = ((PyType)base).getProxyType(); + if (proxy == null) { + continue; + } + if (proxy.isInterface()) { + interfaces.add(proxy); + } else { + if (baseClass != null) { + throw Py.TypeError("no multiple inheritance for Java classes: " + + proxy.getName() + " and " + baseClass.getName()); + } + baseClass = proxy; + } + } // XXX can be subclassed ? if (dict.__finditem__("__module__") == null) { @@ -147,6 +167,33 @@ } // XXX also __doc__ __module__ + + if (baseClass != null || interfaces.size() != 0) { + String proxyName = name; + PyObject module = dict.__finditem__("__module__"); + if (module != null) { + proxyName = module.toString() + "$" + proxyName; + } + Class<?> proxyClass = MakeProxies.makeProxy(baseClass, + interfaces, + name, + proxyName, + dict); + PyType proxyType = PyType.fromClass(proxyClass); + List<PyObject> cleanedBases = Generic.list(); + boolean addedProxyType = false; + for (PyObject base : bases_list) { + if (base instanceof PyJavaType) { + if (!addedProxyType) { + cleanedBases.add(proxyType); + addedProxyType = true; + } + } else { + cleanedBases.add(base); + } + } + bases_list = cleanedBases.toArray(new PyObject[cleanedBases.size()]); + } PyType newtype; if (new_.for_type == metatype) { newtype = new PyType(); // XXX set metatype @@ -294,23 +341,19 @@ } private static void fillInMRO(PyType type, Class<?> base) { - PyType[] mro; - if (base == Object.class || base == null) { - if (type.underlying_class == Object.class) { - mro = new PyType[] {type, PyObject.TYPE}; - } else { - mro = new PyType[] {type}; + if (type.underlying_class == PyObject.class) { + type.mro = new PyType[] {type}; + return; } - } else { - PyType baseType = fromClass(base); - mro = new PyType[baseType.mro.length + 1]; - System.arraycopy(baseType.mro, 0, mro, 1, baseType.mro.length); - mro[0] = type; - type.base = baseType; - type.bases = new PyObject[] {baseType}; + base = PyObject.class; } - type.mro = mro; + PyType baseType = fromClass(base); + type.mro = new PyType[baseType.mro.length + 1]; + System.arraycopy(baseType.mro, 0, type.mro, 1, baseType.mro.length); + type.mro[0] = type; + type.base = baseType; + type.bases = new PyObject[] {baseType}; } public PyObject getStatic() { @@ -417,7 +460,6 @@ mro = savedMro; throw t; } - } private void mro_internal() { @@ -504,6 +546,21 @@ return result; } + /** + * Returns the Java Class that this type inherits from, or null if this type is Python-only. + */ + public Class<?> getProxyType() { + for (PyObject base : bases) { + if (base instanceof PyType) { + Class<?> javaType = ((PyType)base).getProxyType(); + if (javaType != null) { + return javaType; + } + } + } + return null; + } + private synchronized void attachSubclass(PyType subtype) { cleanup_subclasses(); subclasses.add(new WeakReference<PyType>(subtype, subclasses_refq)); Modified: branches/newstyle-java-types/src/org/python/core/ThreadState.java =================================================================== --- branches/newstyle-java-types/src/org/python/core/ThreadState.java 2008-11-10 03:29:23 UTC (rev 5563) +++ branches/newstyle-java-types/src/org/python/core/ThreadState.java 2008-11-10 03:31:53 UTC (rev 5564) @@ -25,20 +25,20 @@ public TraceFunction profilefunc; - private LinkedList<PyInstance> initializingProxies; + private LinkedList<PyObject> initializingProxies; private PyDictionary compareStateDict; - public PyInstance getInitializingProxy() { + public PyObject getInitializingProxy() { if (initializingProxies == null) { return null; } return initializingProxies.peek(); } - public void pushInitializingProxy(PyInstance proxy) { + public void pushInitializingProxy(PyObject proxy) { if (initializingProxies == null) { - initializingProxies = new LinkedList<PyInstance>(); + initializingProxies = new LinkedList<PyObject>(); } initializingProxies.addFirst(proxy); } Modified: branches/newstyle-java-types/src/org/python/core/adapter/ClassicPyObjectAdapter.java =================================================================== --- branches/newstyle-java-types/src/org/python/core/adapter/ClassicPyObjectAdapter.java 2008-11-10 03:29:23 UTC (rev 5563) +++ branches/newstyle-java-types/src/org/python/core/adapter/ClassicPyObjectAdapter.java 2008-11-10 03:31:53 UTC (rev 5564) @@ -4,8 +4,7 @@ import org.python.core.PyArray; import org.python.core.PyFloat; import org.python.core.PyInteger; -import org.python.core.PyJavaClass; -import org.python.core.PyJavaInstance; +import org.python.core.PyJavaType; import org.python.core.PyLong; import org.python.core.PyObject; import org.python.core.PyProxy; @@ -14,14 +13,14 @@ /** * Implements the algorithm originally used in {@link Py#java2py} to adapt objects. - * + * * Pre-class adapters are added to handle instances of PyObject, PyProxy and * null values. Class adapters are added to handle builtin Java classes: String, * Integer, Float, Double, Byte, Long, Short, Character, Class and Boolean. An * adapter is added to the post-class adapters to handle wrapping arrays * properly. Finally, if all of the added adapters can handle an object, it's * wrapped in a PyJavaInstance. - * + * */ public class ClassicPyObjectAdapter extends ExtensiblePyObjectAdapter { @@ -67,19 +66,15 @@ add(new ClassAdapter(Character.class) { public PyObject adapt(Object o) { - return Py.makeCharacter((Character) o); - } + return Py.makeCharacter((Character)o); + } }); add(new ClassAdapter(Class.class) { public PyObject adapt(Object o) { - Class cls = (Class) o; - if (PyObject.class.isAssignableFrom(cls)) { - return PyType.fromClass(cls); - } - return PyJavaClass.lookup(cls); - } + return PyType.fromClass((Class<?>)o); + } }); add(new NumberToPyFloat(Double.class)); @@ -126,7 +121,7 @@ if (result != null) { return result; } - return new PyJavaInstance(o); + return PyJavaType.wrapJavaObject(o); } private static class NumberToPyInteger extends ClassAdapter { Modified: branches/newstyle-java-types/src/org/python/core/adapter/PyObjectAdapter.java =================================================================== --- branches/newstyle-java-types/src/org/python/core/adapter/PyObjectAdapter.java 2008-11-10 03:29:23 UTC (rev 5563) +++ branches/newstyle-java-types/src/org/python/core/adapter/PyObjectAdapter.java 2008-11-10 03:31:53 UTC (rev 5564) @@ -7,14 +7,13 @@ */ public interface PyObjectAdapter { - /** - * @return true if o can be adapted by this adapter. - */ - public abstract boolean canAdapt(Object o); + /** + * Returns true if o can be adapted by this adapter. + */ + public abstract boolean canAdapt(Object o); - /** - * @return the PyObject version of o or null if canAdapt(o) returns false. - */ - public abstract PyObject adapt(Object o); - + /** + * Returns the PyObject version of o or null if canAdapt(o) returns false. + */ + public abstract PyObject adapt(Object o); } \ No newline at end of file This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <cg...@us...> - 2008-11-23 00:46:12
|
Revision: 5605 http://jython.svn.sourceforge.net/jython/?rev=5605&view=rev Author: cgroves Date: 2008-11-23 00:46:06 +0000 (Sun, 23 Nov 2008) Log Message: ----------- Use PyJavaType to initialize array, not PyJavaClass Modified Paths: -------------- branches/newstyle-java-types/Lib/test/test_array_jy.py branches/newstyle-java-types/src/org/python/core/PyArray.java Modified: branches/newstyle-java-types/Lib/test/test_array_jy.py =================================================================== --- branches/newstyle-java-types/Lib/test/test_array_jy.py 2008-11-23 00:18:15 UTC (rev 5604) +++ branches/newstyle-java-types/Lib/test/test_array_jy.py 2008-11-23 00:46:06 UTC (rev 5605) @@ -12,7 +12,7 @@ def test_jarray(self): # until it is fully formally removed - # While jarray is still being phased out, just flex the initilaizers. + # While jarray is still being phased out, just flex the initializers. # The rest of the test for array will catch all the big problems. import jarray jarray.array(range(5), 'i') @@ -23,7 +23,7 @@ def test_java_object_arrays(self): jStringArr = array(String, [String("a"), String("b"), String("c")]) self.assert_( - Arrays.equals(jStringArr.typecode, str(String)), + Arrays.equals(jStringArr.typecode, 'java.lang.String'), "String array typecode of wrong type, expected %s, found %s" % (jStringArr.typecode, str(String))) self.assertEqual(zeros(String, 5), Array.newInstance(String, 5)) Modified: branches/newstyle-java-types/src/org/python/core/PyArray.java =================================================================== --- branches/newstyle-java-types/src/org/python/core/PyArray.java 2008-11-23 00:18:15 UTC (rev 5604) +++ branches/newstyle-java-types/src/org/python/core/PyArray.java 2008-11-23 00:46:06 UTC (rev 5605) @@ -21,7 +21,7 @@ /** * A wrapper class around native java arrays. - * + * * Instances of PyArray are created either by java functions or directly by the * jarray module. * <p> @@ -95,8 +95,8 @@ } typecode = obj.toString(); type = char2class(typecode.charAt(0)); - } else if (obj instanceof PyJavaClass) { - type = ((PyJavaClass)obj).proxyClass; + } else if (obj instanceof PyJavaType) { + type = ((PyJavaType)obj).underlying_class; typecode = type.getName(); } else { throw Py.TypeError("array() argument 1 must be char, not " + obj.getType().fastGetName()); @@ -153,7 +153,7 @@ /** * Create a PyArray storing <em>ctype</em> types and being initialised * with <em>initialiser</em>. - * + * * @param init * an initialiser for the array - can be PyString or PySequence * (including PyArray) or iterable type. @@ -325,7 +325,7 @@ /** * Adds (appends) two PyArrays together - * + * * @param other * a PyArray to be added to the instance * @return the result of the addition as a new PyArray instance @@ -348,7 +348,7 @@ /** * Length of the array - * + * * @return number of elements in the array */ public int __len__() { @@ -393,9 +393,9 @@ if (typecode.length() > 1) return typecode; else return "'" + typecode + "'"; } - + /** - * + * * @param c * target <em>Class</em> for the conversion * @return Java object converted to required class type if possible. @@ -426,7 +426,7 @@ throw Py.TypeError("array item must be unicode character"); } - + // relax to allow mixing with PyString, integers private static int getCodePointOrInt(PyObject obj) { if (obj instanceof PyUnicode) { @@ -444,14 +444,14 @@ return -1; } } - + /** * Append new value x to the end of the array. - * + * * @param value * item to be appended to the array */ - + public void append(PyObject value) { // Currently, this is asymmetric with extend, which // *will* do conversions like append(5.0) to an int array. @@ -497,7 +497,7 @@ /** * Implementation of <em>Cloneable</em> interface. - * + * * @return copy of current PyArray */ public Object clone() { @@ -507,7 +507,7 @@ /** * Converts a character code for the array type to a Java <code>Class</code>. * <p /> - * + * * The following character codes and their native types are supported:<br /> * <table> * <tr> @@ -548,10 +548,10 @@ * </tr> * </table> * <p /> - * + * * @param type * character code for the array type - * + * * @return <code>Class</code> of the native type */ @@ -609,7 +609,7 @@ else return cls.getName(); } - + @ExposedMethod public final int array_count(PyObject value) { // note: cpython does not raise type errors based on item type; @@ -634,7 +634,7 @@ } /** * Return the number of occurrences of x in the array. - * + * * @param value * instances of the value to be counted * @return number of time value was found in the array. @@ -645,7 +645,7 @@ /** * Delete the element at position <em>i</em> from the array - * + * * @param i * index of the item to be deleted from the array */ @@ -658,7 +658,7 @@ /** * Delete the slice defined by <em>start</em>, <em>stop</em> and * <em>step</em> from the array. - * + * * @param start * starting index of slice * @param stop @@ -681,7 +681,7 @@ } } } - + @ExposedMethod public final void array_extend(PyObject iterable){ extendInternal(iterable); @@ -694,7 +694,7 @@ * iterable and its elements must be the right type to be appended to the * array. Changed in version 2.4: Formerly, the argument could only be * another array. - * + * * @param iterable * iterable object used to extend the array */ @@ -707,12 +707,12 @@ * Handles specific cases of <em>iterable</em> being PyStrings or * PyArrays. Default behaviour is to defer to * {@link #extendInternalIter(PyObject) extendInternalIter } - * + * * @param iterable * object of type PyString, PyArray or any object that can be * iterated over. */ - + private void extendInternal(PyObject iterable) { if (iterable instanceof PyUnicode) { if ("u".equals(typecode)) { @@ -737,7 +737,7 @@ /** * Internal extend function to process iterable objects. - * + * * @param iterable * any object that can be iterated over. */ @@ -774,7 +774,7 @@ } } } - + private void extendArray(int[] items) { int last = delegate.getSize(); delegate.ensureCapacity(last + items.length); @@ -783,12 +783,12 @@ delegate.size++; } } - + @ExposedMethod public final void array_fromfile(PyObject f, int count){ fromfile(f, count); } - + /** * Read <em>count</em> items (as machine values) from the file object * <em>f</em> and append them to the end of the array. If less than @@ -796,7 +796,7 @@ * that were available are still inserted into the array. <em>f</em> must * be a real built-in file object; something else with a read() method won't * do. - * + * * @param f * Python builtin file object to retrieve data * @param count @@ -825,7 +825,7 @@ + Integer.toString(readcount) + " actually read"); } } - + @ExposedMethod public final void array_fromlist(PyObject obj){ fromlist(obj); @@ -834,7 +834,7 @@ /** * Append items from the list. This is equivalent to "for x in list: * a.append(x)"except that if there is a type error, the array is unchanged. - * + * * @param obj * input list object that will be appended to the array */ @@ -857,12 +857,12 @@ /** * Generic stream reader to read the entire contents of a stream into the * array. - * + * * @param is * InputStream to source the data from - * + * * @return number of primitives successfully read - * + * * @throws IOException * @throws EOFException */ @@ -873,14 +873,14 @@ /** * Generic stream reader to read <em>count</em> primitive types from a * stream into the array. - * + * * @param is * InputStream to source the data from * @param count * number of primitive types to read from the stream - * + * * @return number of primitives successfully read - * + * * @throws IOException * @throws EOFException */ @@ -948,7 +948,7 @@ * Appends items from the string, interpreting the string as an array of * machine values (as if it had been read from a file using the * {@link #fromfile(PyObject, int) fromfile()} method). - * + * * @param input * string of bytes containing array data */ @@ -990,7 +990,7 @@ /** * Get the element at position <em>i</em> from the array - * + * * @param i * index of the item to be retrieved from the array */ @@ -1003,7 +1003,7 @@ /** * Return the internal Java array storage of the PyArray instance - * + * * @return the <code>Array</code> store. */ public Object getArray() throws PyIgnoreMethodTag { @@ -1013,17 +1013,17 @@ /** * Getter for the storage size of the array's type. * <p /> - * + * * The sizes returned by this method represent the number of bytes used to * store the type. In the case of streams, this is the number of bytes * written to, or read from a stream. For memory this value is the * <em>minimum</em> number of bytes required to store the type. * <p /> - * + * * This method is used by other methods to define read/write quanta from * strings and streams. * <p /> - * + * * Values returned are:<br /> * <table> * <tr> @@ -1063,7 +1063,7 @@ * <td>8</td> * </tr> * </table> - * + * * @return number of bytes used to store array type. */ @ExposedGet(name = "itemsize") @@ -1093,7 +1093,7 @@ /** * Retrieve a slice from the array specified by the <em>start</em>, * <em>stop</em> and <em>step</em>. - * + * * @param start * start index of the slice * @param stop @@ -1124,14 +1124,14 @@ * Getter for the type code of the array. * {@link #char2class(char) char2class} describes the possible type codes * and their meaning. - * + * * @return single character type code for the array */ @ExposedGet(name = "typecode") public String getTypecode() { return typecode; } - + @ExposedMethod public final int array_index(PyObject value){ int index = indexInternal(value); @@ -1144,7 +1144,7 @@ /** * Return the smallest <em>i</em> such that <em>i</em> is the index of * the first occurrence of <em>value</em> in the array. - * + * * @param value * value to find the index of * @return index of the first occurance of <em>value</em> @@ -1156,7 +1156,7 @@ /** * Return the smallest <em>i</em> such that <em>i</em> is the index of * the first occurrence of <em>value</em> in the array. - * + * * @param value * value to find the index of * @return index of the first occurance of <em>value</em> @@ -1181,7 +1181,7 @@ } return -1; } - + @ExposedMethod public final void array_insert(int index, PyObject value){ insert(index, value); @@ -1191,7 +1191,7 @@ * Insert a new item with value <em>value</em> in the array before * position <em>index</em>. Negative values are treated as being relative * to the end of the array. - * + * * @param index * insert position * @param value @@ -1209,7 +1209,7 @@ Array.set(data, index, Py.tojava(value, type)); } } - + @ExposedMethod(defaults="-1") public final PyObject array_pop(int i){ PyObject val = pop(i); @@ -1232,7 +1232,7 @@ * Removes the item with the index <em>index</em> from the array and * returns it. The optional argument defaults to -1, so that by default the * last item is removed and returned. - * + * * @param index * array location to be popped from the array * @return array element popped from index @@ -1249,7 +1249,7 @@ delegate.remove(index); return ret; } - + @ExposedMethod public final void array_remove(PyObject value){ remove(value); @@ -1257,7 +1257,7 @@ /** * Remove the first occurrence of <em>value</em> from the array. - * + * * @param value * array value to be removed */ @@ -1273,7 +1273,7 @@ /** * Repeat the array <em>count</em> times. - * + * * @param count * number of times to repeat the array * @return A new PyArray object containing the source object repeated @@ -1289,7 +1289,7 @@ } return ret; } - + @ExposedMethod public final void array_reverse(){ reverse(); @@ -1297,7 +1297,7 @@ /** * Reverse the elements in the array - * + * */ public void reverse() { // build a new reversed array and set this.data to it when done @@ -1315,10 +1315,10 @@ * {@link AbstractArray#ensureCapacity(int) AbstractArray.ensureCapacity()} * for ways to extend capacity. * <p /> - * + * * This code specifically checks for overflows of the integral types: byte, * short, int and long. - * + * * @param i * index of the element to be set * @param value @@ -1328,8 +1328,8 @@ if ("u".equals(typecode)) { Array.setInt(data, i, getCodePoint(value)); return; - } - + } + if(type == Byte.TYPE) { long val; try { @@ -1401,15 +1401,15 @@ throw Py.TypeError("Type not compatible with array type"); } } - + public void set(int i, char value) { if ("c".equals(typecode) || type == Integer.TYPE || type == Long.TYPE) { Array.setChar(data, i, value); } else { throw Py.TypeError("Type not compatible with array type"); - } + } } - + private boolean isSigned() { return typecode.length() == 1 && typecode.equals(typecode.toUpperCase()); } @@ -1419,7 +1419,7 @@ * <code>byte</code> and <code>char</code> types) or PyArray. If a * PyArray, its type must be convertible into the type of the target * PyArray. - * + * * @param start * start index of the delete slice * @param stop @@ -1486,12 +1486,12 @@ } } } - + @ExposedMethod public final void array_tofile(PyObject f){ tofile(f); } - + @ExposedMethod public void array_write(PyObject f){ tofile(f); @@ -1499,7 +1499,7 @@ /** * Write all items (as machine values) to the file object <em>f</em>. - * + * * @param f * Python builtin file object to write data */ @@ -1521,7 +1521,7 @@ /** * Convert the array to an ordinary list with the same items. - * + * * @return array contents as a list */ public PyObject tolist() { @@ -1542,12 +1542,12 @@ /** * Generic stream writer to write the entire contents of the array to the * stream as primitive types. - * + * * @param os * OutputStream to sink the array data to - * + * * @return number of primitives successfully written - * + * * @throws IOException */ private int toStream(OutputStream os) throws IOException { @@ -1581,7 +1581,7 @@ } return dos.size(); } - + @ExposedMethod public final PyObject array_tostring(){ return new PyString(tostring()); @@ -1610,10 +1610,10 @@ int[] codepoints = new int[len]; for(int i = 0; i < len; i++) codepoints[i] = Array.getInt(data, i); - return new String(codepoints, 0, codepoints.length); + return new String(codepoints, 0, codepoints.length); } - - + + @ExposedMethod public final PyObject array_tounicode() { return new PyUnicode(tounicode()); This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <cg...@us...> - 2008-11-23 02:36:12
|
Revision: 5607 http://jython.svn.sourceforge.net/jython/?rev=5607&view=rev Author: cgroves Date: 2008-11-23 02:36:05 +0000 (Sun, 23 Nov 2008) Log Message: ----------- Rip out PyJavaClass and friends. This isn't even close to passing regrtest, but it runs well enough to start the interpreter and get through the first few. Modified Paths: -------------- branches/newstyle-java-types/src/org/python/core/IdImpl.java branches/newstyle-java-types/src/org/python/core/Py.java branches/newstyle-java-types/src/org/python/core/PyBeanEventProperty.java branches/newstyle-java-types/src/org/python/core/PyClass.java branches/newstyle-java-types/src/org/python/core/PyFile.java branches/newstyle-java-types/src/org/python/core/PyInstance.java branches/newstyle-java-types/src/org/python/core/PyJavaPackage.java branches/newstyle-java-types/src/org/python/core/PyObject.java branches/newstyle-java-types/src/org/python/core/PyReflectedConstructor.java branches/newstyle-java-types/src/org/python/core/PyType.java branches/newstyle-java-types/src/org/python/core/StdoutWrapper.java branches/newstyle-java-types/src/org/python/core/__builtin__.java branches/newstyle-java-types/src/org/python/core/imp.java branches/newstyle-java-types/src/org/python/modules/cPickle.java branches/newstyle-java-types/src/org/python/modules/cStringIO.java Removed Paths: ------------- branches/newstyle-java-types/Lib/jreload.py branches/newstyle-java-types/Lib/jxxload_help/ branches/newstyle-java-types/src/org/python/core/AutoInternalTables.java branches/newstyle-java-types/src/org/python/core/CollectionProxy.java branches/newstyle-java-types/src/org/python/core/InternalTables.java branches/newstyle-java-types/src/org/python/core/PyJavaClass.java branches/newstyle-java-types/src/org/python/core/PyJavaInnerClass.java branches/newstyle-java-types/src/org/python/core/PyJavaInstance.java branches/newstyle-java-types/src/org/python/core/SoftIInternalTables.java branches/newstyle-java-types/src/org/python/core/WeakInternalTables.java branches/newstyle-java-types/src/org/python/modules/_jython.java Deleted: branches/newstyle-java-types/Lib/jreload.py =================================================================== --- branches/newstyle-java-types/Lib/jreload.py 2008-11-23 01:57:09 UTC (rev 5606) +++ branches/newstyle-java-types/Lib/jreload.py 2008-11-23 02:36:05 UTC (rev 5607) @@ -1,119 +0,0 @@ -# java classes reload support (experimental) -# Copyright 2000 Samuele Pedroni - -# ?? could have problem with import pkg.jclass.inner (this should not be used in any case) -# ?? using import * with a load-set together with reloading can be confusing -# cannot be fixed => anyway import * is not for production code - -__version__ = "0.3" - -import sys -from org.python.core import imp,PyJavaPackage,PyJavaClass -from _jython import is_lazy as _is_lazy - -import jxxload_help - - -class _LoaderFactory(jxxload_help.JavaLoaderFactory): - def __init__(self,path): - vfs = jxxload_help.PathVFS() - for fname in path: - vfs.addVFS(fname) - self.vfs = vfs - - def makeLoader(self): - return jxxload_help.PathVFSJavaLoader(self.vfs,imp.getSyspathJavaLoader()) - -class _Unload: - - def __init__(self,ls): - self.ls = ls - self.ls_name = ls._name - self.loader = ls._mgr.loader - - def do_unload(self,pkg): - for n in pkg.__dict__.keys(): - e = pkg.__dict__[n] - if isinstance(e,PyJavaClass): - if _is_lazy(e): continue - if e.classLoader is self.loader: - del pkg.__dict__[n] - if pkg.__name__: - n = self.ls_name + '.' + pkg.__name__ + '.' +n - else: - n = self.ls_name + '.' + n - if sys.modules.has_key(n): del sys.modules[n] - - elif isinstance(e,PyJavaPackage): - self.do_unload(e) - - def __call__(self): - if self.loader: - if self.ls._mgr.checkLoader() is self.loader: - self.do_unload(self.ls._top) - self.ls._mgr.resetLoader() - loader = self.loader - jxxload_help.DiscardHelp.discard(loader,loader.interfaces) - self.loader = None - -class LoadSet: -# ?? for the moment from import * and dir do not work for LoadSet, but work for -# contained pkgs -# need java impl as PyObject - - def __init__(self,name,path): - mgr = jxxload_help.PackageManager(path,_LoaderFactory(path)) - self._name = name - self._mgr = mgr - self._top = mgr.topLevelPackage - - def __getattr__(self,name): - try: - return getattr(self._top,name) - except: - if name == 'unload': return _Unload(self) - raise - - - def __repr__(self): - return "<java load-set %s>" % self._name - -def unloadf(ls): - if not isinstance(ls,LoadSet): raise TypeError,"unloadf(): arg is not a load-set" - return _Unload(ls) - -def makeLoadSet(name,path): - if sys.modules.has_key(name): return sys.modules[name] - sys.modules[name] = ls = LoadSet(name,path) - return ls - -_reload = reload - -def _do_reload(ls_name,mgr,pkg): - pkg_name = pkg.__name__ - for n in pkg.__dict__.keys(): - e = pkg.__dict__[n] - if isinstance(e,PyJavaClass): - if _is_lazy(e): continue - del pkg.__dict__[n] - try : - c = mgr.findClass(pkg_name,n); - if c: - pkg.__dict__[n] = c - if pkg_name: - n = ls_name + '.' + pkg_name + '.' + n - else: - n = ls_name + '.' + n - if sys.modules.has_key(n): sys.modules[n] = c - except: - pass - elif isinstance(e,PyJavaPackage): - _do_reload(ls_name,mgr,e) - -def reload(ls): - if isinstance(ls,LoadSet): - ls._mgr.resetLoader() - _do_reload(ls._name,ls._mgr,ls._top) - return ls - else: - return _reload(ls) Deleted: branches/newstyle-java-types/src/org/python/core/AutoInternalTables.java =================================================================== --- branches/newstyle-java-types/src/org/python/core/AutoInternalTables.java 2008-11-23 01:57:09 UTC (rev 5606) +++ branches/newstyle-java-types/src/org/python/core/AutoInternalTables.java 2008-11-23 02:36:05 UTC (rev 5607) @@ -1,155 +0,0 @@ -// Copyright 2000 Samuele Pedroni - -package org.python.core; - -import java.lang.ref.Reference; -import java.lang.ref.ReferenceQueue; -import java.util.Map; - -public abstract class AutoInternalTables extends InternalTables { - - protected transient ReferenceQueue queue = new ReferenceQueue(); - - protected abstract Reference newAutoRef(short type, Object key, - Object obj); - protected abstract short getAutoRefType(Reference ref); - protected abstract Object getAutoRefKey(Reference ref); - - private synchronized void cleanup() { - if (this.keepstable >= this.GSTABLE) - return; - this.adapters.remove(null); // trick - Reference ref; - while ((ref = this.queue.poll()) != null) { - Object key = getAutoRefKey(ref); - switch(getAutoRefType(ref)) { - case JCLASS: - Class cl = (Class)key; - this.classes.remove(cl); - classesDec(cl.getName()); - break; - case LAZY_JCLASS: - this.lazyClasses.remove(key); - break; - case ADAPTER_CLASS: - this.adapterClasses.remove(key); - } - } - } - - - protected boolean queryCanonical(String name) { - cleanup(); - return super.queryCanonical(name); - } - - protected PyJavaClass getCanonical(Class c) { - cleanup(); - Reference ref = (Reference)classesGet(c); - if (ref == null) return null; - return (PyJavaClass)ref.get(); - } - - protected PyJavaClass getLazyCanonical(String name) { - cleanup(); - Reference ref = (Reference)this.lazyClasses.get(name); - if (ref == null) return null; - return (PyJavaClass)ref.get(); - } - - protected void putCanonical(Class c,PyJavaClass canonical) { - cleanup(); - classesPut(c,newAutoRef(JCLASS,c,canonical)); - } - - protected void putLazyCanonical(String name,PyJavaClass canonical) { - cleanup(); - this.lazyClasses.put(name,newAutoRef(LAZY_JCLASS,name,canonical)); - } - - protected Class getAdapterClass(Class c) { - cleanup(); - Reference ref = (Reference)this.adapterClasses.get(c); - if (ref == null) return null; - return (Class)ref.get(); - } - - protected void putAdapterClass(Class c,Class ac) { - cleanup(); - this.adapterClasses.put(c,newAutoRef(ADAPTER_CLASS,c,ac)); - } - - protected Object getAdapter(Object o,String evc) { - cleanup(); - return super.getAdapter(o,evc); - } - - protected void putAdapter(Object o,String evc,Object ad) { - cleanup(); - super.putAdapter(o,evc,ad); - } - - - public boolean _doesSomeAutoUnload() { return true; } - - public void _forceCleanup() { cleanup(); } - - public void _beginCanonical() { - cleanup(); - super._beginCanonical(); - } - - public void _beginLazyCanonical() { - cleanup(); - super._beginLazyCanonical(); - } - - public void _beginOverAdapterClasses() { - cleanup(); - super._beginOverAdapterClasses(); - - } - - public void _beginOverAdapters() { - cleanup(); - super._beginOverAdapters(); - } - - public Object _next() { - if (this.iterType == ADAPTER) { - Object ret = super._next(); - if (ret != null) return ret; - } else { - while(this.iter.hasNext()) { - this.cur = this.iter.next(); - switch(this.iterType) { - case JCLASS: - PyJavaClass jc = (PyJavaClass)((Reference)this.cur).get(); - if (jc == null ) continue; - this.cur = jc; - return jc; - case LAZY_JCLASS: - PyJavaClass lazy = (PyJavaClass)((Reference)this.cur).get(); - if (lazy == null) continue; - return new _LazyRep(lazy.__name__,lazy.__mgr__); - case ADAPTER_CLASS: - Map.Entry entry = (Map.Entry)this.cur; - if (((Reference)entry.getValue()).get() == null ) - continue; - return entry.getKey(); - } - } - this.cur = null; - this.iter = null; - endStable(); - } - cleanup(); - return null; - } - - public void _flush(PyJavaClass jc) { - cleanup(); - super._flush(jc); - } - -} Deleted: branches/newstyle-java-types/src/org/python/core/CollectionProxy.java =================================================================== --- branches/newstyle-java-types/src/org/python/core/CollectionProxy.java 2008-11-23 01:57:09 UTC (rev 5606) +++ branches/newstyle-java-types/src/org/python/core/CollectionProxy.java 2008-11-23 02:36:05 UTC (rev 5607) @@ -1,295 +0,0 @@ -// Copyright (c) Corporation for National Research Initiatives - -package org.python.core; - -import java.util.Dictionary; -import java.util.Enumeration; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Vector; - -class CollectionProxy { - public static final CollectionProxy NoProxy = new EnumerationProxy(null); - - public static CollectionProxy findCollection(Object object) { - if (object == null) - return NoProxy; - - if (object instanceof List) { - return new ListProxy(((List) object)); - } - if (object instanceof Map) { - return new MapProxy(((Map) object)); - } - if (object instanceof Iterable) { - return new IteratorProxy(((Iterable) object).iterator()); - } - if (object instanceof Iterator) { - return new IteratorProxy(((Iterator) object)); - } - - - if (object instanceof Vector) { - return new VectorProxy(((Vector) object)); - } - if (object instanceof Enumeration) { - return new EnumerationProxy(((Enumeration) object)); - } - if (object instanceof Dictionary) { - return new DictionaryProxy(((Dictionary) object)); - } - - return NoProxy; - } - - /** The basic functions to implement a mapping */ - public int __len__() { - throw Py.AttributeError("__len__"); - } - - public PyObject __finditem__(int key) { - return __finditem__(new PyInteger(key)); - } - - public PyObject __finditem__(PyObject key) { - throw Py.AttributeError("__getitem__"); - } - - public PyObject __getitem__(int key) { - PyObject ret = __finditem__(key); - if (ret == null) - throw Py.KeyError("" + key); - return ret; - } - - public PyObject __getitem__(PyObject key) { - PyObject ret = __finditem__(key); - if (ret == null) - throw Py.KeyError(key.toString()); - return ret; - } - - public void __setitem__(PyObject key, PyObject value) { - throw Py.AttributeError("__setitem__"); - } - - public void __delitem__(PyObject key) { - throw Py.AttributeError("__delitem__"); - } -} - -class EnumerationProxy extends CollectionProxy { - Enumeration proxy; - - int counter; - - public EnumerationProxy(Enumeration proxy) { - this.proxy = proxy; - this.counter = 0; - } - - public PyObject __finditem__(int key) { - if (key != this.counter) { - throw Py.ValueError("enumeration indices must be consecutive ints starting at 0"); - } - this.counter++; - if (this.proxy.hasMoreElements()) { - return Py.java2py(this.proxy.nextElement()); - } else { - return null; - } - } - - public PyObject __finditem__(PyObject key) { - if (key instanceof PyInteger) { - return __finditem__(((PyInteger) key).getValue()); - } else { - throw Py.TypeError("only integer keys accepted"); - } - } -} - -class VectorProxy extends CollectionProxy { - Vector proxy; - - public VectorProxy(Vector proxy) { - this.proxy = proxy; - } - - public int __len__() { - return this.proxy.size(); - } - - public PyObject __finditem__(int key) { - try { - return Py.java2py(this.proxy.elementAt(key)); - } catch (ArrayIndexOutOfBoundsException exc) { - return null; - } - } - - public PyObject __finditem__(PyObject key) { - if (key instanceof PyInteger) { - return __finditem__(((PyInteger) key).getValue()); - } else { - throw Py.TypeError("only integer keys accepted"); - } - } - - public void __setitem__(PyObject key, PyObject value) { - if (key instanceof PyInteger) { - this.proxy.setElementAt(Py.tojava(value, Object.class), ((PyInteger)key).getValue()); - } else { - throw Py.TypeError("only integer keys accepted"); - } - } - - public void __delitem__(PyObject key) { - if (key instanceof PyInteger) { - this.proxy.removeElementAt(((PyInteger) key).getValue()); - } else { - throw Py.TypeError("only integer keys accepted"); - } - } -} - -class DictionaryProxy extends CollectionProxy { - Dictionary proxy; - - public DictionaryProxy(Dictionary proxy) { - this.proxy = proxy; - } - - public int __len__() { - return this.proxy.size(); - } - - public PyObject __finditem__(int key) { - throw Py.TypeError("loop over non-sequence"); - } - - public PyObject __finditem__(PyObject key) { - return Py.java2py(this.proxy.get(Py.tojava(key, Object.class))); - } - - public void __setitem__(PyObject key, PyObject value) { - this.proxy.put(Py.tojava(key, Object.class), Py.tojava(value, - Object.class)); - } - - public void __delitem__(PyObject key) { - this.proxy.remove(Py.tojava(key, Object.class)); - } -} -class ListProxy extends CollectionProxy { - List proxy; - - public ListProxy(List proxy) { - this.proxy = proxy; - } - - public int __len__() { - return this.proxy.size(); - } - - public PyObject __finditem__(int key) { - try { - return Py.java2py(this.proxy.get(key)); - } catch (IndexOutOfBoundsException exc) { - return null; - } - } - - public PyObject __finditem__(PyObject key) { - if (key instanceof PyInteger) { - return __finditem__(((PyInteger) key).getValue()); - } else { - throw Py.TypeError("only integer keys accepted"); - } - } - - public void __setitem__(int key, PyObject value) { - this.proxy.set(key, Py.tojava(value, Object.class)); - } - - public void __setitem__(PyObject key, PyObject value) { - if (key instanceof PyInteger) { - __setitem__(((PyInteger) key).getValue(), value); - } else { - throw Py.TypeError("only integer keys accepted"); - } - } - - public void __delitem__(int key) { - this.proxy.remove(key); - } - - public void __delitem__(PyObject key) { - if (key instanceof PyInteger) { - __delitem__(((PyInteger) key).getValue()); - } else { - throw Py.TypeError("only integer keys accepted"); - } - } -} - -class MapProxy extends CollectionProxy { - Map proxy; - - public MapProxy(Map proxy) { - this.proxy = proxy; - } - - public int __len__() { - return this.proxy.size(); - } - - public PyObject __finditem__(int key) { - throw Py.TypeError("loop over non-sequence"); - } - - public PyObject __finditem__(PyObject key) { - return Py.java2py(this.proxy.get(Py.tojava(key, Object.class))); - } - - public void __setitem__(PyObject key, PyObject value) { - this.proxy.put(Py.tojava(key, Object.class), Py.tojava(value, - Object.class)); - } - - public void __delitem__(PyObject key) { - this.proxy.remove(Py.tojava(key, Object.class)); - } -} - -class IteratorProxy extends CollectionProxy { - Iterator proxy; - - int counter; - - public IteratorProxy(Iterator proxy) { - this.proxy = proxy; - this.counter = 0; - } - - public PyObject __finditem__(int key) { - if (key != this.counter) { - throw Py.ValueError("iterator indices must be consecutive ints starting at 0"); - } - this.counter++; - if (this.proxy.hasNext()) { - return Py.java2py(this.proxy.next()); - } else { - return null; - } - } - - public PyObject __finditem__(PyObject key) { - if (key instanceof PyInteger) { - return __finditem__(((PyInteger) key).getValue()); - } else { - throw Py.TypeError("only integer keys accepted"); - } - } -} Modified: branches/newstyle-java-types/src/org/python/core/IdImpl.java =================================================================== --- branches/newstyle-java-types/src/org/python/core/IdImpl.java 2008-11-23 01:57:09 UTC (rev 5606) +++ branches/newstyle-java-types/src/org/python/core/IdImpl.java 2008-11-23 02:36:05 UTC (rev 5607) @@ -7,48 +7,48 @@ public class IdImpl { public static class WeakIdentityMap { - + private transient ReferenceQueue refqueue = new ReferenceQueue(); private HashMap hashmap = new HashMap(); - + private void cleanup() { Object k; while ((k = this.refqueue.poll()) != null) { this.hashmap.remove(k); } } - + private class WeakIdKey extends WeakReference { private int hashcode; - + WeakIdKey(Object obj) { super(obj,WeakIdentityMap.this.refqueue); - this.hashcode = System.identityHashCode(obj); + this.hashcode = System.identityHashCode(obj); } - + public int hashCode() { return this.hashcode; } - + public boolean equals(Object other) { Object obj = this.get(); if (obj != null) { return obj == ((WeakIdKey)other).get(); } else { return this == other; - } + } } } - + public int _internal_map_size() { return this.hashmap.size(); } - + public void put(Object key,Object val) { cleanup(); this.hashmap.put(new WeakIdKey(key),val); } - + public Object get(Object key) { cleanup(); return this.hashmap.get(new WeakIdKey(key)); @@ -56,20 +56,20 @@ public void remove(Object key) { cleanup(); - this.hashmap.remove(new WeakIdKey(key)); + this.hashmap.remove(new WeakIdKey(key)); } } private WeakIdentityMap id_map = new WeakIdentityMap(); - private long sequential_id = 0; + private long sequential_id = 0; public long id(PyObject o) { - if (o instanceof PyJavaInstance) { - return java_obj_id(((PyJavaInstance)o).javaProxy); + if (o.getType() instanceof PyJavaType) { + return java_obj_id(o.javaProxy); } else { return java_obj_id(o); - } + } } // XXX maybe should display both this id and identityHashCode @@ -82,9 +82,9 @@ Long cand = (Long)this.id_map.get(o); if (cand == null) { this.sequential_id++; - long new_id = this.sequential_id; + long new_id = this.sequential_id; this.id_map.put(o,new Long(new_id)); - return new_id; + return new_id; } return cand.longValue(); } Deleted: branches/newstyle-java-types/src/org/python/core/InternalTables.java =================================================================== --- branches/newstyle-java-types/src/org/python/core/InternalTables.java 2008-11-23 01:57:09 UTC (rev 5606) +++ branches/newstyle-java-types/src/org/python/core/InternalTables.java 2008-11-23 02:36:05 UTC (rev 5607) @@ -1,292 +0,0 @@ -// Copyright 2000 Samuele Pedroni -package org.python.core; - -import java.lang.ref.WeakReference; -import java.util.HashMap; -import java.util.Iterator; -import java.util.Map; -import java.util.StringTokenizer; -import java.util.WeakHashMap; - -import org.python.core.packagecache.PackageManager; - -public class InternalTables { - - // x__ --> org.python.core.X__InternalTables - // (x|X)__> --> org.python.core.X__InternalTables - // other (X__|__.__) --> other - // - private static InternalTables tryImpl(String id) { - try { - if(id.indexOf('.') < 0) { - if(id.charAt(id.length() - 1) == '>') { - id = makeCoreInternalTablesClass(id.substring(0, id.length() - 1)); - } else if(Character.isLowerCase(id.charAt(0))) { - id = makeCoreInternalTablesClass(id); - } - } - // System.err.println("*InternalTables*-create-try: "+id); - return (InternalTables)Class.forName(id).newInstance(); - } catch(Throwable e) { - // System.err.println(" exc: "+e); // ??dbg - return null; - } - } - - private static String makeCoreInternalTablesClass(String id) { - if(Character.isLowerCase(id.charAt(0))) { - id = Character.toUpperCase(id.charAt(0)) + id.substring(1); - } - return "org.python.core." + id + "InternalTables"; - } - - static InternalTables createInternalTables() { - if(PySystemState.registry == null) { - throw new IllegalStateException("Jython interpreter state not initialized. " - + "You need to call PySystemState.initialize or PythonInterpreter.initialize."); - } - String cands = PySystemState.registry.getProperty("python.options.internalTablesImpl"); - if(cands == null) { - return new InternalTables(); - } - StringTokenizer candEnum = new StringTokenizer(cands, ":"); - while(candEnum.hasMoreTokens()) { - InternalTables tbl = tryImpl(candEnum.nextToken().trim()); - if(tbl != null) { - return tbl; - } - } - return new InternalTables(); - } - - final protected static short JCLASS = 0; - - final protected static short LAZY_JCLASS = 1; - - final protected static short ADAPTER_CLASS = 2; - - final protected static short ADAPTER = 3; - - protected Map classes = new HashMap(); - - protected Map temp = new HashMap();; - - protected Map counters = new HashMap();; - - protected Map lazyClasses = new HashMap();; - - protected Map adapterClasses = new HashMap();; - - protected final short GSTABLE = 1; - - protected final short JCSTABLE = 2; - - protected short keepstable; - - protected void commitTemp() { - this.classes.putAll(this.temp); - this.temp.clear(); - } - - protected WeakHashMap adapters = new WeakHashMap();; - - protected Object getAdapter(Object o, String evc) { - HashMap ads = (HashMap)this.adapters.get(o); - if(ads == null) { - return null; - } - WeakReference adw = (WeakReference)ads.get(evc); - if(adw == null) { - return null; - } - return adw.get(); - } - - protected void putAdapter(Object o, String evc, Object ad) { - HashMap ads = (HashMap)this.adapters.get(o); - if(ads == null) { - ads = new HashMap(); - this.adapters.put(o, ads); - } - ads.put(evc, new WeakReference(ad)); - } - - protected Iterator iter; - - protected Iterator grand; - - protected short iterType; - - protected Object cur; - - protected void beginStable(short lvl) { - this.keepstable = lvl; - } - - protected void endStable() { - if(this.keepstable == this.JCSTABLE) - commitTemp(); - this.keepstable = 0; - } - - protected void classesPut(Class c, Object jc) { - if(this.keepstable == this.JCSTABLE) { - this.temp.put(c, jc); - // System.err.println("temp-defer-canonical: "+c.getName()); - } else { - this.classes.put(c, jc); - } - String name = c.getName(); - Integer cnt = (Integer)this.counters.get(name); - if(cnt == null) { - this.counters.put(name, new Integer(1)); - this.lazyClasses.remove(name); - } else { - this.counters.put(name, new Integer(cnt.intValue() + 1)); - } - } - - protected Object classesGet(Class c) { - Object o = this.classes.get(c); - if(o != null || this.keepstable != this.JCSTABLE) - return o; - return this.temp.get(c); - } - - public void _beginCanonical() { - beginStable(this.JCSTABLE); - this.iter = this.classes.values().iterator(); - this.iterType = JCLASS; - } - - public void _beginLazyCanonical() { - beginStable(this.GSTABLE); - this.iter = this.lazyClasses.values().iterator(); - this.iterType = LAZY_JCLASS; - } - - public void _beginOverAdapterClasses() { - beginStable(this.GSTABLE); - this.iter = this.adapterClasses.entrySet().iterator(); - this.iterType = ADAPTER_CLASS; - } - - public void _beginOverAdapters() { - beginStable((short)0); - this.grand = this.adapters.values().iterator(); - this.iter = null; - this.iterType = ADAPTER; - } - - public Object _next() { - if(this.iterType == ADAPTER) { - for(;;) { - if(this.iter == null || !this.iter.hasNext()) { - if(this.grand.hasNext()) { - this.cur = this.grand.next(); - this.iter = ((HashMap)this.cur).values().iterator(); - } else { - this.iter = null; - } - } - if(this.iter != null) { - WeakReference adw = (WeakReference)this.iter.next(); - Object ad = adw.get(); - if(ad != null) { - return ad.getClass().getInterfaces()[0]; - } else { - continue; - } - } - this.grand = null; - break; - } - } else if(this.iter.hasNext()) { - this.cur = this.iter.next(); - switch(this.iterType){ - case JCLASS: - return this.cur; - case LAZY_JCLASS: - PyJavaClass lazy = (PyJavaClass)this.cur; - return new _LazyRep(lazy.__name__, lazy.__mgr__); - case ADAPTER_CLASS: - Map.Entry entry = (Map.Entry)this.cur; - return entry.getKey(); - } - } - this.cur = null; - endStable(); - this.iter = null; - return null; - } - - public void _flushCurrent() { - this.iter.remove(); - switch(this.iterType){ - case JCLASS: - classesDec(((PyJavaClass)this.cur).__name__); - break; - case ADAPTER: - if(((HashMap)this.cur).size() == 0) - this.grand.remove(); - } - } - - public void _flush(PyJavaClass jc) { - Class c = jc.proxyClass; - if(c == null) { - this.lazyClasses.remove(jc.__name__); - } else { - this.classes.remove(c); - classesDec(jc.__name__); - } - } - - protected Class getAdapterClass(Class c) { - return (Class)this.adapterClasses.get(c); - } - - protected PyJavaClass getCanonical(Class c) { - return (PyJavaClass)classesGet(c); - } - - protected PyJavaClass getLazyCanonical(String name) { - return (PyJavaClass)this.lazyClasses.get(name); - } - - protected void putAdapterClass(Class c, Class ac) { - this.adapterClasses.put(c, ac); - } - - protected void putCanonical(Class c, PyJavaClass canonical) { - classesPut(c, canonical); - } - - protected void putLazyCanonical(String name, PyJavaClass canonical) { - this.lazyClasses.put(name, canonical); - } - - protected boolean queryCanonical(String name) { - return this.counters.get(name) != null || this.lazyClasses.get(name) != null; - } - - protected void classesDec(String name) { - int c = ((Integer)this.counters.get(name)).intValue(); - if(c == 1) - this.counters.remove(name); - else - this.counters.put(name, new Integer(c - 1)); - } - - static public class _LazyRep { - - public String name; - - public PackageManager mgr; - - _LazyRep(String name, PackageManager mgr) { - this.name = name; - this.mgr = mgr; - } - } -} Modified: branches/newstyle-java-types/src/org/python/core/Py.java =================================================================== --- branches/newstyle-java-types/src/org/python/core/Py.java 2008-11-23 01:57:09 UTC (rev 5606) +++ branches/newstyle-java-types/src/org/python/core/Py.java 2008-11-23 02:36:05 UTC (rev 5607) @@ -435,8 +435,8 @@ } else if (t instanceof OutOfMemoryError) { memory_error((OutOfMemoryError) t); } - PyJavaInstance exc = new PyJavaInstance(t); - PyException pyex = new PyException(exc.instclass, exc); + PyObject exc = PyJavaType.wrapJavaObject(t); + PyException pyex = new PyException(exc.getType(), exc); // Set the cause to the original throwable to preserve // the exception chain. pyex.initCause(t); @@ -722,7 +722,7 @@ // Pre-initialize the PyJavaClass for OutOfMemoryError so when we need // it it creating the pieces for it won't cause an additional out of // memory error. Fix for bug #1654484 - PyJavaClass.lookup(OutOfMemoryError.class); + PyType.fromClass(OutOfMemoryError.class); } public static PySystemState defaultSystemState; // This is a hack to get initializations to work in proper order @@ -981,7 +981,7 @@ } } - if (value instanceof PyJavaInstance) { + if (value.getType() instanceof PyJavaType) { Object javaError = value.__tojava__(Throwable.class); if (javaError != null && javaError != Py.NoConversion) { @@ -1134,14 +1134,14 @@ // java.io.IOExceptions. This is a hack for 1.0.x until I can do // it right in 1.1 if (exc == Py.IOError) { - if (__builtin__.isinstance(pye.value, PyJavaClass.lookup(IOException.class))) { + if (__builtin__.isinstance(pye.value, PyType.fromClass(IOException.class))) { return true; } } // FIXME too, same approach for OutOfMemoryError if (exc == Py.MemoryError) { if (__builtin__.isinstance(pye.value, - PyJavaClass.lookup(OutOfMemoryError.class))) { + PyType.fromClass(OutOfMemoryError.class))) { return true; } } @@ -1518,7 +1518,7 @@ if (doc != null && dict.__finditem__("__doc__") == null) { dict.__setitem__("__doc__", doc); } - return makeClass(name, bases, dict, null); + return makeClass(name, bases, dict); } public static PyObject makeClass(String name, PyObject base, PyObject dict) { @@ -1526,10 +1526,6 @@ return makeClass(name, bases, dict); } - public static PyObject makeClass(String name, PyObject[] bases, PyObject dict) { - return makeClass(name, bases, dict, null); - } - /** * Create a new Python class. * @@ -1537,11 +1533,9 @@ * @param bases an array of PyObject base classes * @param dict the class's namespace, containing the class body * definition - * @param proxyClass an optional underlying Java class * @return a new Python Class PyObject */ - public static PyObject makeClass(String name, PyObject[] bases, PyObject dict, - Class proxyClass) { + public static PyObject makeClass(String name, PyObject[] bases, PyObject dict) { PyFrame frame = getFrame(); if (dict.__finditem__("__module__") == null) { @@ -1568,9 +1562,7 @@ } } - if (metaclass == null || metaclass == CLASS_TYPE || - (metaclass instanceof PyJavaClass && - ((PyJavaClass)metaclass).proxyClass == Class.class)) { + if (metaclass == null || metaclass == CLASS_TYPE) { boolean moreGeneral = false; for (PyObject base : bases) { if (!(base instanceof PyClass)) { @@ -1580,14 +1572,10 @@ } } if (!moreGeneral) { - return new PyClass(name, new PyTuple(bases), dict, proxyClass); + return new PyClass(name, new PyTuple(bases), dict); } } - if (proxyClass != null) { - throw Py.TypeError("the meta-class cannot handle java subclassing"); - } - try { return metaclass.__call__(new PyString(name), new PyTuple(bases), dict); } catch (PyException pye) { @@ -1946,7 +1934,7 @@ name = "fixed file"; this.file = file; - if (file instanceof PyJavaInstance) { + if (file.getType() instanceof PyJavaType) { Object tojava = file.__tojava__(OutputStream.class); if (tojava != null && tojava != Py.NoConversion) { this.file = new PyFile((OutputStream) tojava); Modified: branches/newstyle-java-types/src/org/python/core/PyBeanEventProperty.java =================================================================== --- branches/newstyle-java-types/src/org/python/core/PyBeanEventProperty.java 2008-11-23 01:57:09 UTC (rev 5606) +++ branches/newstyle-java-types/src/org/python/core/PyBeanEventProperty.java 2008-11-23 02:36:05 UTC (rev 5607) @@ -1,9 +1,14 @@ // Copyright (c) Corporation for National Research Initiatives package org.python.core; +import java.lang.ref.WeakReference; import java.lang.reflect.Field; import java.lang.reflect.Method; +import java.util.Map; +import java.util.WeakHashMap; +import org.python.util.Generic; + public class PyBeanEventProperty extends PyReflectedField { public Method addMethod; @@ -51,22 +56,40 @@ } private synchronized static Class<?> getAdapterClass(Class<?> c) { - InternalTables tbl = PyJavaClass.getInternalTables(); - Class<?> o = tbl.getAdapterClass(c); - if (o != null) - return o; Class<?> pc = Py.findClass("org.python.proxies." + c.getName() + "$Adapter"); if (pc == null) { pc = MakeProxies.makeAdapter(c); } - tbl.putAdapterClass(c, pc); return pc; } + protected Map<Object, Map<String, WeakReference<Object>>> adapters = + new WeakHashMap<Object, Map<String, WeakReference<Object>>>(); + + protected Object getAdapter(Object o, String evc) { + Map<String, WeakReference<Object>> ads = adapters.get(o); + if (ads == null) { + return null; + } + WeakReference<Object> adw = ads.get(evc); + if (adw == null) { + return null; + } + return adw.get(); + } + + protected void putAdapter(Object o, String evc, Object ad) { + Map<String, WeakReference<Object>> ads = adapters.get(o); + if(ads == null) { + ads = Generic.map(); + adapters.put(o, ads); + } + ads.put(evc, new WeakReference<Object>(ad)); + } + private synchronized Object getAdapter(Object self) { - InternalTables tbl = PyJavaClass.getInternalTables(); String eventClassName = eventClass.getName(); - Object adapter = tbl.getAdapter(self, eventClassName); + Object adapter = getAdapter(self, eventClassName); if (adapter != null) return adapter; try { @@ -75,7 +98,7 @@ } catch (Exception e) { throw Py.JavaError(e); } - tbl.putAdapter(self, eventClassName, adapter); + putAdapter(self, eventClassName, adapter); return adapter; } Modified: branches/newstyle-java-types/src/org/python/core/PyClass.java =================================================================== --- branches/newstyle-java-types/src/org/python/core/PyClass.java 2008-11-23 01:57:09 UTC (rev 5606) +++ branches/newstyle-java-types/src/org/python/core/PyClass.java 2008-11-23 02:36:05 UTC (rev 5607) @@ -1,15 +1,9 @@ // Copyright (c) Corporation for National Research Initiatives package org.python.core; -import java.io.Serializable; -import java.lang.reflect.Method; -import java.util.ArrayList; -import java.util.List; - /** * A python class. */ - public class PyClass extends PyObject { /** * Holds the namespace for this class @@ -31,13 +25,6 @@ PyObject __getattr__, __setattr__, __delattr__, __tojava__, __del__, __contains__; - // Holds the classes for which this is a proxy - // Only used when subclassing from a Java class - protected Class<?> proxyClass; - - // xxx map 'super__*' names -> array of methods - protected java.util.HashMap super__methods; - protected PyClass() { super(); } @@ -53,120 +40,12 @@ * @see org.python.core.Py#makeClass(String, PyObject[], PyCode, PyObject) */ public PyClass(String name, PyTuple bases, PyObject dict) { - this(name, bases, dict, null); - } - - /** - * Create a python class which inherits from a java class and where we - * already have generated a proxyclass. If we do not have a pre-generated - * proxyclass, the class initialization method will create such a proxyclass - * if bases contain a java class. - * - * @param name name of the class. - * @param bases A list of base classes. - * @param dict The class dict. Normally this dict is returned by the class - * code object. - * - * @see org.python.core.Py#makeClass(String, PyObject[], PyCode, PyObject, - * Class) - */ - public PyClass(String name, PyTuple bases, PyObject dict, Class proxyClass) { - this.proxyClass = proxyClass; - init(name, bases, dict); - } - - protected Class<?> getProxyClass() { - return proxyClass; - } - - void init(String name, PyTuple bases, PyObject dict) { __name__ = name; __bases__ = bases; __dict__ = dict; findModule(dict); - if (proxyClass == null) { - List<Class<?>> interfaces = new ArrayList<Class<?>>(); - Class<?> baseClass = null; - for (int i = 0; i < bases.size(); i++) { - Object base = bases.pyget(i); - if (base instanceof PyType) { - // xxx this works in CPython, which checks for a callable here - throw Py.TypeError("can't transmogrify old-style class into new-style " - + "class inheriting from " + ((PyType)base).getName()); - } else if (!(base instanceof PyClass)) { - throw Py.TypeError("base must be a class"); - } - Class<?> proxy = ((PyClass) base).getProxyClass(); - if (proxy != null) { - if (proxy.isInterface()) { - interfaces.add(proxy); - } else { - if (baseClass != null) { - throw Py.TypeError("no multiple inheritance for Java classes: " - + proxy.getName() + " and " + baseClass.getName()); - } - baseClass = proxy; - } - } - } - if (baseClass != null || interfaces.size() != 0) { - String proxyName = __name__; - PyObject module = dict.__finditem__("__module__"); - if (module != null) { - proxyName = module.toString() + "$" + __name__; - } - proxyClass = MakeProxies.makeProxy(baseClass, interfaces, - __name__, proxyName, __dict__); - } - } - - if (proxyClass != null) { - // xxx more efficient way without going through a PyJavaClass? - PyObject superDict = PyJavaClass.lookup(proxyClass).__findattr__( - "__dict__"); // xxx getDict perhaps? - // This code will add in the needed super__ methods to the class - PyObject snames = superDict.__finditem__("__supernames__"); - if (snames != null) { - for (PyObject item : snames.asIterable()) { - if (__dict__.__finditem__(item) == null) { - PyObject superFunc = superDict.__finditem__(item); - if (superFunc != null) { - __dict__.__setitem__(item, superFunc); - } - } - } - } - - // xxx populate super__methods, experiment. - - java.lang.reflect.Method proxy_methods[] = proxyClass.getMethods(); - - super__methods = new java.util.HashMap(); - - for (Method meth : proxy_methods) { - String meth_name = meth.getName(); - if (meth_name.startsWith("super__")) { - java.util.ArrayList samename = (java.util.ArrayList) super__methods - .get(meth_name); - if (samename == null) { - samename = new java.util.ArrayList(); - super__methods.put(meth_name, samename); - } - samename.add(meth); - } - } - - java.lang.reflect.Method[] empty_methods = new java.lang.reflect.Method[0]; - for (java.util.Iterator iter = super__methods.entrySet().iterator(); iter - .hasNext();) { - java.util.Map.Entry entry = (java.util.Map.Entry) iter.next(); - entry.setValue(((java.util.ArrayList) entry.getValue()) - .toArray(empty_methods)); - } - } - if (dict.__finditem__("__doc__") == null) { dict.__setitem__("__doc__", Py.None); } @@ -193,14 +72,6 @@ } } - public Object __tojava__(Class<?> c) { - if ((c == Object.class || c == Class.class || c == Serializable.class) - && proxyClass != null) { - return proxyClass; - } - return super.__tojava__(c); - } - // returns [PyObject, PyClass] PyObject[] lookupGivingClass(String name, boolean stop_at_java) { PyObject result = __dict__.__finditem__(name); @@ -348,11 +219,6 @@ if (this == superclass) { return true; } - if (getProxyClass() != null && superclass.getProxyClass() != null) { - if (superclass.proxyClass.isAssignableFrom(this.proxyClass)) { - return true; - } - } if (this.__bases__ == null || superclass.__bases__ == null) { return false; } Modified: branches/newstyle-java-types/src/org/python/core/PyFile.java =================================================================== --- branches/newstyle-java-types/src/org/python/core/PyFile.java 2008-11-23 01:57:09 UTC (rev 5606) +++ branches/newstyle-java-types/src/org/python/core/PyFile.java 2008-11-23 02:36:05 UTC (rev 5607) @@ -473,7 +473,7 @@ @ExposedMethod final PyObject file_fileno() { - return new PyJavaInstance(file.fileno()); + return PyJavaType.wrapJavaObject(file.fileno()); } @ExposedMethod(names = {"__str__", "__repr__"}) Modified: branches/newstyle-java-types/src/org/python/core/PyInstance.java =================================================================== --- branches/newstyle-java-types/src/org/python/core/PyInstance.java 2008-11-23 01:57:09 UTC (rev 5606) +++ branches/newstyle-java-types/src/org/python/core/PyInstance.java 2008-11-23 02:36:05 UTC (rev 5607) @@ -1,8 +1,6 @@ // Copyright (c) Corporation for National Research Initiatives package org.python.core; import java.util.Hashtable; -import java.util.StringTokenizer; -import java.io.Serializable; /** * A python class instance. @@ -38,8 +36,6 @@ PyClass pyc = (PyClass)mod.__getattr__(name.intern()); instclass = pyc; - if (javaProxy != null) - ((PyProxy) javaProxy)._setPySystemState(Py.getSystemState()); } private void writeObject(java.io.ObjectOutputStream out) @@ -82,47 +78,7 @@ private static Hashtable primitiveMap; - protected void makeProxy() { - Class c = instclass.proxyClass; - PyProxy proxy; - ThreadState ts = Py.getThreadState(); - try { - ts.pushInitializingProxy(this); - try { - proxy = (PyProxy)c.newInstance(); - } catch (java.lang.InstantiationException e) { - Class sup = c.getSuperclass(); - String msg = "Default constructor failed for Java superclass"; - if (sup != null) - msg += " " + sup.getName(); - throw Py.TypeError(msg); - } catch (NoSuchMethodError nsme) { - throw Py.TypeError("constructor requires arguments"); - } catch (Exception exc) { - throw Py.JavaError(exc); - } - } finally { - ts.popInitializingProxy(); - } - - if (javaProxy != null && javaProxy != proxy) { - // The javaProxy can be initialized in Py.jfindattr() - throw Py.TypeError("Proxy instance already initialized"); - } - PyObject proxyInstance = proxy._getPyInstance(); - if (proxyInstance != null && proxyInstance != this) { - // The proxy was initialized to another instance!! - throw Py.TypeError("Proxy initialization conflict"); - } - - javaProxy = proxy; - } - public Object __tojava__(Class c) { - if ((c == Object.class || c == Serializable.class) && - javaProxy != null) { - return javaProxy; - } if (c.isInstance(this)) return this; @@ -143,15 +99,9 @@ c = tmp; } - if (javaProxy == null && instclass.proxyClass != null) { - makeProxy(); - } - if (c.isInstance(javaProxy)) - return javaProxy; - if (instclass.__tojava__ != null) { // try { - PyObject ret = instclass.__tojava__.__call__(this, PyJavaClass.lookup(c)); + PyObject ret = instclass.__tojava__.__call__(this, PyType.fromClass(c)); if (ret == Py.None) return Py.NoConversion; @@ -185,10 +135,6 @@ else if (ret != Py.None) { throw Py.TypeError("__init__() should return None"); } - // Now init all superclasses that haven't already been initialized - if (javaProxy == null && instclass.proxyClass != null) { - makeProxy(); - } } public PyObject __jfindattr__(String name) { @@ -325,16 +271,7 @@ if (setter != null) { setter.__call__(this, new PyString(name), value); } else { - if (instclass.getProxyClass() != null) { - PyObject field = instclass.lookup(name, false); - if (field == null) { - noField(name, value); - } else if (!field.jtryset(this, value)) { - unassignableField(name, value); - } - } else { - __dict__.__setitem__(name, value); - } + __dict__.__setitem__(name, value); } } @@ -548,11 +485,6 @@ } catch (PyException exc) { } if (meth == null) { - // Copied form __len__() - CollectionProxy proxy = getCollection(); - if (proxy != CollectionProxy.NoProxy) { - return proxy.__len__() != 0 ? true : false; - } try { meth = __findattr__("__len__"); } catch (PyException exc) { } @@ -564,20 +496,7 @@ return ret.__nonzero__(); } - private CollectionProxy collectionProxy=null; - - private CollectionProxy getCollection() { - if (collectionProxy == null) - collectionProxy = CollectionProxy.findCollection(javaProxy); - return collectionProxy; - } - public int __len__() { - CollectionProxy proxy = getCollection(); - if (proxy != CollectionProxy.NoProxy) { - return proxy.__len__(); - } - PyObject ret = invoke("__len__"); if (ret instanceof PyInteger) return ((PyInteger)ret).getValue(); @@ -585,10 +504,6 @@ } public PyObject __finditem__(int key) { - CollectionProxy proxy = getCollection(); - if (proxy != CollectionProxy.NoProxy) { - return proxy.__finditem__(key); - } return __finditem__(new PyInteger(key)); } @@ -614,11 +529,6 @@ } public PyObject __finditem__(PyObject key) { - CollectionProxy proxy = getCollection(); - if (proxy != CollectionProxy.NoProxy) { - return proxy.__finditem__(key); - } - try { return invoke("__getitem__", key); } catch (PyException e) { @@ -631,32 +541,14 @@ } public PyObject __getitem__(PyObject key) { - CollectionProxy proxy = getCollection(); - if (proxy != CollectionProxy.NoProxy) { - PyObject ret = proxy.__finditem__(key); - if (ret == null) { - throw Py.KeyError(key.toString()); - } - return ret; - } return invoke("__getitem__", key); } public void __setitem__(PyObject key, PyObject value) { - CollectionProxy proxy = getCollection(); - if (proxy != CollectionProxy.NoProxy) { - proxy.__setitem__(key, value); - return; - } invoke("__setitem__", key, value); } public void __delitem__(PyObject key) { - CollectionProxy proxy = getCollection(); - if (proxy != CollectionProxy.NoProxy) { - proxy.__delitem__(key); - return; - } invoke("__delitem__", key); } @@ -688,10 +580,6 @@ } public PyObject __iter__() { - PyObject iter = getCollectionIter(); - if (iter != null) { - return iter; - } PyObject func = __findattr__("__iter__"); if (func != null) return func.__call__(); @@ -715,37 +603,6 @@ throw Py.TypeError("instance has no next() method"); } - private static CollectionIter[] iterFactories; - - private PyObject getCollectionIter() { - if (iterFactories == null) - initializeIterators(); - for (int i = 0; iterFactories[i] != null; i++) { - PyObject iter = iterFactories[i].findCollection(javaProxy); - if (iter != null) - return iter; - } - return null; - } - - private static synchronized void initializeIterators() { - if (iterFactories != null) - return; - String factories = PySystemState.registry.getProperty("python.collections", ""); - int i = 0; - StringTokenizer st = new StringTokenizer(factories, ","); - iterFactories = new CollectionIter[st.countTokens() + 2]; - iterFactories[0] = new CollectionIter(); - while (st.hasMoreTokens()) { - String s = st.nextToken(); - try { - Class factoryClass = Class.forName(s); - CollectionIter factory = (CollectionIter)factoryClass.newInstance(); - iterFactories[i++] = factory; - } catch (Throwable t) { } - } - } - public boolean __contains__(PyObject o) { PyObject func = __findattr__("__contains__"); if (func == null) Deleted: branches/newstyle-java-types/src/org/python/core/PyJavaClass.java =================================================================== --- branches/newstyle-java-types/src/org/python/core/PyJavaClass.java 2008-11-23 01:57:09 UTC (rev 5606) +++ branches/newstyle-java-types/src/org/python/core/PyJavaClass.java 2008-11-23 02:36:05 UTC (rev 5607) @@ -1,774 +0,0 @@ -// Copyright (c) Corporation for National Research Initiatives -package org.python.core; - -import java.beans.Introspector; -import java.lang.reflect.Constructor; -import java.lang.reflect.Field; -import java.lang.reflect.Method; -import java.lang.reflect.Modifier; -import java.util.EventListener; - -import org.python.core.packagecache.PackageManager; - -/** - * A wrapper around a java class. - */ -public class PyJavaClass extends PyClass { - - private static InternalTables tbl; - - public PyReflectedConstructor __init__; - - public PackageManager __mgr__; - - public String __module__; - - private boolean initialized = false; - - // Prevent recursive calls to initialize() - private boolean initializing = false; - - public synchronized final static InternalTables getInternalTables() { - if (tbl == null) { - tbl = InternalTables.createInternalTables(); - } - return tbl; - } - - public final boolean isLazy() { - return proxyClass == null; - } - - public static final PyJavaClass lookup(String name, PackageManager mgr) { - if (tbl.queryCanonical(name)) { - Class<?> c = mgr.findClass(null, name, "forced java class"); - check_lazy_allowed(c); // xxx - return lookup(c); - } - PyJavaClass ret = new PyJavaClass(name, mgr); - tbl.putLazyCanonical(name, ret); - return ret; - } - - public synchronized static final PyJavaClass lookup(Class<?> c) { - if (tbl == null) { - tbl = new InternalTables(); - PyJavaClass jc = new PyJavaClass(); - jc.init(PyJavaClass.class); - tbl.putCanonical(PyJavaClass.class, jc); - } - PyJavaClass ret = tbl.getCanonical(c); - if (ret != null) - return ret; - PyJavaClass lazy = tbl.getLazyCanonical(c.getName()); - if (lazy != null) { - initLazy(lazy); - if (lazy.proxyClass == c) { - return lazy; - } - } - Class<?> parent = c.getDeclaringClass(); - ret = parent == null ? new PyJavaClass(c) : new PyJavaInnerClass(c, lookup(parent)); - tbl.putCanonical(c, ret); - return ret; - } - - private PyJavaClass() {} - - protected PyJavaClass(Class<?> c) { - init(c); - } - - /** - * Set the full name of this class. - */ - private void setName(String name) { - int dotIndex = name.lastIndexOf("."); - if (dotIndex == -1) { - __name__ = name; - __module__ = ""; - } else { - __name__ = name.substring(name.lastIndexOf(".") + 1, name.length()); - __module__ = name.substring(0, name.lastIndexOf(".")); - } - } - - private String fullName() { - if (__module__ == "") - return __name__; - else - return __module__ + "." + __name__; - } - - protected PyJavaClass(String name, PackageManager mgr) { - setName(name); - this.__mgr__ = mgr; - } - - protected void findModule(PyObject dict) {} - - protected Class<?> getProxyClass() { - initialize(); - return proxyClass; - } - - // for the moment trying to lazily load a PyObject subclass - // is not allowed, (because of the PyJavaClass vs PyType class mismatch) - // pending PyJavaClass becoming likely a subclass of PyType - private static final void check_lazy_allowed(Class<?> c) { - if (PyObject.class.isAssignableFrom(c)) { // xxx - throw Py.TypeError("cannot lazy load PyObject subclass"); - } - } - - private static final void initLazy(PyJavaClass jc) { - Class<?> c = jc.__mgr__.findClass(null, jc.fullName(), "lazy java class"); - check_lazy_allowed(c); // xxx - jc.init(c); - tbl.putCanonical(jc.proxyClass, jc); - jc.__mgr__ = null; - } - - private synchronized void initialize() { - if (initialized || initializing) { - return; - } - initializing = true; - synchronized (PyJavaClass.class) { - if (proxyClass == null) { - initLazy(this); - } - } - init__bases__(proxyClass); - ... [truncated message content] |
From: <cg...@us...> - 2008-11-28 10:07:02
|
Revision: 5654 http://jython.svn.sourceforge.net/jython/?rev=5654&view=rev Author: cgroves Date: 2008-11-28 10:06:54 +0000 (Fri, 28 Nov 2008) Log Message: ----------- Expose static fields through PyBeanProperty if they share a name with the property. Instance fields supercede the propery. Modified Paths: -------------- branches/newstyle-java-types/Lib/test/test_java_integration.py branches/newstyle-java-types/src/org/python/core/PyJavaType.java branches/newstyle-java-types/src/org/python/core/PyObject.java Modified: branches/newstyle-java-types/Lib/test/test_java_integration.py =================================================================== --- branches/newstyle-java-types/Lib/test/test_java_integration.py 2008-11-28 09:13:19 UTC (rev 5653) +++ branches/newstyle-java-types/Lib/test/test_java_integration.py 2008-11-28 10:06:54 UTC (rev 5654) @@ -55,9 +55,6 @@ A() class InstantiationTest(unittest.TestCase): - def test_cant_create_abstract(self): - self.assertRaises(TypeError, Component) - def test_can_subclass_abstract(self): class A(Component): pass @@ -339,8 +336,11 @@ class ColorTest(unittest.TestCase): def test_static_fields(self): - Color.red - Color.blue + self.assertEquals(Color(255, 0, 0), Color.RED) + # The bean accessor for getRed should be active on instances, but the static field red + # should be visible on the class + self.assertEquals(255, Color.red.red) + self.assertEquals(Color(0, 0, 255), Color.blue) def test_is_operator(self): red = Color.red @@ -363,7 +363,7 @@ y = BigDecimalTest().asBigDecimal() self.assertEqual(type(x), type(y), "BigDecimal coerced") - self.assertEqual(x, y, "BigDecimal coerced") + self.assertEqual(x, y, "coerced BigDecimal not equal to directly created version") class MethodInvTest(unittest.TestCase): Modified: branches/newstyle-java-types/src/org/python/core/PyJavaType.java =================================================================== --- branches/newstyle-java-types/src/org/python/core/PyJavaType.java 2008-11-28 09:13:19 UTC (rev 5653) +++ branches/newstyle-java-types/src/org/python/core/PyJavaType.java 2008-11-28 10:06:54 UTC (rev 5654) @@ -100,12 +100,13 @@ } } for (String propname : propnames.keySet()) { - if(propname.equals("")) { + if (propname.equals("")) { continue; } String npropname = normalize_name(StringUtil.decapitalize(propname)); PyObject prev = dict.__finditem__(npropname); - if (prev != null && prev instanceof PyReflectedFunction) { + if (prev != null && (!(prev instanceof PyReflectedField) || + !Modifier.isStatic(((PyReflectedField)prev).field.getModifiers()))) { continue; } Method getter = null; @@ -125,7 +126,11 @@ } } if (setter != null || getter != null) { - dict.__setitem__(npropname, new PyBeanProperty(npropname, proptype, getter, setter)); + PyBeanProperty prop = new PyBeanProperty(npropname, proptype, getter, setter); + if (prev != null) { + prop.field = ((PyReflectedField)prev).field; + } + dict.__setitem__(npropname, prop); } else { // XXX error } Modified: branches/newstyle-java-types/src/org/python/core/PyObject.java =================================================================== --- branches/newstyle-java-types/src/org/python/core/PyObject.java 2008-11-28 09:13:19 UTC (rev 5653) +++ branches/newstyle-java-types/src/org/python/core/PyObject.java 2008-11-28 10:06:54 UTC (rev 5654) @@ -267,7 +267,7 @@ return Py.NoConversion; } - protected static final Map<Class<?>, Class<?>> primitiveMap = Generic.map(); + private static final Map<Class<?>, Class<?>> primitiveMap = Generic.map(); static { primitiveMap.put(Character.TYPE, Character.class); primitiveMap.put(Boolean.TYPE, Boolean.class); This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <cg...@us...> - 2008-12-01 00:38:20
|
Revision: 5665 http://jython.svn.sourceforge.net/jython/?rev=5665&view=rev Author: cgroves Date: 2008-12-01 00:38:14 +0000 (Mon, 01 Dec 2008) Log Message: ----------- Merged revisions 5565,5568-5584,5593,5596,5598-5604,5606,5608-5611,5616,5618-5621,5624,5626-5627,5629-5630,5639-5640,5644-5648,5655,5661 via svnmerge from https://jython.svn.sourceforge.net/svnroot/jython/trunk/jython ........ r5565 | fwierzbicki | 2008-11-09 19:36:31 -0800 (Sun, 09 Nov 2008) | 4 lines Just enough AST tweaking to get some of sympy working for Ondrej. On my todo list is to look at Python 2.6's ast testing and see if I can port that over to Jython. ........ r5568 | fwierzbicki | 2008-11-10 07:33:23 -0800 (Mon, 10 Nov 2008) | 2 lines remove dead code. ........ r5569 | fwierzbicki | 2008-11-10 13:12:29 -0800 (Mon, 10 Nov 2008) | 2 lines Make lineno and col_offset writable. ........ r5570 | fwierzbicki | 2008-11-11 09:48:27 -0800 (Tue, 11 Nov 2008) | 4 lines Tor Norbye found this ancient typo just by pointing NetBeans and the latest nbpython at datetime.py. Maybe there is something to be said for these "IDE"s that I keep hearing about :). ........ r5571 | otmarhumbel | 2008-11-11 15:25:25 -0800 (Tue, 11 Nov 2008) | 1 line detect JYTHON_HOME if called from the /bin directory ........ r5572 | pjenvey | 2008-11-11 17:31:02 -0800 (Tue, 11 Nov 2008) | 2 lines more java integration unicode vs str fixes ........ r5573 | fwierzbicki | 2008-11-12 11:10:54 -0800 (Wed, 12 Nov 2008) | 2 lines Upgrade to antlr-3.1.1. ........ r5574 | fwierzbicki | 2008-11-12 11:32:40 -0800 (Wed, 12 Nov 2008) | 2 lines Hopefully helping for eclipse users :). ........ r5575 | fwierzbicki | 2008-11-12 11:33:58 -0800 (Wed, 12 Nov 2008) | 3 lines Oops, try #2. That's what I get for doing this w/o having eclipse installed for verification. ........ r5576 | pjenvey | 2008-11-13 16:02:12 -0800 (Thu, 13 Nov 2008) | 2 lines fix itertools.chain stopping short with two empty iters in a row ........ r5577 | fwierzbicki | 2008-11-13 16:28:42 -0800 (Thu, 13 Nov 2008) | 2 lines Thanks to Tor Norbye for this bug fix. This was also found via NetBeans. ........ r5578 | pjenvey | 2008-11-13 23:35:53 -0800 (Thu, 13 Nov 2008) | 2 lines bring in constantine (0.3dev r80) for better errnos ........ r5579 | fwierzbicki | 2008-11-14 08:07:43 -0800 (Fri, 14 Nov 2008) | 3 lines Fix for NPE's and a weird Antlr error that can occur when Antlr is allowed to recover from parser errrors (for example, when ListErrorHandler is used). ........ r5580 | fwierzbicki | 2008-11-14 09:53:21 -0800 (Fri, 14 Nov 2008) | 2 lines Remove very old commented out code from imp.java. ........ r5581 | fwierzbicki | 2008-11-14 14:54:53 -0800 (Fri, 14 Nov 2008) | 15 lines Fix for http://bugs.jython.org/issue1141. __builtin__.__import__ had subtle differences with CPython. These differences would cause problems for those who wish to override __builtin__.__import__ statement: import hell.first_circle - CPython: ('hell.first_circle', None) - old Jython: ('hell.first_circle', ()) statement: import hell.first_circle as limbo - CPython: ('hell.first_circle', None) - old Jython: ('hell.first_circle', ('*',)) Also note that the second import statement with an "as" would return the head module instead of the tail module, the opposite of what CPython does. ........ r5582 | pjenvey | 2008-11-16 14:52:56 -0800 (Sun, 16 Nov 2008) | 3 lines fix another binop corner case -- trigger the binop 'flip' when left_type < right_type (in terms of the reversed mro) instead of left_type != right_type ........ r5583 | pjenvey | 2008-11-17 12:05:55 -0800 (Mon, 17 Nov 2008) | 4 lines o allow Socket{TCP,UDP}Test HOST/PORT to be overriden per class o use a different port than test_socket for test_select as test_socket sockopt tests don't REUSEADDR ........ r5584 | pjenvey | 2008-11-17 12:06:51 -0800 (Mon, 17 Nov 2008) | 4 lines relax the test ensuring SO_{RCV,SND}BUF matches the *exact* value we set it to after a connection was established. only for the BSDs, but we may not want to assume this anywhere ........ r5593 | pjenvey | 2008-11-20 10:52:08 -0800 (Thu, 20 Nov 2008) | 4 lines hardcode PyString encode results instead of letting java2py return unicode fixes #1177 thanks jcflack ........ r5596 | pjenvey | 2008-11-20 18:00:11 -0800 (Thu, 20 Nov 2008) | 4 lines fix handling of null prefix/exec_prefix values now that they're PyObjects fixes #1173 thanks boisgera ........ r5598 | fwierzbicki | 2008-11-22 11:18:53 -0800 (Sat, 22 Nov 2008) | 5 lines Fixes bug http://bugs.jython.org/issue1174 which reveals a corner case where CompilerFlags can come out as null. Not positive that we should be passing the "flags" value down when there is no frame, but this is probably right. Put an XXX in so it can be looked at again later. ........ r5599 | fwierzbicki | 2008-11-22 12:39:54 -0800 (Sat, 22 Nov 2008) | 3 lines Removed XXX -- looking at the code some more makes me comfortable with passing "flags" on. ........ r5600 | pjenvey | 2008-11-22 14:37:49 -0800 (Sat, 22 Nov 2008) | 3 lines from: http://svn.python.org/projects/python/branches/release25-maint/Lib/warnings.py@47273 ........ r5601 | pjenvey | 2008-11-22 15:23:48 -0800 (Sat, 22 Nov 2008) | 4 lines use the compiled filename for __file__ when appropriate. make imp responsible for setting __file__ instead of the compiler being involved fixes #1138 ........ r5602 | pjenvey | 2008-11-22 15:27:27 -0800 (Sat, 22 Nov 2008) | 3 lines from: http://svn.python.org/projects/python/branches/release25-maint/Lib/pydoc.py@54366 ........ r5603 | pjenvey | 2008-11-22 15:30:45 -0800 (Sat, 22 Nov 2008) | 3 lines o fix help -- our new isatty support confused it into using a real pager o support $py.class in ispackage ........ r5604 | cgroves | 2008-11-22 16:18:15 -0800 (Sat, 22 Nov 2008) | 1 line Assume any instance of PySequence has an accurate __len__. See http://www.nabble.com/PySequenceList-and-fastSequence-td14977175.html ........ r5606 | pjenvey | 2008-11-22 17:57:09 -0800 (Sat, 22 Nov 2008) | 5 lines o allow open({In,Out}putStream) but with a deprecation warning. make open a function o add optional bufsize args to FileUtil.wrap fixes #1171 ........ r5608 | pjenvey | 2008-11-22 20:15:40 -0800 (Sat, 22 Nov 2008) | 4 lines relax struct_time entry types to PyObject, CPython allows non ints here. mostly to get rid of __int__ calls w/ a PyInteger cast refs #1052 ........ r5609 | pjenvey | 2008-11-22 20:18:48 -0800 (Sat, 22 Nov 2008) | 6 lines ((PyInteger)obj.__int__()).getValue() -> obj.asInt() to avoid potential ClassCastException mayhem now that __int__ can return longs. as a side effect TypeErrors are raised on conversion failure rather than AttributeErrors (which is usually more appropriate anyway) fixes #1052 ........ r5610 | pjenvey | 2008-11-22 20:35:59 -0800 (Sat, 22 Nov 2008) | 4 lines zlib docs fixes #1798554, #1798556 thanks ukeshav ........ r5611 | pjenvey | 2008-11-22 22:28:45 -0800 (Sat, 22 Nov 2008) | 4 lines fix the Carlo Verre hack because open builtin classes are only cool in Ruby and JavaScript, or something like that fixes #1058 and test_descr.carloverre ........ r5616 | fwierzbicki | 2008-11-23 07:02:10 -0800 (Sun, 23 Nov 2008) | 3 lines Removed merge tracking for "svnmerge" for https://jython.svn.sourceforge.net/svnroot/jython/branches/nowalker ........ r5618 | pjenvey | 2008-11-23 11:35:19 -0800 (Sun, 23 Nov 2008) | 1 line exclude the antlr tests as they don't have any actual tests ........ r5619 | pjenvey | 2008-11-23 12:58:25 -0800 (Sun, 23 Nov 2008) | 4 lines fix bit rot in the Expose javatests: ensure we setType new descriptors, init sys when needed, fix null method docs (use "" instead) ........ r5620 | pjenvey | 2008-11-23 13:56:25 -0800 (Sun, 23 Nov 2008) | 2 lines turn on javatest/regrtest junit xml output by default, to dist/testreports ........ r5621 | pjenvey | 2008-11-23 14:22:05 -0800 (Sun, 23 Nov 2008) | 3 lines don't buffer the various popen2 helper streams in hopes to make test_cmd_line less flakey ........ r5624 | fwierzbicki | 2008-11-23 16:00:42 -0800 (Sun, 23 Nov 2008) | 3 lines Test for basic eval from a bare PythonInterpreter (was throwing an NPE) see http://bugs.jython.org/issue1174. ........ r5626 | pjenvey | 2008-11-23 18:02:47 -0800 (Sun, 23 Nov 2008) | 5 lines add an isBaseType flag to @ExposedType for toggling whether types are subclassable. disallow subclassing of builtin_function_or_method (fixes test_descr.errors). note that this requires an ant clean refs #1758319 ........ r5627 | pjenvey | 2008-11-23 18:48:33 -0800 (Sun, 23 Nov 2008) | 3 lines disallow sublcassing a number of types fixes #1758319 ........ r5629 | pjenvey | 2008-11-23 21:01:02 -0800 (Sun, 23 Nov 2008) | 4 lines from: http://svn.python.org/projects/python/branches/release25-maint/Lib/zipfile.py@60117 http://svn.python.org/projects/python/branches/release25-maint/Lib/test/test_zipfile.py@46982 ........ r5630 | pjenvey | 2008-11-23 21:02:01 -0800 (Sun, 23 Nov 2008) | 2 lines fix PyZipFile to compile to $py.class ........ r5639 | otmarhumbel | 2008-11-25 06:11:53 -0800 (Tue, 25 Nov 2008) | 2 lines to enable virtualenv again: do not hardcode JYTHON_HOME this fixes issue #1180 ........ r5640 | otmarhumbel | 2008-11-25 13:09:57 -0800 (Tue, 25 Nov 2008) | 1 line check for both jython-complete.jar and jython.jar in findRoot() ........ r5644 | pjenvey | 2008-11-26 19:30:23 -0800 (Wed, 26 Nov 2008) | 1 line update/clarify comment ........ r5645 | fwierzbicki | 2008-11-26 20:01:27 -0800 (Wed, 26 Nov 2008) | 5 lines Make PythonTree (and thus most of the ast nodes) extend PyObject instead of Antlr's CommonTree. This required pulling in much of the CommonTree code for now. Hopefully I can prune some of it out in time. Also PythonTreeAdaptor had to override more of CommonTreeAdaptor's methods. ........ r5646 | pjenvey | 2008-11-26 20:52:37 -0800 (Wed, 26 Nov 2008) | 6 lines temporarily store genexps in Java's frame instead of PyFrame. the latter could modify f_locals when cleaning up the temp slot, which causes an obscure bug if the genexp is iterating over that same f_locals (dict changed size during iteration). e.g., in a module's top level: __all__ = tuple(x for x in locals() if x.isupper()) ........ r5647 | pjenvey | 2008-11-27 12:56:10 -0800 (Thu, 27 Nov 2008) | 5 lines o explicitly convert Strings returned from ExposedGet to str (instead of unicode), just as ExposedMethod does. restores the behavior it had before the big Java integration String/unicode change o add a TypeError message for PyDataDescr.__set__ failed conversions ........ r5648 | pjenvey | 2008-11-27 12:56:40 -0800 (Thu, 27 Nov 2008) | 1 line small cleanup, match CPython's __repr__ ........ r5655 | pjenvey | 2008-11-28 13:10:39 -0800 (Fri, 28 Nov 2008) | 2 lines have exposed methods and fields convert null Strings results to Py.None ........ r5661 | pjenvey | 2008-11-28 23:43:57 -0800 (Fri, 28 Nov 2008) | 2 lines constantine-0.4 release ........ Modified Paths: -------------- branches/newstyle-java-types/.classpath branches/newstyle-java-types/Lib/datetime.py branches/newstyle-java-types/Lib/inspect.py branches/newstyle-java-types/Lib/ntpath.py branches/newstyle-java-types/Lib/os.py branches/newstyle-java-types/Lib/popen2.py branches/newstyle-java-types/Lib/posixpath.py branches/newstyle-java-types/Lib/subprocess.py branches/newstyle-java-types/Lib/test/test_bool.py branches/newstyle-java-types/Lib/test/test_chdir.py branches/newstyle-java-types/Lib/test/test_descr.py branches/newstyle-java-types/Lib/test/test_descr_jy.py branches/newstyle-java-types/Lib/test/test_fileno.py branches/newstyle-java-types/Lib/test/test_genexps.py branches/newstyle-java-types/Lib/test/test_import_jy.py branches/newstyle-java-types/Lib/test/test_inspect.py branches/newstyle-java-types/Lib/test/test_iter_jy.py branches/newstyle-java-types/Lib/test/test_select.py branches/newstyle-java-types/Lib/test/test_socket.py branches/newstyle-java-types/Lib/zlib.py branches/newstyle-java-types/ast/asdl_antlr.py branches/newstyle-java-types/build.xml branches/newstyle-java-types/grammar/Python.g branches/newstyle-java-types/src/com/ziclix/python/sql/Fetch.java branches/newstyle-java-types/src/com/ziclix/python/sql/Procedure.java branches/newstyle-java-types/src/com/ziclix/python/sql/PyCursor.java branches/newstyle-java-types/src/com/ziclix/python/sql/PyStatement.java branches/newstyle-java-types/src/org/python/antlr/AST.java branches/newstyle-java-types/src/org/python/antlr/GrammarActions.java branches/newstyle-java-types/src/org/python/antlr/ParseException.java branches/newstyle-java-types/src/org/python/antlr/PythonErrorNode.java branches/newstyle-java-types/src/org/python/antlr/PythonTree.java branches/newstyle-java-types/src/org/python/antlr/PythonTreeAdaptor.java branches/newstyle-java-types/src/org/python/antlr/ast/Assert.java branches/newstyle-java-types/src/org/python/antlr/ast/Assign.java branches/newstyle-java-types/src/org/python/antlr/ast/Attribute.java branches/newstyle-java-types/src/org/python/antlr/ast/AugAssign.java branches/newstyle-java-types/src/org/python/antlr/ast/BinOp.java branches/newstyle-java-types/src/org/python/antlr/ast/BoolOp.java branches/newstyle-java-types/src/org/python/antlr/ast/Break.java branches/newstyle-java-types/src/org/python/antlr/ast/Call.java branches/newstyle-java-types/src/org/python/antlr/ast/ClassDef.java branches/newstyle-java-types/src/org/python/antlr/ast/Compare.java branches/newstyle-java-types/src/org/python/antlr/ast/Continue.java branches/newstyle-java-types/src/org/python/antlr/ast/Delete.java branches/newstyle-java-types/src/org/python/antlr/ast/Dict.java branches/newstyle-java-types/src/org/python/antlr/ast/Ellipsis.java branches/newstyle-java-types/src/org/python/antlr/ast/ErrorExpr.java branches/newstyle-java-types/src/org/python/antlr/ast/ErrorMod.java branches/newstyle-java-types/src/org/python/antlr/ast/ErrorSlice.java branches/newstyle-java-types/src/org/python/antlr/ast/ErrorStmt.java branches/newstyle-java-types/src/org/python/antlr/ast/Exec.java branches/newstyle-java-types/src/org/python/antlr/ast/Expr.java branches/newstyle-java-types/src/org/python/antlr/ast/Expression.java branches/newstyle-java-types/src/org/python/antlr/ast/ExtSlice.java branches/newstyle-java-types/src/org/python/antlr/ast/For.java branches/newstyle-java-types/src/org/python/antlr/ast/FunctionDef.java branches/newstyle-java-types/src/org/python/antlr/ast/GeneratorExp.java branches/newstyle-java-types/src/org/python/antlr/ast/Global.java branches/newstyle-java-types/src/org/python/antlr/ast/If.java branches/newstyle-java-types/src/org/python/antlr/ast/IfExp.java branches/newstyle-java-types/src/org/python/antlr/ast/Import.java branches/newstyle-java-types/src/org/python/antlr/ast/ImportFrom.java branches/newstyle-java-types/src/org/python/antlr/ast/Index.java branches/newstyle-java-types/src/org/python/antlr/ast/Interactive.java branches/newstyle-java-types/src/org/python/antlr/ast/Lambda.java branches/newstyle-java-types/src/org/python/antlr/ast/List.java branches/newstyle-java-types/src/org/python/antlr/ast/ListComp.java branches/newstyle-java-types/src/org/python/antlr/ast/Module.java branches/newstyle-java-types/src/org/python/antlr/ast/Name.java branches/newstyle-java-types/src/org/python/antlr/ast/Num.java branches/newstyle-java-types/src/org/python/antlr/ast/Pass.java branches/newstyle-java-types/src/org/python/antlr/ast/Print.java branches/newstyle-java-types/src/org/python/antlr/ast/Raise.java branches/newstyle-java-types/src/org/python/antlr/ast/Repr.java branches/newstyle-java-types/src/org/python/antlr/ast/Return.java branches/newstyle-java-types/src/org/python/antlr/ast/Slice.java branches/newstyle-java-types/src/org/python/antlr/ast/Str.java branches/newstyle-java-types/src/org/python/antlr/ast/Subscript.java branches/newstyle-java-types/src/org/python/antlr/ast/Suite.java branches/newstyle-java-types/src/org/python/antlr/ast/TryExcept.java branches/newstyle-java-types/src/org/python/antlr/ast/TryFinally.java branches/newstyle-java-types/src/org/python/antlr/ast/Tuple.java branches/newstyle-java-types/src/org/python/antlr/ast/UnaryOp.java branches/newstyle-java-types/src/org/python/antlr/ast/While.java branches/newstyle-java-types/src/org/python/antlr/ast/With.java branches/newstyle-java-types/src/org/python/antlr/ast/Yield.java branches/newstyle-java-types/src/org/python/antlr/ast/aliasType.java branches/newstyle-java-types/src/org/python/antlr/ast/argumentsType.java branches/newstyle-java-types/src/org/python/antlr/ast/boolopType.java branches/newstyle-java-types/src/org/python/antlr/ast/cmpopType.java branches/newstyle-java-types/src/org/python/antlr/ast/comprehensionType.java branches/newstyle-java-types/src/org/python/antlr/ast/excepthandlerType.java branches/newstyle-java-types/src/org/python/antlr/ast/exprType.java branches/newstyle-java-types/src/org/python/antlr/ast/expr_contextType.java branches/newstyle-java-types/src/org/python/antlr/ast/keywordType.java branches/newstyle-java-types/src/org/python/antlr/ast/modType.java branches/newstyle-java-types/src/org/python/antlr/ast/operatorType.java branches/newstyle-java-types/src/org/python/antlr/ast/sliceType.java branches/newstyle-java-types/src/org/python/antlr/ast/stmtType.java branches/newstyle-java-types/src/org/python/antlr/ast/unaryopType.java branches/newstyle-java-types/src/org/python/compiler/CodeCompiler.java branches/newstyle-java-types/src/org/python/compiler/Module.java branches/newstyle-java-types/src/org/python/compiler/ScopesCompiler.java branches/newstyle-java-types/src/org/python/core/Py.java branches/newstyle-java-types/src/org/python/core/PyArray.java branches/newstyle-java-types/src/org/python/core/PyBoolean.java branches/newstyle-java-types/src/org/python/core/PyBuiltinCallable.java branches/newstyle-java-types/src/org/python/core/PyCell.java branches/newstyle-java-types/src/org/python/core/PyClassMethodDescr.java branches/newstyle-java-types/src/org/python/core/PyDataDescr.java branches/newstyle-java-types/src/org/python/core/PyDictProxy.java branches/newstyle-java-types/src/org/python/core/PyEllipsis.java branches/newstyle-java-types/src/org/python/core/PyFile.java branches/newstyle-java-types/src/org/python/core/PyFunction.java branches/newstyle-java-types/src/org/python/core/PyGenerator.java branches/newstyle-java-types/src/org/python/core/PyMethod.java branches/newstyle-java-types/src/org/python/core/PyMethodDescr.java branches/newstyle-java-types/src/org/python/core/PyNone.java branches/newstyle-java-types/src/org/python/core/PyNotImplemented.java branches/newstyle-java-types/src/org/python/core/PyObject.java branches/newstyle-java-types/src/org/python/core/PySequence.java branches/newstyle-java-types/src/org/python/core/PySlice.java branches/newstyle-java-types/src/org/python/core/PySlot.java branches/newstyle-java-types/src/org/python/core/PyString.java branches/newstyle-java-types/src/org/python/core/PySystemState.java branches/newstyle-java-types/src/org/python/core/PyTraceback.java branches/newstyle-java-types/src/org/python/core/PyType.java branches/newstyle-java-types/src/org/python/core/PyXRange.java branches/newstyle-java-types/src/org/python/core/__builtin__.java branches/newstyle-java-types/src/org/python/core/imp.java branches/newstyle-java-types/src/org/python/core/io/FileIO.java branches/newstyle-java-types/src/org/python/core/io/IOBase.java branches/newstyle-java-types/src/org/python/core/io/ServerSocketIO.java branches/newstyle-java-types/src/org/python/core/util/FileUtil.java branches/newstyle-java-types/src/org/python/expose/BaseTypeBuilder.java branches/newstyle-java-types/src/org/python/expose/ExposedType.java branches/newstyle-java-types/src/org/python/expose/TypeBuilder.java branches/newstyle-java-types/src/org/python/expose/generate/DescriptorExposer.java branches/newstyle-java-types/src/org/python/expose/generate/ExposedTypeProcessor.java branches/newstyle-java-types/src/org/python/expose/generate/ExposedTypeVisitor.java branches/newstyle-java-types/src/org/python/expose/generate/Exposer.java branches/newstyle-java-types/src/org/python/expose/generate/InstanceMethodExposer.java branches/newstyle-java-types/src/org/python/expose/generate/TypeExposer.java branches/newstyle-java-types/src/org/python/modules/PyTeeIterator.java branches/newstyle-java-types/src/org/python/modules/_codecs.java branches/newstyle-java-types/src/org/python/modules/_py_compile.java branches/newstyle-java-types/src/org/python/modules/_weakref/CallableProxyType.java branches/newstyle-java-types/src/org/python/modules/_weakref/ProxyType.java branches/newstyle-java-types/src/org/python/modules/errno.java branches/newstyle-java-types/src/org/python/modules/imp.java branches/newstyle-java-types/src/org/python/modules/itertools.java branches/newstyle-java-types/src/org/python/modules/operator.java branches/newstyle-java-types/src/org/python/modules/struct.java branches/newstyle-java-types/src/org/python/modules/thread/thread.java branches/newstyle-java-types/src/org/python/modules/time/PyTimeTuple.java branches/newstyle-java-types/src/org/python/modules/time/Time.java branches/newstyle-java-types/src/org/python/modules/zipimport/zipimporter.java branches/newstyle-java-types/src/shell/jython branches/newstyle-java-types/src/shell/jython.bat branches/newstyle-java-types/tests/java/org/python/expose/generate/DescriptorExposerTest.java branches/newstyle-java-types/tests/java/org/python/expose/generate/ExposedTypeProcessorTest.java branches/newstyle-java-types/tests/java/org/python/expose/generate/ExposedTypeVisitorTest.java branches/newstyle-java-types/tests/java/org/python/expose/generate/MethodExposerTest.java branches/newstyle-java-types/tests/java/org/python/expose/generate/SimpleExposed.java branches/newstyle-java-types/tests/java/org/python/expose/generate/TypeExposerTest.java Added Paths: ----------- branches/newstyle-java-types/Lib/pydoc.py branches/newstyle-java-types/Lib/test/test_genexps_jy.py branches/newstyle-java-types/Lib/test/test_zipfile.py branches/newstyle-java-types/Lib/warnings.py branches/newstyle-java-types/Lib/zipfile.py branches/newstyle-java-types/extlibs/antlr-3.1.1-runtime.jar branches/newstyle-java-types/extlibs/antlr-3.1.1.jar branches/newstyle-java-types/extlibs/constantine-0.4.jar branches/newstyle-java-types/tests/java/org/python/util/ branches/newstyle-java-types/tests/java/org/python/util/InterpreterTest.java Removed Paths: ------------- branches/newstyle-java-types/extlibs/antlr-3.1.jar branches/newstyle-java-types/extlibs/antlr-runtime-3.1.jar branches/newstyle-java-types/tests/java/org/python/util/InterpreterTest.java Property Changed: ---------------- branches/newstyle-java-types/ Property changes on: branches/newstyle-java-types ___________________________________________________________________ Modified: svnmerge-integrated - /branches/nowalker:1-5263 /trunk/jython:1-5562 + /branches/nowalker:1-5263 /trunk/jython:1-5664 Added: svn:mergeinfo + /trunk/jython:5565-5661 Modified: branches/newstyle-java-types/.classpath =================================================================== --- branches/newstyle-java-types/.classpath 2008-11-30 05:37:11 UTC (rev 5664) +++ branches/newstyle-java-types/.classpath 2008-12-01 00:38:14 UTC (rev 5665) @@ -14,6 +14,6 @@ <classpathentry kind="lib" path="extlibs/servlet-api-2.5.jar"/> <classpathentry kind="lib" path="build/jarjar"/> <classpathentry kind="var" path="ANT_HOME/lib/ant.jar"/> - <classpathentry kind="lib" path="extlibs/antlr-runtime-3.1.jar"/> + <classpathentry kind="lib" path="extlibs/antlr-3.1.1-runtime.jar"/> <classpathentry kind="output" path="bugtests/classes"/> </classpath> Modified: branches/newstyle-java-types/Lib/datetime.py =================================================================== --- branches/newstyle-java-types/Lib/datetime.py 2008-11-30 05:37:11 UTC (rev 5664) +++ branches/newstyle-java-types/Lib/datetime.py 2008-12-01 00:38:14 UTC (rev 5665) @@ -1574,7 +1574,7 @@ # Convert self to UTC, and attach the new time zone object. myoffset = self.utcoffset() if myoffset is None: - raise ValuError("astimezone() requires an aware datetime") + raise ValueError("astimezone() requires an aware datetime") utc = (self - myoffset).replace(tzinfo=tz) # Convert from UTC to tz's local time. Modified: branches/newstyle-java-types/Lib/inspect.py =================================================================== --- branches/newstyle-java-types/Lib/inspect.py 2008-11-30 05:37:11 UTC (rev 5664) +++ branches/newstyle-java-types/Lib/inspect.py 2008-12-01 00:38:14 UTC (rev 5665) @@ -383,6 +383,8 @@ filename = getfile(object) if string.lower(filename[-4:]) in ('.pyc', '.pyo'): filename = filename[:-4] + '.py' + elif filename.endswith('$py.class'): + filename = filename[:-9] + '.py' for suffix, mode, kind in imp.get_suffixes(): if 'b' in mode and string.lower(filename[-len(suffix):]) == suffix: # Looks like a binary file. We want to only return a text file. Modified: branches/newstyle-java-types/Lib/ntpath.py =================================================================== --- branches/newstyle-java-types/Lib/ntpath.py 2008-11-30 05:37:11 UTC (rev 5664) +++ branches/newstyle-java-types/Lib/ntpath.py 2008-12-01 00:38:14 UTC (rev 5665) @@ -9,6 +9,7 @@ import os import stat import sys +from org.python.core.Py import newString __all__ = ["normcase","isabs","join","splitdrive","split","splitext", "basename","dirname","commonprefix","getsize","getmtime", @@ -493,7 +494,8 @@ if not splitunc(path)[0] and not splitdrive(path)[0]: # cwd lacks a UNC mount point, so it should have a drive # letter (but lacks one): determine it - drive = splitdrive(java.io.File(path).getCanonicalPath())[0] + canon_path = newString(java.io.File(path).getCanonicalPath()) + drive = splitdrive(canon_path)[0] path = join(drive, path) return normpath(path) Modified: branches/newstyle-java-types/Lib/os.py =================================================================== --- branches/newstyle-java-types/Lib/os.py 2008-11-30 05:37:11 UTC (rev 5664) +++ branches/newstyle-java-types/Lib/os.py 2008-12-01 00:38:14 UTC (rev 5665) @@ -46,6 +46,7 @@ import stat as _stat import sys from java.io import File +from org.python.constantine.platform import Errno from org.python.core.io import FileDescriptors, FileIO, IOBase from org.python.core.Py import newString as asPyString @@ -101,7 +102,7 @@ err = getattr(errno, error.name(), None) if err is None: raise OSError('%s: %s' % (error, msg)) - raise OSError(err, errno.strerror(err), msg) + raise OSError(err, strerror(err), msg) def unimplementedError(self, method_name): raise NotImplementedError(method_name) def warn(self, warning_id, msg, rest): @@ -237,7 +238,7 @@ Return a string representing the current working directory. """ - return sys.getCurrentWorkingDir() + return asPyString(sys.getCurrentWorkingDir()) def chdir(path): """chdir(path) @@ -246,9 +247,9 @@ """ realpath = _path.realpath(path) if not _path.exists(realpath): - raise OSError(errno.ENOENT, errno.strerror(errno.ENOENT), path) + raise OSError(errno.ENOENT, strerror(errno.ENOENT), path) if not _path.isdir(realpath): - raise OSError(errno.ENOTDIR, errno.strerror(errno.ENOTDIR), path) + raise OSError(errno.ENOTDIR, strerror(errno.ENOTDIR), path) sys.setCurrentWorkingDir(realpath) def listdir(path): @@ -275,7 +276,7 @@ # catch not found errors explicitly here, for now abs_path = sys.getPath(path) if not File(abs_path).exists(): - raise OSError(errno.ENOENT, errno.strerror(errno.ENOENT), path) + raise OSError(errno.ENOENT, strerror(errno.ENOENT), path) _posix.chmod(abs_path, mode) def mkdir(path, mode='ignored'): @@ -292,7 +293,7 @@ err = errno.EEXIST else: err = 0 - msg = errno.strerror(err) if err else "couldn't make directory" + msg = strerror(err) if err else "couldn't make directory" raise OSError(err, msg, path) def makedirs(path, mode='ignored'): @@ -371,9 +372,9 @@ Remove a directory.""" f = File(sys.getPath(path)) if not f.exists(): - raise OSError(errno.ENOENT, errno.strerror(errno.ENOENT), path) + raise OSError(errno.ENOENT, strerror(errno.ENOENT), path) elif not f.isDirectory(): - raise OSError(errno.ENOTDIR, errno.strerror(errno.ENOTDIR), path) + raise OSError(errno.ENOTDIR, strerror(errno.ENOTDIR), path) elif not f.delete(): raise OSError(0, "couldn't delete directory", path) @@ -409,10 +410,17 @@ """ if not isinstance(code, (int, long)): raise TypeError('an integer is required') - try: - return errno.strerror(code) - except KeyError: + constant = Errno.valueOf(code) + if constant is Errno.__UNKNOWN_CONSTANT__: return 'Unknown error: %d' % code + if constant.name() == constant.description(): + # XXX: have constantine handle this fallback + # Fake constant or just lacks a description, fallback to Linux's + from org.python.constantine.platform.linux import Errno as LinuxErrno + constant = getattr(LinuxErrno, constant.name(), None) + if not constant: + return 'Unknown error: %d' % code + return asPyString(constant.toString()) def access(path, mode): """access(path, mode) -> True if granted, False otherwise @@ -459,7 +467,7 @@ raise f = File(abs_path) if not f.exists(): - raise OSError(errno.ENOENT, errno.strerror(errno.ENOENT), path) + raise OSError(errno.ENOENT, strerror(errno.ENOENT), path) size = f.length() mtime = f.lastModified() / 1000.0 mode = 0 @@ -509,7 +517,7 @@ # Not a link, only now can we determine if it exists (because # File.exists() returns False for dead links) if not f.exists(): - raise OSError(errno.ENOENT, errno.strerror(errno.ENOENT), path) + raise OSError(errno.ENOENT, strerror(errno.ENOENT), path) return stat(path) def utime(path, times): @@ -550,12 +558,12 @@ if (len(mode) and mode[0] or '') not in 'rwa': raise ValueError("invalid file mode '%s'" % mode) if rawio.closed(): - raise OSError(errno.EBADF, errno.strerror(errno.EBADF)) + raise OSError(errno.EBADF, strerror(errno.EBADF)) try: fp = FileDescriptors.wrap(rawio, mode, bufsize) except IOError: - raise OSError(errno.EINVAL, errno.strerror(errno.EINVAL)) + raise OSError(errno.EINVAL, strerror(errno.EINVAL)) return fp def ftruncate(fd, length): @@ -567,7 +575,7 @@ try: rawio.truncate(length) except Exception, e: - raise IOError(errno.EBADF, errno.strerror(errno.EBADF)) + raise IOError(errno.EBADF, strerror(errno.EBADF)) def lseek(fd, pos, how): """lseek(fd, pos, how) -> newpos @@ -593,10 +601,10 @@ appending = flag & O_APPEND if updating and writing: - raise OSError(errno.EINVAL, errno.strerror(errno.EINVAL), filename) + raise OSError(errno.EINVAL, strerror(errno.EINVAL), filename) if not creating and not path.exists(filename): - raise OSError(errno.ENOENT, errno.strerror(errno.ENOENT), filename) + raise OSError(errno.ENOENT, strerror(errno.ENOENT), filename) if not writing: if updating: @@ -611,7 +619,7 @@ if exclusive and creating: try: if not File(sys.getPath(filename)).createNewFile(): - raise OSError(errno.EEXIST, errno.strerror(errno.EEXIST), + raise OSError(errno.EEXIST, strerror(errno.EEXIST), filename) except java.io.IOException, ioe: raise OSError(ioe) @@ -627,8 +635,8 @@ fchannel = RandomAccessFile(sys.getPath(filename), 'rws').getChannel() except FileNotFoundException, fnfe: if path.isdir(filename): - raise OSError(errno.EISDIR, errno.strerror(errno.EISDIR)) - raise OSError(errno.ENOENT, errno.strerror(errno.ENOENT), filename) + raise OSError(errno.EISDIR, strerror(errno.EISDIR)) + raise OSError(errno.ENOENT, strerror(errno.ENOENT), filename) return FileIO(fchannel, mode) return FileIO(filename, mode) @@ -659,7 +667,7 @@ try: return func(*args, **kwargs) except: - raise OSError(errno.EBADF, errno.strerror(errno.EBADF)) + raise OSError(errno.EBADF, strerror(errno.EBADF)) if _name == 'posix' and _native_posix: def link(src, dst): Modified: branches/newstyle-java-types/Lib/popen2.py =================================================================== --- branches/newstyle-java-types/Lib/popen2.py 2008-11-30 05:37:11 UTC (rev 5664) +++ branches/newstyle-java-types/Lib/popen2.py 2008-12-01 00:38:14 UTC (rev 5665) @@ -44,7 +44,7 @@ the close method. """ def __init__(self, stream, process, name): - self._file = FileUtil.wrap(stream) + self._file = FileUtil.wrap(stream, 0) self._process = process def __getattr__(self, name): @@ -93,10 +93,10 @@ bufsize ) - self.tochild = FileUtil.wrap(self._tochild) - self.fromchild = FileUtil.wrap(self._fromchild) + self.tochild = FileUtil.wrap(self._tochild, 0) + self.fromchild = FileUtil.wrap(self._fromchild, 0) if self._childerr: - self.childerr = FileUtil.wrap(self._childerr) + self.childerr = FileUtil.wrap(self._childerr, 0) def _startChildWaiter(self): """Start a subthread that waits for the child process to exit.""" @@ -198,7 +198,7 @@ "%s-stderr" % self.process, self._close ) - return FileUtil.wrap(joinedStream) + return FileUtil.wrap(joinedStream, 0) def _close( self ): """Must be closed twice (once for each of the two joined pipes)""" Modified: branches/newstyle-java-types/Lib/posixpath.py =================================================================== --- branches/newstyle-java-types/Lib/posixpath.py 2008-11-30 05:37:11 UTC (rev 5664) +++ branches/newstyle-java-types/Lib/posixpath.py 2008-12-01 00:38:14 UTC (rev 5665) @@ -14,6 +14,7 @@ import java.io.IOException import os import stat +from org.python.core.Py import newString __all__ = ["normcase","isabs","join","splitdrive","split","splitext", "basename","dirname","commonprefix","getsize","getmtime", @@ -218,8 +219,8 @@ if not os._native_posix: def samefile(f1, f2): """Test whether two pathnames reference the same actual file""" - canon1 = java.io.File(_ensure_str(f1)).getCanonicalPath() - canon2 = java.io.File(_ensure_str(f2)).getCanonicalPath() + canon1 = newString(java.io.File(_ensure_str(f1)).getCanonicalPath()) + canon2 = newString(java.io.File(_ensure_str(f2)).getCanonicalPath()) return canon1 == canon2 else: def samefile(f1, f2): @@ -240,7 +241,7 @@ s2 = os.fstat(fp2) return samestat(s1, s2) - __all__append("sameopenfile") + __all__.append("sameopenfile") if os._native_posix: @@ -448,7 +449,7 @@ encounter a path we've seen before (meaning that there's a loop). """ try: - return str(java.io.File(abspath(path)).getCanonicalPath()) + return newString(java.io.File(abspath(path)).getCanonicalPath()) except java.io.IOException: return None else: Copied: branches/newstyle-java-types/Lib/pydoc.py (from rev 5661, trunk/jython/Lib/pydoc.py) =================================================================== --- branches/newstyle-java-types/Lib/pydoc.py (rev 0) +++ branches/newstyle-java-types/Lib/pydoc.py 2008-12-01 00:38:14 UTC (rev 5665) @@ -0,0 +1,2257 @@ +#!/usr/bin/env python +# -*- coding: Latin-1 -*- +"""Generate Python documentation in HTML or text for interactive use. + +In the Python interpreter, do "from pydoc import help" to provide online +help. Calling help(thing) on a Python object documents the object. + +Or, at the shell command line outside of Python: + +Run "pydoc <name>" to show documentation on something. <name> may be +the name of a function, module, package, or a dotted reference to a +class or function within a module or module in a package. If the +argument contains a path segment delimiter (e.g. slash on Unix, +backslash on Windows) it is treated as the path to a Python source file. + +Run "pydoc -k <keyword>" to search for a keyword in the synopsis lines +of all available modules. + +Run "pydoc -p <port>" to start an HTTP server on a given port on the +local machine to generate documentation web pages. + +For platforms without a command line, "pydoc -g" starts the HTTP server +and also pops up a little window for controlling it. + +Run "pydoc -w <name>" to write out the HTML documentation for a module +to a file named "<name>.html". + +Module docs for core modules are assumed to be in + + http://www.python.org/doc/current/lib/ + +This can be overridden by setting the PYTHONDOCS environment variable +to a different URL or to a local directory containing the Library +Reference Manual pages. +""" + +__author__ = "Ka-Ping Yee <pi...@lf...>" +__date__ = "26 February 2001" + +__version__ = "$Revision: 54366 $" +__credits__ = """Guido van Rossum, for an excellent programming language. +Tommy Burnette, the original creator of manpy. +Paul Prescod, for all his work on onlinehelp. +Richard Chamberlain, for the first implementation of textdoc. +""" + +# Known bugs that can't be fixed here: +# - imp.load_module() cannot be prevented from clobbering existing +# loaded modules, so calling synopsis() on a binary module file +# changes the contents of any existing module with the same name. +# - If the __file__ attribute on a module is a relative path and +# the current directory is changed with os.chdir(), an incorrect +# path will be displayed. + +import sys, imp, os, re, types, inspect, __builtin__, pkgutil +from repr import Repr +from string import expandtabs, find, join, lower, split, strip, rfind, rstrip +try: + from collections import deque +except ImportError: + # Python 2.3 compatibility + class deque(list): + def popleft(self): + return self.pop(0) + +# --------------------------------------------------------- common routines + +def pathdirs(): + """Convert sys.path into a list of absolute, existing, unique paths.""" + dirs = [] + normdirs = [] + for dir in sys.path: + dir = os.path.abspath(dir or '.') + normdir = os.path.normcase(dir) + if normdir not in normdirs and os.path.isdir(dir): + dirs.append(dir) + normdirs.append(normdir) + return dirs + +def getdoc(object): + """Get the doc string or comments for an object.""" + result = inspect.getdoc(object) or inspect.getcomments(object) + return result and re.sub('^ *\n', '', rstrip(result)) or '' + +def splitdoc(doc): + """Split a doc string into a synopsis line (if any) and the rest.""" + lines = split(strip(doc), '\n') + if len(lines) == 1: + return lines[0], '' + elif len(lines) >= 2 and not rstrip(lines[1]): + return lines[0], join(lines[2:], '\n') + return '', join(lines, '\n') + +def classname(object, modname): + """Get a class name and qualify it with a module name if necessary.""" + name = object.__name__ + if object.__module__ != modname: + name = object.__module__ + '.' + name + return name + +def isdata(object): + """Check if an object is of a type that probably means it's data.""" + return not (inspect.ismodule(object) or inspect.isclass(object) or + inspect.isroutine(object) or inspect.isframe(object) or + inspect.istraceback(object) or inspect.iscode(object)) + +def replace(text, *pairs): + """Do a series of global replacements on a string.""" + while pairs: + text = join(split(text, pairs[0]), pairs[1]) + pairs = pairs[2:] + return text + +def cram(text, maxlen): + """Omit part of a string if needed to make it fit in a maximum length.""" + if len(text) > maxlen: + pre = max(0, (maxlen-3)//2) + post = max(0, maxlen-3-pre) + return text[:pre] + '...' + text[len(text)-post:] + return text + +_re_stripid = re.compile(r' at 0x[0-9a-f]{6,16}(>+)$', re.IGNORECASE) +def stripid(text): + """Remove the hexadecimal id from a Python object representation.""" + # The behaviour of %p is implementation-dependent in terms of case. + if _re_stripid.search(repr(Exception)): + return _re_stripid.sub(r'\1', text) + return text + +def _is_some_method(obj): + return inspect.ismethod(obj) or inspect.ismethoddescriptor(obj) + +def allmethods(cl): + methods = {} + for key, value in inspect.getmembers(cl, _is_some_method): + methods[key] = 1 + for base in cl.__bases__: + methods.update(allmethods(base)) # all your base are belong to us + for key in methods.keys(): + methods[key] = getattr(cl, key) + return methods + +def _split_list(s, predicate): + """Split sequence s via predicate, and return pair ([true], [false]). + + The return value is a 2-tuple of lists, + ([x for x in s if predicate(x)], + [x for x in s if not predicate(x)]) + """ + + yes = [] + no = [] + for x in s: + if predicate(x): + yes.append(x) + else: + no.append(x) + return yes, no + +def visiblename(name, all=None): + """Decide whether to show documentation on a variable.""" + # Certain special names are redundant. + if name in ('__builtins__', '__doc__', '__file__', '__path__', + '__module__', '__name__', '__slots__'): return 0 + # Private names are hidden, but special names are displayed. + if name.startswith('__') and name.endswith('__'): return 1 + if all is not None: + # only document that which the programmer exported in __all__ + return name in all + else: + return not name.startswith('_') + +def classify_class_attrs(object): + """Wrap inspect.classify_class_attrs, with fixup for data descriptors.""" + def fixup((name, kind, cls, value)): + if inspect.isdatadescriptor(value): + kind = 'data descriptor' + return name, kind, cls, value + return map(fixup, inspect.classify_class_attrs(object)) + +# ----------------------------------------------------- module manipulation + +def ispackage(path): + """Guess whether a path refers to a package directory.""" + if os.path.isdir(path): + for ext in ('.py', '.pyc', '.pyo', '$py.class'): + if os.path.isfile(os.path.join(path, '__init__' + ext)): + return True + return False + +def source_synopsis(file): + line = file.readline() + while line[:1] == '#' or not strip(line): + line = file.readline() + if not line: break + line = strip(line) + if line[:4] == 'r"""': line = line[1:] + if line[:3] == '"""': + line = line[3:] + if line[-1:] == '\\': line = line[:-1] + while not strip(line): + line = file.readline() + if not line: break + result = strip(split(line, '"""')[0]) + else: result = None + return result + +def synopsis(filename, cache={}): + """Get the one-line summary out of a module file.""" + mtime = os.stat(filename).st_mtime + lastupdate, result = cache.get(filename, (0, None)) + if lastupdate < mtime: + info = inspect.getmoduleinfo(filename) + try: + file = open(filename) + except IOError: + # module can't be opened, so skip it + return None + if info and 'b' in info[2]: # binary modules have to be imported + try: module = imp.load_module('__temp__', file, filename, info[1:]) + except: return None + result = (module.__doc__ or '').splitlines()[0] + del sys.modules['__temp__'] + else: # text modules can be directly examined + result = source_synopsis(file) + file.close() + cache[filename] = (mtime, result) + return result + +class ErrorDuringImport(Exception): + """Errors that occurred while trying to import something to document it.""" + def __init__(self, filename, (exc, value, tb)): + self.filename = filename + self.exc = exc + self.value = value + self.tb = tb + + def __str__(self): + exc = self.exc + if type(exc) is types.ClassType: + exc = exc.__name__ + return 'problem in %s - %s: %s' % (self.filename, exc, self.value) + +def importfile(path): + """Import a Python source file or compiled file given its path.""" + magic = imp.get_magic() + file = open(path, 'r') + if file.read(len(magic)) == magic: + kind = imp.PY_COMPILED + else: + kind = imp.PY_SOURCE + file.close() + filename = os.path.basename(path) + name, ext = os.path.splitext(filename) + file = open(path, 'r') + try: + module = imp.load_module(name, file, path, (ext, 'r', kind)) + except: + raise ErrorDuringImport(path, sys.exc_info()) + file.close() + return module + +def safeimport(path, forceload=0, cache={}): + """Import a module; handle errors; return None if the module isn't found. + + If the module *is* found but an exception occurs, it's wrapped in an + ErrorDuringImport exception and reraised. Unlike __import__, if a + package path is specified, the module at the end of the path is returned, + not the package at the beginning. If the optional 'forceload' argument + is 1, we reload the module from disk (unless it's a dynamic extension).""" + try: + # If forceload is 1 and the module has been previously loaded from + # disk, we always have to reload the module. Checking the file's + # mtime isn't good enough (e.g. the module could contain a class + # that inherits from another module that has changed). + if forceload and path in sys.modules: + if path not in sys.builtin_module_names: + # Avoid simply calling reload() because it leaves names in + # the currently loaded module lying around if they're not + # defined in the new source file. Instead, remove the + # module from sys.modules and re-import. Also remove any + # submodules because they won't appear in the newly loaded + # module's namespace if they're already in sys.modules. + subs = [m for m in sys.modules if m.startswith(path + '.')] + for key in [path] + subs: + # Prevent garbage collection. + cache[key] = sys.modules[key] + del sys.modules[key] + module = __import__(path) + except: + # Did the error occur before or after the module was found? + (exc, value, tb) = info = sys.exc_info() + if path in sys.modules: + # An error occurred while executing the imported module. + raise ErrorDuringImport(sys.modules[path].__file__, info) + elif exc is SyntaxError: + # A SyntaxError occurred before we could execute the module. + raise ErrorDuringImport(value.filename, info) + elif exc is ImportError and \ + split(lower(str(value)))[:2] == ['no', 'module']: + # The module was not found. + return None + else: + # Some other error occurred during the importing process. + raise ErrorDuringImport(path, sys.exc_info()) + for part in split(path, '.')[1:]: + try: module = getattr(module, part) + except AttributeError: return None + return module + +# ---------------------------------------------------- formatter base class + +class Doc: + def document(self, object, name=None, *args): + """Generate documentation for an object.""" + args = (object, name) + args + # 'try' clause is to attempt to handle the possibility that inspect + # identifies something in a way that pydoc itself has issues handling; + # think 'super' and how it is a descriptor (which raises the exception + # by lacking a __name__ attribute) and an instance. + if inspect.isgetsetdescriptor(object): return self.docdata(*args) + if inspect.ismemberdescriptor(object): return self.docdata(*args) + try: + if inspect.ismodule(object): return self.docmodule(*args) + if inspect.isclass(object): return self.docclass(*args) + if inspect.isroutine(object): return self.docroutine(*args) + except AttributeError: + pass + if isinstance(object, property): return self.docproperty(*args) + return self.docother(*args) + + def fail(self, object, name=None, *args): + """Raise an exception for unimplemented types.""" + message = "don't know how to document object%s of type %s" % ( + name and ' ' + repr(name), type(object).__name__) + raise TypeError, message + + docmodule = docclass = docroutine = docother = docproperty = docdata = fail + + def getdocloc(self, object): + """Return the location of module docs or None""" + + try: + file = inspect.getabsfile(object) + except TypeError: + file = '(built-in)' + + docloc = os.environ.get("PYTHONDOCS", + "http://www.python.org/doc/current/lib") + basedir = os.path.join(sys.exec_prefix, "lib", + "python"+sys.version[0:3]) + if (isinstance(object, type(os)) and + (object.__name__ in ('errno', 'exceptions', 'gc', 'imp', + 'marshal', 'posix', 'signal', 'sys', + 'thread', 'zipimport') or + (file.startswith(basedir) and + not file.startswith(os.path.join(basedir, 'site-packages'))))): + htmlfile = "module-%s.html" % object.__name__ + if docloc.startswith("http://"): + docloc = "%s/%s" % (docloc.rstrip("/"), htmlfile) + else: + docloc = os.path.join(docloc, htmlfile) + else: + docloc = None + return docloc + +# -------------------------------------------- HTML documentation generator + +class HTMLRepr(Repr): + """Class for safely making an HTML representation of a Python object.""" + def __init__(self): + Repr.__init__(self) + self.maxlist = self.maxtuple = 20 + self.maxdict = 10 + self.maxstring = self.maxother = 100 + + def escape(self, text): + return replace(text, '&', '&', '<', '<', '>', '>') + + def repr(self, object): + return Repr.repr(self, object) + + def repr1(self, x, level): + if hasattr(type(x), '__name__'): + methodname = 'repr_' + join(split(type(x).__name__), '_') + if hasattr(self, methodname): + return getattr(self, methodname)(x, level) + return self.escape(cram(stripid(repr(x)), self.maxother)) + + def repr_string(self, x, level): + test = cram(x, self.maxstring) + testrepr = repr(test) + if '\\' in test and '\\' not in replace(testrepr, r'\\', ''): + # Backslashes are only literal in the string and are never + # needed to make any special characters, so show a raw string. + return 'r' + testrepr[0] + self.escape(test) + testrepr[0] + return re.sub(r'((\\[\\abfnrtv\'"]|\\[0-9]..|\\x..|\\u....)+)', + r'<font color="#c040c0">\1</font>', + self.escape(testrepr)) + + repr_str = repr_string + + def repr_instance(self, x, level): + try: + return self.escape(cram(stripid(repr(x)), self.maxstring)) + except: + return self.escape('<%s instance>' % x.__class__.__name__) + + repr_unicode = repr_string + +class HTMLDoc(Doc): + """Formatter class for HTML documentation.""" + + # ------------------------------------------- HTML formatting utilities + + _repr_instance = HTMLRepr() + repr = _repr_instance.repr + escape = _repr_instance.escape + + def page(self, title, contents): + """Format an HTML page.""" + return ''' +<!doctype html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> +<html><head><title>Python: %s</title> +</head><body bgcolor="#f0f0f8"> +%s +</body></html>''' % (title, contents) + + def heading(self, title, fgcol, bgcol, extras=''): + """Format a page heading.""" + return ''' +<table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="heading"> +<tr bgcolor="%s"> +<td valign=bottom> <br> +<font color="%s" face="helvetica, arial"> <br>%s</font></td +><td align=right valign=bottom +><font color="%s" face="helvetica, arial">%s</font></td></tr></table> + ''' % (bgcol, fgcol, title, fgcol, extras or ' ') + + def section(self, title, fgcol, bgcol, contents, width=6, + prelude='', marginalia=None, gap=' '): + """Format a section with a heading.""" + if marginalia is None: + marginalia = '<tt>' + ' ' * width + '</tt>' + result = '''<p> +<table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="section"> +<tr bgcolor="%s"> +<td colspan=3 valign=bottom> <br> +<font color="%s" face="helvetica, arial">%s</font></td></tr> + ''' % (bgcol, fgcol, title) + if prelude: + result = result + ''' +<tr bgcolor="%s"><td rowspan=2>%s</td> +<td colspan=2>%s</td></tr> +<tr><td>%s</td>''' % (bgcol, marginalia, prelude, gap) + else: + result = result + ''' +<tr><td bgcolor="%s">%s</td><td>%s</td>''' % (bgcol, marginalia, gap) + + return result + '\n<td width="100%%">%s</td></tr></table>' % contents + + def bigsection(self, title, *args): + """Format a section with a big heading.""" + title = '<big><strong>%s</strong></big>' % title + return self.section(title, *args) + + def preformat(self, text): + """Format literal preformatted text.""" + text = self.escape(expandtabs(text)) + return replace(text, '\n\n', '\n \n', '\n\n', '\n \n', + ' ', ' ', '\n', '<br>\n') + + def multicolumn(self, list, format, cols=4): + """Format a list of items into a multi-column list.""" + result = '' + rows = (len(list)+cols-1)/cols + for col in range(cols): + result = result + '<td width="%d%%" valign=top>' % (100/cols) + for i in range(rows*col, rows*col+rows): + if i < len(list): + result = result + format(list[i]) + '<br>\n' + result = result + '</td>' + return '<table width="100%%" summary="list"><tr>%s</tr></table>' % result + + def grey(self, text): return '<font color="#909090">%s</font>' % text + + def namelink(self, name, *dicts): + """Make a link for an identifier, given name-to-URL mappings.""" + for dict in dicts: + if name in dict: + return '<a href="%s">%s</a>' % (dict[name], name) + return name + + def classlink(self, object, modname): + """Make a link for a class.""" + name, module = object.__name__, sys.modules.get(object.__module__) + if hasattr(module, name) and getattr(module, name) is object: + return '<a href="%s.html#%s">%s</a>' % ( + module.__name__, name, classname(object, modname)) + return classname(object, modname) + + def modulelink(self, object): + """Make a link for a module.""" + return '<a href="%s.html">%s</a>' % (object.__name__, object.__name__) + + def modpkglink(self, (name, path, ispackage, shadowed)): + """Make a link for a module or package to display in an index.""" + if shadowed: + return self.grey(name) + if path: + url = '%s.%s.html' % (path, name) + else: + url = '%s.html' % name + if ispackage: + text = '<strong>%s</strong> (package)' % name + else: + text = name + return '<a href="%s">%s</a>' % (url, text) + + def markup(self, text, escape=None, funcs={}, classes={}, methods={}): + """Mark up some plain text, given a context of symbols to look for. + Each context dictionary maps object names to anchor names.""" + escape = escape or self.escape + results = [] + here = 0 + pattern = re.compile(r'\b((http|ftp)://\S+[\w/]|' + r'RFC[- ]?(\d+)|' + r'PEP[- ]?(\d+)|' + r'(self\.)?(\w+))') + while True: + match = pattern.search(text, here) + if not match: break + start, end = match.span() + results.append(escape(text[here:start])) + + all, scheme, rfc, pep, selfdot, name = match.groups() + if scheme: + url = escape(all).replace('"', '"') + results.append('<a href="%s">%s</a>' % (url, url)) + elif rfc: + url = 'http://www.rfc-editor.org/rfc/rfc%d.txt' % int(rfc) + results.append('<a href="%s">%s</a>' % (url, escape(all))) + elif pep: + url = 'http://www.python.org/peps/pep-%04d.html' % int(pep) + results.append('<a href="%s">%s</a>' % (url, escape(all))) + elif text[end:end+1] == '(': + results.append(self.namelink(name, methods, funcs, classes)) + elif selfdot: + results.append('self.<strong>%s</strong>' % name) + else: + results.append(self.namelink(name, classes)) + here = end + results.append(escape(text[here:])) + return join(results, '') + + # ---------------------------------------------- type-specific routines + + def formattree(self, tree, modname, parent=None): + """Produce HTML for a class tree as given by inspect.getclasstree().""" + result = '' + for entry in tree: + if type(entry) is type(()): + c, bases = entry + result = result + '<dt><font face="helvetica, arial">' + result = result + self.classlink(c, modname) + if bases and bases != (parent,): + parents = [] + for base in bases: + parents.append(self.classlink(base, modname)) + result = result + '(' + join(parents, ', ') + ')' + result = result + '\n</font></dt>' +... [truncated message content] |
From: <cg...@us...> - 2008-12-01 01:09:00
|
Revision: 5668 http://jython.svn.sourceforge.net/jython/?rev=5668&view=rev Author: cgroves Date: 2008-12-01 01:08:51 +0000 (Mon, 01 Dec 2008) Log Message: ----------- Go ahead and take multiple methods in PyReflectedFunction's constructor Modified Paths: -------------- branches/newstyle-java-types/Lib/test/test_joverload.py branches/newstyle-java-types/src/org/python/core/PyReflectedFunction.java Modified: branches/newstyle-java-types/Lib/test/test_joverload.py =================================================================== --- branches/newstyle-java-types/Lib/test/test_joverload.py 2008-12-01 01:06:33 UTC (rev 5667) +++ branches/newstyle-java-types/Lib/test/test_joverload.py 2008-12-01 01:08:51 UTC (rev 5668) @@ -11,9 +11,7 @@ class PyReflFuncEnvl: def __init__(self,name,meths): - self.reflfunc = PyReflectedFunction(meths[0]) - for meth in meths[1:]: - self.reflfunc.addMethod(meth) + self.reflfunc = PyReflectedFunction(meths) def __call__(self,inst,args): return self.reflfunc(inst,*args) Modified: branches/newstyle-java-types/src/org/python/core/PyReflectedFunction.java =================================================================== --- branches/newstyle-java-types/src/org/python/core/PyReflectedFunction.java 2008-12-01 01:06:33 UTC (rev 5667) +++ branches/newstyle-java-types/src/org/python/core/PyReflectedFunction.java 2008-12-01 01:08:51 UTC (rev 5668) @@ -21,12 +21,16 @@ __name__ = name; } - public PyReflectedFunction(Method method) { - this(method.getName()); - addMethod(method); + public PyReflectedFunction(Method... methods) { + this(methods[0].getName()); + for (Method meth : methods) { + addMethod(meth); + } if (nargs == 0) { String msg = String.format("Attempted to make Java method visible, but it isn't " - + "callable[method=%s, class=%s]", method.getName(), method.getDeclaringClass()); + + "callable[method=%s, class=%s]", + methods[0].getName(), + methods[0].getDeclaringClass()); throw Py.SystemError(msg); } } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <cg...@us...> - 2008-12-02 07:47:28
|
Revision: 5675 http://jython.svn.sourceforge.net/jython/?rev=5675&view=rev Author: cgroves Date: 2008-12-02 07:47:23 +0000 (Tue, 02 Dec 2008) Log Message: ----------- Hook up container methods for Map separately as it isn't actually a Collection. Modified Paths: -------------- branches/newstyle-java-types/Lib/test/test_java_integration.py branches/newstyle-java-types/src/org/python/core/Py.java branches/newstyle-java-types/src/org/python/core/PyJavaType.java branches/newstyle-java-types/src/org/python/core/PyObject.java Modified: branches/newstyle-java-types/Lib/test/test_java_integration.py =================================================================== --- branches/newstyle-java-types/Lib/test/test_java_integration.py 2008-12-02 07:46:14 UTC (rev 5674) +++ branches/newstyle-java-types/Lib/test/test_java_integration.py 2008-12-02 07:47:23 UTC (rev 5675) @@ -6,7 +6,7 @@ from test import test_support from java.awt import (Dimension, Component, Rectangle, Button, Color, HeadlessException) -from java.util import Vector, Hashtable +from java.util import ArrayList, Vector, HashMap, Hashtable from java.io import FileOutputStream, FileWriter, OutputStreamWriter from java.lang import Runnable, Thread, ThreadGroup, System, Runtime, Math, Byte @@ -394,6 +394,37 @@ x = lang.String('test') self.assertRaises(TypeError, list, x) +class JavaDelegationTest(unittest.TestCase): + def test_list_delegation(self): + for c in ArrayList, Vector: + a = c() + a.add("blah") + self.assertTrue("blah" in a) + self.assertEquals(1, len(a)) + n = 0 + for i in a: + n += 1 + self.assertEquals("blah", i) + self.assertEquals(1, n) + self.assertEquals("blah", a[0]) + a[0] = "bleh" + del a[0] + self.assertEquals(0, len(a)) + + def test_map_delegation(self): + m = HashMap() + m["a"] = "b" + self.assertTrue("a" in m) + self.assertEquals("b", m["a"]) + n = 0 + for k in m: + n += 1 + self.assertEquals("a", k) + self.assertEquals(1, n) + del m["a"] + self.assertEquals(0, len(m)) + + def test_main(): test_support.run_unittest(AbstractOnSyspathTest, InstantiationTest, @@ -414,6 +445,7 @@ MethodInvTest, InterfaceTest, JavaStringTest, + JavaDelegationTest, ) if __name__ == "__main__": Modified: branches/newstyle-java-types/src/org/python/core/Py.java =================================================================== --- branches/newstyle-java-types/src/org/python/core/Py.java 2008-12-02 07:46:14 UTC (rev 5674) +++ branches/newstyle-java-types/src/org/python/core/Py.java 2008-12-02 07:47:23 UTC (rev 5675) @@ -90,7 +90,6 @@ BOOTSTRAP_TYPES.add(PyType.class); BOOTSTRAP_TYPES.add(PyBuiltinCallable.class); BOOTSTRAP_TYPES.add(PyDataDescr.class); - BOOTSTRAP_TYPES.add(PyMethodDescr.class); } /** A unique object to indicate no conversion is possible Modified: branches/newstyle-java-types/src/org/python/core/PyJavaType.java =================================================================== --- branches/newstyle-java-types/src/org/python/core/PyJavaType.java 2008-12-02 07:46:14 UTC (rev 5674) +++ branches/newstyle-java-types/src/org/python/core/PyJavaType.java 2008-12-02 07:47:23 UTC (rev 5675) @@ -247,7 +247,7 @@ dict.__setitem__(inner.getSimpleName(), PyType.fromClass(inner)); } for (Map.Entry<Class<?>, PyBuiltinMethod[]> entry : getCollectionProxies().entrySet()) { - if (entry.getKey().isAssignableFrom(underlying_class)) { + if (entry.getKey() == underlying_class) { for (PyBuiltinMethod meth : entry.getValue()) { dict.__setitem__(meth.info.getName(), new PyMethodDescr(this, meth)); } @@ -268,7 +268,7 @@ has_delete = getDescrMethod(underlying_class, "__delete__", PyObject.class) != null || getDescrMethod(underlying_class, "_dodel", PyObject.class) != null; } else { - // Pass __eq__ through to subclasses of Object + // Pass __eq__ and __repr__ through to subclasses of Object PyBuiltinCallable equals = new PyBuiltinMethodNarrow("__eq__", 1, 1) { @Override public PyObject __call__(PyObject o) { @@ -277,6 +277,13 @@ } }; dict.__setitem__("__eq__", new PyMethodDescr(this, equals)); + PyBuiltinCallable repr = new PyBuiltinMethodNarrow("__repr__", 0, 0) { + @Override + public PyObject __call__() { + return Py.newString(self.getJavaProxy().toString()); + } + }; + dict.__setitem__("__repr__", new PyMethodDescr(this, repr)); } } @@ -328,12 +335,12 @@ } } - private static class IteratorIter extends PyIterator { + private static class IterableIter extends PyIterator { private Iterator<Object> proxy; - public IteratorIter(Iterator<Object> proxy) { - this.proxy = proxy; + public IterableIter(Iterable<Object> proxy) { + this.proxy = proxy.iterator(); } public PyObject __iternext__() { @@ -365,6 +372,13 @@ if (collectionProxies == null) { collectionProxies = Generic.map(); + PyBuiltinMethodNarrow iterableProxy = new PyBuiltinMethodNarrow("__iter__", 0, 0) { + public PyObject __call__() { + return new IterableIter(((Iterable)self.getJavaProxy())); + } + }; + collectionProxies.put(Iterable.class, new PyBuiltinMethod[] {iterableProxy}); + PyBuiltinMethodNarrow lenProxy = new PyBuiltinMethodNarrow("__len__", 0, 0) { @Override public PyObject __call__() { @@ -372,13 +386,42 @@ } }; + PyBuiltinMethodNarrow containsProxy = new PyBuiltinMethodNarrow("__contains__", 1, 1) { + @Override + public PyObject __call__(PyObject obj) { + Object other = obj.__tojava__(Object.class); + boolean contained = ((Collection<?>)self.getJavaProxy()).contains(other); + return contained ? Py.True : Py.False; + } + }; + collectionProxies.put(Collection.class, new PyBuiltinMethod[] {lenProxy, + containsProxy}); + + // Map doesn't extend Collection, so it needs its own version of len, iter and contains + PyBuiltinMethodNarrow mapLenProxy = new MapMethod("__len__", 0, 0) { + @Override + public PyObject __call__() { + return Py.java2py(asMap().size()); + } + }; + PyBuiltinMethodNarrow mapIterProxy = new MapMethod("__iter__", 0, 0) { + @Override + public PyObject __call__() { + return new IterableIter(asMap().keySet()); + } + }; + PyBuiltinMethodNarrow mapContainsProxy = new MapMethod("__contains__", 1, 1) { + public PyObject __call__(PyObject obj) { + Object other = obj.__tojava__(Object.class); + return asMap().containsKey(other) ? Py.True : Py.False; + } + }; PyBuiltinMethodNarrow mapGetProxy = new MapMethod("__getitem__", 1, 1) { @Override public PyObject __call__(PyObject key) { return Py.java2py(asMap().get(Py.tojava(key, Object.class))); } }; - PyBuiltinMethodNarrow mapPutProxy = new MapMethod("__setitem__", 2, 2) { @Override public PyObject __call__(PyObject key, PyObject value) { @@ -386,13 +429,18 @@ Py.tojava(value, Object.class))); } }; - PyBuiltinMethodNarrow mapRemoveProxy = new MapMethod("__delitem__", 1, 1) { @Override - public PyObject __call__(PyObject key, PyObject value) { + public PyObject __call__(PyObject key) { return Py.java2py(asMap().remove(Py.tojava(key, Object.class))); } }; + collectionProxies.put(Map.class, new PyBuiltinMethod[] {mapLenProxy, + mapIterProxy, + mapContainsProxy, + mapGetProxy, + mapPutProxy, + mapRemoveProxy}); PyBuiltinMethodNarrow listGetProxy = new ListMethod("__getitem__", 1, 1) { @Override @@ -404,7 +452,6 @@ } } }; - PyBuiltinMethodNarrow listSetProxy = new ListMethod("__setitem__", 2, 2) { @Override public PyObject __call__(PyObject key, PyObject value) { @@ -416,10 +463,9 @@ return Py.None; } }; - PyBuiltinMethodNarrow listRemoveProxy = new ListMethod("__delitem__", 1, 1) { @Override - public PyObject __call__(PyObject key, PyObject value) { + public PyObject __call__(PyObject key) { if (key instanceof PyInteger) { return Py.java2py(asList().remove(((PyInteger)key).getValue())); } else { @@ -427,20 +473,9 @@ } } }; - - PyBuiltinMethodNarrow iterableProxy = new PyBuiltinMethodNarrow("__iter__", 0, 0) { - public PyObject __call__() { - return new IteratorIter(((Iterable)self.getJavaProxy()).iterator()); - } - }; - collectionProxies.put(Iterable.class, new PyBuiltinMethod[] {iterableProxy}); - collectionProxies.put(Collection.class, new PyBuiltinMethod[] {lenProxy}); - collectionProxies.put(Map.class, new PyBuiltinMethod[] {mapGetProxy, - mapPutProxy, - mapRemoveProxy}); collectionProxies.put(List.class, new PyBuiltinMethod[] {listGetProxy, - listSetProxy, - listRemoveProxy}); + listSetProxy, + listRemoveProxy}); } return collectionProxies; } Modified: branches/newstyle-java-types/src/org/python/core/PyObject.java =================================================================== --- branches/newstyle-java-types/src/org/python/core/PyObject.java 2008-12-02 07:46:14 UTC (rev 5674) +++ branches/newstyle-java-types/src/org/python/core/PyObject.java 2008-12-02 07:47:23 UTC (rev 5675) @@ -754,9 +754,9 @@ } /** - * @return an Iterable over the Python iterator returned by __iter__ on this object. If this - * object doesn't support __iter__, a TypeException will be raised when iterator is - * called on the returned Iterable. + * Returns an Iterable over the Python iterator returned by __iter__ on this object. If this + * object doesn't support __iter__, a TypeException will be raised when iterator is called on + * the returned Iterable. */ public Iterable<PyObject> asIterable() { return new Iterable<PyObject>() { This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <cg...@us...> - 2008-12-02 10:54:30
|
Revision: 5676 http://jython.svn.sourceforge.net/jython/?rev=5676&view=rev Author: cgroves Date: 2008-12-02 10:54:26 +0000 (Tue, 02 Dec 2008) Log Message: ----------- Patch #1148 from Geoffrey French. Adds slice and negative index support to get, set and del methods on wrapped instances of java.util.List. Modified Paths: -------------- branches/newstyle-java-types/src/org/python/core/PyArray.java branches/newstyle-java-types/src/org/python/core/PyJavaType.java branches/newstyle-java-types/src/org/python/core/PyList.java branches/newstyle-java-types/src/org/python/core/PySequence.java branches/newstyle-java-types/src/org/python/core/ThreadState.java Added Paths: ----------- branches/newstyle-java-types/Lib/test/test_java_list_delegate.py branches/newstyle-java-types/src/org/python/core/SequenceIndexDelegate.java Added: branches/newstyle-java-types/Lib/test/test_java_list_delegate.py =================================================================== --- branches/newstyle-java-types/Lib/test/test_java_list_delegate.py (rev 0) +++ branches/newstyle-java-types/Lib/test/test_java_list_delegate.py 2008-12-02 10:54:26 UTC (rev 5676) @@ -0,0 +1,181 @@ +from java.util import ArrayList, List, Vector + +from copy import copy + +import unittest +import test.test_support + +class CollectionProxyTest(unittest.TestCase): + def _perform_op(self, value, op_func): + """ + Perform an operation + + value - the value to operate on + op_func - the function that applies the operation to value + + Returns: + the result of calling op_func, OR the exception that was raised in op_func + """ + try: + return op_func(value) + except Exception, e: + return type(e) + + def check_list(self, control, results, initial): + for result in results: + try: + len(result) + except: + print result + self.assertEquals(len(control), len(result), "%s is wrong for %s" % (type(result), initial)) + for pvalue, jvalue in zip(control, result): + self.assertEquals(pvalue, jvalue) + + def _list_op_test(self, initial_value, op_func, check_value): + """ + Tests a list operation + + Ensures that performing an operation on: + - a python list + - a java.util.List instance + + givens the same result in both cases + """ + lists = [list(initial_value), ArrayList(initial_value), Vector(initial_value)] + + results = [self._perform_op(l, op_func) for l in lists] + self.check_list(lists[0], lists[1:], initial_value) + if check_value or not isinstance(results[0], list): + for r in results[1:]: + self.assertEquals(results[0], r) + else: + self.check_list(results[0], results[1:], initial_value) + + def test_get_integer(self): + initial_value = range(0, 5) + + for i in xrange(-7, 7): + self._list_op_test(initial_value, lambda xs: xs[i], True) + + def test_set_integer(self): + initial_value = range(0, 5) + + def make_op_func(index): + def _f(xs): + xs[index] = 100 + return _f + + for i in xrange(-7, 7): + self._list_op_test(initial_value, make_op_func(i), True) + + def test_set_slice(self): + initial_value = range(0, 10) + + def make_op_func(i, j, k, v): + def _f(xs): + xs[i:j:k] = v + return _f + + for i in xrange(-12, 12): + for j in xrange(-12, 12): + for k in xrange(-12, 12): + self._list_op_test(initial_value, make_op_func(i, j, k, []), True) + self._list_op_test(initial_value, make_op_func(i, j, k, range(0,2)), True) + self._list_op_test(initial_value, make_op_func(i, j, k, range(0,4)), True) + self._list_op_test(initial_value, make_op_func(i, j, k, xrange(0,2)), True) + + def test_del_integer(self): + initial_value = range(0,5) + + def make_op_func(index): + def _f(xs): + del xs[index] + return _f + + for i in xrange(-7, 7): + self._list_op_test(initial_value, make_op_func(i), True) + + def test_del_slice(self): + initial_value = range(0,10) + + def make_op_func(i, j, k): + def _f(xs): + del xs[i:j:k] + return _f + + for i in xrange(-12, 12): + for j in xrange(-12, 12): + for k in xrange(-12, 12): + self._list_op_test(initial_value, make_op_func(i, j, k), True) + + def test_len(self): + jlist = ArrayList() + jlist.addAll(range(0, 10)) + + self.assert_(len(jlist) == 10) + + def test_iter(self): + jlist = ArrayList() + jlist.addAll(range(0, 10)) + + i = iter(jlist) + + x = list(i) + + self.assert_(x == range(0, 10)) + + def test_override_len(self): + class MyList (ArrayList): + def __len__(self): + return self.size() + 1; + + m = MyList() + m.addAll(range(0,10)) + + self.assert_(len(m) == 11) + + def test_override_iter(self): + class MyList (ArrayList): + def __iter__(self): + return iter(self.subList(0, self.size() - 1)); + + + m = MyList() + m.addAll(range(0,10)) + i = iter(m) + x = list(i) + + self.assert_(x == range(0, 9)) + + def test_override_getsetdelitem(self): + # Create an ArrayList subclass that provides some silly overrides for get/set/del item + class MyList (ArrayList): + def __getitem__(self, key): + return self.get(key) * 2; + + def __setitem__(self, key, value): + return self.set(key, value * 2); + + def __delitem__(self, key): + self.add(84) + + + m = MyList() + m.addAll(range(0,10)) + + self.assert_(m[1] == 2) + self.assert_(m.get(1) == 1) + + m[0] = 3 + self.assert_(m.get(0) == 6) + self.assert_(m[0] == 12) + + del m[0] + self.assert_(m.size() == 11) + self.assert_(m.get(10) == 84) + +def test_main(): + test.test_support.run_unittest(CollectionProxyTest) + +if __name__ == "__main__": + test_main() Modified: branches/newstyle-java-types/src/org/python/core/PyArray.java =================================================================== --- branches/newstyle-java-types/src/org/python/core/PyArray.java 2008-12-02 07:47:23 UTC (rev 5675) +++ branches/newstyle-java-types/src/org/python/core/PyArray.java 2008-12-02 10:54:26 UTC (rev 5676) @@ -239,10 +239,7 @@ @ExposedMethod(defaults = "null") final void array___setslice__(PyObject start, PyObject stop, PyObject step, PyObject value) { - if(value == null) { - value = step; - step = null; - } + seq___setslice__(start, stop, step, value); } @@ -656,30 +653,15 @@ } /** - * Delete the slice defined by <em>start</em>, <em>stop</em> and - * <em>step</em> from the array. + * Delete the slice defined by <em>start</em> to <em>stop</em> from the array. * * @param start * starting index of slice * @param stop * finishing index of slice - * @param step - * stepping increment between start and stop */ - protected void delRange(int start, int stop, int step) { - if (step == 1) { - delegate.remove(start, stop); - } else if (step > 1) { - for (int i = start; i < stop; i += step) { - delegate.remove(i); - i--; - stop--; - } - } else if (step < 0) { - for (int i = start; i >= 0 && i >= stop; i += step) { - delegate.remove(i); - } - } + protected void delRange(int start, int stop) { + delegate.remove(start, stop); } @ExposedMethod @@ -1198,7 +1180,7 @@ * value to be inserted into array */ public void insert(int index, PyObject value) { - index = calculateIndex(index); + index = boundToSequence(index); if ("u".equals(typecode)) { int codepoint = getCodePoint(value); delegate.makeInsertSpace(index); @@ -1241,7 +1223,7 @@ if (delegate.getSize() == 0) { throw Py.IndexError("pop from empty array"); } - index = fixindex(index); + index = delegator.fixindex(index); if (index == -1) { throw Py.IndexError("pop index out of range"); } Modified: branches/newstyle-java-types/src/org/python/core/PyJavaType.java =================================================================== --- branches/newstyle-java-types/src/org/python/core/PyJavaType.java 2008-12-02 07:47:23 UTC (rev 5675) +++ branches/newstyle-java-types/src/org/python/core/PyJavaType.java 2008-12-02 10:54:26 UTC (rev 5676) @@ -5,6 +5,7 @@ import java.lang.reflect.Member; import java.lang.reflect.Method; import java.lang.reflect.Modifier; +import java.util.ArrayList; import java.util.Collection; import java.util.Enumeration; import java.util.EventListener; @@ -445,32 +446,21 @@ PyBuiltinMethodNarrow listGetProxy = new ListMethod("__getitem__", 1, 1) { @Override public PyObject __call__(PyObject key) { - if (key instanceof PyInteger) { - return Py.java2py(asList().get(((PyInteger)key).getValue())); - } else { - throw Py.TypeError("only integer keys accepted"); - } + return new ListIndexDelegate(asList()).checkIdxAndGetItem(key); } }; PyBuiltinMethodNarrow listSetProxy = new ListMethod("__setitem__", 2, 2) { @Override public PyObject __call__(PyObject key, PyObject value) { - if (key instanceof PyInteger) { - asList().set(((PyInteger)key).getValue(), Py.tojava(value, Object.class)); - } else { - throw Py.TypeError("only integer keys accepted"); - } + new ListIndexDelegate(asList()).checkIdxAndSetItem(key, value); return Py.None; } }; PyBuiltinMethodNarrow listRemoveProxy = new ListMethod("__delitem__", 1, 1) { @Override public PyObject __call__(PyObject key) { - if (key instanceof PyInteger) { - return Py.java2py(asList().remove(((PyInteger)key).getValue())); - } else { - throw Py.TypeError("only integer keys accepted"); - } + new ListIndexDelegate(asList()).checkIdxAndDelItem(key); + return Py.None; } }; collectionProxies.put(List.class, new PyBuiltinMethod[] {listGetProxy, @@ -479,4 +469,86 @@ } return collectionProxies; } + + protected static class ListIndexDelegate extends SequenceIndexDelegate { + + private final List list; + + public ListIndexDelegate(List list) { + this.list = list; + } + @Override + public void delItem(int idx) { + list.remove(idx); + } + + @Override + public PyObject getItem(int idx) { + return Py.java2py(list.get(idx)); + } + + @Override + public PyObject getSlice(int start, int stop, int step) { + if (step > 0 && stop < start) { + stop = start; + } + int n = PySequence.sliceLength(start, stop, step); + List<Object> newList; + try { + newList = list.getClass().newInstance(); + } catch (Exception e) { + throw Py.JavaError(e); + } + int j = 0; + for (int i = start; j < n; i += step) { + newList.add(list.get(i)); + } + return Py.java2py(newList); + } + + @Override + public String getTypeName() { + return list.getClass().getName(); + } + + @Override + public int len() { + return list.size(); + } + + @Override + public void setItem(int idx, PyObject value) { + list.set(idx, value.__tojava__(Object.class)); + } + + @Override + public void setSlice(int start, int stop, int step, PyObject value) { + if (stop < start) { + stop = start; + } + if (step == 0) { + return; + } + if (value.javaProxy == this) { + List newseq = new ArrayList(len()); + for (Object object : ((List)value.javaProxy)) { + newseq.add(object); + } + value = Py.java2py(newseq); + } + int j = start; + for (PyObject obj : value.asIterable()) { + setItem(j, obj); + j += step; + } + } + + @Override + public void delItems(int start, int stop) { + int n = stop - start; + while (n-- > 0) { + delItem(start); + } + } + } } Modified: branches/newstyle-java-types/src/org/python/core/PyList.java =================================================================== --- branches/newstyle-java-types/src/org/python/core/PyList.java 2008-12-02 07:47:23 UTC (rev 5675) +++ branches/newstyle-java-types/src/org/python/core/PyList.java 2008-12-02 10:54:26 UTC (rev 5676) @@ -49,9 +49,9 @@ append(item); } } - + private static List<PyObject> listify(Iterator<PyObject> iter) { - final List<PyObject> list = new LinkedList<PyObject>(); + final List<PyObject> list = new LinkedList<PyObject>(); while (iter.hasNext()) { list.add(iter.next()); } @@ -112,20 +112,8 @@ remove(i); } - protected void delRange(int start, int stop, int step) { - if(step == 1) { - remove(start, stop); - } else if(step > 1) { - for(int i = start; i < stop; i += step) { - remove(i); - i--; - stop--; - } - } else if(step < 0) { - for(int i = start; i >= 0 && i >= stop; i += step) { - remove(i); - } - } + protected void delRange(int start, int stop) { + remove(start, stop); } protected void set(int i, PyObject value) { @@ -164,13 +152,7 @@ otherArray = otherArray.clone(); } list.replaceSubArray(start, stop, otherArray, 0, n); - } else if(step > 1) { - int n = value.__len__(); - for(int i = 0, j = 0; i < n; i++, j += step) { - list.pyset(j + start, value.pyget(i)); - } - } else if(step < 0) { - int n = value.__len__(); + } else if(step != 0) { if(value == this) { PyList newseq = new PyList(); PyObject iter = value.__iter__(); @@ -179,7 +161,8 @@ } value = newseq; } - for(int i = 0, j = list.size() - 1; i < n; i++, j += step) { + int n = value.__len__(); + for (int i = 0, j = start; i < n; i++, j += step) { list.pyset(j, value.pyget(i)); } } @@ -289,7 +272,7 @@ System.arraycopy(array, 0, array, i * size, size); } gListAllocatedStatus = __len__(); - return this; + return this; } @Override @@ -409,10 +392,6 @@ @ExposedMethod(defaults = "null") final void list___setslice__(PyObject start, PyObject stop, PyObject step, PyObject value) { - if(value == null) { - value = step; - step = null; - } seq___setslice__(start, stop, step, value); } @@ -455,7 +434,7 @@ /** * Add a single element to the end of list. - * + * * @param o * the element to add. */ @@ -471,7 +450,7 @@ /** * Return the number elements in the list that equals the argument. - * + * * @param o * the argument to test for. Testing is done with the <code>==</code> operator. */ @@ -493,7 +472,7 @@ /** * return smallest index where an element in the list equals the argument. - * + * * @param o * the argument to test for. Testing is done with the <code>==</code> operator. */ @@ -530,8 +509,8 @@ private int _index(PyObject o, String message, int start, int stop) { // Follow Python 2.3+ behavior - int validStop = calculateIndex(stop); - int validStart = calculateIndex(start); + int validStop = boundToSequence(stop); + int validStart = boundToSequence(start); PyObject[] array = getArray(); for(int i = validStart; i < validStop && i < size(); i++) { if(array[i].equals(o)) { @@ -544,7 +523,7 @@ /** * Insert the argument element into the list at the specified index. <br> * Same as <code>s[index:index] = [o] if index >= 0</code>. - * + * * @param index * the position where the element will be inserted. * @param o @@ -570,7 +549,7 @@ * Remove the first occurence of the argument from the list. The elements arecompared with the * <code>==</code> operator. <br> * Same as <code>del s[s.index(x)]</code> - * + * * @param o * the element to search for and remove. */ @@ -616,7 +595,7 @@ /** * Removes and return the <code>n</code> indexed element in the list. - * + * * @param n * the index of the element to remove and return. */ @@ -644,7 +623,7 @@ /** * Append the elements in the argument sequence to the end of the list. <br> * Same as <code>s[len(s):len(s)] = o</code>. - * + * * @param o * the sequence of items to append to the list. */ @@ -691,11 +670,11 @@ * the sorting process down considerably; e.g. to sort a list in reverse order it is much faster * to use calls to the methods sort() and reverse() than to use the built-in function sort() * with a comparison function that reverses the ordering of the elements. - * + * * @param compare * the comparison function. */ - + /** * Sort the items of the list in place. Items is compared with the normal relative comparison * operators. @@ -723,7 +702,7 @@ MergeState ms = new MergeState(this, cmp, key, reverse.__nonzero__()); ms.sort(); } - + public int hashCode() { return list___hash__(); } Modified: branches/newstyle-java-types/src/org/python/core/PySequence.java =================================================================== --- branches/newstyle-java-types/src/org/python/core/PySequence.java 2008-12-02 07:47:23 UTC (rev 5675) +++ branches/newstyle-java-types/src/org/python/core/PySequence.java 2008-12-02 10:54:26 UTC (rev 5676) @@ -80,9 +80,10 @@ getType().fastGetName())); } - protected void delRange(int start, int stop, int step) { + protected void delRange(int start, int stop) { throw Py.TypeError(String.format("'%s' object does not support item deletion", getType().fastGetName())); + } public boolean __nonzero__() { @@ -244,20 +245,11 @@ return ret; } - protected int fixindex(int index) { - int l = __len__(); - if(index < 0) { - index += l; - } - if(index < 0 || index >= l) { - return -1; - } else { - return index; - } - } - - // XXX: more appropriate naming of this vs fixindex - protected int calculateIndex(int index) { + /** + * 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) { index = index += length; @@ -275,12 +267,7 @@ } final synchronized PyObject seq___finditem__(int index) { - index = fixindex(index); - if(index == -1) { - return null; - } else { - return pyget(index); - } + return delegator.checkIdxAndFindItem(index); } public PyObject __finditem__(PyObject index) { @@ -288,14 +275,7 @@ } final PyObject seq___finditem__(PyObject index) { - if (index.isIndex()) { - return seq___finditem__(index.asIndex(Py.IndexError)); - } else if (index instanceof PySlice) { - PySlice s = (PySlice)index; - return seq___getslice__(s.start, s.stop, s.step); - } else { - throw Py.TypeError(getType().fastGetName() + " indices must be integers"); - } + return delegator.checkIdxAndFindItem(index); } public PyObject __getitem__(PyObject index) { @@ -303,11 +283,7 @@ } final PyObject seq___getitem__(PyObject index) { - PyObject ret = __finditem__(index); - if(ret == null) { - throw Py.IndexError("index out of range: " + index); - } - return ret; + return delegator.checkIdxAndGetItem(index); } public boolean isMappingType() throws PyIgnoreMethodTag { @@ -322,13 +298,8 @@ return seq___getslice__(start, stop, step); } - final synchronized PyObject seq___getslice__(PyObject start, PyObject stop) { - return seq___getslice__(start, stop, null); - } - final synchronized PyObject seq___getslice__(PyObject start, PyObject stop, PyObject step) { - int[] indices = new PySlice(start, stop, step).indicesEx(__len__()); - return getslice(indices[0], indices[1], indices[2]); + return delegator.getSlice(new PySlice(start, stop, step)); } public synchronized void __setslice__(PyObject start, @@ -338,21 +309,15 @@ seq___setslice__(start, stop, step, value); } - final synchronized void seq___setslice__(PyObject start, PyObject stop, PyObject value) { - seq___setslice__(start, stop, null, value); - } - final synchronized void seq___setslice__(PyObject start, PyObject stop, PyObject step, PyObject value) { - PySlice slice = new PySlice(start, stop, step); - int[] indices = slice.indicesEx(__len__()); - if ((slice.step != Py.None) && value.__len__() != indices[3]) { - throw Py.ValueError(String.format("attempt to assign sequence of size %d to extended " - + "slice of size %d", value.__len__(), indices[3])); + if (value == null) { + value = step; + step = null; } - setslice(indices[0], indices[1], indices[2], value); + delegator.checkIdxAndSetSlice(new PySlice(start, stop, step), value); } public synchronized void __delslice__(PyObject start, PyObject stop, PyObject step) { @@ -360,35 +325,19 @@ } final synchronized void seq___delslice__(PyObject start, PyObject stop, PyObject step) { - int[] indices = new PySlice(start, stop, step).indicesEx(__len__()); - delRange(indices[0], indices[1], indices[2]); + delegator.checkIdxAndDelItem(new PySlice(start, stop, step)); } public synchronized void __setitem__(int index, PyObject value) { - seq___setitem__(index, value); + delegator.checkIdxAndSetItem(index, value); } - final synchronized void seq___setitem__(int index, PyObject value) { - int i = fixindex(index); - if(i == -1) { - throw Py.IndexError(getType().fastGetName() + " assignment index out of range"); - } - set(i, value); - } - public void __setitem__(PyObject index, PyObject value) { seq___setitem__(index, value); } final void seq___setitem__(PyObject index, PyObject value) { - if (index.isIndex()) { - seq___setitem__(index.asIndex(Py.IndexError), value); - } else if (index instanceof PySlice) { - PySlice s = (PySlice)index; - seq___setslice__(s.start, s.stop, s.step, value); - } else { - throw Py.TypeError(getType().fastGetName() + " indices must be integers"); - } + delegator.checkIdxAndSetItem(index, value); } public synchronized void __delitem__(PyObject index) { @@ -396,18 +345,7 @@ } final synchronized void seq___delitem__(PyObject index) { - if (index.isIndex()) { - int i = fixindex(index.asIndex(Py.IndexError)); - if (i == -1) { - throw Py.IndexError(getType().fastGetName() + " assignment index out of range"); - } - del(i); - } else if (index instanceof PySlice) { - PySlice s = (PySlice)index; - seq___delslice__(s.start, s.stop, s.step); - } else { - throw Py.TypeError(getType().fastGetName() + " indices must be integers"); - } + delegator.checkIdxAndDelItem(index); } public synchronized Object __tojava__(Class c) throws PyIgnoreMethodTag { @@ -451,4 +389,48 @@ } return null; } + + protected final SequenceIndexDelegate delegator = new SequenceIndexDelegate() { + + @Override + public String getTypeName() { + return getType().fastGetName(); + } + + @Override + public void setItem(int idx, PyObject value) { + set(idx, value); + } + + @Override + public void setSlice(int start, int stop, int step, PyObject value) { + setslice(start, stop, step, value); + } + + @Override + public int len() { + return __len__(); + } + + @Override + public void delItem(int idx) { + del(idx); + } + + @Override + public void delItems(int start, int stop) { + delRange(start, stop); + } + + + @Override + public PyObject getItem(int idx) { + return pyget(idx); + } + + @Override + public PyObject getSlice(int start, int stop, int step) { + return getslice(start, stop, step); + } + }; } Added: branches/newstyle-java-types/src/org/python/core/SequenceIndexDelegate.java =================================================================== --- branches/newstyle-java-types/src/org/python/core/SequenceIndexDelegate.java (rev 0) +++ branches/newstyle-java-types/src/org/python/core/SequenceIndexDelegate.java 2008-12-02 10:54:26 UTC (rev 5676) @@ -0,0 +1,127 @@ +package org.python.core; + +/** + * Handles all the index checking and manipulation for get, set and del operations on a sequence. + */ +public abstract class SequenceIndexDelegate { + + public abstract int len(); + + public abstract PyObject getItem(int idx); + + public abstract void setItem(int idx, PyObject value); + + public abstract void delItem(int idx); + + public abstract PyObject getSlice(int start, int stop, int step); + + public abstract void setSlice(int start, int stop, int step, PyObject value); + + public abstract void delItems(int start, int stop); + + public abstract String getTypeName(); + + public void checkIdxAndSetItem(PyObject idx, PyObject value) { + if (idx.isIndex()) { + checkIdxAndSetItem(idx.asIndex(Py.IndexError), value); + } else if (idx instanceof PySlice) { + checkIdxAndSetSlice((PySlice)idx, value); + } else { + throw Py.TypeError(getTypeName() + " indices must be integers"); + } + } + + public void checkIdxAndSetSlice(PySlice slice, PyObject value) { + int[] indices = slice.indicesEx(len()); + if ((slice.step != Py.None) && value.__len__() != indices[3]) { + throw Py.ValueError(String.format("attempt to assign sequence of size %d to extended " + + "slice of size %d", value.__len__(), indices[3])); + } + setSlice(indices[0], indices[1], indices[2], value); + } + + public void checkIdxAndSetItem(int idx, PyObject value) { + setItem(checkIdx(idx), value); + } + + public void checkIdxAndDelItem(PyObject idx) { + if (idx.isIndex()) { + delItem(checkIdx(idx.asIndex(Py.IndexError))); + } else if (idx instanceof PySlice) { + int[] indices = ((PySlice)idx).indicesEx(len()); + delSlice(indices[0], indices[1], indices[2]); + } else { + throw Py.TypeError(getTypeName() + " indices must be integers"); + } + } + + public PyObject checkIdxAndGetItem(PyObject idx) { + PyObject res = checkIdxAndFindItem(idx); + if (res == null) { + throw Py.IndexError("index out of range: " + idx); + } + return res; + } + + public PyObject checkIdxAndFindItem(PyObject idx) { + if (idx.isIndex()) { + return checkIdxAndFindItem(idx.asIndex(Py.IndexError)); + } else if (idx instanceof PySlice) { + return getSlice((PySlice)idx); + } else { + throw Py.TypeError(getTypeName() + " indices must be integers"); + } + } + + public PyObject getSlice(PySlice slice) { + int[] indices = slice.indicesEx(len()); + return getSlice(indices[0], indices[1], indices[2]); + } + + public PyObject checkIdxAndFindItem(int idx) { + idx = fixindex(idx); + if(idx == -1) { + return null; + } else { + return getItem(idx); + } + } + + private int checkIdx(int idx) { + int i = fixindex(idx); + if (i == -1) { + throw Py.IndexError(getTypeName() + " assignment index out of range"); + } + return i; + } + + int fixindex(int index) { + int l = len(); + if(index < 0) { + index += l; + } + if(index < 0 || index >= l) { + return -1; + } else { + return index; + } + } + + private void delSlice(int start, int stop, int step) { + if(step == 1) { + if (stop > start) { + delItems(start, stop); + } + } else if(step > 1) { + for(int i = start; i < stop; i += step) { + delItem(i); + i--; + stop--; + } + } else if(step < 0) { + for(int i = start; i >= 0 && i >= stop; i += step) { + delItem(i); + } + } + } +} \ No newline at end of file Modified: branches/newstyle-java-types/src/org/python/core/ThreadState.java =================================================================== --- branches/newstyle-java-types/src/org/python/core/ThreadState.java 2008-12-02 07:47:23 UTC (rev 5675) +++ branches/newstyle-java-types/src/org/python/core/ThreadState.java 2008-12-02 10:54:26 UTC (rev 5676) @@ -75,7 +75,7 @@ } for (int i = reprStack.size() - 1; i >= 0; i--) { if (reprStack.pyget(i) == obj) { - reprStack.delRange(i, reprStack.size(), 1); + reprStack.delRange(i, reprStack.size()); } } } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <cg...@us...> - 2008-12-04 02:30:38
|
Revision: 5692 http://jython.svn.sourceforge.net/jython/?rev=5692&view=rev Author: cgroves Date: 2008-12-04 02:30:34 +0000 (Thu, 04 Dec 2008) Log Message: ----------- Leave ExposedType annotations on processed types so they'll be visible at runtime. Use that to detect exposed inner classes in classes being loaded. Inner classes being loaded won't have set their builder in PyType yet, so they need to be added to BOOTSTRAP_TYPES so they're created as PyType instead of PyJavaType. Modified Paths: -------------- branches/newstyle-java-types/src/org/python/core/PyJavaType.java branches/newstyle-java-types/src/org/python/expose/generate/ExposedTypeProcessor.java branches/newstyle-java-types/src/org/python/expose/generate/ExposedTypeVisitor.java branches/newstyle-java-types/src/org/python/modules/_hashlib.java branches/newstyle-java-types/tests/java/org/python/expose/generate/ExposedTypeVisitorTest.java Modified: branches/newstyle-java-types/src/org/python/core/PyJavaType.java =================================================================== --- branches/newstyle-java-types/src/org/python/core/PyJavaType.java 2008-12-04 02:20:28 UTC (rev 5691) +++ branches/newstyle-java-types/src/org/python/core/PyJavaType.java 2008-12-04 02:30:34 UTC (rev 5692) @@ -16,6 +16,7 @@ import org.python.core.util.StringUtil; import org.python.expose.ExposeAsSuperclass; +import org.python.expose.ExposedType; import org.python.util.Generic; public class PyJavaType extends PyType implements ExposeAsSuperclass { @@ -245,8 +246,17 @@ dict.__setitem__("__init__", reflctr); } for (Class<?> inner : underlying_class.getClasses()) { - // Only add the class if there isn't something else with that name - if (dict.__finditem__(inner.getSimpleName()) == null) { + // Only add the class if there isn't something else with that name and it came from this + // class + if (inner.getDeclaringClass() == underlying_class && + dict.__finditem__(inner.getSimpleName()) == null) { + // If this class is currently being loaded, any exposed types it contains won't have + // set their builder in PyType yet, so add them to BOOTSTRAP_TYPES so they're + // created as PyType instead of PyJavaType + if (inner.getAnnotation(ExposedType.class) != null + || ExposeAsSuperclass.class.isAssignableFrom(inner)) { + Py.BOOTSTRAP_TYPES.add(inner); + } dict.__setitem__(inner.getSimpleName(), PyType.fromClass(inner)); } } Modified: branches/newstyle-java-types/src/org/python/expose/generate/ExposedTypeProcessor.java =================================================================== --- branches/newstyle-java-types/src/org/python/expose/generate/ExposedTypeProcessor.java 2008-12-04 02:20:28 UTC (rev 5691) +++ branches/newstyle-java-types/src/org/python/expose/generate/ExposedTypeProcessor.java 2008-12-04 02:30:34 UTC (rev 5692) @@ -130,8 +130,9 @@ @Override public AnnotationVisitor visitAnnotation(String desc, boolean visible) { + AnnotationVisitor visitor = super.visitAnnotation(desc, visible); if(desc.equals(EXPOSED_TYPE.getDescriptor())) { - return new ExposedTypeVisitor(onType) { + return new ExposedTypeVisitor(onType, visitor) { @Override public void handleResult(String name) { @@ -148,7 +149,7 @@ } }; } - return super.visitAnnotation(desc, visible); + return visitor; } private void throwInvalid(String msg) { Modified: branches/newstyle-java-types/src/org/python/expose/generate/ExposedTypeVisitor.java =================================================================== --- branches/newstyle-java-types/src/org/python/expose/generate/ExposedTypeVisitor.java 2008-12-04 02:20:28 UTC (rev 5691) +++ branches/newstyle-java-types/src/org/python/expose/generate/ExposedTypeVisitor.java 2008-12-04 02:30:34 UTC (rev 5692) @@ -1,5 +1,6 @@ package org.python.expose.generate; +import org.python.objectweb.asm.AnnotationVisitor; import org.python.objectweb.asm.Type; /** @@ -15,8 +16,11 @@ private boolean isBaseType = true; - public ExposedTypeVisitor(Type onType) { + private final AnnotationVisitor passthrough; + + public ExposedTypeVisitor(Type onType, AnnotationVisitor passthrough) { this.onType = onType; + this.passthrough = passthrough; } @Override @@ -30,6 +34,9 @@ } else { super.visit(name, value); } + if (passthrough != null) { + passthrough.visit(name, value); + } } @Override @@ -41,6 +48,9 @@ handleResult(typeName); handleResult(base); handleResult(isBaseType); + if (passthrough != null) { + passthrough.visitEnd(); + } } public abstract void handleResult(Type base); Modified: branches/newstyle-java-types/src/org/python/modules/_hashlib.java =================================================================== --- branches/newstyle-java-types/src/org/python/modules/_hashlib.java 2008-12-04 02:20:28 UTC (rev 5691) +++ branches/newstyle-java-types/src/org/python/modules/_hashlib.java 2008-12-04 02:30:34 UTC (rev 5692) @@ -121,16 +121,18 @@ put("sha-512", 128); }}; - public Hash(String name) { - super(TYPE); - this.name = name; + private static final MessageDigest getDigest(String name) { try { - digest = MessageDigest.getInstance(name); + return MessageDigest.getInstance(name); } catch (NoSuchAlgorithmException nsae) { throw Py.ValueError("unsupported hash type"); } } + public Hash(String name) { + this(name, getDigest(name)); + } + private Hash(String name, MessageDigest digest) { super(TYPE); this.name = name; @@ -192,10 +194,10 @@ // Make hex version of the digest char[] hexDigest = new char[result.length * 2]; for (int i = 0, j = 0; i < result.length; i++) { - int c = (int)((result[i] >> 4) & 0xf); + int c = ((result[i] >> 4) & 0xf); c = c > 9 ? c + 'a' - 10 : c + '0'; hexDigest[j++] = (char)c; - c = (int)result[i] & 0xf; + c = result[i] & 0xf; c = c > 9 ? c + 'a' - 10 : c + '0'; hexDigest[j++] = (char)c; } Modified: branches/newstyle-java-types/tests/java/org/python/expose/generate/ExposedTypeVisitorTest.java =================================================================== --- branches/newstyle-java-types/tests/java/org/python/expose/generate/ExposedTypeVisitorTest.java 2008-12-04 02:20:28 UTC (rev 5691) +++ branches/newstyle-java-types/tests/java/org/python/expose/generate/ExposedTypeVisitorTest.java 2008-12-04 02:30:34 UTC (rev 5692) @@ -9,7 +9,7 @@ public class ExposedTypeVisitorTest extends TestCase { public void setUp() { - etv = new ExposedTypeVisitor(Type.getType("Lsimpletype;")) { + etv = new ExposedTypeVisitor(Type.getType("Lsimpletype;"), null) { @Override public void handleResult(String name) { @@ -47,7 +47,7 @@ ExposedTypeVisitor etv; private String result; - + private Type baseResult; private boolean isBaseTypeResult; This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <cg...@us...> - 2008-12-05 04:06:27
|
Revision: 5698 http://jython.svn.sourceforge.net/jython/?rev=5698&view=rev Author: cgroves Date: 2008-12-05 04:06:23 +0000 (Fri, 05 Dec 2008) Log Message: ----------- Get test_jy_internals passing again Modified Paths: -------------- branches/newstyle-java-types/Lib/test/test_jy_internals.py branches/newstyle-java-types/src/org/python/core/IdImpl.java Modified: branches/newstyle-java-types/Lib/test/test_jy_internals.py =================================================================== --- branches/newstyle-java-types/Lib/test/test_jy_internals.py 2008-12-05 03:33:30 UTC (rev 5697) +++ branches/newstyle-java-types/Lib/test/test_jy_internals.py 2008-12-05 04:06:23 UTC (rev 5698) @@ -60,7 +60,7 @@ iarr = java.lang.Object.getClass(self.e) sdv = java.lang.Class.getMethod(long, 'scaledDoubleValue', [iarr]) import org.python.core.PyReflectedFunction as ReflFunc - self.sdv = ReflFunc(sdv) + self.sdv = ReflFunc([sdv]) def test_basic_roundtrip(self): e = self.e Modified: branches/newstyle-java-types/src/org/python/core/IdImpl.java =================================================================== --- branches/newstyle-java-types/src/org/python/core/IdImpl.java 2008-12-05 03:33:30 UTC (rev 5697) +++ branches/newstyle-java-types/src/org/python/core/IdImpl.java 2008-12-05 04:06:23 UTC (rev 5698) @@ -43,6 +43,11 @@ } } + // Used by test_jy_internals + public int _internal_map_size() { + return objHashcodeToPyId.size(); + } + public void put(Object key, Object val) { cleanup(); objHashcodeToPyId.put(new WeakIdKey(key), val); This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <cg...@us...> - 2008-12-05 11:21:59
|
Revision: 5700 http://jython.svn.sourceforge.net/jython/?rev=5700&view=rev Author: cgroves Date: 2008-12-05 11:21:55 +0000 (Fri, 05 Dec 2008) Log Message: ----------- Make methods from superclasses and superinterfaces of private, protected or package protected classes call through their parent versions. Fixes blowups with a package protected implementation of attributes in sax. Modified Paths: -------------- branches/newstyle-java-types/Lib/test/test_java_visibility.py branches/newstyle-java-types/src/org/python/core/PyJavaType.java Added Paths: ----------- branches/newstyle-java-types/tests/java/org/python/tests/InterfaceCombination.java Modified: branches/newstyle-java-types/Lib/test/test_java_visibility.py =================================================================== --- branches/newstyle-java-types/Lib/test/test_java_visibility.py 2008-12-05 09:06:12 UTC (rev 5699) +++ branches/newstyle-java-types/Lib/test/test_java_visibility.py 2008-12-05 11:21:55 UTC (rev 5700) @@ -1,6 +1,6 @@ import unittest from test import test_support -from org.python.tests import Invisible, SubVisible, Visible, VisibleOverride +from org.python.tests import InterfaceCombination, Invisible, SubVisible, Visible, VisibleOverride from org.python.tests import VisibilityResults as Results class VisibilityTest(unittest.TestCase): @@ -67,6 +67,21 @@ self.failUnless('visibleInstance' in c.__dict__, 'visibleInstance expected in %s __dict__' % c) + def test_interface_combination(self): + '''Checks that a private class that extends a public class and public interfaces has only the items + from the public bases visible''' + i = InterfaceCombination.newImplementation() + self.assertEquals(InterfaceCombination.NO_ARG_RESULT, i.getValue(), + "methods from IFace should be visible on Implementation") + self.assertEquals(InterfaceCombination.ONE_ARG_RESULT, i.getValue("one arg"), + "methods from IIFace should be visible on Implementation") + self.assertEquals(InterfaceCombination.TWO_ARG_RESULT, i.getValue("one arg", "two arg"), + "methods from Base should be visible on Implementation") + self.assertRaises(TypeError, i.getValue, "one arg", "two arg", "three arg", + "methods defined solely on Implementation shouldn't be visible") + self.assertFalse(hasattr(i, "internalMethod"), + "methods from private interfaces shouldn't be visible on a private class") + def test_main(): test_support.run_unittest(VisibilityTest) Modified: branches/newstyle-java-types/src/org/python/core/PyJavaType.java =================================================================== --- branches/newstyle-java-types/src/org/python/core/PyJavaType.java 2008-12-05 09:06:12 UTC (rev 5699) +++ branches/newstyle-java-types/src/org/python/core/PyJavaType.java 2008-12-05 11:21:55 UTC (rev 5700) @@ -83,6 +83,7 @@ // org.python.core if (!Modifier.isPublic(underlying_class.getModifiers()) && !name.startsWith("org.python.core")) { + handleSuperMethodArgCollisions(); return; } @@ -308,6 +309,59 @@ } } + /** + * Private, protected or package protected classes that implement public interfaces or extend + * public classes can't have their implementations of the methods of their supertypes called + * through reflection due to Sun VM bug 4071957(http://tinyurl.com/le9vo). They can be called + * through the supertype version of the method though. Unfortunately we can't just let normal + * mro lookup of those methods handle routing the call to the correct version as a class can + * implement interfaces or classes that each have methods with the same name that takes + * different number or types of arguments. Instead this method goes through all interfaces + * implemented by this class, and combines same-named methods into a single PyReflectedFunction. + * + * Prior to Jython 2.5, this was handled in PyJavaClass.setMethods by setting methods in package + * protected classes accessible which made them callable through reflection. That had the + * drawback of failing when running in a security environment that didn't allow setting + * accessibility, so this method replaced it. + */ + private void handleSuperMethodArgCollisions() { + for (Class iface : underlying_class.getInterfaces()) { + for (Method meth : iface.getMethods()) { + String nmethname = normalize(meth.getName()); + PyObject[] where = new PyObject[1]; + PyObject obj = lookup_where(nmethname, where); + if (obj == null) { + // Nothing in our supertype hierarchy defines something with this name, so it + // must not be visible there. + continue; + } else if (where[0] == this) { + // This method is the only thing defining items in this class' dict, so it must + // be a PyReflectedFunction created here. See if it needs the current method + // added to it. + if (!((PyReflectedFunction)obj).handles(meth)) { + ((PyReflectedFunction)obj).addMethod(meth); + } + } else { + // There's something in a superclass with the same name. If this class extends a + // class and doesn't just implement something, the extended class is first in + // mro, so items defined on the extended class will show up here. Thanks to that + // and copying the base function, we can get away with just looping over + // interface methods. + PyReflectedFunction func; + if (obj instanceof PyReflectedFunction) { + func = ((PyReflectedFunction)obj).copy(); + if (!func.handles(meth)) { + func.addMethod(meth); + } + } else { + func = new PyReflectedFunction(meth); + } + dict.__setitem__(nmethname, func); + } + } + } + } + private static boolean declaredOnMember(Class<?> base, Member declaring) { return base == null || (declaring.getDeclaringClass() != base && base.isAssignableFrom(declaring.getDeclaringClass())); Added: branches/newstyle-java-types/tests/java/org/python/tests/InterfaceCombination.java =================================================================== --- branches/newstyle-java-types/tests/java/org/python/tests/InterfaceCombination.java (rev 0) +++ branches/newstyle-java-types/tests/java/org/python/tests/InterfaceCombination.java 2008-12-05 11:21:55 UTC (rev 5700) @@ -0,0 +1,49 @@ +package org.python.tests; + +public class InterfaceCombination { + + public static final String NO_ARG_RESULT = "no_arg_result"; + + public static final String ONE_ARG_RESULT = "one_arg_result"; + + public static final String TWO_ARG_RESULT = "two_arg_result"; + + public interface IFace { + String getValue(); + } + + public interface IIFace { + String getValue(String name); + } + + interface Hidden { + void internalMethod(); + } + + public static class Base { + public String getValue(String one, String two) { + return TWO_ARG_RESULT; + } + } + + private static class Implementation extends Base implements IFace, IIFace, Hidden { + + public String getValue(String one, String two, String three) { + return three; + } + + public String getValue() { + return NO_ARG_RESULT; + } + + public String getValue(String name) { + return ONE_ARG_RESULT; + } + + public void internalMethod() {} + } + + public static Object newImplementation() { + return new Implementation(); + } +} This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <cg...@us...> - 2008-12-06 03:01:21
|
Revision: 5707 http://jython.svn.sourceforge.net/jython/?rev=5707&view=rev Author: cgroves Date: 2008-12-06 03:01:16 +0000 (Sat, 06 Dec 2008) Log Message: ----------- Tidying Modified Paths: -------------- branches/newstyle-java-types/Lib/test/jser2_classes.py branches/newstyle-java-types/Lib/test/test_jser2.py branches/newstyle-java-types/src/org/python/util/PythonObjectInputStream.java branches/newstyle-java-types/tests/java/org/python/util/InterpreterTest.java Property Changed: ---------------- branches/newstyle-java-types/Lib/test/jser2_classes.py branches/newstyle-java-types/Lib/test/test_jser2.py Modified: branches/newstyle-java-types/Lib/test/jser2_classes.py =================================================================== (Binary files differ) Property changes on: branches/newstyle-java-types/Lib/test/jser2_classes.py ___________________________________________________________________ Deleted: svn:mime-type - application/octet-stream Modified: branches/newstyle-java-types/Lib/test/test_jser2.py =================================================================== (Binary files differ) Property changes on: branches/newstyle-java-types/Lib/test/test_jser2.py ___________________________________________________________________ Deleted: svn:mime-type - application/octet-stream Modified: branches/newstyle-java-types/src/org/python/util/PythonObjectInputStream.java =================================================================== --- branches/newstyle-java-types/src/org/python/util/PythonObjectInputStream.java 2008-12-06 02:49:45 UTC (rev 5706) +++ branches/newstyle-java-types/src/org/python/util/PythonObjectInputStream.java 2008-12-06 03:01:16 UTC (rev 5707) @@ -1,52 +1,53 @@ // Copyright 2000 Finn Bock - package org.python.util; -import java.io.*; -import org.python.core.*; +import java.io.IOException; +import java.io.InputStream; +import java.io.ObjectInputStream; +import java.io.ObjectStreamClass; +import org.python.core.Py; +import org.python.core.PyObject; +import org.python.core.PyTuple; +import org.python.core.__builtin__; + public class PythonObjectInputStream extends ObjectInputStream { + public PythonObjectInputStream(InputStream istr) throws IOException { super(istr); } - protected Class resolveClass(ObjectStreamClass v) - throws IOException, ClassNotFoundException { + protected Class<?> resolveClass(ObjectStreamClass v) throws IOException, ClassNotFoundException { String clsName = v.getName(); - //System.out.println(clsName); if (clsName.startsWith("org.python.proxies")) { int idx = clsName.lastIndexOf('$'); - if (idx > 19) - clsName = clsName.substring(19, idx); - //System.out.println("new:" + clsName); - + if (idx > 19) { + clsName = clsName.substring(19, idx); + } idx = clsName.indexOf('$'); if (idx >= 0) { String mod = clsName.substring(0, idx); - clsName = clsName.substring(idx+1); - + clsName = clsName.substring(idx + 1); PyObject module = importModule(mod); PyObject pycls = module.__getattr__(clsName.intern()); Object cls = pycls.__tojava__(Class.class); - - if (cls != null && cls != Py.NoConversion) - return (Class) cls; + if (cls != null && cls != Py.NoConversion) { + return (Class<?>)cls; + } } } try { return super.resolveClass(v); } catch (ClassNotFoundException exc) { PyObject m = importModule(clsName); - //System.out.println("m:" + m); Object cls = m.__tojava__(Class.class); - //System.out.println("cls:" + cls); - if (cls != null && cls != Py.NoConversion) - return (Class) cls; + if (cls != null && cls != Py.NoConversion) { + return (Class<?>)cls; + } throw exc; } } - private static PyObject importModule(String name) { PyObject fromlist = new PyTuple(Py.newString("__doc__")); return __builtin__.__import__(name, null, null, fromlist); Modified: branches/newstyle-java-types/tests/java/org/python/util/InterpreterTest.java =================================================================== --- branches/newstyle-java-types/tests/java/org/python/util/InterpreterTest.java 2008-12-06 02:49:45 UTC (rev 5706) +++ branches/newstyle-java-types/tests/java/org/python/util/InterpreterTest.java 2008-12-06 03:01:16 UTC (rev 5707) @@ -2,8 +2,9 @@ import junit.framework.TestCase; -import org.python.core.*; -import org.python.util.*; +import org.python.core.PyDictionary; +import org.python.core.PyObject; +import org.python.core.PyUnicode; public class InterpreterTest extends TestCase { @@ -13,8 +14,7 @@ public void testBasicEval() throws Exception { PyDictionary test = new PyDictionary(); test.__setitem__(new PyUnicode("one"), new PyUnicode("two")); - PythonInterpreter.initialize(System.getProperties(), null, new -String[] {}); + PythonInterpreter.initialize(System.getProperties(), null, new String[] {}); PythonInterpreter interp = new PythonInterpreter(); PyObject pyo = interp.eval("{u'one': u'two'}"); assertEquals(test, pyo); This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <cg...@us...> - 2008-12-06 04:23:49
|
Revision: 5710 http://jython.svn.sourceforge.net/jython/?rev=5710&view=rev Author: cgroves Date: 2008-12-06 04:23:45 +0000 (Sat, 06 Dec 2008) Log Message: ----------- Fix deserializing Jython objects while not in Python code. __builtin__.__import__ was changed to bail if Py.getFrame was null, but it can be called from Java code as in PyObjectInputStream, so it should just use PySystemState.builtins if it doesn't have a set of builtins from the frame. Modified Paths: -------------- branches/newstyle-java-types/src/org/python/core/__builtin__.java Added Paths: ----------- branches/newstyle-java-types/tests/java/org/python/tests/SerializationTest.java Modified: branches/newstyle-java-types/src/org/python/core/__builtin__.java =================================================================== --- branches/newstyle-java-types/src/org/python/core/__builtin__.java 2008-12-06 04:19:46 UTC (rev 5709) +++ branches/newstyle-java-types/src/org/python/core/__builtin__.java 2008-12-06 04:23:45 UTC (rev 5710) @@ -1221,11 +1221,10 @@ public static PyObject __import__(String name, PyObject globals, PyObject locals, PyObject fromlist, int level) { PyFrame frame = Py.getFrame(); - if (frame == null) { - return null; - } - PyObject builtins = frame.f_builtins; - if (builtins == null) { + PyObject builtins; + if (frame != null && frame.f_builtins != null) { + builtins = frame.f_builtins; + } else { builtins = PySystemState.builtins; } Added: branches/newstyle-java-types/tests/java/org/python/tests/SerializationTest.java =================================================================== --- branches/newstyle-java-types/tests/java/org/python/tests/SerializationTest.java (rev 0) +++ branches/newstyle-java-types/tests/java/org/python/tests/SerializationTest.java 2008-12-06 04:23:45 UTC (rev 5710) @@ -0,0 +1,37 @@ +package org.python.tests; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.ObjectOutputStream; + +import junit.framework.TestCase; + +import org.python.core.PyStringMap; +import org.python.core.PySystemState; +import org.python.util.PythonInterpreter; +import org.python.util.PythonObjectInputStream; + +public class SerializationTest extends TestCase { + + private PythonInterpreter interp; + + @Override + protected void setUp() throws Exception { + interp = new PythonInterpreter(new PyStringMap(), new PySystemState()); + interp.exec("from java.io import Serializable"); + interp.exec("class Test(Serializable): pass"); + interp.exec("x = Test()"); + } + + public void testDirect() throws IOException, ClassNotFoundException { + ByteArrayOutputStream os = new ByteArrayOutputStream(); + new ObjectOutputStream(os).writeObject(interp.get("x")); + new PythonObjectInputStream(new ByteArrayInputStream(os.toByteArray())).readObject(); + } + + public void testJython() { + interp.set("t", this); + interp.exec("t.testDirect()"); + } +} This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <cg...@us...> - 2008-12-10 08:24:02
|
Revision: 5732 http://jython.svn.sourceforge.net/jython/?rev=5732&view=rev Author: cgroves Date: 2008-12-10 08:23:53 +0000 (Wed, 10 Dec 2008) Log Message: ----------- Merged revisions 5670,5680-5682,5687,5691,5695-5697,5702-5704,5706,5712-5726 via svnmerge from https://jython.svn.sourceforge.net/svnroot/jython/trunk/jython I removed a bunch of unused imports of PyJavaInstance in the ast code and ripped out all the collection updates as they landed separately in PyJavaType. ........ r5670 | nriley | 2008-12-01 10:33:00 -0800 (Mon, 01 Dec 2008) | 1 line PyStringMap should not be hashable, just as PyDictionary isn't. ........ r5680 | otmarhumbel | 2008-12-03 01:30:15 -0800 (Wed, 03 Dec 2008) | 5 lines prevent JYTHON_OPTS from being enriched with arguments (this could lead to an infinite recursion of subprocesses) test_subprocess_jy.py now passes issue #1187 is fixed now ........ r5681 | nriley | 2008-12-03 01:39:46 -0800 (Wed, 03 Dec 2008) | 1 line --print option for start script ........ r5682 | otmarhumbel | 2008-12-03 06:43:11 -0800 (Wed, 03 Dec 2008) | 1 line added tests for issue #1187 ........ r5687 | nriley | 2008-12-03 14:08:15 -0800 (Wed, 03 Dec 2008) | 1 line avoid test_asynchat on Windows too; refs #1064 ........ r5691 | fwierzbicki | 2008-12-03 18:20:28 -0800 (Wed, 03 Dec 2008) | 3 lines Initialized merge tracking via "svnmerge" with revisions "1-5585" from https://jython.svn.sourceforge.net/svnroot/jython/branches/astwrite ........ r5695 | fwierzbicki | 2008-12-04 17:10:49 -0800 (Thu, 04 Dec 2008) | 13 lines Merging the astwrite branch into trunk. While I was testing, I noticed some problems stemming from the package names and the "Type" at the end of some of the asdl_antlr.py generated code -- so I fixed that up as well. This checkin changes all of the access on ast nodes to be getters and setters with Lists instead of arrays. The ast nodes also now descend from PyObject instead of Antlr's CommonTree. There are new adapter classes that handle the back and forth of ast nodes from Java to Python. Merged revisions 5586-5592,5594-5595,5597,5612,5628,5633-5634,5636-5637,5641-5643,5660,5672,5677-5679,5683,5685-5686 via svnmerge from https://jython.svn.sourceforge.net/svnroot/jython/branches/astwrite ........ r5696 | fwierzbicki | 2008-12-04 17:11:47 -0800 (Thu, 04 Dec 2008) | 2 lines Ack missed these new files for the astwrite merge. ........ r5697 | fwierzbicki | 2008-12-04 19:33:30 -0800 (Thu, 04 Dec 2008) | 2 lines Fix missing exposed classes. ........ r5702 | fwierzbicki | 2008-12-05 06:26:10 -0800 (Fri, 05 Dec 2008) | 2 lines Derived classes for org/python/antlr/ast/* ........ r5703 | fwierzbicki | 2008-12-05 08:10:15 -0800 (Fri, 05 Dec 2008) | 2 lines org/python/antlr/op/* Derived classes, and fixed lineno, col_offset from ast_antlr.py ........ r5704 | nriley | 2008-12-05 10:43:33 -0800 (Fri, 05 Dec 2008) | 1 line avoid test_asynchat on Solaris (everywhere but Linux?); refs #1064 ........ r5706 | fwierzbicki | 2008-12-05 18:49:45 -0800 (Fri, 05 Dec 2008) | 3 lines Added better lineno and col_offset support to a couple of ast nodes, also finished slice support in AstList. ........ r5712 | pjenvey | 2008-12-05 22:52:28 -0800 (Fri, 05 Dec 2008) | 4 lines o fix str/unicode add/join to decode when appropriate o fix '%r' % u'' returning unicode o cast fastSequence to a PySequence ........ r5713 | pjenvey | 2008-12-05 22:55:48 -0800 (Fri, 05 Dec 2008) | 1 line correct mismatch between partition/rpartition and their exposed versions ........ r5714 | pjenvey | 2008-12-06 01:02:53 -0800 (Sat, 06 Dec 2008) | 1 line revert the astlist workaround as it subclasses list now ........ r5715 | fwierzbicki | 2008-12-06 07:00:08 -0800 (Sat, 06 Dec 2008) | 5 lines Now able to use the exact copy of CPython's ast.py Copied from: http://svn.python.org/projects/python/branches/release26-maint/Lib/ast.py ........ r5716 | otmarhumbel | 2008-12-06 13:44:53 -0800 (Sat, 06 Dec 2008) | 2 lines fork the biggest javac task this hopefully enables hudson's build ........ r5717 | otmarhumbel | 2008-12-06 14:14:43 -0800 (Sat, 06 Dec 2008) | 1 line javac ignores the optimize option, according to http://ant.apache.org/manual/ ........ r5718 | nriley | 2008-12-06 14:50:19 -0800 (Sat, 06 Dec 2008) | 1 line Java 6 javac on Mac OS X requires more memory to compile Jython ........ r5719 | fwierzbicki | 2008-12-06 20:15:26 -0800 (Sat, 06 Dec 2008) | 2 lines Fixed bugs in mutable ast revealed by running sympy tests. ........ r5720 | nriley | 2008-12-06 22:35:04 -0800 (Sat, 06 Dec 2008) | 1 line Java 6 javac on x64 Linux requires even more memory to compile Jython ........ r5721 | fwierzbicki | 2008-12-07 10:57:27 -0800 (Sun, 07 Dec 2008) | 2 lines A couple more missed adaptations revealed by sympy testing. ........ r5722 | pjenvey | 2008-12-08 11:44:12 -0800 (Mon, 08 Dec 2008) | 2 lines use hex idstrs (without any padding) to more closely resemble CPython ........ r5723 | pjenvey | 2008-12-09 00:45:33 -0800 (Tue, 09 Dec 2008) | 3 lines avoid an NPE when getSQLState is null thanks Matthew Harrison ........ r5724 | pjenvey | 2008-12-09 13:56:51 -0800 (Tue, 09 Dec 2008) | 8 lines o allow overriding of ExceptionHandler's inline finally block o fix the with statement's normal finally/exit block so it also happens for non local gotos (e.g. return, continue) o modify test_with instead of adding test_with_jy to test for this case -- the lack of these tests is really a test bug IMO fixes #1194 pointed out by Terrence Cole ........ r5725 | pjenvey | 2008-12-09 14:25:56 -0800 (Tue, 09 Dec 2008) | 1 line these are no longer used ........ r5726 | pjenvey | 2008-12-09 16:07:22 -0800 (Tue, 09 Dec 2008) | 4 lines match CPython's dir() more closely fixes #1196 pointed out by doublep ........ Modified Paths: -------------- branches/newstyle-java-types/CoreExposed.includes branches/newstyle-java-types/Lib/ast.py branches/newstyle-java-types/Lib/inspect.py branches/newstyle-java-types/Lib/test/test_ast.py branches/newstyle-java-types/Lib/test/test_asynchat.py branches/newstyle-java-types/Lib/test/test_builtin_jy.py branches/newstyle-java-types/Lib/test/test_stringmap.py branches/newstyle-java-types/Lib/test/test_subprocess_jy.py branches/newstyle-java-types/Lib/test/test_unicode_jy.py branches/newstyle-java-types/Lib/test/test_with.py branches/newstyle-java-types/ast/Python.asdl branches/newstyle-java-types/ast/asdl_antlr.py branches/newstyle-java-types/build.xml branches/newstyle-java-types/grammar/Python.g branches/newstyle-java-types/src/com/ziclix/python/sql/zxJDBC.java branches/newstyle-java-types/src/org/python/antlr/AST.java branches/newstyle-java-types/src/org/python/antlr/ErrorHandler.java branches/newstyle-java-types/src/org/python/antlr/ExpressionParser.java branches/newstyle-java-types/src/org/python/antlr/FailFastHandler.java branches/newstyle-java-types/src/org/python/antlr/GrammarActions.java branches/newstyle-java-types/src/org/python/antlr/InteractiveParser.java branches/newstyle-java-types/src/org/python/antlr/ListErrorHandler.java branches/newstyle-java-types/src/org/python/antlr/ModuleParser.java branches/newstyle-java-types/src/org/python/antlr/PythonTree.java branches/newstyle-java-types/src/org/python/antlr/ast/Assert.java branches/newstyle-java-types/src/org/python/antlr/ast/Assign.java branches/newstyle-java-types/src/org/python/antlr/ast/Attribute.java branches/newstyle-java-types/src/org/python/antlr/ast/AugAssign.java branches/newstyle-java-types/src/org/python/antlr/ast/BinOp.java branches/newstyle-java-types/src/org/python/antlr/ast/BoolOp.java branches/newstyle-java-types/src/org/python/antlr/ast/Break.java branches/newstyle-java-types/src/org/python/antlr/ast/Call.java branches/newstyle-java-types/src/org/python/antlr/ast/ClassDef.java branches/newstyle-java-types/src/org/python/antlr/ast/Compare.java branches/newstyle-java-types/src/org/python/antlr/ast/Continue.java branches/newstyle-java-types/src/org/python/antlr/ast/Delete.java branches/newstyle-java-types/src/org/python/antlr/ast/Dict.java branches/newstyle-java-types/src/org/python/antlr/ast/Ellipsis.java branches/newstyle-java-types/src/org/python/antlr/ast/ErrorExpr.java branches/newstyle-java-types/src/org/python/antlr/ast/ErrorMod.java branches/newstyle-java-types/src/org/python/antlr/ast/ErrorSlice.java branches/newstyle-java-types/src/org/python/antlr/ast/ErrorStmt.java branches/newstyle-java-types/src/org/python/antlr/ast/Exec.java branches/newstyle-java-types/src/org/python/antlr/ast/Expr.java branches/newstyle-java-types/src/org/python/antlr/ast/Expression.java branches/newstyle-java-types/src/org/python/antlr/ast/ExtSlice.java branches/newstyle-java-types/src/org/python/antlr/ast/For.java branches/newstyle-java-types/src/org/python/antlr/ast/FunctionDef.java branches/newstyle-java-types/src/org/python/antlr/ast/GeneratorExp.java branches/newstyle-java-types/src/org/python/antlr/ast/Global.java branches/newstyle-java-types/src/org/python/antlr/ast/If.java branches/newstyle-java-types/src/org/python/antlr/ast/IfExp.java branches/newstyle-java-types/src/org/python/antlr/ast/Import.java branches/newstyle-java-types/src/org/python/antlr/ast/ImportFrom.java branches/newstyle-java-types/src/org/python/antlr/ast/Index.java branches/newstyle-java-types/src/org/python/antlr/ast/Interactive.java branches/newstyle-java-types/src/org/python/antlr/ast/Lambda.java branches/newstyle-java-types/src/org/python/antlr/ast/List.java branches/newstyle-java-types/src/org/python/antlr/ast/ListComp.java branches/newstyle-java-types/src/org/python/antlr/ast/Module.java branches/newstyle-java-types/src/org/python/antlr/ast/Name.java branches/newstyle-java-types/src/org/python/antlr/ast/Num.java branches/newstyle-java-types/src/org/python/antlr/ast/Pass.java branches/newstyle-java-types/src/org/python/antlr/ast/Print.java branches/newstyle-java-types/src/org/python/antlr/ast/Raise.java branches/newstyle-java-types/src/org/python/antlr/ast/Repr.java branches/newstyle-java-types/src/org/python/antlr/ast/Return.java branches/newstyle-java-types/src/org/python/antlr/ast/Slice.java branches/newstyle-java-types/src/org/python/antlr/ast/Str.java branches/newstyle-java-types/src/org/python/antlr/ast/Subscript.java branches/newstyle-java-types/src/org/python/antlr/ast/Suite.java branches/newstyle-java-types/src/org/python/antlr/ast/TryExcept.java branches/newstyle-java-types/src/org/python/antlr/ast/TryFinally.java branches/newstyle-java-types/src/org/python/antlr/ast/Tuple.java branches/newstyle-java-types/src/org/python/antlr/ast/UnaryOp.java branches/newstyle-java-types/src/org/python/antlr/ast/VisitorBase.java branches/newstyle-java-types/src/org/python/antlr/ast/VisitorIF.java branches/newstyle-java-types/src/org/python/antlr/ast/While.java branches/newstyle-java-types/src/org/python/antlr/ast/With.java branches/newstyle-java-types/src/org/python/antlr/ast/Yield.java branches/newstyle-java-types/src/org/python/antlr/ast/boolopType.java branches/newstyle-java-types/src/org/python/antlr/ast/cmpopType.java branches/newstyle-java-types/src/org/python/antlr/ast/expr_contextType.java branches/newstyle-java-types/src/org/python/antlr/ast/operatorType.java branches/newstyle-java-types/src/org/python/antlr/ast/unaryopType.java branches/newstyle-java-types/src/org/python/compiler/ArgListCompiler.java branches/newstyle-java-types/src/org/python/compiler/CodeCompiler.java branches/newstyle-java-types/src/org/python/compiler/Future.java branches/newstyle-java-types/src/org/python/compiler/Module.java branches/newstyle-java-types/src/org/python/compiler/ProxyMaker.java branches/newstyle-java-types/src/org/python/compiler/ScopeInfo.java branches/newstyle-java-types/src/org/python/compiler/ScopesCompiler.java branches/newstyle-java-types/src/org/python/core/AbstractArray.java branches/newstyle-java-types/src/org/python/core/IdImpl.java branches/newstyle-java-types/src/org/python/core/ParserFacade.java branches/newstyle-java-types/src/org/python/core/Py.java branches/newstyle-java-types/src/org/python/core/PyClass.java branches/newstyle-java-types/src/org/python/core/PyInstance.java branches/newstyle-java-types/src/org/python/core/PyList.java branches/newstyle-java-types/src/org/python/core/PyObject.java branches/newstyle-java-types/src/org/python/core/PySequence.java branches/newstyle-java-types/src/org/python/core/PyString.java branches/newstyle-java-types/src/org/python/core/PyStringMap.java branches/newstyle-java-types/src/org/python/core/PyType.java branches/newstyle-java-types/src/org/python/core/PyUnicode.java branches/newstyle-java-types/src/org/python/core/__builtin__.java branches/newstyle-java-types/src/org/python/core/imp.java branches/newstyle-java-types/src/org/python/modules/Setup.java branches/newstyle-java-types/src/shell/jython branches/newstyle-java-types/src/shell/jython.bat branches/newstyle-java-types/src/templates/mappings Added Paths: ----------- branches/newstyle-java-types/src/org/python/antlr/adapter/ branches/newstyle-java-types/src/org/python/antlr/adapter/AliasAdapter.java branches/newstyle-java-types/src/org/python/antlr/adapter/AstAdapter.java branches/newstyle-java-types/src/org/python/antlr/adapter/AstAdapters.java branches/newstyle-java-types/src/org/python/antlr/adapter/CmpopAdapter.java branches/newstyle-java-types/src/org/python/antlr/adapter/ComprehensionAdapter.java branches/newstyle-java-types/src/org/python/antlr/adapter/ExcepthandlerAdapter.java branches/newstyle-java-types/src/org/python/antlr/adapter/ExprAdapter.java branches/newstyle-java-types/src/org/python/antlr/adapter/IdentifierAdapter.java branches/newstyle-java-types/src/org/python/antlr/adapter/KeywordAdapter.java branches/newstyle-java-types/src/org/python/antlr/adapter/SliceAdapter.java branches/newstyle-java-types/src/org/python/antlr/adapter/StmtAdapter.java branches/newstyle-java-types/src/org/python/antlr/ast/AssertDerived.java branches/newstyle-java-types/src/org/python/antlr/ast/AssignDerived.java branches/newstyle-java-types/src/org/python/antlr/ast/AstModule.java branches/newstyle-java-types/src/org/python/antlr/ast/AttributeDerived.java branches/newstyle-java-types/src/org/python/antlr/ast/AugAssignDerived.java branches/newstyle-java-types/src/org/python/antlr/ast/BinOpDerived.java branches/newstyle-java-types/src/org/python/antlr/ast/BoolOpDerived.java branches/newstyle-java-types/src/org/python/antlr/ast/BreakDerived.java branches/newstyle-java-types/src/org/python/antlr/ast/CallDerived.java branches/newstyle-java-types/src/org/python/antlr/ast/ClassDefDerived.java branches/newstyle-java-types/src/org/python/antlr/ast/CompareDerived.java branches/newstyle-java-types/src/org/python/antlr/ast/ContinueDerived.java branches/newstyle-java-types/src/org/python/antlr/ast/DeleteDerived.java branches/newstyle-java-types/src/org/python/antlr/ast/DictDerived.java branches/newstyle-java-types/src/org/python/antlr/ast/EllipsisDerived.java branches/newstyle-java-types/src/org/python/antlr/ast/ExceptHandler.java branches/newstyle-java-types/src/org/python/antlr/ast/ExceptHandlerDerived.java branches/newstyle-java-types/src/org/python/antlr/ast/ExecDerived.java branches/newstyle-java-types/src/org/python/antlr/ast/ExprDerived.java branches/newstyle-java-types/src/org/python/antlr/ast/ExpressionDerived.java branches/newstyle-java-types/src/org/python/antlr/ast/ExtSliceDerived.java branches/newstyle-java-types/src/org/python/antlr/ast/ForDerived.java branches/newstyle-java-types/src/org/python/antlr/ast/FunctionDefDerived.java branches/newstyle-java-types/src/org/python/antlr/ast/GeneratorExpDerived.java branches/newstyle-java-types/src/org/python/antlr/ast/GlobalDerived.java branches/newstyle-java-types/src/org/python/antlr/ast/IfDerived.java branches/newstyle-java-types/src/org/python/antlr/ast/IfExpDerived.java branches/newstyle-java-types/src/org/python/antlr/ast/ImportDerived.java branches/newstyle-java-types/src/org/python/antlr/ast/ImportFromDerived.java branches/newstyle-java-types/src/org/python/antlr/ast/IndexDerived.java branches/newstyle-java-types/src/org/python/antlr/ast/InteractiveDerived.java branches/newstyle-java-types/src/org/python/antlr/ast/LambdaDerived.java branches/newstyle-java-types/src/org/python/antlr/ast/ListCompDerived.java branches/newstyle-java-types/src/org/python/antlr/ast/ListDerived.java branches/newstyle-java-types/src/org/python/antlr/ast/ModuleDerived.java branches/newstyle-java-types/src/org/python/antlr/ast/NameDerived.java branches/newstyle-java-types/src/org/python/antlr/ast/NumDerived.java branches/newstyle-java-types/src/org/python/antlr/ast/PassDerived.java branches/newstyle-java-types/src/org/python/antlr/ast/PrintDerived.java branches/newstyle-java-types/src/org/python/antlr/ast/RaiseDerived.java branches/newstyle-java-types/src/org/python/antlr/ast/ReprDerived.java branches/newstyle-java-types/src/org/python/antlr/ast/ReturnDerived.java branches/newstyle-java-types/src/org/python/antlr/ast/SliceDerived.java branches/newstyle-java-types/src/org/python/antlr/ast/StrDerived.java branches/newstyle-java-types/src/org/python/antlr/ast/SubscriptDerived.java branches/newstyle-java-types/src/org/python/antlr/ast/SuiteDerived.java branches/newstyle-java-types/src/org/python/antlr/ast/TryExceptDerived.java branches/newstyle-java-types/src/org/python/antlr/ast/TryFinallyDerived.java branches/newstyle-java-types/src/org/python/antlr/ast/TupleDerived.java branches/newstyle-java-types/src/org/python/antlr/ast/UnaryOpDerived.java branches/newstyle-java-types/src/org/python/antlr/ast/WhileDerived.java branches/newstyle-java-types/src/org/python/antlr/ast/WithDerived.java branches/newstyle-java-types/src/org/python/antlr/ast/YieldDerived.java branches/newstyle-java-types/src/org/python/antlr/ast/alias.java branches/newstyle-java-types/src/org/python/antlr/ast/aliasDerived.java branches/newstyle-java-types/src/org/python/antlr/ast/arguments.java branches/newstyle-java-types/src/org/python/antlr/ast/argumentsDerived.java branches/newstyle-java-types/src/org/python/antlr/ast/comprehension.java branches/newstyle-java-types/src/org/python/antlr/ast/comprehensionDerived.java branches/newstyle-java-types/src/org/python/antlr/ast/keyword.java branches/newstyle-java-types/src/org/python/antlr/ast/keywordDerived.java branches/newstyle-java-types/src/org/python/antlr/base/ branches/newstyle-java-types/src/org/python/antlr/base/excepthandler.java branches/newstyle-java-types/src/org/python/antlr/base/expr.java branches/newstyle-java-types/src/org/python/antlr/base/mod.java branches/newstyle-java-types/src/org/python/antlr/base/slice.java branches/newstyle-java-types/src/org/python/antlr/base/stmt.java branches/newstyle-java-types/src/org/python/antlr/op/ branches/newstyle-java-types/src/org/python/antlr/op/Add.java branches/newstyle-java-types/src/org/python/antlr/op/AddDerived.java branches/newstyle-java-types/src/org/python/antlr/op/And.java branches/newstyle-java-types/src/org/python/antlr/op/AndDerived.java branches/newstyle-java-types/src/org/python/antlr/op/AugLoad.java branches/newstyle-java-types/src/org/python/antlr/op/AugLoadDerived.java branches/newstyle-java-types/src/org/python/antlr/op/AugStore.java branches/newstyle-java-types/src/org/python/antlr/op/AugStoreDerived.java branches/newstyle-java-types/src/org/python/antlr/op/BitAnd.java branches/newstyle-java-types/src/org/python/antlr/op/BitAndDerived.java branches/newstyle-java-types/src/org/python/antlr/op/BitOr.java branches/newstyle-java-types/src/org/python/antlr/op/BitOrDerived.java branches/newstyle-java-types/src/org/python/antlr/op/BitXor.java branches/newstyle-java-types/src/org/python/antlr/op/BitXorDerived.java branches/newstyle-java-types/src/org/python/antlr/op/Del.java branches/newstyle-java-types/src/org/python/antlr/op/DelDerived.java branches/newstyle-java-types/src/org/python/antlr/op/Div.java branches/newstyle-java-types/src/org/python/antlr/op/DivDerived.java branches/newstyle-java-types/src/org/python/antlr/op/Eq.java branches/newstyle-java-types/src/org/python/antlr/op/EqDerived.java branches/newstyle-java-types/src/org/python/antlr/op/FloorDiv.java branches/newstyle-java-types/src/org/python/antlr/op/FloorDivDerived.java branches/newstyle-java-types/src/org/python/antlr/op/Gt.java branches/newstyle-java-types/src/org/python/antlr/op/GtDerived.java branches/newstyle-java-types/src/org/python/antlr/op/GtE.java branches/newstyle-java-types/src/org/python/antlr/op/GtEDerived.java branches/newstyle-java-types/src/org/python/antlr/op/In.java branches/newstyle-java-types/src/org/python/antlr/op/InDerived.java branches/newstyle-java-types/src/org/python/antlr/op/Invert.java branches/newstyle-java-types/src/org/python/antlr/op/InvertDerived.java branches/newstyle-java-types/src/org/python/antlr/op/Is.java branches/newstyle-java-types/src/org/python/antlr/op/IsDerived.java branches/newstyle-java-types/src/org/python/antlr/op/IsNot.java branches/newstyle-java-types/src/org/python/antlr/op/IsNotDerived.java branches/newstyle-java-types/src/org/python/antlr/op/LShift.java branches/newstyle-java-types/src/org/python/antlr/op/LShiftDerived.java branches/newstyle-java-types/src/org/python/antlr/op/Load.java branches/newstyle-java-types/src/org/python/antlr/op/LoadDerived.java branches/newstyle-java-types/src/org/python/antlr/op/Lt.java branches/newstyle-java-types/src/org/python/antlr/op/LtDerived.java branches/newstyle-java-types/src/org/python/antlr/op/LtE.java branches/newstyle-java-types/src/org/python/antlr/op/LtEDerived.java branches/newstyle-java-types/src/org/python/antlr/op/Mod.java branches/newstyle-java-types/src/org/python/antlr/op/ModDerived.java branches/newstyle-java-types/src/org/python/antlr/op/Mult.java branches/newstyle-java-types/src/org/python/antlr/op/MultDerived.java branches/newstyle-java-types/src/org/python/antlr/op/Not.java branches/newstyle-java-types/src/org/python/antlr/op/NotDerived.java branches/newstyle-java-types/src/org/python/antlr/op/NotEq.java branches/newstyle-java-types/src/org/python/antlr/op/NotEqDerived.java branches/newstyle-java-types/src/org/python/antlr/op/NotIn.java branches/newstyle-java-types/src/org/python/antlr/op/NotInDerived.java branches/newstyle-java-types/src/org/python/antlr/op/Or.java branches/newstyle-java-types/src/org/python/antlr/op/OrDerived.java branches/newstyle-java-types/src/org/python/antlr/op/Param.java branches/newstyle-java-types/src/org/python/antlr/op/ParamDerived.java branches/newstyle-java-types/src/org/python/antlr/op/Pow.java branches/newstyle-java-types/src/org/python/antlr/op/PowDerived.java branches/newstyle-java-types/src/org/python/antlr/op/RShift.java branches/newstyle-java-types/src/org/python/antlr/op/RShiftDerived.java branches/newstyle-java-types/src/org/python/antlr/op/Store.java branches/newstyle-java-types/src/org/python/antlr/op/StoreDerived.java branches/newstyle-java-types/src/org/python/antlr/op/Sub.java branches/newstyle-java-types/src/org/python/antlr/op/SubDerived.java branches/newstyle-java-types/src/org/python/antlr/op/UAdd.java branches/newstyle-java-types/src/org/python/antlr/op/UAddDerived.java branches/newstyle-java-types/src/org/python/antlr/op/USub.java branches/newstyle-java-types/src/org/python/antlr/op/USubDerived.java branches/newstyle-java-types/src/org/python/core/AstList.java branches/newstyle-java-types/src/templates/ast_Assert.derived branches/newstyle-java-types/src/templates/ast_Assign.derived branches/newstyle-java-types/src/templates/ast_Attribute.derived branches/newstyle-java-types/src/templates/ast_AugAssign.derived branches/newstyle-java-types/src/templates/ast_BinOp.derived branches/newstyle-java-types/src/templates/ast_BoolOp.derived branches/newstyle-java-types/src/templates/ast_Break.derived branches/newstyle-java-types/src/templates/ast_Call.derived branches/newstyle-java-types/src/templates/ast_ClassDef.derived branches/newstyle-java-types/src/templates/ast_Compare.derived branches/newstyle-java-types/src/templates/ast_Continue.derived branches/newstyle-java-types/src/templates/ast_Delete.derived branches/newstyle-java-types/src/templates/ast_Dict.derived branches/newstyle-java-types/src/templates/ast_Ellipsis.derived branches/newstyle-java-types/src/templates/ast_ExceptHandler.derived branches/newstyle-java-types/src/templates/ast_Exec.derived branches/newstyle-java-types/src/templates/ast_Expr.derived branches/newstyle-java-types/src/templates/ast_Expression.derived branches/newstyle-java-types/src/templates/ast_ExtSlice.derived branches/newstyle-java-types/src/templates/ast_For.derived branches/newstyle-java-types/src/templates/ast_FunctionDef.derived branches/newstyle-java-types/src/templates/ast_GeneratorExp.derived branches/newstyle-java-types/src/templates/ast_Global.derived branches/newstyle-java-types/src/templates/ast_If.derived branches/newstyle-java-types/src/templates/ast_IfExp.derived branches/newstyle-java-types/src/templates/ast_Import.derived branches/newstyle-java-types/src/templates/ast_ImportFrom.derived branches/newstyle-java-types/src/templates/ast_Index.derived branches/newstyle-java-types/src/templates/ast_Interactive.derived branches/newstyle-java-types/src/templates/ast_Lambda.derived branches/newstyle-java-types/src/templates/ast_List.derived branches/newstyle-java-types/src/templates/ast_ListComp.derived branches/newstyle-java-types/src/templates/ast_Module.derived branches/newstyle-java-types/src/templates/ast_Name.derived branches/newstyle-java-types/src/templates/ast_Num.derived branches/newstyle-java-types/src/templates/ast_Pass.derived branches/newstyle-java-types/src/templates/ast_Print.derived branches/newstyle-java-types/src/templates/ast_Raise.derived branches/newstyle-java-types/src/templates/ast_Repr.derived branches/newstyle-java-types/src/templates/ast_Return.derived branches/newstyle-java-types/src/templates/ast_Slice.derived branches/newstyle-java-types/src/templates/ast_Str.derived branches/newstyle-java-types/src/templates/ast_Subscript.derived branches/newstyle-java-types/src/templates/ast_Suite.derived branches/newstyle-java-types/src/templates/ast_TryExcept.derived branches/newstyle-java-types/src/templates/ast_TryFinally.derived branches/newstyle-java-types/src/templates/ast_Tuple.derived branches/newstyle-java-types/src/templates/ast_UnaryOp.derived branches/newstyle-java-types/src/templates/ast_While.derived branches/newstyle-java-types/src/templates/ast_With.derived branches/newstyle-java-types/src/templates/ast_Yield.derived branches/newstyle-java-types/src/templates/ast_alias.derived branches/newstyle-java-types/src/templates/ast_arguments.derived branches/newstyle-java-types/src/templates/ast_comprehension.derived branches/newstyle-java-types/src/templates/ast_keyword.derived branches/newstyle-java-types/src/templates/op_Add.derived branches/newstyle-java-types/src/templates/op_And.derived branches/newstyle-java-types/src/templates/op_AugLoad.derived branches/newstyle-java-types/src/templates/op_AugStore.derived branches/newstyle-java-types/src/templates/op_BitAnd.derived branches/newstyle-java-types/src/templates/op_BitOr.derived branches/newstyle-java-types/src/templates/op_BitXor.derived branches/newstyle-java-types/src/templates/op_Del.derived branches/newstyle-java-types/src/templates/op_Div.derived branches/newstyle-java-types/src/templates/op_Eq.derived branches/newstyle-java-types/src/templates/op_FloorDiv.derived branches/newstyle-java-types/src/templates/op_Gt.derived branches/newstyle-java-types/src/templates/op_GtE.derived branches/newstyle-java-types/src/templates/op_In.derived branches/newstyle-java-types/src/templates/op_Invert.derived branches/newstyle-java-types/src/templates/op_Is.derived branches/newstyle-java-types/src/templates/op_IsNot.derived branches/newstyle-java-types/src/templates/op_LShift.derived branches/newstyle-java-types/src/templates/op_Load.derived branches/newstyle-java-types/src/templates/op_Lt.derived branches/newstyle-java-types/src/templates/op_LtE.derived branches/newstyle-java-types/src/templates/op_Mod.derived branches/newstyle-java-types/src/templates/op_Mult.derived branches/newstyle-java-types/src/templates/op_Not.derived branches/newstyle-java-types/src/templates/op_NotEq.derived branches/newstyle-java-types/src/templates/op_NotIn.derived branches/newstyle-java-types/src/templates/op_Or.derived branches/newstyle-java-types/src/templates/op_Param.derived branches/newstyle-java-types/src/templates/op_Pow.derived branches/newstyle-java-types/src/templates/op_RShift.derived branches/newstyle-java-types/src/templates/op_Store.derived branches/newstyle-java-types/src/templates/op_Sub.derived branches/newstyle-java-types/src/templates/op_UAdd.derived branches/newstyle-java-types/src/templates/op_USub.derived Removed Paths: ------------- branches/newstyle-java-types/Lib/_ast.py branches/newstyle-java-types/src/org/python/antlr/adapter/AliasAdapter.java branches/newstyle-java-types/src/org/python/antlr/adapter/AstAdapter.java branches/newstyle-java-types/src/org/python/antlr/adapter/AstAdapters.java branches/newstyle-java-types/src/org/python/antlr/adapter/CmpopAdapter.java branches/newstyle-java-types/src/org/python/antlr/adapter/ComprehensionAdapter.java branches/newstyle-java-types/src/org/python/antlr/adapter/ExcepthandlerAdapter.java branches/newstyle-java-types/src/org/python/antlr/adapter/ExprAdapter.java branches/newstyle-java-types/src/org/python/antlr/adapter/IdentifierAdapter.java branches/newstyle-java-types/src/org/python/antlr/adapter/KeywordAdapter.java branches/newstyle-java-types/src/org/python/antlr/adapter/SliceAdapter.java branches/newstyle-java-types/src/org/python/antlr/adapter/StmtAdapter.java branches/newstyle-java-types/src/org/python/antlr/ast/aliasType.java branches/newstyle-java-types/src/org/python/antlr/ast/argumentsType.java branches/newstyle-java-types/src/org/python/antlr/ast/comprehensionType.java branches/newstyle-java-types/src/org/python/antlr/ast/excepthandlerType.java branches/newstyle-java-types/src/org/python/antlr/ast/exprType.java branches/newstyle-java-types/src/org/python/antlr/ast/keywordType.java branches/newstyle-java-types/src/org/python/antlr/ast/modType.java branches/newstyle-java-types/src/org/python/antlr/ast/sliceType.java branches/newstyle-java-types/src/org/python/antlr/ast/stmtType.java branches/newstyle-java-types/src/org/python/antlr/base/excepthandler.java branches/newstyle-java-types/src/org/python/antlr/base/expr.java branches/newstyle-java-types/src/org/python/antlr/base/mod.java branches/newstyle-java-types/src/org/python/antlr/base/slice.java branches/newstyle-java-types/src/org/python/antlr/base/stmt.java branches/newstyle-java-types/src/org/python/antlr/op/Add.java branches/newstyle-java-types/src/org/python/antlr/op/AddDerived.java branches/newstyle-java-types/src/org/python/antlr/op/And.java branches/newstyle-java-types/src/org/python/antlr/op/AndDerived.java branches/newstyle-java-types/src/org/python/antlr/op/AugLoad.java branches/newstyle-java-types/src/org/python/antlr/op/AugLoadDerived.java branches/newstyle-java-types/src/org/python/antlr/op/AugStore.java branches/newstyle-java-types/src/org/python/antlr/op/AugStoreDerived.java branches/newstyle-java-types/src/org/python/antlr/op/BitAnd.java branches/newstyle-java-types/src/org/python/antlr/op/BitAndDerived.java branches/newstyle-java-types/src/org/python/antlr/op/BitOr.java branches/newstyle-java-types/src/org/python/antlr/op/BitOrDerived.java branches/newstyle-java-types/src/org/python/antlr/op/BitXor.java branches/newstyle-java-types/src/org/python/antlr/op/BitXorDerived.java branches/newstyle-java-types/src/org/python/antlr/op/Del.java branches/newstyle-java-types/src/org/python/antlr/op/DelDerived.java branches/newstyle-java-types/src/org/python/antlr/op/Div.java branches/newstyle-java-types/src/org/python/antlr/op/DivDerived.java branches/newstyle-java-types/src/org/python/antlr/op/Eq.java branches/newstyle-java-types/src/org/python/antlr/op/EqDerived.java branches/newstyle-java-types/src/org/python/antlr/op/FloorDiv.java branches/newstyle-java-types/src/org/python/antlr/op/FloorDivDerived.java branches/newstyle-java-types/src/org/python/antlr/op/Gt.java branches/newstyle-java-types/src/org/python/antlr/op/GtDerived.java branches/newstyle-java-types/src/org/python/antlr/op/GtE.java branches/newstyle-java-types/src/org/python/antlr/op/GtEDerived.java branches/newstyle-java-types/src/org/python/antlr/op/In.java branches/newstyle-java-types/src/org/python/antlr/op/InDerived.java branches/newstyle-java-types/src/org/python/antlr/op/Invert.java branches/newstyle-java-types/src/org/python/antlr/op/InvertDerived.java branches/newstyle-java-types/src/org/python/antlr/op/Is.java branches/newstyle-java-types/src/org/python/antlr/op/IsDerived.java branches/newstyle-java-types/src/org/python/antlr/op/IsNot.java branches/newstyle-java-types/src/org/python/antlr/op/IsNotDerived.java branches/newstyle-java-types/src/org/python/antlr/op/LShift.java branches/newstyle-java-types/src/org/python/antlr/op/LShiftDerived.java branches/newstyle-java-types/src/org/python/antlr/op/Load.java branches/newstyle-java-types/src/org/python/antlr/op/LoadDerived.java branches/newstyle-java-types/src/org/python/antlr/op/Lt.java branches/newstyle-java-types/src/org/python/antlr/op/LtDerived.java branches/newstyle-java-types/src/org/python/antlr/op/LtE.java branches/newstyle-java-types/src/org/python/antlr/op/LtEDerived.java branches/newstyle-java-types/src/org/python/antlr/op/Mod.java branches/newstyle-java-types/src/org/python/antlr/op/ModDerived.java branches/newstyle-java-types/src/org/python/antlr/op/Mult.java branches/newstyle-java-types/src/org/python/antlr/op/MultDerived.java branches/newstyle-java-types/src/org/python/antlr/op/Not.java branches/newstyle-java-types/src/org/python/antlr/op/NotDerived.java branches/newstyle-java-types/src/org/python/antlr/op/NotEq.java branches/newstyle-java-types/src/org/python/antlr/op/NotEqDerived.java branches/newstyle-java-types/src/org/python/antlr/op/NotIn.java branches/newstyle-java-types/src/org/python/antlr/op/NotInDerived.java branches/newstyle-java-types/src/org/python/antlr/op/Or.java branches/newstyle-java-types/src/org/python/antlr/op/OrDerived.java branches/newstyle-java-types/src/org/python/antlr/op/Param.java branches/newstyle-java-types/src/org/python/antlr/op/ParamDerived.java branches/newstyle-java-types/src/org/python/antlr/op/Pow.java branches/newstyle-java-types/src/org/python/antlr/op/PowDerived.java branches/newstyle-java-types/src/org/python/antlr/op/RShift.java branches/newstyle-java-types/src/org/python/antlr/op/RShiftDerived.java branches/newstyle-java-types/src/org/python/antlr/op/Store.java branches/newstyle-java-types/src/org/python/antlr/op/StoreDerived.java branches/newstyle-java-types/src/org/python/antlr/op/Sub.java branches/newstyle-java-types/src/org/python/antlr/op/SubDerived.java branches/newstyle-java-types/src/org/python/antlr/op/UAdd.java branches/newstyle-java-types/src/org/python/antlr/op/UAddDerived.java branches/newstyle-java-types/src/org/python/antlr/op/USub.java branches/newstyle-java-types/src/org/python/antlr/op/USubDerived.java Property Changed: ---------------- branches/newstyle-java-types/ branches/newstyle-java-types/ast/ branches/newstyle-java-types/src/org/python/antlr/ branches/newstyle-java-types/src/org/python/antlr/ast/ branches/newstyle-java-types/src/org/python/compiler/ Property changes on: branches/newstyle-java-types ___________________________________________________________________ Modified: svnmerge-integrated - /branches/nowalker:1-5263 /trunk/jython:1-5664 + /branches/nowalker:1-5263 /trunk/jython:1-5729 /branches/astwrite:1-5692 Modified: svn:mergeinfo - /trunk/jython:5565-5661 + /trunk/jython:5565-5661,5670-5726 Modified: branches/newstyle-java-types/CoreExposed.includes =================================================================== --- branches/newstyle-java-types/CoreExposed.includes 2008-12-10 08:10:31 UTC (rev 5731) +++ branches/newstyle-java-types/CoreExposed.includes 2008-12-10 08:23:53 UTC (rev 5732) @@ -1,3 +1,4 @@ +org/python/core/AstList.class org/python/core/PyArray.class org/python/core/PyBaseString.class org/python/core/PyBaseException.class @@ -55,3 +56,98 @@ org/python/modules/zipimport/zipimporter.class org/python/modules/PyStruct.class org/python/modules/PyTeeIterator.class +org/python/antlr/AST.class +org/python/antlr/ast/alias.class +org/python/antlr/ast/arguments.class +org/python/antlr/ast/Assert.class +org/python/antlr/ast/Assign.class +org/python/antlr/ast/Attribute.class +org/python/antlr/ast/AugAssign.class +org/python/antlr/ast/BinOp.class +org/python/antlr/ast/BoolOp.class +org/python/antlr/ast/Break.class +org/python/antlr/ast/Call.class +org/python/antlr/ast/ClassDef.class +org/python/antlr/ast/Compare.class +org/python/antlr/ast/comprehension.class +org/python/antlr/ast/Continue.class +org/python/antlr/ast/Delete.class +org/python/antlr/ast/Dict.class +org/python/antlr/ast/Ellipsis.class +org/python/antlr/ast/ExceptHandler.class +org/python/antlr/ast/Exec.class +org/python/antlr/ast/Expr.class +org/python/antlr/ast/Expression.class +org/python/antlr/ast/ExtSlice.class +org/python/antlr/ast/For.class +org/python/antlr/ast/FunctionDef.class +org/python/antlr/ast/GeneratorExp.class +org/python/antlr/ast/Global.class +org/python/antlr/ast/If.class +org/python/antlr/ast/IfExp.class +org/python/antlr/ast/Import.class +org/python/antlr/ast/ImportFrom.class +org/python/antlr/ast/Index.class +org/python/antlr/ast/Interactive.class +org/python/antlr/ast/keyword.class +org/python/antlr/ast/Lambda.class +org/python/antlr/ast/List.class +org/python/antlr/ast/ListComp.class +org/python/antlr/ast/Module.class +org/python/antlr/ast/Name.class +org/python/antlr/ast/Num.class +org/python/antlr/ast/Pass.class +org/python/antlr/ast/Print.class +org/python/antlr/ast/Raise.class +org/python/antlr/ast/Repr.class +org/python/antlr/ast/Return.class +org/python/antlr/ast/Slice.class +org/python/antlr/ast/Str.class +org/python/antlr/ast/Subscript.class +org/python/antlr/ast/Suite.class +org/python/antlr/ast/TryExcept.class +org/python/antlr/ast/TryFinally.class +org/python/antlr/ast/Tuple.class +org/python/antlr/ast/UnaryOp.class +org/python/antlr/ast/While.class +org/python/antlr/ast/With.class +org/python/antlr/ast/Yield.class +org/python/antlr/base/excepthandler.class +org/python/antlr/base/expr.class +org/python/antlr/base/mod.class +org/python/antlr/base/slice.class +org/python/antlr/base/stmt.class +org/python/antlr/op/Add.class +org/python/antlr/op/And.class +org/python/antlr/op/AugLoad.class +org/python/antlr/op/AugStore.class +org/python/antlr/op/BitAnd.class +org/python/antlr/op/BitOr.class +org/python/antlr/op/BitXor.class +org/python/antlr/op/Del.class +org/python/antlr/op/Div.class +org/python/antlr/op/Eq.class +org/python/antlr/op/FloorDiv.class +org/python/antlr/op/Gt.class +org/python/antlr/op/GtE.class +org/python/antlr/op/In.class +org/python/antlr/op/Invert.class +org/python/antlr/op/Is.class +org/python/antlr/op/IsNot.class +org/python/antlr/op/Load.class +org/python/antlr/op/LShift.class +org/python/antlr/op/Lt.class +org/python/antlr/op/LtE.class +org/python/antlr/op/Mod.class +org/python/antlr/op/Mult.class +org/python/antlr/op/Not.class +org/python/antlr/op/NotEq.class +org/python/antlr/op/NotIn.class +org/python/antlr/op/Or.class +org/python/antlr/op/Param.class +org/python/antlr/op/Pow.class +org/python/antlr/op/RShift.class +org/python/antlr/op/Store.class +org/python/antlr/op/Sub.class +org/python/antlr/op/UAdd.class +org/python/antlr/op/USub.class Deleted: branches/newstyle-java-types/Lib/_ast.py =================================================================== --- branches/newstyle-java-types/Lib/_ast.py 2008-12-10 08:10:31 UTC (rev 5731) +++ branches/newstyle-java-types/Lib/_ast.py 2008-12-10 08:23:53 UTC (rev 5732) @@ -1,79 +0,0 @@ -from org.python.antlr.ast.boolopType import And,Or -from org.python.antlr.ast.operatorType import Add,Sub,Mult,Div,FloorDiv,Mod,LShift,RShift,BitOr,BitAnd,BitXor,Pow -from org.python.antlr.ast.cmpopType import Eq,Gt,GtE,In,Is,IsNot,Lt,LtE,NotEq,NotIn -from org.python.antlr.ast.unaryopType import Invert,Not,UAdd,USub -from org.python.core.PyTableCode import PyCF_ONLY_AST -from org.python.antlr.ast.expr_contextType import Load, Store, Del, AugLoad, AugStore, Param - -from org.python.antlr import AST - -from org.python.antlr.ast import Assert -from org.python.antlr.ast import Assign -from org.python.antlr.ast import Attribute -from org.python.antlr.ast import AugAssign -from org.python.antlr.ast import BinOp -from org.python.antlr.ast import BoolOp -from org.python.antlr.ast import Break -from org.python.antlr.ast import Call -from org.python.antlr.ast import ClassDef -from org.python.antlr.ast import Compare -from org.python.antlr.ast import Continue -from org.python.antlr.ast import Delete -from org.python.antlr.ast import Dict -from org.python.antlr.ast import Ellipsis -from org.python.antlr.ast import Exec -from org.python.antlr.ast import Expr -from org.python.antlr.ast import Expression -from org.python.antlr.ast import ExtSlice -from org.python.antlr.ast import For -from org.python.antlr.ast import FunctionDef -from org.python.antlr.ast import GeneratorExp -from org.python.antlr.ast import Global -from org.python.antlr.ast import If -from org.python.antlr.ast import IfExp -from org.python.antlr.ast import Import -from org.python.antlr.ast import ImportFrom -from org.python.antlr.ast import Index -from org.python.antlr.ast import Interactive -from org.python.antlr.ast import Lambda -from org.python.antlr.ast import List -from org.python.antlr.ast import ListComp -from org.python.antlr.ast import Module -from org.python.antlr.ast import Name -from org.python.antlr.ast import Num -from org.python.antlr.ast import Pass -from org.python.antlr.ast import Print -from org.python.antlr.ast import Raise -from org.python.antlr.ast import Repr -from org.python.antlr.ast import Return -from org.python.antlr.ast import Slice -from org.python.antlr.ast import Str -from org.python.antlr.ast import Subscript -from org.python.antlr.ast import Suite -from org.python.antlr.ast import TryExcept -from org.python.antlr.ast import TryFinally -from org.python.antlr.ast import Tuple -from org.python.antlr.ast import UnaryOp -#from org.python.antlr.ast import Unicode -from org.python.antlr.ast import While -from org.python.antlr.ast import With -from org.python.antlr.ast import Yield - -import org.python.antlr.ast.aliasType as alias -import org.python.antlr.ast.argumentsType as arguments -import org.python.antlr.ast.boolopType as boolop -import org.python.antlr.ast.cmpopType as cmpop -import org.python.antlr.ast.comprehensionType as comprehension -import org.python.antlr.ast.excepthandlerType as excepthandler -import org.python.antlr.ast.exprType as expr -import org.python.antlr.ast.expr_contextType as expr_context -import org.python.antlr.ast.keywordType as keyword -import org.python.antlr.ast.modType as mod -import org.python.antlr.ast.operatorType as operator -import org.python.antlr.ast.sliceType as slice -import org.python.antlr.ast.stmtType as stmt -import org.python.antlr.ast.unaryopType as unaryop - -#Set to the same value as the CPython version we are targetting. -#note that this number comes from the revision number in CPython's repository. -__version__ = 43614 Modified: branches/newstyle-java-types/Lib/ast.py =================================================================== --- branches/newstyle-java-types/Lib/ast.py 2008-12-10 08:10:31 UTC (rev 5731) +++ branches/newstyle-java-types/Lib/ast.py 2008-12-10 08:23:53 UTC (rev 5732) @@ -25,35 +25,10 @@ :copyright: Copyright 2008 by Armin Ronacher. :license: Python License. """ -import sys from _ast import * from _ast import __version__ -if sys.platform.startswith('java'): - import array - ast_list = array.ArrayType - - def get_class_name(t): - result = t.__class__.__name__ - if result in ("expr_contextType", - "boolopType", - "unaryopType", - "cmpopType", - "operatorType"): - result = str(t) - if result == "AugLoad": - result = "Load" - elif result == "AugStore": - result = "Store" - elif result.endswith("Type"): - result = result[:-4] - return result -else: - ast_list = list - get_class_name = lambda node: node.__class__.__name__ - - def parse(expr, filename='<unknown>', mode='exec'): """ Parse an expression into an AST node. @@ -105,7 +80,7 @@ def _format(node): if isinstance(node, AST): fields = [(a, _format(b)) for a, b in iter_fields(node)] - rv = '%s(%s' % (get_class_name(node), ', '.join( + rv = '%s(%s' % (node.__class__.__name__, ', '.join( ('%s=%s' % field for field in fields) if annotate_fields else (b for a, b in fields) @@ -115,11 +90,11 @@ rv += ', '.join('%s=%s' % (a, _format(getattr(node, a))) for a in node._attributes) return rv + ')' - elif isinstance(node, ast_list): + elif isinstance(node, list): return '[%s]' % ', '.join(_format(x) for x in node) return repr(node) if not isinstance(node, AST): - raise TypeError('expected AST, got %r' % get_class_name(node)) + raise TypeError('expected AST, got %r' % node.__class__.__name__) return _format(node) @@ -193,7 +168,7 @@ for name, field in iter_fields(node): if isinstance(field, AST): yield field - elif isinstance(field, ast_list): + elif isinstance(field, list): for item in field: if isinstance(item, AST): yield item @@ -206,7 +181,7 @@ will be raised. """ if not isinstance(node, (FunctionDef, ClassDef, Module)): - raise TypeError("%r can't have docstrings" % get_class_name(node)) + raise TypeError("%r can't have docstrings" % node.__class__.__name__) if node.body and isinstance(node.body[0], Expr) and \ isinstance(node.body[0].value, Str): if clean: @@ -251,14 +226,14 @@ def visit(self, node): """Visit a node.""" - method = 'visit_' + get_class_name(node) + method = 'visit_' + node.__class__.__name__ visitor = getattr(self, method, self.generic_visit) return visitor(node) def generic_visit(self, node): """Called if no explicit visitor function exists for a node.""" for field, value in iter_fields(node): - if isinstance(value, ast_list): + if isinstance(value, list): for item in value: if isinstance(item, AST): self.visit(item) @@ -305,7 +280,7 @@ def generic_visit(self, node): for field, old_value in iter_fields(node): old_value = getattr(node, field, None) - if isinstance(old_value, ast_list): + if isinstance(old_value, list): new_values = [] for value in old_value: if isinstance(value, AST): Modified: branches/newstyle-java-types/Lib/inspect.py =================================================================== --- branches/newstyle-java-types/Lib/inspect.py 2008-12-10 08:10:31 UTC (rev 5731) +++ branches/newstyle-java-types/Lib/inspect.py 2008-12-10 08:23:53 UTC (rev 5732) @@ -315,6 +315,13 @@ return None if not isinstance(doc, types.StringTypes): return None + return cleandoc(doc) + +def cleandoc(doc): + """Clean up indentation from docstrings. + + Any whitespace that can be uniformly removed from the second line + onwards is removed.""" try: lines = string.split(string.expandtabs(doc), '\n') except UnicodeError: Modified: branches/newstyle-java-types/Lib/test/test_ast.py =================================================================== --- branches/newstyle-java-types/Lib/test/test_ast.py 2008-12-10 08:10:31 UTC (rev 5731) +++ branches/newstyle-java-types/Lib/test/test_ast.py 2008-12-10 08:23:53 UTC (rev 5732) @@ -1,36 +1,22 @@ -#Taken and modified from CPython's release25-maint branch, revision 62446. -import sys,os, itertools +import sys, itertools, unittest +from test import test_support import ast -def get_class_name(t): - result = t.__class__.__name__ - if os.name.startswith('java'): - if result in ("expr_contextType", - "boolopType", - "unaryopType", - "cmpopType", - "operatorType"): - result = t.name() - else: - result = result.split(".")[-1] - if result.endswith("Type"): - result = result[:-4] - return result - def to_tuple(t): if t is None or isinstance(t, (basestring, int, long, complex)): return t - elif hasattr(t, '__iter__'): + elif isinstance(t, list): return [to_tuple(e) for e in t] - result = [get_class_name(t)] + result = [t.__class__.__name__] if hasattr(t, 'lineno') and hasattr(t, 'col_offset'): result.append((t.lineno, t.col_offset)) - if not hasattr(t, '_fields') or t._fields is None: + if t._fields is None: return tuple(result) for f in t._fields: result.append(to_tuple(getattr(t, f))) return tuple(result) + # These tests are compiled through "exec" # There should be atleast one test per statement exec_tests = [ @@ -134,49 +120,192 @@ # TODO: expr_context, slice, boolop, operator, unaryop, cmpop, comprehension # excepthandler, arguments, keywords, alias -if __name__=='__main__' and sys.argv[1:] == ['-g']: - for statements, kind in ((exec_tests, "exec"), (single_tests, "single"), - (eval_tests, "eval")): - print kind+"_results = [" - for s in statements: - print repr(to_tuple(compile(s, "?", kind, 0x400)))+"," - print "]" - print "run_tests()" - raise SystemExit +class AST_Tests(unittest.TestCase): -def test_order(ast_node, parent_pos): - - if (not isinstance(ast_node, ast.AST) - or not hasattr(ast_node, '_fields') - or ast_node._fields == None): + def _assert_order(self, ast_node, parent_pos): + if not isinstance(ast_node, ast.AST) or ast_node._fields is None: return - if isinstance(ast_node, (ast.expr, ast.stmt, ast.excepthandler)): - node_pos = (ast_node.lineno, ast_node.col_offset) - assert node_pos >= parent_pos, (node_pos, parent_pos) - parent_pos = (ast_node.lineno, ast_node.col_offset) - for name in ast_node._fields: - value = getattr(ast_node, name) - if hasattr(value, '__iter__'): - for child in value: - test_order(child, parent_pos) - elif value != None: - test_order(value, parent_pos) + if isinstance(ast_node, (ast.expr, ast.stmt, ast.excepthandler)): + node_pos = (ast_node.lineno, ast_node.col_offset) + self.assert_(node_pos >= parent_pos) + parent_pos = (ast_node.lineno, ast_node.col_offset) + for name in ast_node._fields: + value = getattr(ast_node, name) + if isinstance(value, list): + for child in value: + self._assert_order(child, parent_pos) + elif value is not None: + self._assert_order(value, parent_pos) -def run_tests(): - for input, output, kind in ((exec_tests, exec_results, "exec"), - (single_tests, single_results, "single"), - (eval_tests, eval_results, "eval")): - for i, o in itertools.izip(input, output): - ast_tree = compile(i, "?", kind, 0x400) - assert to_tuple(ast_tree) == o, "expected %s, got %s" % ( - o, to_tuple(ast_tree)) - test_order(ast_tree, (0, 0)) + def test_snippets(self): + for input, output, kind in ((exec_tests, exec_results, "exec"), + (single_tests, single_results, "single"), + (eval_tests, eval_results, "eval")): + for i, o in itertools.izip(input, output): + ast_tree = compile(i, "?", kind, ast.PyCF_ONLY_AST) + self.assertEquals(to_tuple(ast_tree), o) + self._assert_order(ast_tree, (0, 0)) -# XXX: AugStore added for Jython. Short term it is too hard to emit just "Store" as CPython does. + def test_nodeclasses(self): + x = ast.BinOp(1, 2, 3, lineno=0) + self.assertEquals(x.left.n, 1) + self.assertEquals(int(x.op), 2) + self.assertEquals(x.right.n, 3) + self.assertEquals(x.lineno, 0) + + # node raises exception when not given enough arguments + self.assertRaises(TypeError, ast.BinOp, 1, 2) + + # can set attributes through kwargs too + x = ast.BinOp(left=1, op=2, right=3, lineno=0) + self.assertEquals(x.left.n, 1) + self.assertEquals(int(x.op), 2) + self.assertEquals(x.right.n, 3) + self.assertEquals(x.lineno, 0) + + # this used to fail because Sub._fields was None + x = ast.Sub() + + def test_pickling(self): + import pickle + mods = [pickle] + try: + import cPickle + mods.append(cPickle) + except ImportError: + pass + protocols = [0, 1, 2] + for mod in mods: + for protocol in protocols: + for ast in (compile(i, "?", "exec", 0x400) for i in exec_tests): + ast2 = mod.loads(mod.dumps(ast, protocol)) + self.assertEquals(to_tuple(ast2), to_tuple(ast)) + + +class ASTHelpers_Test(unittest.TestCase): + + def test_parse(self): + a = ast.parse('foo(1 + 1)') + b = compile('foo(1 + 1)', '<unknown>', 'exec', ast.PyCF_ONLY_AST) + self.assertEqual(ast.dump(a), ast.dump(b)) + + def test_dump(self): + node = ast.parse('spam(eggs, "and cheese")') + self.assertEqual(ast.dump(node), + "Module(body=[Expr(value=Call(func=Name(id='spam', ctx=Load()), " + "args=[Name(id='eggs', ctx=Load()), Str(s='and cheese')], " + "keywords=[], starargs=None, kwargs=None))])" + ) + self.assertEqual(ast.dump(node, annotate_fields=False), + "Module([Expr(Call(Name('spam', Load()), [Name('eggs', Load()), " + "Str('and cheese')], [], None, None))])" + ) + self.assertEqual(ast.dump(node, include_attributes=True), + "Module(body=[Expr(value=Call(func=Name(id='spam', ctx=Load(), " + "lineno=1, col_offset=0), args=[Name(id='eggs', ctx=Load(), " + "lineno=1, col_offset=5), Str(s='and cheese', lineno=1, " + "col_offset=11)], keywords=[], starargs=None, kwargs=None, " + "lineno=1, col_offset=0), lineno=1, col_offset=0)])" + ) + + def test_copy_location(self): + src = ast.parse('1 + 1', mode='eval') + src.body.right = ast.copy_location(ast.Num(2), src.body.right) + self.assertEqual(ast.dump(src, include_attributes=True), + 'Expression(body=BinOp(left=Num(n=1, lineno=1, col_offset=0), ' + 'op=Add(), right=Num(n=2, lineno=1, col_offset=4), lineno=1, ' + 'col_offset=0))' + ) + + def test_fix_missing_locations(self): + src = ast.parse('write("spam")') + src.body.append(ast.Expr(ast.Call(ast.Name('spam', ast.Load()), + [ast.Str('eggs')], [], None, None))) + self.assertEqual(src, ast.fix_missing_locations(src)) + self.assertEqual(ast.dump(src, include_attributes=True), + "Module(body=[Expr(value=Call(func=Name(id='write', ctx=Load(), " + "lineno=1, col_offset=0), args=[Str(s='spam', lineno=1, " + "col_offset=6)], keywords=[], starargs=None, kwargs=None, " + "lineno=1, col_offset=0), lineno=1, col_offset=0), " + "Expr(value=Call(func=Name(id='spam', ctx=Load(), lineno=1, " + "col_offset=0), args=[Str(s='eggs', lineno=1, col_offset=0)], " + "keywords=[], starargs=None, kwargs=None, lineno=1, " + "col_offset=0), lineno=1, col_offset=0)])" + ) + + def test_increment_lineno(self): + src = ast.parse('1 + 1', mode='eval') + self.assertEqual(ast.increment_lineno(src, n=3), src) + self.assertEqual(ast.dump(src, include_attributes=True), + 'Expression(body=BinOp(left=Num(n=1, lineno=4, col_offset=0), ' + 'op=Add(), right=Num(n=1, lineno=4, col_offset=4), lineno=4, ' + 'col_offset=0))' + ) + + def test_iter_fields(self): + node = ast.parse('foo()', mode='eval') + d = dict(ast.iter_fields(node.body)) + self.assertEqual(d.pop('func').id, 'foo') + + #XXX: tests for equality between astlist and regular lists not + # working, breaking this test up into its components. + #self.assertEqual(d, {'keywords': [], 'kwargs': None, + # 'args': [], 'starargs': None}) + assert len(d) == 4 + assert d['keywords'] is not None + assert len(d['keywords']) == 0 + assert d['args'] is not None + assert len(d['args']) == 0 + assert d['kwargs'] is None + assert d['starargs'] is None + + def test_iter_child_nodes(self): + node = ast.parse("spam(23, 42, eggs='leek')", mode='eval') + self.assertEqual(len(list(ast.iter_child_nodes(node.body))), 4) + iterator = ast.iter_child_nodes(node.body) + self.assertEqual(iterator.next().id, 'spam') + self.assertEqual(iterator.next().n, 23) + self.assertEqual(iterator.next().n, 42) + self.assertEqual(ast.dump(iterator.next()), + "keyword(arg='eggs', value=Str(s='leek'))" + ) + + def test_get_docstring(self): + node = ast.parse('def foo():\n """line one\n line two"""') + self.assertEqual(ast.get_docstring(node.body[0]), + 'line one\nline two') + + def test_literal_eval(self): + self.assertEqual(ast.literal_eval(... [truncated message content] |
From: <cg...@us...> - 2008-12-12 03:29:55
|
Revision: 5737 http://jython.svn.sourceforge.net/jython/?rev=5737&view=rev Author: cgroves Date: 2008-12-12 03:29:49 +0000 (Fri, 12 Dec 2008) Log Message: ----------- Merged revisions 5730-5731,5733-5735 via svnmerge from https://jython.svn.sourceforge.net/svnroot/jython/trunk/jython ........ r5730 | pjenvey | 2008-12-09 23:34:57 -0800 (Tue, 09 Dec 2008) | 1 line hide posixy stuff when not on posix ........ r5731 | pjenvey | 2008-12-10 00:10:31 -0800 (Wed, 10 Dec 2008) | 3 lines merge in new test from: http://svn.python.org/projects/python/branches/release25-maint/Lib/test/test_with.py -c 67684 ........ r5733 | pjenvey | 2008-12-10 16:10:25 -0800 (Wed, 10 Dec 2008) | 4 lines fail fast when path exists but isn't a normal file suggested by Ethan Glasser-Camp fixes #1199 ........ r5734 | pjenvey | 2008-12-10 16:39:49 -0800 (Wed, 10 Dec 2008) | 1 line COMPUTE_FRAMES implies COMPUTE_MAXS ........ r5735 | pjenvey | 2008-12-10 21:20:55 -0800 (Wed, 10 Dec 2008) | 6 lines o fix imp.find_module not finding builtin modules o add __builtin__ and sys to sys.builtin_module_names and another hack for re-importing __builtin__ like we have for sys fixes #1161 thanks Sven Reimers ........ Modified Paths: -------------- branches/newstyle-java-types/Lib/os.py branches/newstyle-java-types/Lib/test/test_import_jy.py branches/newstyle-java-types/Lib/test/test_with.py branches/newstyle-java-types/src/org/python/compiler/ClassFile.java branches/newstyle-java-types/src/org/python/core/PySystemState.java branches/newstyle-java-types/src/org/python/core/imp.java branches/newstyle-java-types/src/org/python/modules/imp.java branches/newstyle-java-types/src/org/python/modules/zipimport/zipimporter.java Property Changed: ---------------- branches/newstyle-java-types/ Property changes on: branches/newstyle-java-types ___________________________________________________________________ Modified: svnmerge-integrated - /branches/nowalker:1-5263 /trunk/jython:1-5729 /branches/astwrite:1-5692 + /branches/astwrite:1-5692 /branches/nowalker:1-5263 /trunk/jython:1-5736 Modified: svn:mergeinfo - /trunk/jython:5565-5661,5670-5726 + /trunk/jython:5565-5661,5670-5726,5730-5735 Modified: branches/newstyle-java-types/Lib/os.py =================================================================== --- branches/newstyle-java-types/Lib/os.py 2008-12-11 09:15:43 UTC (rev 5736) +++ branches/newstyle-java-types/Lib/os.py 2008-12-12 03:29:49 UTC (rev 5737) @@ -494,6 +494,9 @@ except: raise f = File(sys.getPath(path)) + # XXX: jna-posix implements similar link detection in + # JavaFileStat.calculateSymlink, fallback to that instead when not + # native abs_parent = f.getAbsoluteFile().getParentFile() if not abs_parent: # root isn't a link @@ -669,29 +672,6 @@ except: raise OSError(errno.EBADF, strerror(errno.EBADF)) -if _name == 'posix' and _native_posix: - def link(src, dst): - """link(src, dst) - - Create a hard link to a file. - """ - _posix.link(sys.getPath(src), sys.getPath(dst)) - - def symlink(src, dst): - """symlink(src, dst) - - Create a symbolic link pointing to src named dst. - """ - _posix.symlink(src, sys.getPath(dst)) - - def readlink(path): - """readlink(path) -> path - - Return a string representing the path to which the symbolic link - points. - """ - return _posix.readlink(sys.getPath(path)) - # Provide lazy popen*, and system objects # Do these lazily, as most jython programs don't need them, # and they are very expensive to initialize @@ -906,66 +886,89 @@ The optional second argument can specify an alternate default.""" return environ.get(key, default) -def getegid(): - """getegid() -> egid +if _name == 'posix': + def link(src, dst): + """link(src, dst) - Return the current process's effective group id.""" - return _posix.getegid() + Create a hard link to a file. + """ + _posix.link(sys.getPath(src), sys.getPath(dst)) -def geteuid(): - """geteuid() -> euid + def symlink(src, dst): + """symlink(src, dst) - Return the current process's effective user id.""" - return _posix.geteuid() + Create a symbolic link pointing to src named dst. + """ + _posix.symlink(src, sys.getPath(dst)) -def getgid(): - """getgid() -> gid + def readlink(path): + """readlink(path) -> path - Return the current process's group id.""" - return _posix.getgid() + Return a string representing the path to which the symbolic link + points. + """ + return _posix.readlink(sys.getPath(path)) -def getlogin(): - """getlogin() -> string + def getegid(): + """getegid() -> egid - Return the actual login name.""" - return _posix.getlogin() + Return the current process's effective group id.""" + return _posix.getegid() -def getpgrp(): - """getpgrp() -> pgrp + def geteuid(): + """geteuid() -> euid - Return the current process group id.""" - return _posix.getpgrp() + Return the current process's effective user id.""" + return _posix.geteuid() -def getpid(): - """getpid() -> pid + def getgid(): + """getgid() -> gid - Return the current process id.""" - return _posix.getpid() + Return the current process's group id.""" + return _posix.getgid() -def getppid(): - """getppid() -> ppid + def getlogin(): + """getlogin() -> string - Return the parent's process id.""" - return _posix.getppid() + Return the actual login name.""" + return _posix.getlogin() -def getuid(): - """getuid() -> uid + def getpgrp(): + """getpgrp() -> pgrp - Return the current process's user id.""" - return _posix.getuid() + Return the current process group id.""" + return _posix.getpgrp() -def setpgrp(): - """setpgrp() + def getppid(): + """getppid() -> ppid - Make this process a session leader.""" - return _posix.setpgrp() + Return the parent's process id.""" + return _posix.getppid() -def setsid(): - """setsid() + def getuid(): + """getuid() -> uid - Call the system call setsid().""" - return _posix.setsid() + Return the current process's user id.""" + return _posix.getuid() + def setpgrp(): + """setpgrp() + + Make this process a session leader.""" + return _posix.setpgrp() + + def setsid(): + """setsid() + + Call the system call setsid().""" + return _posix.setsid() + +def getpid(): + """getpid() -> pid + + Return the current process id.""" + return _posix.getpid() + def isatty(fileno): """isatty(fd) -> bool Modified: branches/newstyle-java-types/Lib/test/test_import_jy.py =================================================================== --- branches/newstyle-java-types/Lib/test/test_import_jy.py 2008-12-11 09:15:43 UTC (rev 5736) +++ branches/newstyle-java-types/Lib/test/test_import_jy.py 2008-12-12 03:29:49 UTC (rev 5737) @@ -90,6 +90,7 @@ self.assertEquals(bytecode, read(init_compiled), 'bytecode was recompiled') + class OverrideBuiltinsImportTestCase(unittest.TestCase): def test_override(self): tests = [ @@ -127,9 +128,19 @@ finally: __builtin__.__import__ = oldimp +class ImpTestCase(unittest.TestCase): + + def test_imp_find_module_builtins(self): + self.assertEqual(imp.find_module('sys'), (None, 'sys', ('', '', 6))) + self.assertEqual(imp.find_module('__builtin__'), + (None, '__builtin__', ('', '', 6))) + self.assertEqual(imp.find_module('imp'), (None, 'imp', ('', '', 6))) + + def test_main(): - test_classes = [MislabeledImportTestCase, OverrideBuiltinsImportTestCase] - test_support.run_unittest(*test_classes) + test_support.run_unittest(MislabeledImportTestCase, + OverrideBuiltinsImportTestCase, + ImpTestCase) if __name__ == '__main__': test_main() Modified: branches/newstyle-java-types/Lib/test/test_with.py =================================================================== --- branches/newstyle-java-types/Lib/test/test_with.py 2008-12-11 09:15:43 UTC (rev 5736) +++ branches/newstyle-java-types/Lib/test/test_with.py 2008-12-12 03:29:49 UTC (rev 5737) @@ -505,7 +505,37 @@ self.assertRaises(GeneratorExit, shouldThrow) + def testErrorsInBool(self): + # issue4589: __exit__ return code may raise an exception + # when looking at its truth value. + class cm(object): + def __init__(self, bool_conversion): + class Bool: + def __nonzero__(self): + return bool_conversion() + self.exit_result = Bool() + def __enter__(self): + return 3 + def __exit__(self, a, b, c): + return self.exit_result + + def trueAsBool(): + with cm(lambda: True): + self.fail("Should NOT see this") + trueAsBool() + + def falseAsBool(): + with cm(lambda: False): + self.fail("Should raise") + self.assertRaises(AssertionError, falseAsBool) + + def failAsBool(): + with cm(lambda: 1//0): + self.fail("Should NOT see this") + self.assertRaises(ZeroDivisionError, failAsBool) + + class NonLocalFlowControlTestCase(unittest.TestCase, ContextmanagerAssertionMixin): Modified: branches/newstyle-java-types/src/org/python/compiler/ClassFile.java =================================================================== --- branches/newstyle-java-types/src/org/python/compiler/ClassFile.java 2008-12-11 09:15:43 UTC (rev 5736) +++ branches/newstyle-java-types/src/org/python/compiler/ClassFile.java 2008-12-12 03:29:49 UTC (rev 5737) @@ -46,7 +46,7 @@ this.interfaces = new String[0]; this.access = access; - cw = new ClassWriter(ClassWriter.COMPUTE_MAXS | ClassWriter.COMPUTE_FRAMES); + cw = new ClassWriter(ClassWriter.COMPUTE_FRAMES); methodVisitors = Collections.synchronizedList(new ArrayList()); fieldVisitors = Collections.synchronizedList(new ArrayList()); } Modified: branches/newstyle-java-types/src/org/python/core/PySystemState.java =================================================================== --- branches/newstyle-java-types/src/org/python/core/PySystemState.java 2008-12-11 09:15:43 UTC (rev 5736) +++ branches/newstyle-java-types/src/org/python/core/PySystemState.java 2008-12-12 03:29:49 UTC (rev 5737) @@ -709,6 +709,10 @@ private static void initBuiltins(Properties props) { builtinNames = new Hashtable(); + // add the oddball builtins that are specially handled + builtinNames.put("__builtin__", ""); + builtinNames.put("sys", ""); + // add builtins specified in the Setup.java file for (int i=0; i < Setup.builtinModules.length; i++) addBuiltin(Setup.builtinModules[i]); @@ -727,7 +731,7 @@ builtin_module_names = new PyTuple(built_mod); } - static String getBuiltin(String name) { + public static String getBuiltin(String name) { return (String)builtinNames.get(name); } Modified: branches/newstyle-java-types/src/org/python/core/imp.java =================================================================== --- branches/newstyle-java-types/src/org/python/core/imp.java 2008-12-11 09:15:43 UTC (rev 5736) +++ branches/newstyle-java-types/src/org/python/core/imp.java 2008-12-12 03:29:49 UTC (rev 5737) @@ -387,10 +387,13 @@ private static PyObject loadBuiltin(String name) { if (name == "sys") { - Py.writeComment(IMPORT_LOG, "'" + name + "' as sys in " - + "builtin modules"); + Py.writeComment(IMPORT_LOG, "'" + name + "' as sys in builtin modules"); return Py.java2py(Py.getSystemState()); } + if (name == "__builtin__") { + Py.writeComment(IMPORT_LOG, "'" + name + "' as __builtin__ in builtin modules"); + return new PyModule("__builtin__", PySystemState.builtins); + } String mod = PySystemState.getBuiltin(name); if (mod != null) { Class c = Py.findClassEx(mod, "builtin modules"); Modified: branches/newstyle-java-types/src/org/python/modules/imp.java =================================================================== --- branches/newstyle-java-types/src/org/python/modules/imp.java 2008-12-11 09:15:43 UTC (rev 5736) +++ branches/newstyle-java-types/src/org/python/modules/imp.java 2008-12-12 03:29:49 UTC (rev 5737) @@ -129,10 +129,6 @@ return null; } - public static PyObject find_module(String name) { - return find_module(name, null); - } - public static PyObject load_source(String modname, String filename) { return load_source(modname, filename, null); } @@ -158,11 +154,20 @@ return mod; } + public static PyObject find_module(String name) { + return find_module(name, Py.None); + } + public static PyObject find_module(String name, PyObject path) { - if (path == null || path == Py.None) { + if (path == Py.None && PySystemState.getBuiltin(name) != null) { + return new PyTuple(Py.None, Py.newString(name), + new PyTuple(Py.EmptyString, Py.EmptyString, + Py.newInteger(C_BUILTIN))); + } + + if (path == Py.None) { path = Py.getSystemState().path; } - for (PyObject p : path.asIterable()) { ModuleInfo mi = findFromSource(name, p.toString(), false, true); if(mi == null) { Modified: branches/newstyle-java-types/src/org/python/modules/zipimport/zipimporter.java =================================================================== --- branches/newstyle-java-types/src/org/python/modules/zipimport/zipimporter.java 2008-12-11 09:15:43 UTC (rev 5736) +++ branches/newstyle-java-types/src/org/python/modules/zipimport/zipimporter.java 2008-12-12 03:29:49 UTC (rev 5737) @@ -115,8 +115,10 @@ prefix = ""; while (true) { File fullPathFile = new File(sys.getPath(pathFile.getPath())); - if (fullPathFile.isFile()) { - archive = pathFile.getPath(); + if (fullPathFile.exists()) { + if (fullPathFile.isFile()) { + archive = pathFile.getPath(); + } break; } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |