From: <fwi...@us...> - 2006-05-13 16:50:50
|
Revision: 2724 Author: fwierzbicki Date: 2006-05-13 09:50:46 -0700 (Sat, 13 May 2006) ViewCVS: http://svn.sourceforge.net/jython/?rev=2724&view=rev Log Message: ----------- replaced ByteArrayInputStream with StringBufferInputStream from suggestion in bug 550200 from David Griffiths. Unfortunately this does not close 550200 since it has more to do with parsing non-ascii streams. ByteArrayInputStream has been deprecated for quite a while. Modified Paths: -------------- trunk/jython/src/org/python/core/Py.java trunk/jython/src/org/python/core/parser.java Modified: trunk/jython/src/org/python/core/Py.java =================================================================== --- trunk/jython/src/org/python/core/Py.java 2006-05-08 02:27:47 UTC (rev 2723) +++ trunk/jython/src/org/python/core/Py.java 2006-05-13 16:50:46 UTC (rev 2724) @@ -1696,7 +1696,7 @@ String type,CompilerFlags cflags) { return Py.compile_flags( - new java.io.StringBufferInputStream(data+"\n\n"), + new java.io.ByteArrayInputStream((data+"\n\n").getBytes()), filename, type,cflags); } Modified: trunk/jython/src/org/python/core/parser.java =================================================================== --- trunk/jython/src/org/python/core/parser.java 2006-05-08 02:27:47 UTC (rev 2723) +++ trunk/jython/src/org/python/core/parser.java 2006-05-13 16:50:46 UTC (rev 2724) @@ -75,7 +75,7 @@ public static Node parse(String string, String kind) { - return parse(new StringBufferInputStream(string), + return parse(new ByteArrayInputStream(string.getBytes()), kind, "<string>", null); } @@ -103,7 +103,7 @@ modType node = null; //System.err.println(new PyString(string).__repr__().toString()); - BufferedReader bufreader = prepBufreader(new StringBufferInputStream(string), + BufferedReader bufreader = prepBufreader(new ByteArrayInputStream(string.getBytes()), cflags); PythonGrammar g = new PythonGrammar(new ReaderCharStream(bufreader), @@ -260,4 +260,4 @@ return PyString.decode_UnicodeEscape(str, start, end, errors, unicode); } -} \ 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: <fwi...@us...> - 2006-05-14 02:39:00
|
Revision: 2728 Author: fwierzbicki Date: 2006-05-13 19:38:55 -0700 (Sat, 13 May 2006) ViewCVS: http://svn.sourceforge.net/jython/?rev=2728&view=rev Log Message: ----------- This a reworked patch 1465481. classmethod() now checks for non-callable arguments. Added new-style support for __get__. Code generated from new classmethod.expose and classmethod.dervid. Thanks Khalid Zuberi. Modified Paths: -------------- trunk/jython/src/org/python/core/PyClassMethod.java Added Paths: ----------- trunk/jython/src/org/python/core/PyClassMethodDerived.java Modified: trunk/jython/src/org/python/core/PyClassMethod.java =================================================================== --- trunk/jython/src/org/python/core/PyClassMethod.java 2006-05-14 02:30:47 UTC (rev 2727) +++ trunk/jython/src/org/python/core/PyClassMethod.java 2006-05-14 02:38:55 UTC (rev 2728) @@ -1,41 +1,79 @@ package org.python.core; public class PyClassMethod extends PyObject implements PyType.Newstyle { + // xxx __init__ + //~ BEGIN GENERATED REGION -- DO NOT EDIT SEE gexpose.py /* type info */ - public final static String exposed_name = "classmethod"; - - public static void typeSetup(PyObject dict, PyType.Newstyle marker) { - // xxx __get__ - // xxx __init__ - - dict - .__setitem__( - "__new__", - new PyNewWrapper(PyClassMethod.class, "__new__", 1, 1) { - public PyObject new_impl( - boolean init, - PyType subtype, - PyObject[] args, - String[] keywords) { - if (keywords.length != 0 || args.length!=1) { - throw info.unexpectedCall(args.length,keywords.length!=0); - } - return new PyClassMethod(args[0]); - } // xxx subclassing - }); + + public static final String exposed_name="classmethod"; + + public static void typeSetup(PyObject dict,PyType.Newstyle marker) { + class exposed___get__ extends PyBuiltinFunctionNarrow { + + private PyClassMethod self; + + public PyObject getSelf() { + return self; + } + + exposed___get__(PyClassMethod self,PyBuiltinFunction.Info info) { + super(info); + this.self=self; + } + + public PyBuiltinFunction makeBound(PyObject self) { + return new exposed___get__((PyClassMethod)self,info); + } + + public PyObject __call__(PyObject arg0,PyObject arg1) { + return self.classmethod___get__(arg0,arg1); + } + + public PyObject inst_call(PyObject gself,PyObject arg0,PyObject arg1) { + PyClassMethod self=(PyClassMethod)gself; + return self.classmethod___get__(arg0,arg1); + } + + } + dict.__setitem__("__get__",new PyMethodDescr("__get__",PyClassMethod.class,2,2,new exposed___get__(null,null))); + dict.__setitem__("__new__",new PyNewWrapper(PyClassMethod.class,"__new__",1,1) { + + public PyObject new_impl(boolean init,PyType subtype,PyObject[]args,String[]keywords) { + return classmethod_new(this,init,subtype,args,keywords); + } + + }); } + //~ END GENERATED REGION -- DO NOT EDIT SEE gexpose.py protected PyObject callable; public PyClassMethod(PyObject callable) { + if (!callable.isCallable()) { + throw Py.TypeError("'" + callable.getType().fastGetName() + "' object is not callable"); + } this.callable = callable; } public PyObject __get__(PyObject obj, PyObject type) { + return classmethod___get__(obj, type); + } + + final PyObject classmethod___get__(PyObject obj, PyObject type) { if (type == null) type = obj.getType(); return new PyMethod(type, callable, type.getType()); } + final static PyObject classmethod_new(PyNewWrapper new_, boolean init, PyType subtype, + PyObject[] args, String[] keywords) { + if (keywords.length != 0) { + throw Py.TypeError("classmethod does not accept keyword arguments"); + } + if (args.length != 1) { + throw Py.TypeError("classmethod expected 1 argument, got " + args.length); + } + return new PyClassMethod(args[0]); + } } Added: trunk/jython/src/org/python/core/PyClassMethodDerived.java =================================================================== --- trunk/jython/src/org/python/core/PyClassMethodDerived.java (rev 0) +++ trunk/jython/src/org/python/core/PyClassMethodDerived.java 2006-05-14 02:38:55 UTC (rev 2728) @@ -0,0 +1,906 @@ +package org.python.core; + +public class PyClassMethodDerived extends PyClassMethod { + + private PyObject dict; + + public PyObject fastGetDict() { + return dict; + } + + public PyObject getDict() { + return dict; + } + + public PyClassMethodDerived(PyType subtype) { + super(subtype); + dict=subtype.instDict(); + } + + public PyString __str__() { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__str__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(); + if (res instanceof PyString) + return(PyString)res; + throw Py.TypeError("__str__"+" should return a "+"string"); + } + return super.__str__(); + } + + public PyString __repr__() { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__repr__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(); + if (res instanceof PyString) + return(PyString)res; + throw Py.TypeError("__repr__"+" should return a "+"string"); + } + return super.__repr__(); + } + + public PyUnicode __unicode__() { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__unicode__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(); + if (res instanceof PyUnicode) + return(PyUnicode)res; + throw Py.TypeError("__unicode__"+" should return a "+"unicode"); + } + return super.__unicode__(); + } + + public PyString __hex__() { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__hex__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(); + if (res instanceof PyString) + return(PyString)res; + throw Py.TypeError("__hex__"+" should return a "+"string"); + } + return super.__hex__(); + } + + public PyString __oct__() { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__oct__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(); + if (res instanceof PyString) + return(PyString)res; + throw Py.TypeError("__oct__"+" should return a "+"string"); + } + return super.__oct__(); + } + + public PyObject __int__() { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__int__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(); + if (res instanceof PyObject) + return(PyObject)res; + throw Py.TypeError("__int__"+" should return a "+"int"); + } + return super.__int__(); + } + + public PyFloat __float__() { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__float__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(); + if (res instanceof PyFloat) + return(PyFloat)res; + throw Py.TypeError("__float__"+" should return a "+"float"); + } + return super.__float__(); + } + + public PyLong __long__() { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__long__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(); + if (res instanceof PyLong) + return(PyLong)res; + throw Py.TypeError("__long__"+" should return a "+"long"); + } + return super.__long__(); + } + + public PyComplex __complex__() { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__complex__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(); + if (res instanceof PyComplex) + return(PyComplex)res; + throw Py.TypeError("__complex__"+" should return a "+"complex"); + } + return super.__complex__(); + } + + public PyObject __pos__() { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__pos__"); + if (impl!=null) + return impl.__get__(this,self_type).__call__(); + return super.__pos__(); + } + + public PyObject __neg__() { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__neg__"); + if (impl!=null) + return impl.__get__(this,self_type).__call__(); + return super.__neg__(); + } + + public PyObject __abs__() { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__abs__"); + if (impl!=null) + return impl.__get__(this,self_type).__call__(); + return super.__abs__(); + } + + public PyObject __invert__() { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__invert__"); + if (impl!=null) + return impl.__get__(this,self_type).__call__(); + return super.__invert__(); + } + + public PyObject __add__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__add__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res==Py.NotImplemented) + return null; + return res; + } + return super.__add__(other); + } + + public PyObject __radd__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__radd__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res==Py.NotImplemented) + return null; + return res; + } + return super.__radd__(other); + } + + public PyObject __sub__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__sub__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res==Py.NotImplemented) + return null; + return res; + } + return super.__sub__(other); + } + + public PyObject __rsub__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__rsub__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res==Py.NotImplemented) + return null; + return res; + } + return super.__rsub__(other); + } + + public PyObject __mul__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__mul__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res==Py.NotImplemented) + return null; + return res; + } + return super.__mul__(other); + } + + public PyObject __rmul__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__rmul__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res==Py.NotImplemented) + return null; + return res; + } + return super.__rmul__(other); + } + + public PyObject __div__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__div__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res==Py.NotImplemented) + return null; + return res; + } + return super.__div__(other); + } + + public PyObject __rdiv__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__rdiv__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res==Py.NotImplemented) + return null; + return res; + } + return super.__rdiv__(other); + } + + public PyObject __floordiv__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__floordiv__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res==Py.NotImplemented) + return null; + return res; + } + return super.__floordiv__(other); + } + + public PyObject __rfloordiv__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__rfloordiv__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res==Py.NotImplemented) + return null; + return res; + } + return super.__rfloordiv__(other); + } + + public PyObject __truediv__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__truediv__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res==Py.NotImplemented) + return null; + return res; + } + return super.__truediv__(other); + } + + public PyObject __rtruediv__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__rtruediv__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res==Py.NotImplemented) + return null; + return res; + } + return super.__rtruediv__(other); + } + + public PyObject __mod__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__mod__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res==Py.NotImplemented) + return null; + return res; + } + return super.__mod__(other); + } + + public PyObject __rmod__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__rmod__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res==Py.NotImplemented) + return null; + return res; + } + return super.__rmod__(other); + } + + public PyObject __divmod__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__divmod__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res==Py.NotImplemented) + return null; + return res; + } + return super.__divmod__(other); + } + + public PyObject __rdivmod__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__rdivmod__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res==Py.NotImplemented) + return null; + return res; + } + return super.__rdivmod__(other); + } + + public PyObject __pow__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__pow__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res==Py.NotImplemented) + return null; + return res; + } + return super.__pow__(other); + } + + public PyObject __rpow__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__rpow__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res==Py.NotImplemented) + return null; + return res; + } + return super.__rpow__(other); + } + + public PyObject __lshift__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__lshift__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res==Py.NotImplemented) + return null; + return res; + } + return super.__lshift__(other); + } + + public PyObject __rlshift__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__rlshift__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res==Py.NotImplemented) + return null; + return res; + } + return super.__rlshift__(other); + } + + public PyObject __rshift__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__rshift__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res==Py.NotImplemented) + return null; + return res; + } + return super.__rshift__(other); + } + + public PyObject __rrshift__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__rrshift__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res==Py.NotImplemented) + return null; + return res; + } + return super.__rrshift__(other); + } + + public PyObject __and__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__and__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res==Py.NotImplemented) + return null; + return res; + } + return super.__and__(other); + } + + public PyObject __rand__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__rand__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res==Py.NotImplemented) + return null; + return res; + } + return super.__rand__(other); + } + + public PyObject __or__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__or__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res==Py.NotImplemented) + return null; + return res; + } + return super.__or__(other); + } + + public PyObject __ror__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__ror__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res==Py.NotImplemented) + return null; + return res; + } + return super.__ror__(other); + } + + public PyObject __xor__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__xor__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res==Py.NotImplemented) + return null; + return res; + } + return super.__xor__(other); + } + + public PyObject __rxor__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__rxor__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res==Py.NotImplemented) + return null; + return res; + } + return super.__rxor__(other); + } + + public PyObject __lt__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__lt__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res==Py.NotImplemented) + return null; + return res; + } + return super.__lt__(other); + } + + public PyObject __le__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__le__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res==Py.NotImplemented) + return null; + return res; + } + return super.__le__(other); + } + + public PyObject __gt__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__gt__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res==Py.NotImplemented) + return null; + return res; + } + return super.__gt__(other); + } + + public PyObject __ge__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__ge__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res==Py.NotImplemented) + return null; + return res; + } + return super.__ge__(other); + } + + public PyObject __eq__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__eq__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res==Py.NotImplemented) + return null; + return res; + } + return super.__eq__(other); + } + + public PyObject __ne__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__ne__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res==Py.NotImplemented) + return null; + return res; + } + return super.__ne__(other); + } + + public PyObject __iadd__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__iadd__"); + if (impl!=null) + return impl.__get__(this,self_type).__call__(other); + return super.__iadd__(other); + } + + public PyObject __isub__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__isub__"); + if (impl!=null) + return impl.__get__(this,self_type).__call__(other); + return super.__isub__(other); + } + + public PyObject __imul__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__imul__"); + if (impl!=null) + return impl.__get__(this,self_type).__call__(other); + return super.__imul__(other); + } + + public PyObject __idiv__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__idiv__"); + if (impl!=null) + return impl.__get__(this,self_type).__call__(other); + return super.__idiv__(other); + } + + public PyObject __ifloordiv__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__ifloordiv__"); + if (impl!=null) + return impl.__get__(this,self_type).__call__(other); + return super.__ifloordiv__(other); + } + + public PyObject __itruediv__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__itruediv__"); + if (impl!=null) + return impl.__get__(this,self_type).__call__(other); + return super.__itruediv__(other); + } + + public PyObject __imod__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__imod__"); + if (impl!=null) + return impl.__get__(this,self_type).__call__(other); + return super.__imod__(other); + } + + public PyObject __ipow__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__ipow__"); + if (impl!=null) + return impl.__get__(this,self_type).__call__(other); + return super.__ipow__(other); + } + + public PyObject __ilshift__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__ilshift__"); + if (impl!=null) + return impl.__get__(this,self_type).__call__(other); + return super.__ilshift__(other); + } + + public PyObject __irshift__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__irshift__"); + if (impl!=null) + return impl.__get__(this,self_type).__call__(other); + return super.__irshift__(other); + } + + public PyObject __iand__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__iand__"); + if (impl!=null) + return impl.__get__(this,self_type).__call__(other); + return super.__iand__(other); + } + + public PyObject __ior__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__ior__"); + if (impl!=null) + return impl.__get__(this,self_type).__call__(other); + return super.__ior__(other); + } + + public PyObject __ixor__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__ixor__"); + if (impl!=null) + return impl.__get__(this,self_type).__call__(other); + return super.__ixor__(other); + } + + public String toString() { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__repr__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(); + if (!(res instanceof PyString)) + throw Py.TypeError("__repr__ should return a string"); + return((PyString)res).toString(); + } + return super.toString(); + } + + public int hashCode() { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__hash__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(); + if (res instanceof PyInteger) + return((PyInteger)res).getValue(); + throw Py.TypeError("__hash__ should return a int"); + } + if (self_type.lookup("__eq__")!=null||self_type.lookup("__cmp__")!=null) + throw Py.TypeError("unhashable type"); + return super.hashCode(); + } + + public int __cmp__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__cmp__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res instanceof PyInteger) { + int v=((PyInteger)res).getValue(); + return v<0?-1:v>0?1:0; + } + throw Py.TypeError("__cmp__ should return a int"); + } + return super.__cmp__(other); + } + + public boolean __nonzero__() { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__nonzero__"); + if (impl==null) { + impl=self_type.lookup("__len__"); + if (impl==null) + return super.__nonzero__(); + } + return impl.__get__(this,self_type).__call__().__nonzero__(); + } + + public boolean __contains__(PyObject o) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__contains__"); + if (impl==null) + return super.__contains__(o); + return impl.__get__(this,self_type).__call__(o).__nonzero__(); + } + + public int __len__() { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__len__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(); + if (res instanceof PyInteger) + return((PyInteger)res).getValue(); + throw Py.TypeError("__len__ should return a int"); + } + return super.__len__(); + } + + public PyObject __iter__() { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__iter__"); + if (impl!=null) + return impl.__get__(this,self_type).__call__(); + impl=self_type.lookup("__getitem__"); + if (impl==null) + return super.__iter__(); + return new PySequenceIter(this); + } + + public PyObject __iternext__() { + PyType self_type=getType(); + PyObject impl=self_type.lookup("next"); + if (impl!=null) { + try { + return impl.__get__(this,self_type).__call__(); + } catch (PyException exc) { + if (Py.matchException(exc,Py.StopIteration)) + return null; + throw exc; + } + } + return super.__iternext__(); // ??? + } + + public PyObject __finditem__(PyObject key) { // ??? + PyType self_type=getType(); + PyObject impl=self_type.lookup("__getitem__"); + if (impl!=null) + try { + return impl.__get__(this,self_type).__call__(key); + } catch (PyException exc) { + if (Py.matchException(exc,Py.LookupError)) + return null; + throw exc; + } + return super.__finditem__(key); + } + + public void __setitem__(PyObject key,PyObject value) { // ??? + PyType self_type=getType(); + PyObject impl=self_type.lookup("__setitem__"); + if (impl!=null) { + impl.__get__(this,self_type).__call__(key,value); + return; + } + super.__setitem__(key,value); + } + + public void __delitem__(PyObject key) { // ??? + PyType self_type=getType(); + PyObject impl=self_type.lookup("__delitem__"); + if (impl!=null) { + impl.__get__(this,self_type).__call__(key); + return; + } + super.__delitem__(key); + } + + public PyObject __call__(PyObject args[],String keywords[]) { + ThreadState ts=Py.getThreadState(); + if (ts.recursion_depth++>ts.systemState.getrecursionlimit()) + throw Py.RuntimeError("maximum __call__ recursion depth exceeded"); + try { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__call__"); + if (impl!=null) + return impl.__get__(this,self_type).__call__(args,keywords); + return super.__call__(args,keywords); + } finally { + --ts.recursion_depth; + } + } + + public PyObject __findattr__(String name) { + PyType self_type=getType(); + PyObject getattribute=self_type.lookup("__getattribute__"); + PyString py_name=null; + try { + if (getattribute!=null) { + return getattribute.__get__(this,self_type).__call__(py_name=new PyString(name)); + } else { + return super.__findattr__(name); + } + } catch (PyException e) { + if (Py.matchException(e,Py.AttributeError)) { + PyObject getattr=self_type.lookup("__getattr__"); + if (getattr!=null) + try { + return getattr.__get__(this,self_type).__call__(py_name!=null?py_name:new PyString(name)); + } catch (PyException e1) { + if (!Py.matchException(e1,Py.AttributeError)) + throw e1; + } + return null; + } + throw e; + } + } + + public void __setattr__(String name,PyObject value) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__setattr__"); + if (impl!=null) { + impl.__get__(this,self_type).__call__(new PyString(name),value); + return; + } + super.__setattr__(name,value); + } + + public void __delattr__(String name) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__delattr__"); + if (impl!=null) { + impl.__get__(this,self_type).__call__(new PyString(name)); + return; + } + super.__delattr__(name); + } + + public PyObject __get__(PyObject obj,PyObject type) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__get__"); + if (impl!=null) { + if (obj==null) + obj=Py.None; + if (type==null) + type=Py.None; + return impl.__get__(this,self_type).__call__(obj,type); + } + return super.__get__(obj,type); + } + + public void __set__(PyObject obj,PyObject value) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__set__"); + if (impl!=null) { + impl.__get__(this,self_type).__call__(obj,value); + return; + } + super.__set__(obj,value); + } + + public void __delete__(PyObject obj) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__delete__"); + if (impl!=null) { + impl.__get__(this,self_type).__call__(obj); + return; + } + super.__delete__(obj); + } + + public void dispatch__init__(PyType type,PyObject[]args,String[]keywords) { + PyType self_type=getType(); + if (self_type.isSubType(type)) { + PyObject impl=self_type.lookup("__init__"); + if (impl!=null) + impl.__get__(this,self_type).__call__(args,keywords); + } + } + +} This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <fwi...@us...> - 2006-05-19 19:06:22
|
Revision: 2749 Author: fwierzbicki Date: 2006-05-19 12:06:10 -0700 (Fri, 19 May 2006) ViewCVS: http://svn.sourceforge.net/jython/?rev=2749&view=rev Log Message: ----------- cleanup of new-style class support. Modified Paths: -------------- trunk/jython/src/org/python/core/PyBuiltinFunction.java trunk/jython/src/org/python/core/PyFile.java trunk/jython/src/org/python/core/PyList.java trunk/jython/src/org/python/core/PyNone.java Modified: trunk/jython/src/org/python/core/PyBuiltinFunction.java =================================================================== --- trunk/jython/src/org/python/core/PyBuiltinFunction.java 2006-05-19 19:05:31 UTC (rev 2748) +++ trunk/jython/src/org/python/core/PyBuiltinFunction.java 2006-05-19 19:06:10 UTC (rev 2749) @@ -2,6 +2,7 @@ public abstract class PyBuiltinFunction extends PyObject implements PyType.Newstyle { + //~ BEGIN GENERATED REGION -- DO NOT EDIT SEE gexpose.py /* type info */ public static final String exposed_name="builtin_function_or_method"; @@ -14,6 +15,7 @@ dict.__setitem__("__doc__", new PyGetSetDescr("__doc__", PyBuiltinFunction.class, "fastGetDoc", null)); } + //~ END GENERATED REGION -- DO NOT EDIT SEE gexpose.py public interface Info { String getName(); Modified: trunk/jython/src/org/python/core/PyFile.java =================================================================== --- trunk/jython/src/org/python/core/PyFile.java 2006-05-19 19:05:31 UTC (rev 2748) +++ trunk/jython/src/org/python/core/PyFile.java 2006-05-19 19:06:10 UTC (rev 2749) @@ -596,7 +596,7 @@ } } - //~ BEGIN GENERATED + //~ BEGIN GENERATED REGION -- DO NOT EDIT SEE gexpose.py /* type info */ public static final String exposed_name="file"; @@ -1424,7 +1424,7 @@ }); } - //~ END GENERATED + //~ END GENERATED REGION -- DO NOT EDIT SEE gexpose.py public String name; public String mode; Modified: trunk/jython/src/org/python/core/PyList.java =================================================================== --- trunk/jython/src/org/python/core/PyList.java 2006-05-19 19:05:31 UTC (rev 2748) +++ trunk/jython/src/org/python/core/PyList.java 2006-05-19 19:06:10 UTC (rev 2749) @@ -16,6 +16,7 @@ public static void classDictInit(PyObject dict) throws PyIgnoreMethodTag {} + //~ BEGIN GENERATED REGION -- DO NOT EDIT SEE gexpose.py /* type info */ public static final String exposed_name="list"; @@ -1038,6 +1039,7 @@ }); } + //~ END GENERATED REGION -- DO NOT EDIT SEE gexpose.py public PyList() { this(Py.EmptyObjects); Modified: trunk/jython/src/org/python/core/PyNone.java =================================================================== --- trunk/jython/src/org/python/core/PyNone.java 2006-05-19 19:05:31 UTC (rev 2748) +++ trunk/jython/src/org/python/core/PyNone.java 2006-05-19 19:06:10 UTC (rev 2749) @@ -9,6 +9,7 @@ public class PyNone extends PyObject implements Serializable { + //~ BEGIN GENERATED REGION -- DO NOT EDIT SEE gexpose.py /* type info */ public static final String exposed_name="NoneType"; @@ -42,7 +43,6 @@ } dict.__setitem__("__repr__",new PyMethodDescr("__repr__",PyNone.class,0,0,new exposed___repr__(null,null))); - class exposed___nonzero__ extends PyBuiltinFunctionNarrow { private PyNone self; @@ -72,6 +72,8 @@ } dict.__setitem__("__nonzero__",new PyMethodDescr("__nonzero__",PyNone.class,0,0,new exposed___nonzero__(null,null))); } + //~ END GENERATED REGION -- DO NOT EDIT SEE gexpose.py + private static final PyType NONETYPE = PyType.fromClass(PyNone.class); PyNone() { This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <fwi...@us...> - 2006-05-19 19:57:39
|
Revision: 2751 Author: fwierzbicki Date: 2006-05-19 12:57:32 -0700 (Fri, 19 May 2006) ViewCVS: http://svn.sourceforge.net/jython/?rev=2751&view=rev Log Message: ----------- new-style class cleanup. Modified Paths: -------------- trunk/jython/src/org/python/core/PyList.java trunk/jython/src/org/python/core/PyLong.java Modified: trunk/jython/src/org/python/core/PyList.java =================================================================== --- trunk/jython/src/org/python/core/PyList.java 2006-05-19 19:54:50 UTC (rev 2750) +++ trunk/jython/src/org/python/core/PyList.java 2006-05-19 19:57:32 UTC (rev 2751) @@ -516,7 +516,6 @@ } dict.__setitem__("index",new PyMethodDescr("index",PyList.class,1,3,new exposed_index(null,null))); - class exposed_insert extends PyBuiltinFunctionNarrow { private PyList self; @@ -1025,19 +1024,19 @@ dict.__setitem__("__init__",new PyMethodDescr("__init__",PyList.class,-1,-1,new exposed___init__(null,null))); dict.__setitem__("__new__",new PyNewWrapper(PyList.class,"__new__",-1,-1) { - public PyObject new_impl(boolean init,PyType subtype,PyObject[]args,String[]keywords) { - PyList newobj; - if (for_type==subtype) { - newobj=new PyList(); - if (init) - newobj.list_init(args,keywords); - } else { - newobj=new PyListDerived(subtype); - } - return newobj; - } + public PyObject new_impl(boolean init,PyType subtype,PyObject[]args,String[]keywords) { + PyList newobj; + if (for_type==subtype) { + newobj=new PyList(); + if (init) + newobj.list_init(args,keywords); + } else { + newobj=new PyListDerived(subtype); + } + return newobj; + } - }); + }); } //~ END GENERATED REGION -- DO NOT EDIT SEE gexpose.py Modified: trunk/jython/src/org/python/core/PyLong.java =================================================================== --- trunk/jython/src/org/python/core/PyLong.java 2006-05-19 19:54:50 UTC (rev 2750) +++ trunk/jython/src/org/python/core/PyLong.java 2006-05-19 19:57:32 UTC (rev 2751) @@ -1126,10 +1126,12 @@ } dict.__setitem__("__hash__",new PyMethodDescr("__hash__",PyLong.class,0,0,new exposed___hash__(null,null))); dict.__setitem__("__new__",new PyNewWrapper(PyLong.class,"__new__",-1,-1) { - public PyObject new_impl(boolean init,PyType subtype,PyObject[]args,String[]keywords) { - return long_new(this,init,subtype,args,keywords); - } - }); + + public PyObject new_impl(boolean init,PyType subtype,PyObject[]args,String[]keywords) { + return long_new(this,init,subtype,args,keywords); + } + + }); } //~ END GENERATED REGION -- DO NOT EDIT SEE gexpose.py This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <fwi...@us...> - 2006-05-19 21:12:40
|
Revision: 2752 Author: fwierzbicki Date: 2006-05-19 14:12:31 -0700 (Fri, 19 May 2006) ViewCVS: http://svn.sourceforge.net/jython/?rev=2752&view=rev Log Message: ----------- Updated PyProperty's new-style class support. Modified Paths: -------------- trunk/jython/src/org/python/core/PyProperty.java Added Paths: ----------- trunk/jython/src/org/python/core/PyPropertyDerived.java Modified: trunk/jython/src/org/python/core/PyProperty.java =================================================================== --- trunk/jython/src/org/python/core/PyProperty.java 2006-05-19 19:57:32 UTC (rev 2751) +++ trunk/jython/src/org/python/core/PyProperty.java 2006-05-19 21:12:31 UTC (rev 2752) @@ -4,17 +4,13 @@ //~ BEGIN GENERATED REGION -- DO NOT EDIT SEE gexpose.py /* type info */ - public static final String exposed_name = "property"; + public static final String exposed_name="property"; - public static void typeSetup(PyObject dict, PyType.Newstyle marker) { - dict.__setitem__("fget", new PyGetSetDescr("fget", PyProperty.class, - "getFget", null)); - dict.__setitem__("fset", new PyGetSetDescr("fset", PyProperty.class, - "getFset", null)); - dict.__setitem__("fdel", new PyGetSetDescr("fdel", PyProperty.class, - "getFdel", null)); - dict.__setitem__("__doc__", new PyGetSetDescr("__doc__", - PyProperty.class, "getDoc", null)); + public static void typeSetup(PyObject dict,PyType.Newstyle marker) { + dict.__setitem__("fget",new PyGetSetDescr("fget",PyProperty.class,"getFget",null)); + dict.__setitem__("fset",new PyGetSetDescr("fset",PyProperty.class,"getFset",null)); + dict.__setitem__("fdel",new PyGetSetDescr("fdel",PyProperty.class,"getFdel",null)); + dict.__setitem__("__doc__",new PyGetSetDescr("__doc__",PyProperty.class,"getDoc",null)); class exposed___get__ extends PyBuiltinFunctionNarrow { private PyProperty self; @@ -23,45 +19,43 @@ return self; } - exposed___get__(PyProperty self, PyBuiltinFunction.Info info) { + exposed___get__(PyProperty self,PyBuiltinFunction.Info info) { super(info); - this.self = self; + this.self=self; } public PyBuiltinFunction makeBound(PyObject self) { - return new exposed___get__((PyProperty) self, info); + return new exposed___get__((PyProperty)self,info); } - public PyObject __call__(PyObject arg0, PyObject arg1) { - PyObject obj = (arg0 == Py.None) ? null : arg1; - PyObject type = (arg1 == Py.None) ? null : arg0; - return self.property___get__(obj, type); + public PyObject __call__(PyObject arg0,PyObject arg1) { + PyObject obj=(arg0==Py.None)?null:arg1; + PyObject type=(arg1==Py.None)?null:arg0; + return self.property___get__(obj,type); } - public PyObject inst_call(PyObject gself, PyObject arg0, - PyObject arg1) { - PyProperty self = (PyProperty) gself; - PyObject obj = (arg0 == Py.None) ? null : arg1; - PyObject type = (arg1 == Py.None) ? null : arg0; - return self.property___get__(obj, type); + public PyObject inst_call(PyObject gself,PyObject arg0,PyObject arg1) { + PyProperty self=(PyProperty)gself; + PyObject obj=(arg0==Py.None)?null:arg1; + PyObject type=(arg1==Py.None)?null:arg0; + return self.property___get__(obj,type); } public PyObject __call__(PyObject arg0) { - PyObject obj = (arg0 == Py.None) ? null : (null); - PyObject type = ((null) == Py.None) ? null : arg0; - return self.property___get__(obj, type); + PyObject obj=(arg0==Py.None)?null:(null); + PyObject type=((null)==Py.None)?null:arg0; + return self.property___get__(obj,type); } - public PyObject inst_call(PyObject gself, PyObject arg0) { - PyProperty self = (PyProperty) gself; - PyObject obj = (arg0 == Py.None) ? null : (null); - PyObject type = ((null) == Py.None) ? null : arg0; - return self.property___get__(obj, type); + public PyObject inst_call(PyObject gself,PyObject arg0) { + PyProperty self=(PyProperty)gself; + PyObject obj=(arg0==Py.None)?null:(null); + PyObject type=((null)==Py.None)?null:arg0; + return self.property___get__(obj,type); } } - dict.__setitem__("__get__", new PyMethodDescr("__get__", - PyProperty.class, 1, 2, new exposed___get__(null, null))); + dict.__setitem__("__get__",new PyMethodDescr("__get__",PyProperty.class,1,2,new exposed___get__(null,null))); class exposed___set__ extends PyBuiltinFunctionNarrow { private PyProperty self; @@ -70,30 +64,28 @@ return self; } - exposed___set__(PyProperty self, PyBuiltinFunction.Info info) { + exposed___set__(PyProperty self,PyBuiltinFunction.Info info) { super(info); - this.self = self; + this.self=self; } public PyBuiltinFunction makeBound(PyObject self) { - return new exposed___set__((PyProperty) self, info); + return new exposed___set__((PyProperty)self,info); } - public PyObject __call__(PyObject arg0, PyObject arg1) { - self.property___set__(arg0, arg1); + public PyObject __call__(PyObject arg0,PyObject arg1) { + self.property___set__(arg0,arg1); return Py.None; } - public PyObject inst_call(PyObject gself, PyObject arg0, - PyObject arg1) { - PyProperty self = (PyProperty) gself; - self.property___set__(arg0, arg1); + public PyObject inst_call(PyObject gself,PyObject arg0,PyObject arg1) { + PyProperty self=(PyProperty)gself; + self.property___set__(arg0,arg1); return Py.None; } } - dict.__setitem__("__set__", new PyMethodDescr("__set__", - PyProperty.class, 2, 2, new exposed___set__(null, null))); + dict.__setitem__("__set__",new PyMethodDescr("__set__",PyProperty.class,2,2,new exposed___set__(null,null))); class exposed___delete__ extends PyBuiltinFunctionNarrow { private PyProperty self; @@ -102,13 +94,13 @@ return self; } - exposed___delete__(PyProperty self, PyBuiltinFunction.Info info) { + exposed___delete__(PyProperty self,PyBuiltinFunction.Info info) { super(info); - this.self = self; + this.self=self; } public PyBuiltinFunction makeBound(PyObject self) { - return new exposed___delete__((PyProperty) self, info); + return new exposed___delete__((PyProperty)self,info); } public PyObject __call__(PyObject arg0) { @@ -116,15 +108,14 @@ return Py.None; } - public PyObject inst_call(PyObject gself, PyObject arg0) { - PyProperty self = (PyProperty) gself; + public PyObject inst_call(PyObject gself,PyObject arg0) { + PyProperty self=(PyProperty)gself; self.property___delete__(arg0); return Py.None; } } - dict.__setitem__("__delete__", new PyMethodDescr("__delete__", - PyProperty.class, 1, 1, new exposed___delete__(null, null))); + dict.__setitem__("__delete__",new PyMethodDescr("__delete__",PyProperty.class,1,1,new exposed___delete__(null,null))); class exposed___init__ extends PyBuiltinFunctionWide { private PyProperty self; @@ -133,63 +124,69 @@ return self; } - exposed___init__(PyProperty self, PyBuiltinFunction.Info info) { + exposed___init__(PyProperty self,PyBuiltinFunction.Info info) { super(info); - this.self = self; + this.self=self; } public PyBuiltinFunction makeBound(PyObject self) { - return new exposed___init__((PyProperty) self, info); + return new exposed___init__((PyProperty)self,info); } - public PyObject inst_call(PyObject self, PyObject[] args) { - return inst_call(self, args, Py.NoKeywords); + public PyObject inst_call(PyObject self,PyObject[]args) { + return inst_call(self,args,Py.NoKeywords); } - public PyObject __call__(PyObject[] args) { - return __call__(args, Py.NoKeywords); + public PyObject __call__(PyObject[]args) { + return __call__(args,Py.NoKeywords); } - public PyObject __call__(PyObject[] args, String[] keywords) { - self.property_init(args, keywords); + public PyObject __call__(PyObject[]args,String[]keywords) { + self.property_init(args,keywords); return Py.None; } - public PyObject inst_call(PyObject gself, PyObject[] args, - String[] keywords) { - PyProperty self = (PyProperty) gself; - self.property_init(args, keywords); + public PyObject inst_call(PyObject gself,PyObject[]args,String[]keywords) { + PyProperty self=(PyProperty)gself; + self.property_init(args,keywords); return Py.None; } } - dict.__setitem__("__init__", new PyMethodDescr("__init__", - PyProperty.class, -1, -1, new exposed___init__(null, null))); - dict.__setitem__("__new__", new PyNewWrapper(PyProperty.class, - "__new__", -1, -1) { + dict.__setitem__("__init__",new PyMethodDescr("__init__",PyProperty.class,-1,-1,new exposed___init__(null,null))); + dict.__setitem__("__new__",new PyNewWrapper(PyProperty.class,"__new__",-1,-1) { - public PyObject new_impl(boolean init, PyType subtype, - PyObject[] args, String[] keywords) { - PyProperty newobj; - if (for_type == subtype) { - newobj = new PyProperty(); - if (init) - newobj.property_init(args, keywords); - } else { - newobj = null; // new PyPropertyDerived(subtype); - } - return newobj; - } + public PyObject new_impl(boolean init,PyType subtype,PyObject[]args,String[]keywords) { + PyProperty newobj; + if (for_type==subtype) { + newobj=new PyProperty(); + if (init) + newobj.property_init(args,keywords); + } else { + newobj=new PyPropertyDerived(subtype); + } + return newobj; + } - }); + }); } //~ END GENERATED REGION -- DO NOT EDIT SEE gexpose.py + private static final PyType PROPERTYTYPE = PyType.fromClass(PyProperty.class); + protected PyObject fget; protected PyObject fset; protected PyObject fdel; protected PyObject doc; + public PyProperty() { + this(PROPERTYTYPE); + } + + public PyProperty(PyType subType) { + super(subType); + } + public PyObject getDoc() { return doc; } Added: trunk/jython/src/org/python/core/PyPropertyDerived.java =================================================================== --- trunk/jython/src/org/python/core/PyPropertyDerived.java (rev 0) +++ trunk/jython/src/org/python/core/PyPropertyDerived.java 2006-05-19 21:12:31 UTC (rev 2752) @@ -0,0 +1,906 @@ +package org.python.core; + +public class PyPropertyDerived extends PyProperty { + + private PyObject dict; + + public PyObject fastGetDict() { + return dict; + } + + public PyObject getDict() { + return dict; + } + + public PyPropertyDerived(PyType subtype) { + super(subtype); + dict=subtype.instDict(); + } + + public PyString __str__() { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__str__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(); + if (res instanceof PyString) + return(PyString)res; + throw Py.TypeError("__str__"+" should return a "+"string"); + } + return super.__str__(); + } + + public PyString __repr__() { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__repr__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(); + if (res instanceof PyString) + return(PyString)res; + throw Py.TypeError("__repr__"+" should return a "+"string"); + } + return super.__repr__(); + } + + public PyUnicode __unicode__() { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__unicode__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(); + if (res instanceof PyUnicode) + return(PyUnicode)res; + throw Py.TypeError("__unicode__"+" should return a "+"unicode"); + } + return super.__unicode__(); + } + + public PyString __hex__() { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__hex__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(); + if (res instanceof PyString) + return(PyString)res; + throw Py.TypeError("__hex__"+" should return a "+"string"); + } + return super.__hex__(); + } + + public PyString __oct__() { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__oct__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(); + if (res instanceof PyString) + return(PyString)res; + throw Py.TypeError("__oct__"+" should return a "+"string"); + } + return super.__oct__(); + } + + public PyObject __int__() { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__int__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(); + if (res instanceof PyObject) + return(PyObject)res; + throw Py.TypeError("__int__"+" should return a "+"int"); + } + return super.__int__(); + } + + public PyFloat __float__() { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__float__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(); + if (res instanceof PyFloat) + return(PyFloat)res; + throw Py.TypeError("__float__"+" should return a "+"float"); + } + return super.__float__(); + } + + public PyLong __long__() { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__long__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(); + if (res instanceof PyLong) + return(PyLong)res; + throw Py.TypeError("__long__"+" should return a "+"long"); + } + return super.__long__(); + } + + public PyComplex __complex__() { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__complex__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(); + if (res instanceof PyComplex) + return(PyComplex)res; + throw Py.TypeError("__complex__"+" should return a "+"complex"); + } + return super.__complex__(); + } + + public PyObject __pos__() { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__pos__"); + if (impl!=null) + return impl.__get__(this,self_type).__call__(); + return super.__pos__(); + } + + public PyObject __neg__() { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__neg__"); + if (impl!=null) + return impl.__get__(this,self_type).__call__(); + return super.__neg__(); + } + + public PyObject __abs__() { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__abs__"); + if (impl!=null) + return impl.__get__(this,self_type).__call__(); + return super.__abs__(); + } + + public PyObject __invert__() { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__invert__"); + if (impl!=null) + return impl.__get__(this,self_type).__call__(); + return super.__invert__(); + } + + public PyObject __add__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__add__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res==Py.NotImplemented) + return null; + return res; + } + return super.__add__(other); + } + + public PyObject __radd__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__radd__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res==Py.NotImplemented) + return null; + return res; + } + return super.__radd__(other); + } + + public PyObject __sub__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__sub__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res==Py.NotImplemented) + return null; + return res; + } + return super.__sub__(other); + } + + public PyObject __rsub__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__rsub__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res==Py.NotImplemented) + return null; + return res; + } + return super.__rsub__(other); + } + + public PyObject __mul__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__mul__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res==Py.NotImplemented) + return null; + return res; + } + return super.__mul__(other); + } + + public PyObject __rmul__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__rmul__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res==Py.NotImplemented) + return null; + return res; + } + return super.__rmul__(other); + } + + public PyObject __div__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__div__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res==Py.NotImplemented) + return null; + return res; + } + return super.__div__(other); + } + + public PyObject __rdiv__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__rdiv__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res==Py.NotImplemented) + return null; + return res; + } + return super.__rdiv__(other); + } + + public PyObject __floordiv__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__floordiv__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res==Py.NotImplemented) + return null; + return res; + } + return super.__floordiv__(other); + } + + public PyObject __rfloordiv__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__rfloordiv__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res==Py.NotImplemented) + return null; + return res; + } + return super.__rfloordiv__(other); + } + + public PyObject __truediv__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__truediv__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res==Py.NotImplemented) + return null; + return res; + } + return super.__truediv__(other); + } + + public PyObject __rtruediv__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__rtruediv__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res==Py.NotImplemented) + return null; + return res; + } + return super.__rtruediv__(other); + } + + public PyObject __mod__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__mod__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res==Py.NotImplemented) + return null; + return res; + } + return super.__mod__(other); + } + + public PyObject __rmod__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__rmod__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res==Py.NotImplemented) + return null; + return res; + } + return super.__rmod__(other); + } + + public PyObject __divmod__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__divmod__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res==Py.NotImplemented) + return null; + return res; + } + return super.__divmod__(other); + } + + public PyObject __rdivmod__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__rdivmod__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res==Py.NotImplemented) + return null; + return res; + } + return super.__rdivmod__(other); + } + + public PyObject __pow__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__pow__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res==Py.NotImplemented) + return null; + return res; + } + return super.__pow__(other); + } + + public PyObject __rpow__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__rpow__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res==Py.NotImplemented) + return null; + return res; + } + return super.__rpow__(other); + } + + public PyObject __lshift__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__lshift__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res==Py.NotImplemented) + return null; + return res; + } + return super.__lshift__(other); + } + + public PyObject __rlshift__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__rlshift__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res==Py.NotImplemented) + return null; + return res; + } + return super.__rlshift__(other); + } + + public PyObject __rshift__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__rshift__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res==Py.NotImplemented) + return null; + return res; + } + return super.__rshift__(other); + } + + public PyObject __rrshift__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__rrshift__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res==Py.NotImplemented) + return null; + return res; + } + return super.__rrshift__(other); + } + + public PyObject __and__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__and__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res==Py.NotImplemented) + return null; + return res; + } + return super.__and__(other); + } + + public PyObject __rand__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__rand__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res==Py.NotImplemented) + return null; + return res; + } + return super.__rand__(other); + } + + public PyObject __or__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__or__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res==Py.NotImplemented) + return null; + return res; + } + return super.__or__(other); + } + + public PyObject __ror__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__ror__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res==Py.NotImplemented) + return null; + return res; + } + return super.__ror__(other); + } + + public PyObject __xor__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__xor__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res==Py.NotImplemented) + return null; + return res; + } + return super.__xor__(other); + } + + public PyObject __rxor__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__rxor__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res==Py.NotImplemented) + return null; + return res; + } + return super.__rxor__(other); + } + + public PyObject __lt__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__lt__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res==Py.NotImplemented) + return null; + return res; + } + return super.__lt__(other); + } + + public PyObject __le__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__le__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res==Py.NotImplemented) + return null; + return res; + } + return super.__le__(other); + } + + public PyObject __gt__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__gt__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res==Py.NotImplemented) + return null; + return res; + } + return super.__gt__(other); + } + + public PyObject __ge__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__ge__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res==Py.NotImplemented) + return null; + return res; + } + return super.__ge__(other); + } + + public PyObject __eq__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__eq__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res==Py.NotImplemented) + return null; + return res; + } + return super.__eq__(other); + } + + public PyObject __ne__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__ne__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res==Py.NotImplemented) + return null; + return res; + } + return super.__ne__(other); + } + + public PyObject __iadd__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__iadd__"); + if (impl!=null) + return impl.__get__(this,self_type).__call__(other); + return super.__iadd__(other); + } + + public PyObject __isub__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__isub__"); + if (impl!=null) + return impl.__get__(this,self_type).__call__(other); + return super.__isub__(other); + } + + public PyObject __imul__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__imul__"); + if (impl!=null) + return impl.__get__(this,self_type).__call__(other); + return super.__imul__(other); + } + + public PyObject __idiv__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__idiv__"); + if (impl!=null) + return impl.__get__(this,self_type).__call__(other); + return super.__idiv__(other); + } + + public PyObject __ifloordiv__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__ifloordiv__"); + if (impl!=null) + return impl.__get__(this,self_type).__call__(other); + return super.__ifloordiv__(other); + } + + public PyObject __itruediv__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__itruediv__"); + if (impl!=null) + return impl.__get__(this,self_type).__call__(other); + return super.__itruediv__(other); + } + + public PyObject __imod__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__imod__"); + if (impl!=null) + return impl.__get__(this,self_type).__call__(other); + return super.__imod__(other); + } + + public PyObject __ipow__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__ipow__"); + if (impl!=null) + return impl.__get__(this,self_type).__call__(other); + return super.__ipow__(other); + } + + public PyObject __ilshift__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__ilshift__"); + if (impl!=null) + return impl.__get__(this,self_type).__call__(other); + return super.__ilshift__(other); + } + + public PyObject __irshift__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__irshift__"); + if (impl!=null) + return impl.__get__(this,self_type).__call__(other); + return super.__irshift__(other); + } + + public PyObject __iand__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__iand__"); + if (impl!=null) + return impl.__get__(this,self_type).__call__(other); + return super.__iand__(other); + } + + public PyObject __ior__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__ior__"); + if (impl!=null) + return impl.__get__(this,self_type).__call__(other); + return super.__ior__(other); + } + + public PyObject __ixor__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__ixor__"); + if (impl!=null) + return impl.__get__(this,self_type).__call__(other); + return super.__ixor__(other); + } + + public String toString() { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__repr__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(); + if (!(res instanceof PyString)) + throw Py.TypeError("__repr__ should return a string"); + return((PyString)res).toString(); + } + return super.toString(); + } + + public int hashCode() { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__hash__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(); + if (res instanceof PyInteger) + return((PyInteger)res).getValue(); + throw Py.TypeError("__hash__ should return a int"); + } + if (self_type.lookup("__eq__")!=null||self_type.lookup("__cmp__")!=null) + throw Py.TypeError("unhashable type"); + return super.hashCode(); + } + + public int __cmp__(PyObject other) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__cmp__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res instanceof PyInteger) { + int v=((PyInteger)res).getValue(); + return v<0?-1:v>0?1:0; + } + throw Py.TypeError("__cmp__ should return a int"); + } + return super.__cmp__(other); + } + + public boolean __nonzero__() { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__nonzero__"); + if (impl==null) { + impl=self_type.lookup("__len__"); + if (impl==null) + return super.__nonzero__(); + } + return impl.__get__(this,self_type).__call__().__nonzero__(); + } + + public boolean __contains__(PyObject o) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__contains__"); + if (impl==null) + return super.__contains__(o); + return impl.__get__(this,self_type).__call__(o).__nonzero__(); + } + + public int __len__() { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__len__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(); + if (res instanceof PyInteger) + return((PyInteger)res).getValue(); + throw Py.TypeError("__len__ should return a int"); + } + return super.__len__(); + } + + public PyObject __iter__() { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__iter__"); + if (impl!=null) + return impl.__get__(this,self_type).__call__(); + impl=self_type.lookup("__getitem__"); + if (impl==null) + return super.__iter__(); + return new PySequenceIter(this); + } + + public PyObject __iternext__() { + PyType self_type=getType(); + PyObject impl=self_type.lookup("next"); + if (impl!=null) { + try { + return impl.__get__(this,self_type).__call__(); + } catch (PyException exc) { + if (Py.matchException(exc,Py.StopIteration)) + return null; + throw exc; + } + } + return super.__iternext__(); // ??? + } + + public PyObject __finditem__(PyObject key) { // ??? + PyType self_type=getType(); + PyObject impl=self_type.lookup("__getitem__"); + if (impl!=null) + try { + return impl.__get__(this,self_type).__call__(key); + } catch (PyException exc) { + if (Py.matchException(exc,Py.LookupError)) + return null; + throw exc; + } + return super.__finditem__(key); + } + + public void __setitem__(PyObject key,PyObject value) { // ??? + PyType self_type=getType(); + PyObject impl=self_type.lookup("__setitem__"); + if (impl!=null) { + impl.__get__(this,self_type).__call__(key,value); + return; + } + super.__setitem__(key,value); + } + + public void __delitem__(PyObject key) { // ??? + PyType self_type=getType(); + PyObject impl=self_type.lookup("__delitem__"); + if (impl!=null) { + impl.__get__(this,self_type).__call__(key); + return; + } + super.__delitem__(key); + } + + public PyObject __call__(PyObject args[],String keywords[]) { + ThreadState ts=Py.getThreadState(); + if (ts.recursion_depth++>ts.systemState.getrecursionlimit()) + throw Py.RuntimeError("maximum __call__ recursion depth exceeded"); + try { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__call__"); + if (impl!=null) + return impl.__get__(this,self_type).__call__(args,keywords); + return super.__call__(args,keywords); + } finally { + --ts.recursion_depth; + } + } + + public PyObject __findattr__(String name) { + PyType self_type=getType(); + PyObject getattribute=self_type.lookup("__getattribute__"); + PyString py_name=null; + try { + if (getattribute!=null) { + return getattribute.__get__(this,self_type).__call__(py_name=new PyString(name)); + } else { + return super.__findattr__(name); + } + } catch (PyException e) { + if (Py.matchException(e,Py.AttributeError)) { + PyObject getattr=self_type.lookup("__getattr__"); + if (getattr!=null) + try { + return getattr.__get__(this,self_type).__call__(py_name!=null?py_name:new PyString(name)); + } catch (PyException e1) { + if (!Py.matchException(e1,Py.AttributeError)) + throw e1; + } + return null; + } + throw e; + } + } + + public void __setattr__(String name,PyObject value) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__setattr__"); + if (impl!=null) { + impl.__get__(this,self_type).__call__(new PyString(name),value); + return; + } + super.__setattr__(name,value); + } + + public void __delattr__(String name) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__delattr__"); + if (impl!=null) { + impl.__get__(this,self_type).__call__(new PyString(name)); + return; + } + super.__delattr__(name); + } + + public PyObject __get__(PyObject obj,PyObject type) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__get__"); + if (impl!=null) { + if (obj==null) + obj=Py.None; + if (type==null) + type=Py.None; + return impl.__get__(this,self_type).__call__(obj,type); + } + return super.__get__(obj,type); + } + + public void __set__(PyObject obj,PyObject value) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__set__"); + if (impl!=null) { + impl.__get__(this,self_type).__call__(obj,value); + return; + } + super.__set__(obj,value); + } + + public void __delete__(PyObject obj) { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__delete__"); + if (impl!=null) { + impl.__get__(this,self_type).__call__(obj); + return; + } + super.__delete__(obj); + } + + public void dispatch__init__(PyType type,PyObject[]args,String[]keywords) { + PyType self_type=getType(); + if (self_type.isSubType(type)) { + PyObject impl=self_type.lookup("__init__"); + if (impl!=null) + impl.__get__(this,self_type).__call__(args,keywords); + } + } + +} This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <fwi...@us...> - 2006-05-28 03:58:58
|
Revision: 2769 Author: fwierzbicki Date: 2006-05-27 20:58:51 -0700 (Sat, 27 May 2006) ViewCVS: http://svn.sourceforge.net/jython/?rev=2769&view=rev Log Message: ----------- pickling support for complex, list, and timetuple. Also some cleanup of list internals. Modified Paths: -------------- trunk/jython/src/org/python/core/PyComplex.java trunk/jython/src/org/python/core/PyList.java trunk/jython/src/org/python/core/PyListDerived.java trunk/jython/src/org/python/core/PyObjectList.java trunk/jython/src/org/python/core/PySequenceList.java trunk/jython/src/org/python/modules/time/PyTimeTuple.java Modified: trunk/jython/src/org/python/core/PyComplex.java =================================================================== --- trunk/jython/src/org/python/core/PyComplex.java 2006-05-27 03:58:08 UTC (rev 2768) +++ trunk/jython/src/org/python/core/PyComplex.java 2006-05-28 03:58:51 UTC (rev 2769) @@ -869,6 +869,34 @@ } dict.__setitem__("__nonzero__",new PyMethodDescr("__nonzero__",PyComplex.class,0,0,new exposed___nonzero__(null,null))); + class exposed___reduce__ extends PyBuiltinFunctionNarrow { + + private PyComplex self; + + public PyObject getSelf() { + return self; + } + + exposed___reduce__(PyComplex self,PyBuiltinFunction.Info info) { + super(info); + this.self=self; + } + + public PyBuiltinFunction makeBound(PyObject self) { + return new exposed___reduce__((PyComplex)self,info); + } + + public PyObject __call__() { + return self.complex___reduce__(); + } + + public PyObject inst_call(PyObject gself) { + PyComplex self=(PyComplex)gself; + return self.complex___reduce__(); + } + + } + dict.__setitem__("__reduce__",new PyMethodDescr("__reduce__",PyComplex.class,0,0,new exposed___reduce__(null,null))); class exposed___repr__ extends PyBuiltinFunctionNarrow { private PyComplex self; @@ -1595,6 +1623,24 @@ return new PyComplex(real, -imag); } + /** + * Used for pickling. + * + * @return a tuple of (class, (Integer)) + */ + public PyObject __reduce__() { + return complex___reduce__(); + } + + final PyObject complex___reduce__() { + return new PyTuple(new PyObject[]{ + getType(), + new PyTuple(new PyObject[]{ + getReal(), getImag() + }) + }); + } + public boolean isMappingType() { return false; } public boolean isSequenceType() { return false; } } Modified: trunk/jython/src/org/python/core/PyList.java =================================================================== --- trunk/jython/src/org/python/core/PyList.java 2006-05-27 03:58:08 UTC (rev 2768) +++ trunk/jython/src/org/python/core/PyList.java 2006-05-28 03:58:51 UTC (rev 2769) @@ -892,6 +892,34 @@ } dict.__setitem__("__imul__",new PyMethodDescr("__imul__",PyList.class,1,1,new exposed___imul__(null,null))); + class exposed___reduce__ extends PyBuiltinFunctionNarrow { + + private PyList self; + + public PyObject getSelf() { + return self; + } + + exposed___reduce__(PyList self,PyBuiltinFunction.Info info) { + super(info); + this.self=self; + } + + public PyBuiltinFunction makeBound(PyObject self) { + return new exposed___reduce__((PyList)self,info); + } + + public PyObject __call__() { + return self.list___reduce__(); + } + + public PyObject inst_call(PyObject gself) { + PyList self=(PyList)gself; + return self.list___reduce__(); + } + + } + dict.__setitem__("__reduce__",new PyMethodDescr("__reduce__",PyList.class,0,0,new exposed___reduce__(null,null))); class exposed___mul__ extends PyBuiltinFunctionNarrow { private PyList self; @@ -1060,31 +1088,37 @@ } //~ END GENERATED REGION -- DO NOT EDIT SEE gexpose.py + private static final PyType LISTTYPE = PyType.fromClass(PyList.class); + public PyList() { - this(Py.EmptyObjects); + this(LISTTYPE, Py.EmptyObjects); } public PyList(PyType type) { super(type); } - public PyList(Collection c) { - super(c); + public PyList(PyType type, PyObject[] elements) { + super(type, elements); } + public PyList(PyType type, Collection c) { + super(type, c); + } + // TODO: fix dependency so it can be removed. // Shouldn't be required (see PyList(Collection c), but test_re.py fails // without it. Probably used by reflection. public PyList(Vector v) { - super(v); + super(LISTTYPE, v); } public PyList(PyObject[] elements) { - super(elements); + this(LISTTYPE, elements); } public PyList(PyObject o) { - this(); + this(LISTTYPE); PyObject iter = o.__iter__(); for (PyObject item = null; (item = iter.__iternext__()) != null; ) { append(item); @@ -1676,4 +1710,26 @@ final int list_hashCode() { throw Py.TypeError("unhashable type"); } + + /** + * Used for pickling. + * + * @return a tuple of (class, tuple) + */ + public PyObject __reduce__() { + return list___reduce__(); + } + + final PyObject list___reduce__() { + PyTuple newargs = __getnewargs__(); + return new PyTuple(new PyObject[]{ + getType(), newargs + }); + } + + public PyTuple __getnewargs__() { + return new PyTuple(new PyObject[] + {new PyTuple(list.getArray())} + ); + } } Modified: trunk/jython/src/org/python/core/PyListDerived.java =================================================================== --- trunk/jython/src/org/python/core/PyListDerived.java 2006-05-27 03:58:08 UTC (rev 2768) +++ trunk/jython/src/org/python/core/PyListDerived.java 2006-05-28 03:58:51 UTC (rev 2769) @@ -41,18 +41,6 @@ return super.__repr__(); } - public PyUnicode __unicode__() { - PyType self_type=getType(); - PyObject impl=self_type.lookup("__unicode__"); - if (impl!=null) { - PyObject res=impl.__get__(this,self_type).__call__(); - if (res instanceof PyUnicode) - return(PyUnicode)res; - throw Py.TypeError("__unicode__"+" should return a "+"unicode"); - } - return super.__unicode__(); - } - public PyString __hex__() { PyType self_type=getType(); PyObject impl=self_type.lookup("__hex__"); @@ -157,6 +145,14 @@ return super.__invert__(); } + public PyObject __reduce__() { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__reduce__"); + if (impl!=null) + return impl.__get__(this,self_type).__call__(); + return super.__reduce__(); + } + public PyObject __add__(PyObject other) { PyType self_type=getType(); PyObject impl=self_type.lookup("__add__"); @@ -695,6 +691,20 @@ return super.hashCode(); } + public PyUnicode __unicode__() { + PyType self_type=getType(); + PyObject impl=self_type.lookup("__unicode__"); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(); + if (res instanceof PyUnicode) + return(PyUnicode)res; + if (res instanceof PyString) + return new PyUnicode((PyString)res); + throw Py.TypeError("__unicode__"+" should return a "+"unicode"); + } + return super.__unicode__(); + } + public int __cmp__(PyObject other) { PyType self_type=getType(); PyObject impl=self_type.lookup("__cmp__"); @@ -768,7 +778,7 @@ public PyObject __finditem__(PyObject key) { // ??? PyType self_type=getType(); - PyObject impl=self_type.lookup("__finditem__"); + PyObject impl=self_type.lookup("__getitem__"); if (impl!=null) try { return impl.__get__(this,self_type).__call__(key); @@ -793,7 +803,7 @@ public PyObject __getitem__(PyObject key) { // ??? PyType self_type=getType(); PyObject impl=self_type.lookup("__getitem__"); - if (impl!=null) + if (impl!=null) { try { return impl.__get__(this,self_type).__call__(key); } catch (PyException exc) { @@ -801,10 +811,11 @@ return null; throw exc; } + } return super.__getitem__(key); } - public PyObject __getslice__(PyObject start,PyObject stop,PyObject step) { + public PyObject __getslice__(PyObject start,PyObject stop,PyObject step) { // ??? PyType self_type=getType(); PyObject impl=self_type.lookup("__getslice__"); if (impl!=null) Modified: trunk/jython/src/org/python/core/PyObjectList.java =================================================================== --- trunk/jython/src/org/python/core/PyObjectList.java 2006-05-27 03:58:08 UTC (rev 2768) +++ trunk/jython/src/org/python/core/PyObjectList.java 2006-05-28 03:58:51 UTC (rev 2769) @@ -175,7 +175,7 @@ * * @return backing array object */ - PyObject[] getArray() { + protected PyObject[] getArray() { return (PyObject[])array.getArray(); } Modified: trunk/jython/src/org/python/core/PySequenceList.java =================================================================== --- trunk/jython/src/org/python/core/PySequenceList.java 2006-05-27 03:58:08 UTC (rev 2768) +++ trunk/jython/src/org/python/core/PySequenceList.java 2006-05-28 03:58:51 UTC (rev 2769) @@ -47,7 +47,8 @@ list = new PyObjectList(elements); } - public PySequenceList(Collection c) { + public PySequenceList(PyType type, Collection c) { + super(type); list = new PyObjectList(c); } Modified: trunk/jython/src/org/python/modules/time/PyTimeTuple.java =================================================================== --- trunk/jython/src/org/python/modules/time/PyTimeTuple.java 2006-05-27 03:58:08 UTC (rev 2768) +++ trunk/jython/src/org/python/modules/time/PyTimeTuple.java 2006-05-28 03:58:51 UTC (rev 2769) @@ -1,7 +1,12 @@ package org.python.modules.time; import org.python.core.Py; +import org.python.core.PyBuiltinFunction; +import org.python.core.PyBuiltinFunctionNarrow; +import org.python.core.PyGetSetDescr; import org.python.core.PyInteger; +import org.python.core.PyList; +import org.python.core.PyMethodDescr; import org.python.core.PyObject; import org.python.core.PyTuple; import org.python.core.PyType; @@ -17,6 +22,7 @@ private PyInteger tm_yday; private PyInteger tm_isdst; + //~ BEGIN GENERATED REGION -- DO NOT EDIT SEE gexpose.py /* type info */ public static final String exposed_name="timetuple"; @@ -24,8 +30,113 @@ public static final Class exposed_base=PyTuple.class; public static void typeSetup(PyObject dict,PyType.Newstyle marker) { - PyTimeTupleSetup.typeSetup(dict, marker); + dict.__setitem__("tm_year",new PyGetSetDescr("tm_year",PyTimeTuple.class,"getYear",null)); + dict.__setitem__("tm_mon",new PyGetSetDescr("tm_mon",PyTimeTuple.class,"getMon",null)); + dict.__setitem__("tm_mday",new PyGetSetDescr("tm_mday",PyTimeTuple.class,"getMday",null)); + dict.__setitem__("tm_hour",new PyGetSetDescr("tm_hour",PyTimeTuple.class,"getHour",null)); + dict.__setitem__("tm_min",new PyGetSetDescr("tm_min",PyTimeTuple.class,"getMin",null)); + dict.__setitem__("tm_sec",new PyGetSetDescr("tm_sec",PyTimeTuple.class,"getSec",null)); + dict.__setitem__("tm_wday",new PyGetSetDescr("tm_wday",PyTimeTuple.class,"getWday",null)); + dict.__setitem__("tm_yday",new PyGetSetDescr("tm_yday",PyTimeTuple.class,"getYday",null)); + dict.__setitem__("tm_isdst",new PyGetSetDescr("tm_isdst",PyTimeTuple.class,"getIsdst",null)); + class exposed___ne__ extends PyBuiltinFunctionNarrow { + + private PyTimeTuple self; + + public PyObject getSelf() { + return self; + } + + exposed___ne__(PyTimeTuple self,PyBuiltinFunction.Info info) { + super(info); + this.self=self; + } + + public PyBuiltinFunction makeBound(PyObject self) { + return new exposed___ne__((PyTimeTuple)self,info); + } + + public PyObject __call__(PyObject arg0) { + PyObject ret=self.timetuple___ne__(arg0); + if (ret==null) + return Py.NotImplemented; + return ret; + } + + public PyObject inst_call(PyObject gself,PyObject arg0) { + PyTimeTuple self=(PyTimeTuple)gself; + PyObject ret=self.timetuple___ne__(arg0); + if (ret==null) + return Py.NotImplemented; + return ret; + } + + } + dict.__setitem__("__ne__",new PyMethodDescr("__ne__",PyTimeTuple.class,1,1,new exposed___ne__(null,null))); + class exposed___eq__ extends PyBuiltinFunctionNarrow { + + private PyTimeTuple self; + + public PyObject getSelf() { + return self; + } + + exposed___eq__(PyTimeTuple self,PyBuiltinFunction.Info info) { + super(info); + this.self=self; + } + + public PyBuiltinFunction makeBound(PyObject self) { + return new exposed___eq__((PyTimeTuple)self,info); + } + + public PyObject __call__(PyObject arg0) { + PyObject ret=self.timetuple___eq__(arg0); + if (ret==null) + return Py.NotImplemented; + return ret; + } + + public PyObject inst_call(PyObject gself,PyObject arg0) { + PyTimeTuple self=(PyTimeTuple)gself; + PyObject ret=self.timetuple___eq__(arg0); + if (ret==null) + return Py.NotImplemented; + return ret; + } + + } + dict.__setitem__("__eq__",new PyMethodDescr("__eq__",PyTimeTuple.class,1,1,new exposed___eq__(null,null))); + class exposed___reduce__ extends PyBuiltinFunctionNarrow { + + private PyTimeTuple self; + + public PyObject getSelf() { + return self; + } + + exposed___reduce__(PyTimeTuple self,PyBuiltinFunction.Info info) { + super(info); + this.self=self; + } + + public PyBuiltinFunction makeBound(PyObject self) { + return new exposed___reduce__((PyTimeTuple)self,info); + } + + public PyObject __call__() { + return self.timetuple___reduce__(); + } + + public PyObject inst_call(PyObject gself) { + PyTimeTuple self=(PyTimeTuple)gself; + return self.timetuple___reduce__(); + } + + } + dict.__setitem__("__reduce__",new PyMethodDescr("__reduce__",PyTimeTuple.class,0,0,new exposed___reduce__(null,null))); } + //~ END GENERATED REGION -- DO NOT EDIT SEE gexpose.py private static final PyType TIMETUPLETYPE = PyType.fromClass(PyTimeTuple.class); @@ -134,4 +245,26 @@ int i = cmp(this, tl, o, ol); return (i < 0) ? Py.Zero : Py.One; } + + /** + * Used for pickling. + * + * @return a tuple of (class, tuple) + */ + public PyObject __reduce__() { + return timetuple___reduce__(); + } + + final PyObject timetuple___reduce__() { + PyTuple newargs = __getnewargs__(); + return new PyTuple(new PyObject[]{ + getType(), newargs + }); + } + + public PyTuple __getnewargs__() { + return new PyTuple(new PyObject[] + {new PyList(getArray())} + ); + } } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <fwi...@us...> - 2006-05-31 20:37:10
|
Revision: 2788 Author: fwierzbicki Date: 2006-05-31 13:37:06 -0700 (Wed, 31 May 2006) ViewCVS: http://svn.sourceforge.net/jython/?rev=2788&view=rev Log Message: ----------- Removing jdk 1.4 stuff. Modified Paths: -------------- trunk/jython/src/org/python/core/PyArray.java trunk/jython/src/org/python/core/PyObjectList.java Modified: trunk/jython/src/org/python/core/PyArray.java =================================================================== --- trunk/jython/src/org/python/core/PyArray.java 2006-05-31 19:44:22 UTC (rev 2787) +++ trunk/jython/src/org/python/core/PyArray.java 2006-05-31 20:37:06 UTC (rev 2788) @@ -79,7 +79,9 @@ public static PyArray zeros(int n, char typecode) { PyArray array = zeros(n, char2class(typecode)); - array.typecode = Character.toString(typecode); + //Character.toString(char) is jdk 1.4 + //array.typecode = Character.toString(typecode); + array.typecode = "" + typecode; return array; } @@ -91,7 +93,9 @@ public static PyArray array(PyObject seq, char typecode) { PyArray array = PyArray.array(seq, char2class(typecode)); - array.typecode = Character.toString(typecode); + //Character.toString(char) is jdk 1.4 + //array.typecode = Character.toString(typecode); + array.typecode = "" + typecode; return array; } Modified: trunk/jython/src/org/python/core/PyObjectList.java =================================================================== --- trunk/jython/src/org/python/core/PyObjectList.java 2006-05-31 19:44:22 UTC (rev 2787) +++ trunk/jython/src/org/python/core/PyObjectList.java 2006-05-31 20:37:06 UTC (rev 2788) @@ -5,7 +5,6 @@ import java.util.AbstractList; import java.util.Collection; import java.util.Iterator; -import java.util.RandomAccess; /** * <CODE>java.util.List</CODE> implementation using an underlying PyObject @@ -20,7 +19,8 @@ * @author Clark Updike */ public class PyObjectList - extends AbstractList implements RandomAccess, Cloneable, Serializable { + //RandomAcces is jdk 1.4 -- restore when 1.4 becomes the min + extends AbstractList implements /*RandomAccess,*/ Cloneable, Serializable { /* Design note: * This class let's PySequenceList implement java.util.List by delegating This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <fwi...@us...> - 2006-06-08 02:57:43
|
Revision: 2804 Author: fwierzbicki Date: 2006-06-07 13:19:37 -0700 (Wed, 07 Jun 2006) ViewCVS: http://svn.sourceforge.net/jython/?rev=2804&view=rev Log Message: ----------- Changed calls that return "this", like int's version of __int__ to return new objects instead. This is necessary to support subclasses properly, so that int(derived_from_int) will actually be of type int, and not derived_from_int. Modified Paths: -------------- trunk/jython/src/org/python/core/Py.java trunk/jython/src/org/python/core/PyComplex.java trunk/jython/src/org/python/core/PyDictionary.java trunk/jython/src/org/python/core/PyFloat.java trunk/jython/src/org/python/core/PyInteger.java trunk/jython/src/org/python/core/PyLong.java Modified: trunk/jython/src/org/python/core/Py.java =================================================================== --- trunk/jython/src/org/python/core/Py.java 2006-06-07 18:52:25 UTC (rev 2803) +++ trunk/jython/src/org/python/core/Py.java 2006-06-07 20:19:37 UTC (rev 2804) @@ -462,6 +462,10 @@ return new PyLong(i); } + public static PyLong newLong(int i) { + return new PyLong(i); + } + public static PyComplex newImaginary(double v) { return new PyComplex(0, v); } Modified: trunk/jython/src/org/python/core/PyComplex.java =================================================================== --- trunk/jython/src/org/python/core/PyComplex.java 2006-06-07 18:52:25 UTC (rev 2803) +++ trunk/jython/src/org/python/core/PyComplex.java 2006-06-07 20:19:37 UTC (rev 2804) @@ -1570,7 +1570,7 @@ } final PyObject complex___pos__() { - return this; + return new PyComplex(real, imag); } public PyObject __invert__() { @@ -1612,7 +1612,7 @@ } public PyComplex __complex__() { - return this; + return new PyComplex(real, imag); } public PyComplex conjugate() { Modified: trunk/jython/src/org/python/core/PyDictionary.java =================================================================== --- trunk/jython/src/org/python/core/PyDictionary.java 2006-06-07 18:52:25 UTC (rev 2803) +++ trunk/jython/src/org/python/core/PyDictionary.java 2006-06-07 20:19:37 UTC (rev 2804) @@ -975,9 +975,13 @@ + /* commenting this out -- PyObject.safeRepr() does the same thing, and this one + messes up subclasses of dict. XXX: delete all of this if this turns out okay. + public String safeRepr() throws PyIgnoreMethodTag { return "'dict' object"; } + */ public int __len__() { return dict___len__(); Modified: trunk/jython/src/org/python/core/PyFloat.java =================================================================== --- trunk/jython/src/org/python/core/PyFloat.java 2006-06-07 18:52:25 UTC (rev 2803) +++ trunk/jython/src/org/python/core/PyFloat.java 2006-06-07 20:19:37 UTC (rev 2804) @@ -880,12 +880,12 @@ } public PyObject __call__() { - return Py.newFloat(self.float_hashCode()); + return Py.newInteger(self.float_hashCode()); } public PyObject inst_call(PyObject gself) { PyFloat self=(PyFloat)gself; - return Py.newFloat(self.float_hashCode()); + return Py.newInteger(self.float_hashCode()); } } @@ -1309,7 +1309,7 @@ } final PyObject float___pos__() { - return this; + return Py.newFloat(value); } public PyObject __invert__() { @@ -1322,7 +1322,7 @@ final PyObject float___abs__() { if (value >= 0) - return this; + return Py.newFloat(value); else return __neg__(); } @@ -1351,7 +1351,7 @@ } final PyFloat float___float__() { - return this; + return Py.newFloat(value); } public PyComplex __complex__() { return new PyComplex(value, 0.); Modified: trunk/jython/src/org/python/core/PyInteger.java =================================================================== --- trunk/jython/src/org/python/core/PyInteger.java 2006-06-07 18:52:25 UTC (rev 2803) +++ trunk/jython/src/org/python/core/PyInteger.java 2006-06-07 20:19:37 UTC (rev 2804) @@ -1536,8 +1536,8 @@ int xdivy = divide(value, rightv); return new PyTuple(new PyObject[] { - new PyInteger(xdivy), - new PyInteger(modulo(value, rightv, xdivy)) + Py.newInteger(xdivy), + Py.newInteger(modulo(value, rightv, xdivy)) }); } @@ -1642,7 +1642,7 @@ return null; if (rightv > 31) - return new PyInteger(0); + return Py.newInteger(0); else if(rightv < 0) throw Py.ValueError("negative shift count"); return Py.newInteger(value << rightv); @@ -1723,7 +1723,7 @@ } final PyObject int___pos__() { - return this; + return Py.newInteger(value); } public PyObject __abs__() { @@ -1732,7 +1732,7 @@ final PyObject int___abs__() { if (value >= 0) - return this; + return Py.newInteger(value); else return __neg__(); } @@ -1750,7 +1750,7 @@ } final PyInteger int___int__() { - return this; + return Py.newInteger(value); } public PyLong __long__() { @@ -1824,7 +1824,7 @@ return new PyTuple(new PyObject[]{ getType(), new PyTuple(new PyObject[]{ - new PyInteger(getValue()) + Py.newInteger(value) }) }); } Modified: trunk/jython/src/org/python/core/PyLong.java =================================================================== --- trunk/jython/src/org/python/core/PyLong.java 2006-06-07 18:52:25 UTC (rev 2803) +++ trunk/jython/src/org/python/core/PyLong.java 2006-06-07 20:19:37 UTC (rev 2804) @@ -1152,7 +1152,7 @@ Object o = x.__tojava__(BigInteger.class); if(o != Py.NoConversion) { - return new PyLong((BigInteger)o); + return Py.newLong((BigInteger)o); } if (base == -909) { @@ -1333,7 +1333,7 @@ return other; else if (other instanceof PyInteger) { - return new PyLong(((PyInteger)other).getValue()); + return Py.newLong(((PyInteger)other).getValue()); } else { return Py.None; } @@ -1360,7 +1360,7 @@ final PyObject long___add__(PyObject right) { if (!canCoerce(right)) return null; - return new PyLong(value.add(coerce(right))); + return Py.newLong(value.add(coerce(right))); } public PyObject __radd__(PyObject left) { @@ -1378,7 +1378,7 @@ final PyObject long___sub__(PyObject right) { if (!canCoerce(right)) return null; - return new PyLong(value.subtract(coerce(right))); + return Py.newLong(value.subtract(coerce(right))); } public PyObject __rsub__(PyObject left) { @@ -1386,7 +1386,7 @@ } final PyObject long___rsub__(PyObject left) { - return new PyLong(coerce(left).subtract(value)); + return Py.newLong(coerce(left).subtract(value)); } public PyObject __mul__(PyObject right) { @@ -1399,7 +1399,7 @@ if (!canCoerce(right)) return null; - return new PyLong(value.multiply(coerce(right))); + return Py.newLong(value.multiply(coerce(right))); } public PyObject __rmul__(PyObject left) { @@ -1411,7 +1411,7 @@ return ((PySequence) left).repeat(coerceInt(this)); if (!canCoerce(left)) return null; - return new PyLong(coerce(left).multiply(value)); + return Py.newLong(coerce(left).multiply(value)); } // Getting signs correct for integer division @@ -1441,7 +1441,7 @@ return null; if (Options.divisionWarning > 0) Py.warning(Py.DeprecationWarning, "classic long division"); - return new PyLong(divide(value, coerce(right))); + return Py.newLong(divide(value, coerce(right))); } public PyObject __rdiv__(PyObject left) { @@ -1453,7 +1453,7 @@ return null; if (Options.divisionWarning > 0) Py.warning(Py.DeprecationWarning, "classic long division"); - return new PyLong(divide(coerce(left), value)); + return Py.newLong(divide(coerce(left), value)); } public PyObject __floordiv__(PyObject right) { @@ -1463,7 +1463,7 @@ final PyObject long___floordiv__(PyObject right) { if (!canCoerce(right)) return null; - return new PyLong(divide(value, coerce(right))); + return Py.newLong(divide(value, coerce(right))); } public PyObject __rfloordiv__(PyObject left) { @@ -1473,7 +1473,7 @@ final PyObject long___rfloordiv__(PyObject left) { if (!canCoerce(left)) return null; - return new PyLong(divide(coerce(left), value)); + return Py.newLong(divide(coerce(left), value)); } private static final PyFloat true_divide(BigInteger a,BigInteger b) { @@ -1536,7 +1536,7 @@ if (!canCoerce(right)) return null; BigInteger rightv = coerce(right); - return new PyLong(modulo(value, rightv, divide(value, rightv))); + return Py.newLong(modulo(value, rightv, divide(value, rightv))); } public PyObject __rmod__(PyObject left) { @@ -1547,7 +1547,7 @@ if (!canCoerce(left)) return null; BigInteger leftv = coerce(left); - return new PyLong(modulo(leftv, value, divide(leftv, value))); + return Py.newLong(modulo(leftv, value, divide(leftv, value))); } public PyObject __divmod__(PyObject right) { @@ -1561,8 +1561,8 @@ BigInteger xdivy = divide(value, rightv); return new PyTuple(new PyObject[] { - new PyLong(xdivy), - new PyLong(modulo(value, rightv, xdivy)) + Py.newLong(xdivy), + Py.newLong(modulo(value, rightv, xdivy)) }); } @@ -1577,8 +1577,8 @@ BigInteger xdivy = divide(leftv, value); return new PyTuple(new PyObject[] { - new PyLong(xdivy), - new PyLong(modulo(leftv, value, xdivy)) + Py.newLong(xdivy), + Py.newLong(modulo(leftv, value, xdivy)) }); } @@ -1614,7 +1614,7 @@ throw Py.ZeroDivisionError("zero to a negative power"); } if (modulo == null) - return new PyLong(value.pow(y.intValue())); + return Py.newLong(value.pow(y.intValue())); else { // This whole thing can be trivially rewritten after bugs // in modPow are fixed by SUN @@ -1625,7 +1625,7 @@ if (zi == 0) throw Py.ValueError("pow(x, y, z) with z == 0"); if (zi == 1 || zi == -1) - return new PyLong(0); + return Py.newLong(0); if (z.compareTo(BigInteger.valueOf(0)) <= 0) { // Handle negative modulo's specially @@ -1634,16 +1634,16 @@ }*/ y = value.modPow(y, z.negate()); if (y.compareTo(BigInteger.valueOf(0)) > 0) { - return new PyLong(z.add(y)); + return Py.newLong(z.add(y)); } else { - return new PyLong(y); + return Py.newLong(y); } //return __pow__(right).__mod__(modulo); } else { // XXX: 1.1 no longer supported so review this. // This is buggy in SUN's jdk1.1.5 // Extra __mod__ improves things slightly - return new PyLong(value.modPow(y, z)); + return Py.newLong(value.modPow(y, z)); //return __pow__(right).__mod__(modulo); } } @@ -1669,7 +1669,7 @@ int rightv = coerceInt(right); if(rightv < 0) throw Py.ValueError("negative shift count"); - return new PyLong(value.shiftLeft(rightv)); + return Py.newLong(value.shiftLeft(rightv)); } public PyObject __rshift__(PyObject right) { @@ -1682,7 +1682,7 @@ int rightv = coerceInt(right); if(rightv < 0) throw Py.ValueError("negative shift count"); - return new PyLong(value.shiftRight(rightv)); + return Py.newLong(value.shiftRight(rightv)); } public PyObject __and__(PyObject right) { @@ -1692,7 +1692,7 @@ final PyObject long___and__(PyObject right) { if (!canCoerce(right)) return null; - return new PyLong(value.and(coerce(right))); + return Py.newLong(value.and(coerce(right))); } public PyObject __rand__(PyObject left) { @@ -1702,7 +1702,7 @@ final PyObject long___rand__(PyObject left) { if (!canCoerce(left)) return null; - return new PyLong(coerce(left).and(value)); + return Py.newLong(coerce(left).and(value)); } public PyObject __xor__(PyObject right) { @@ -1712,7 +1712,7 @@ final PyObject long___xor__(PyObject right) { if (!canCoerce(right)) return null; - return new PyLong(value.xor(coerce(right))); + return Py.newLong(value.xor(coerce(right))); } public PyObject __rxor__(PyObject left) { @@ -1722,7 +1722,7 @@ final PyObject long___rxor__(PyObject left) { if (!canCoerce(left)) return null; - return new PyLong(coerce(left).xor(value)); + return Py.newLong(coerce(left).xor(value)); } public PyObject __or__(PyObject right) { @@ -1732,7 +1732,7 @@ final PyObject long___or__(PyObject right) { if (!canCoerce(right)) return null; - return new PyLong(value.or(coerce(right))); + return Py.newLong(value.or(coerce(right))); } public PyObject __ror__(PyObject left) { @@ -1742,7 +1742,7 @@ final PyObject long___ror__(PyObject left) { if (!canCoerce(left)) return null; - return new PyLong(coerce(left).or(value)); + return Py.newLong(coerce(left).or(value)); } public PyObject __neg__() { @@ -1750,7 +1750,7 @@ } final PyObject long___neg__() { - return new PyLong(value.negate()); + return Py.newLong(value.negate()); } public PyObject __pos__() { @@ -1758,14 +1758,14 @@ } final PyObject long___pos__() { - return this; + return Py.newLong(value); } public PyObject __abs__() { return long___abs__(); } final PyObject long___abs__() { - return new PyLong(value.abs()); + return Py.newLong(value.abs()); } public PyObject __invert__() { @@ -1773,7 +1773,7 @@ } final PyObject long___invert__() { - return new PyLong(value.not()); + return Py.newLong(value.not()); } public PyObject __int__() { @@ -1783,9 +1783,9 @@ final PyObject long___int__() { long v = value.longValue(); if (v < Integer.MIN_VALUE || v > Integer.MAX_VALUE) { - return this; + return Py.newLong(value); } - return new PyInteger((int)getLong(Integer.MIN_VALUE, + return Py.newInteger((int)getLong(Integer.MIN_VALUE, Integer.MAX_VALUE)); } @@ -1795,7 +1795,7 @@ } final PyLong long___long__() { - return this; + return Py.newLong(value); } public PyFloat __float__() { This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <fwi...@us...> - 2006-06-12 19:31:19
|
Revision: 2816 Author: fwierzbicki Date: 2006-06-12 12:31:11 -0700 (Mon, 12 Jun 2006) ViewCVS: http://svn.sourceforge.net/jython/?rev=2816&view=rev Log Message: ----------- A very simple-minded implementation of slots. It may have bugs since I have written it to pass the "slots" test in test_descr. It does not do anything about __weakref__ yet, since __weakref__ needs some work yet. Modified Paths: -------------- trunk/jython/src/org/python/core/PyObject.java trunk/jython/src/org/python/core/PyType.java Modified: trunk/jython/src/org/python/core/PyObject.java =================================================================== --- trunk/jython/src/org/python/core/PyObject.java 2006-06-12 01:47:39 UTC (rev 2815) +++ trunk/jython/src/org/python/core/PyObject.java 2006-06-12 19:31:11 UTC (rev 2816) @@ -2,6 +2,7 @@ package org.python.core; import java.text.MessageFormat; +import java.util.List; /** * All objects known to the Jython runtime system are represented @@ -2820,14 +2821,25 @@ throw Py.AttributeError("object internal __delete__ impl is abstract"); } + private void slotscheck(String name) { + List slotnames = objtype.getSlotnames(); + if (slotnames != null) { + if (!slotnames.contains(name) && !slotnames.contains("__dict__")) { + noAttributeError(name); + } + } + } + // name must be interned final PyObject object___findattr__(String name) { - PyObject descr = objtype.lookup(name); PyObject res; if (descr != null) { if (descr.isDataDescr()) { + if (objtype.hide_dict && name.equals("__dict__")) { + noAttributeError(name); + } res = descr.__get__(this, objtype); if (res != null) return res; @@ -2856,6 +2868,7 @@ if (descr != null) { set = descr.implementsDescrSet(); if (set && descr.isDataDescr()) { + //slotscheck(name); descr.__set__(this, value); return; } @@ -2863,16 +2876,19 @@ PyObject obj_dict = fastGetDict(); if (obj_dict != null) { + slotscheck(name); obj_dict.__setitem__(name, value); return; } if (set) { + //XXX: need slotscheck here? descr.__set__(this, value); } - if (descr != null) + if (descr != null) { readonlyAttributeError(name); + } noAttributeError(name); } Modified: trunk/jython/src/org/python/core/PyType.java =================================================================== --- trunk/jython/src/org/python/core/PyType.java 2006-06-12 01:47:39 UTC (rev 2815) +++ trunk/jython/src/org/python/core/PyType.java 2006-06-12 19:31:11 UTC (rev 2816) @@ -8,6 +8,7 @@ import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; +import java.util.List; /** * first-class Python type. @@ -61,7 +62,7 @@ } } - dict.__setitem__("mro", new PyClassMethod(new PyMethodDescr("mro",PyType.class,0,1,new exposed_mro(null,null)))); + dict.__setitem__("mro",new PyClassMethod(new PyMethodDescr("mro",PyType.class,0,1,new exposed_mro(null,null)))); class exposed___getattribute__ extends PyBuiltinFunctionNarrow { private PyType self; @@ -381,16 +382,22 @@ return null; } + public List getSlotnames() { + return slotnames; + } + + private String name; private PyType base; private PyObject[] bases; private PyObject dict; private PyObject[] mro; private Class underlying_class; + private List slotnames; private boolean non_instantiable = false; - boolean has_set, has_delete; + boolean has_set, has_delete, hide_dict; private boolean needs_finalizer; @@ -701,7 +708,32 @@ } // xxx also __doc__ __module__ - // xxx __slots__! + List slotnames = null; + boolean hide_dict = false; + + PyObject slots = dict.__finditem__("__slots__"); + if (slots != null) { + hide_dict = true; + if (base.nuserslots > 0) { + nuserslots = base.nuserslots; + slotnames = new ArrayList(base.getSlotnames()); + } + else { + slotnames = new ArrayList(); + } + PyObject iter = slots.__iter__(); + PyObject slotname; + for (; (slotname = iter.__iternext__())!= null; ) { + confirmIdentifier(slotname); + String slotstring = slotname.toString(); + if (slotstring.equals("__dict__")) { + hide_dict = false; + } + slotnames.add(mangleName(name, slotstring)); + nuserslots += 1; + } + } + PyType newtype; if (new_.for_type == metatype) { newtype = new PyType(); // xxx set metatype @@ -715,9 +747,12 @@ newtype.needs_userdict = needs_userdict; newtype.nuserslots = nuserslots; + newtype.hide_dict = hide_dict; newtype.dict = dict; + newtype.slotnames = slotnames; + // special case __new__, if function => static method PyObject tmp = dict.__finditem__("__new__"); if (tmp != null && tmp instanceof PyFunction) { // xxx java functions? @@ -1442,5 +1477,41 @@ return invoke_new_(new_,this,true,args,keywords); } + //XXX: consider pulling this out into a generally accessible place + // I bet this is duplicated more or less in other places. + private static void confirmIdentifier(PyObject o) { + String msg = "__slots__ must be identifiers"; + if (o == Py.None) { + throw Py.TypeError(msg); + } + String identifier = o.toString(); + if (identifier == null || + identifier.length() < 1 || + (!Character.isLetter(identifier.charAt(0)) && identifier.charAt(0) != '_') + ) { + throw Py.TypeError(msg); + } + char[] chars = identifier.toCharArray(); + for(int i = 0; i < chars.length; i++) { + if (!Character.isLetterOrDigit(chars[i]) && chars[i] != '_') { + throw Py.TypeError(msg); + } + } + } + //XXX: copied from CodeCompiler.java and changed variable names. + // Maybe this should go someplace for all classes to use. + private static String mangleName(String classname, String methodname) { + if (classname != null && methodname.startsWith("__") && + !methodname.endsWith("__")) + { + //remove leading '_' from classname + int i = 0; + while (classname.charAt(i) == '_') + i++; + return "_"+classname.substring(i)+methodname; + } + return methodname; + } + } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: Samuele P. <ped...@st...> - 2006-06-12 19:54:18
|
fwi...@us... wrote: > Revision: 2816 > Author: fwierzbicki > Date: 2006-06-12 12:31:11 -0700 (Mon, 12 Jun 2006) > ViewCVS: http://svn.sourceforge.net/jython/?rev=2816&view=rev > > Log Message: > ----------- > A very simple-minded implementation of slots. It may have bugs since I have > written it to pass the "slots" test in test_descr. It does not do anything about > __weakref__ yet, since __weakref__ needs some work yet. > I don't understand the need for changes in PyObject, __dict__ and slots should really be reflected by the presence absence of descriptors in the type dict, is not an implementation detail, taking a slot descriptor and using it directly is quite common! > Modified Paths: > -------------- > trunk/jython/src/org/python/core/PyObject.java > trunk/jython/src/org/python/core/PyType.java > Modified: trunk/jython/src/org/python/core/PyObject.java > =================================================================== > --- trunk/jython/src/org/python/core/PyObject.java 2006-06-12 01:47:39 UTC (rev 2815) > +++ trunk/jython/src/org/python/core/PyObject.java 2006-06-12 19:31:11 UTC (rev 2816) > @@ -2,6 +2,7 @@ > package org.python.core; > > import java.text.MessageFormat; > +import java.util.List; > > /** > * All objects known to the Jython runtime system are represented > @@ -2820,14 +2821,25 @@ > throw Py.AttributeError("object internal __delete__ impl is abstract"); > } > > + private void slotscheck(String name) { > + List slotnames = objtype.getSlotnames(); > + if (slotnames != null) { > + if (!slotnames.contains(name) && !slotnames.contains("__dict__")) { > + noAttributeError(name); > + } > + } > + } > + > // name must be interned > final PyObject object___findattr__(String name) { > - > PyObject descr = objtype.lookup(name); > PyObject res; > > if (descr != null) { > if (descr.isDataDescr()) { > + if (objtype.hide_dict && name.equals("__dict__")) { > + noAttributeError(name); > + } > res = descr.__get__(this, objtype); > if (res != null) > return res; > @@ -2856,6 +2868,7 @@ > if (descr != null) { > set = descr.implementsDescrSet(); > if (set && descr.isDataDescr()) { > + //slotscheck(name); > descr.__set__(this, value); > return; > } > @@ -2863,16 +2876,19 @@ > > PyObject obj_dict = fastGetDict(); > if (obj_dict != null) { > + slotscheck(name); > obj_dict.__setitem__(name, value); > return; > } > > if (set) { > + //XXX: need slotscheck here? > descr.__set__(this, value); > } > > - if (descr != null) > + if (descr != null) { > readonlyAttributeError(name); > + } > > noAttributeError(name); > } > > Modified: trunk/jython/src/org/python/core/PyType.java > =================================================================== > --- trunk/jython/src/org/python/core/PyType.java 2006-06-12 01:47:39 UTC (rev 2815) > +++ trunk/jython/src/org/python/core/PyType.java 2006-06-12 19:31:11 UTC (rev 2816) > @@ -8,6 +8,7 @@ > import java.util.ArrayList; > import java.util.HashMap; > import java.util.Iterator; > +import java.util.List; > > /** > * first-class Python type. > @@ -61,7 +62,7 @@ > } > > } > - dict.__setitem__("mro", new PyClassMethod(new PyMethodDescr("mro",PyType.class,0,1,new exposed_mro(null,null)))); > + dict.__setitem__("mro",new PyClassMethod(new PyMethodDescr("mro",PyType.class,0,1,new exposed_mro(null,null)))); > class exposed___getattribute__ extends PyBuiltinFunctionNarrow { > > private PyType self; > @@ -381,16 +382,22 @@ > return null; > } > > + public List getSlotnames() { > + return slotnames; > + } > + > + > private String name; > private PyType base; > private PyObject[] bases; > private PyObject dict; > private PyObject[] mro; > private Class underlying_class; > + private List slotnames; > > private boolean non_instantiable = false; > > - boolean has_set, has_delete; > + boolean has_set, has_delete, hide_dict; > > private boolean needs_finalizer; > > @@ -701,7 +708,32 @@ > } > > // xxx also __doc__ __module__ > - // xxx __slots__! > + List slotnames = null; > + boolean hide_dict = false; > + > + PyObject slots = dict.__finditem__("__slots__"); > + if (slots != null) { > + hide_dict = true; > + if (base.nuserslots > 0) { > + nuserslots = base.nuserslots; > + slotnames = new ArrayList(base.getSlotnames()); > + } > + else { > + slotnames = new ArrayList(); > + } > + PyObject iter = slots.__iter__(); > + PyObject slotname; > + for (; (slotname = iter.__iternext__())!= null; ) { > + confirmIdentifier(slotname); > + String slotstring = slotname.toString(); > + if (slotstring.equals("__dict__")) { > + hide_dict = false; > + } > + slotnames.add(mangleName(name, slotstring)); > + nuserslots += 1; > + } > + } > + > PyType newtype; > if (new_.for_type == metatype) { > newtype = new PyType(); // xxx set metatype > @@ -715,9 +747,12 @@ > > newtype.needs_userdict = needs_userdict; > newtype.nuserslots = nuserslots; > + newtype.hide_dict = hide_dict; > > newtype.dict = dict; > > + newtype.slotnames = slotnames; > + > // special case __new__, if function => static method > PyObject tmp = dict.__finditem__("__new__"); > if (tmp != null && tmp instanceof PyFunction) { // xxx java functions? > @@ -1442,5 +1477,41 @@ > > return invoke_new_(new_,this,true,args,keywords); > } > + //XXX: consider pulling this out into a generally accessible place > + // I bet this is duplicated more or less in other places. > + private static void confirmIdentifier(PyObject o) { > + String msg = "__slots__ must be identifiers"; > + if (o == Py.None) { > + throw Py.TypeError(msg); > + } > + String identifier = o.toString(); > + if (identifier == null || > + identifier.length() < 1 || > + (!Character.isLetter(identifier.charAt(0)) && identifier.charAt(0) != '_') > + ) { > + throw Py.TypeError(msg); > + } > + char[] chars = identifier.toCharArray(); > + for(int i = 0; i < chars.length; i++) { > + if (!Character.isLetterOrDigit(chars[i]) && chars[i] != '_') { > + throw Py.TypeError(msg); > + } > + } > + } > > + //XXX: copied from CodeCompiler.java and changed variable names. > + // Maybe this should go someplace for all classes to use. > + private static String mangleName(String classname, String methodname) { > + if (classname != null && methodname.startsWith("__") && > + !methodname.endsWith("__")) > + { > + //remove leading '_' from classname > + int i = 0; > + while (classname.charAt(i) == '_') > + i++; > + return "_"+classname.substring(i)+methodname; > + } > + return methodname; > + } > + > } > > > This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. > > > > _______________________________________________ > Jython-checkins mailing list > Jyt...@li... > https://lists.sourceforge.net/lists/listinfo/jython-checkins |
From: <fwi...@us...> - 2006-06-25 03:41:41
|
Revision: 2829 Author: fwierzbicki Date: 2006-06-24 20:41:37 -0700 (Sat, 24 Jun 2006) ViewCVS: http://svn.sourceforge.net/jython/?rev=2829&view=rev Log Message: ----------- merge from 2.3 branch. Mainly replaced calls to value in PyInteger with getValue() for future subclassing in PyBoolean. slight clean of PyObject. Modified Paths: -------------- trunk/jython/src/org/python/core/PyInteger.java trunk/jython/src/org/python/core/PyObject.java Modified: trunk/jython/src/org/python/core/PyInteger.java =================================================================== --- trunk/jython/src/org/python/core/PyInteger.java 2006-06-25 03:34:21 UTC (rev 2828) +++ trunk/jython/src/org/python/core/PyInteger.java 2006-06-25 03:41:37 UTC (rev 2829) @@ -1245,7 +1245,7 @@ } final String int_toString() { - return Integer.toString(value); + return Integer.toString(getValue()); } public int hashCode() { @@ -1253,7 +1253,7 @@ } final int int_hashCode() { - return value; + return getValue(); } private static void err_ovf(String msg) { @@ -1270,7 +1270,7 @@ } final boolean int___nonzero__() { - return value != 0; + return getValue() != 0; } public Object __tojava__(Class c) { @@ -1278,22 +1278,22 @@ c == Object.class || c == Integer.class || c == Serializable.class) { - return new Integer(value); + return new Integer(getValue()); } if (c == Boolean.TYPE || c == Boolean.class) - return new Boolean(value != 0); + return new Boolean(getValue() != 0); if (c == Byte.TYPE || c == Byte.class) - return new Byte((byte)value); + return new Byte((byte)getValue()); if (c == Short.TYPE || c == Short.class) - return new Short((short)value); + return new Short((short)getValue()); if (c == Long.TYPE || c == Long.class) - return new Long(value); + return new Long(getValue()); if (c == Float.TYPE || c == Float.class) - return new Float(value); + return new Float(getValue()); if (c == Double.TYPE || c == Double.class) - return new Double(value); + return new Double(getValue()); return super.__tojava__(c); } @@ -1305,7 +1305,7 @@ if (!canCoerce(other)) return -2; int v = coerce(other); - return value < v ? -1 : value > v ? 1 : 0; + return getValue() < v ? -1 : getValue() > v ? 1 : 0; } public Object __coerce_ex__(PyObject other) { @@ -1321,7 +1321,7 @@ private static final int coerce(PyObject other) { if (other instanceof PyInteger) - return ((PyInteger) other).value; + return ((PyInteger) other).getValue(); else throw Py.TypeError("xxx"); } @@ -1335,7 +1335,7 @@ if (!canCoerce(right)) return null; int rightv = coerce(right); - int a = value; + int a = getValue(); int b = rightv; int x = a + b; if ((x^a) >= 0 || (x^b) >= 0) @@ -1367,7 +1367,7 @@ final PyObject int___sub__(PyObject right) { if (!canCoerce(right)) return null; - return _sub(value, coerce(right)); + return _sub(getValue(), coerce(right)); } public PyObject __rsub__(PyObject left) { @@ -1377,7 +1377,7 @@ final PyObject int___rsub__(PyObject left) { if (!canCoerce(left)) return null; - return _sub(coerce(left), value); + return _sub(coerce(left), getValue()); } public PyObject __mul__(PyObject right) { @@ -1386,15 +1386,15 @@ final PyObject int___mul__(PyObject right) { if (right instanceof PySequence) - return ((PySequence) right).repeat(value); + return ((PySequence) right).repeat(getValue()); if (!canCoerce(right)) return null; int rightv = coerce(right); - double x = (double)value; + double x = (double)getValue(); x *= rightv; - //long x = ((long)value)*((PyInteger)right).value; + //long x = ((long)getValue())*((PyInteger)right).getValue(); //System.out.println("mul: "+this+" * "+right+" = "+x); if (x <= Integer.MAX_VALUE && x >= Integer.MIN_VALUE) @@ -1444,7 +1444,7 @@ return null; if (Options.divisionWarning > 0) Py.warning(Py.DeprecationWarning, "classic int division"); - return Py.newInteger(divide(value, coerce(right))); + return Py.newInteger(divide(getValue(), coerce(right))); } public PyObject __rdiv__(PyObject left) { @@ -1456,7 +1456,7 @@ return null; if (Options.divisionWarning > 0) Py.warning(Py.DeprecationWarning, "classic int division"); - return Py.newInteger(divide(coerce(left), value)); + return Py.newInteger(divide(coerce(left), getValue())); } public PyObject __floordiv__(PyObject right) { @@ -1466,7 +1466,7 @@ final PyObject int___floordiv__(PyObject right) { if (!canCoerce(right)) return null; - return Py.newInteger(divide(value, coerce(right))); + return Py.newInteger(divide(getValue(), coerce(right))); } public PyObject __rfloordiv__(PyObject left) { @@ -1476,7 +1476,7 @@ final PyObject int___rfloordiv__(PyObject left) { if (!canCoerce(left)) return null; - return Py.newInteger(divide(coerce(left), value)); + return Py.newInteger(divide(coerce(left), getValue())); } public PyObject __truediv__(PyObject right) { @@ -1511,7 +1511,8 @@ if (!canCoerce(right)) return null; int rightv = coerce(right); - return Py.newInteger(modulo(value, rightv, divide(value, rightv))); + int v = getValue(); + return Py.newInteger(modulo(v, rightv, divide(v, rightv))); } public PyObject __rmod__(PyObject left) { @@ -1522,7 +1523,8 @@ if (!canCoerce(left)) return null; int leftv = coerce(left); - return Py.newInteger(modulo(leftv, value, divide(leftv, value))); + int v = getValue(); + return Py.newInteger(modulo(leftv, v, divide(leftv, v))); } public PyObject __divmod__(PyObject right) { @@ -1534,10 +1536,11 @@ return null; int rightv = coerce(right); - int xdivy = divide(value, rightv); + int v = getValue(); + int xdivy = divide(v, rightv); return new PyTuple(new PyObject[] { Py.newInteger(xdivy), - Py.newInteger(modulo(value, rightv, xdivy)) + Py.newInteger(modulo(v, rightv, xdivy)) }); } @@ -1552,7 +1555,7 @@ if (modulo != null && !canCoerce(modulo)) return null; - return _pow(value, coerce(right), modulo, this, right); + return _pow(getValue(), coerce(right), modulo, this, right); } public PyObject __rpow__(PyObject left, PyObject modulo) { @@ -1562,7 +1565,7 @@ if (modulo != null && !canCoerce(modulo)) return null; - return _pow(coerce(left), value, modulo, left, this); + return _pow(coerce(left), getValue(), modulo, left, this); } private static PyObject _pow(int value, int pow, PyObject modulo, @@ -1637,7 +1640,7 @@ final PyObject int___lshift__(PyObject right) { int rightv; if (right instanceof PyInteger) - rightv = ((PyInteger)right).value; + rightv = ((PyInteger)right).getValue(); else return null; @@ -1645,7 +1648,7 @@ return Py.newInteger(0); else if(rightv < 0) throw Py.ValueError("negative shift count"); - return Py.newInteger(value << rightv); + return Py.newInteger(getValue() << rightv); } public PyObject __rshift__(PyObject right) { @@ -1655,14 +1658,14 @@ final PyObject int___rshift__(PyObject right) { int rightv; if (right instanceof PyInteger) - rightv = ((PyInteger)right).value; + rightv = ((PyInteger)right).getValue(); else return null; if(rightv < 0) throw Py.ValueError("negative shift count"); - return Py.newInteger(value >> rightv); + return Py.newInteger(getValue() >> rightv); } public PyObject __and__(PyObject right) { @@ -1672,11 +1675,11 @@ final PyObject int___and__(PyObject right) { int rightv; if (right instanceof PyInteger) - rightv = ((PyInteger)right).value; + rightv = ((PyInteger)right).getValue(); else return null; - return Py.newInteger(value & rightv); + return Py.newInteger(getValue() & rightv); } public PyObject __xor__(PyObject right) { @@ -1686,11 +1689,11 @@ final PyObject int___xor__(PyObject right) { int rightv; if (right instanceof PyInteger) - rightv = ((PyInteger)right).value; + rightv = ((PyInteger)right).getValue(); else return null; - return Py.newInteger(value ^ rightv); + return Py.newInteger(getValue() ^ rightv); } public PyObject __or__(PyObject right) { @@ -1700,11 +1703,11 @@ final PyObject int___or__(PyObject right) { int rightv; if (right instanceof PyInteger) - rightv = ((PyInteger)right).value; + rightv = ((PyInteger)right).getValue(); else return null; - return Py.newInteger(value | rightv); + return Py.newInteger(getValue() | rightv); } public PyObject __neg__() { @@ -1712,8 +1715,8 @@ } final PyObject int___neg__() { - int x = -value; - if (value < 0 && x < 0) + int x = -getValue(); + if (getValue() < 0 && x < 0) err_ovf("integer negation"); return Py.newInteger(x); } @@ -1723,7 +1726,7 @@ } final PyObject int___pos__() { - return Py.newInteger(value); + return Py.newInteger(getValue()); } public PyObject __abs__() { @@ -1731,8 +1734,8 @@ } final PyObject int___abs__() { - if (value >= 0) - return Py.newInteger(value); + if (getValue() >= 0) + return Py.newInteger(getValue()); else return __neg__(); } @@ -1742,7 +1745,7 @@ } final PyObject int___invert__() { - return Py.newInteger(~value); + return Py.newInteger(~getValue()); } public PyObject __int__() { @@ -1750,7 +1753,7 @@ } final PyInteger int___int__() { - return Py.newInteger(value); + return Py.newInteger(getValue()); } public PyLong __long__() { @@ -1758,7 +1761,7 @@ } final PyLong int___long__() { - return new PyLong(value); + return new PyLong(getValue()); } public PyFloat __float__() { @@ -1766,11 +1769,11 @@ } final PyFloat int___float__() { - return new PyFloat((double)value); + return new PyFloat((double)getValue()); } public PyComplex __complex__() { - return new PyComplex((double)value, 0.); + return new PyComplex((double)getValue(), 0.); } public PyString __oct__() { @@ -1778,11 +1781,11 @@ } final PyString int___oct__() { - if (value < 0) { + if (getValue() < 0) { return new PyString( - "0"+Long.toString(0x100000000l+(long)value, 8)); - } else if (value > 0) { - return new PyString("0"+Integer.toString(value, 8)); + "0"+Long.toString(0x100000000l+(long)getValue(), 8)); + } else if (getValue() > 0) { + return new PyString("0"+Integer.toString(getValue(), 8)); } else return new PyString("0"); } @@ -1792,11 +1795,11 @@ } final PyString int___hex__() { - if (value < 0) { + if (getValue() < 0) { return new PyString( - "0x"+Long.toString(0x100000000l+(long)value, 16)); + "0x"+Long.toString(0x100000000l+(long)getValue(), 16)); } else { - return new PyString("0x"+Integer.toString(value, 16)); + return new PyString("0x"+Integer.toString(getValue(), 16)); } } @@ -1824,7 +1827,7 @@ return new PyTuple(new PyObject[]{ getType(), new PyTuple(new PyObject[]{ - Py.newInteger(value) + Py.newInteger(getValue()) }) }); } Modified: trunk/jython/src/org/python/core/PyObject.java =================================================================== --- trunk/jython/src/org/python/core/PyObject.java 2006-06-25 03:34:21 UTC (rev 2828) +++ trunk/jython/src/org/python/core/PyObject.java 2006-06-25 03:41:37 UTC (rev 2829) @@ -2908,8 +2908,9 @@ descr.__delete__(this); } - if (descr != null) + if (descr != null) { readonlyAttributeError(name); + } noAttributeError(name); } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <cg...@us...> - 2006-08-12 19:13:50
|
Revision: 2884 Author: cgroves Date: 2006-08-12 12:13:39 -0700 (Sat, 12 Aug 2006) ViewCVS: http://svn.sourceforge.net/jython/?rev=2884&view=rev Log Message: ----------- merge of r2859 and r2866-2883 from the 2.3 branch Modified Paths: -------------- trunk/jython/src/org/python/core/BytecodeLoader2.java trunk/jython/src/org/python/core/JavaImporter.java trunk/jython/src/org/python/core/PyBuiltinFunction.java trunk/jython/src/org/python/core/PyCallIter.java trunk/jython/src/org/python/core/PyClass.java trunk/jython/src/org/python/core/PyEnumerate.java trunk/jython/src/org/python/core/PyGenerator.java trunk/jython/src/org/python/core/PyIterator.java trunk/jython/src/org/python/core/PyJavaClass.java trunk/jython/src/org/python/core/PySystemState.java trunk/jython/src/org/python/core/PyTableCode.java trunk/jython/src/org/python/core/PyTuple.java trunk/jython/src/org/python/core/PyType.java trunk/jython/src/org/python/core/PythonTraceFunction.java trunk/jython/src/org/python/core/SyspathJavaLoader.java trunk/jython/src/org/python/core/imp.java trunk/jython/src/org/python/parser/TreeBuilder.java Modified: trunk/jython/src/org/python/core/BytecodeLoader2.java =================================================================== --- trunk/jython/src/org/python/core/BytecodeLoader2.java 2006-08-12 18:56:26 UTC (rev 2883) +++ trunk/jython/src/org/python/core/BytecodeLoader2.java 2006-08-12 19:13:39 UTC (rev 2884) @@ -17,7 +17,7 @@ public void addParent(ClassLoader referent) { if (!this.parents.contains(referent)) { - this.parents.addElement(referent); + this.parents.add(0, referent); } } Modified: trunk/jython/src/org/python/core/JavaImporter.java =================================================================== --- trunk/jython/src/org/python/core/JavaImporter.java 2006-08-12 18:56:26 UTC (rev 2883) +++ trunk/jython/src/org/python/core/JavaImporter.java 2006-08-12 19:13:39 UTC (rev 2884) @@ -8,6 +8,13 @@ public JavaImporter() { super(); } + + public PyObject __call__(PyObject args[], String keywords[]) { + if(args[0].toString().endsWith("__classpath__")){ + return this; + } + throw Py.ImportError("unable to handle"); + } /** * Find the module for the fully qualified name. Modified: trunk/jython/src/org/python/core/PyBuiltinFunction.java =================================================================== --- trunk/jython/src/org/python/core/PyBuiltinFunction.java 2006-08-12 18:56:26 UTC (rev 2883) +++ trunk/jython/src/org/python/core/PyBuiltinFunction.java 2006-08-12 19:13:39 UTC (rev 2884) @@ -2,9 +2,6 @@ public abstract class PyBuiltinFunction extends PyObject implements PyType.Newstyle { - //~ BEGIN GENERATED REGION -- DO NOT EDIT SEE gexpose.py - /* type info */ - public static final String exposed_name="builtin_function_or_method"; public static void typeSetup(PyObject dict,PyType.Newstyle marker) { @@ -14,9 +11,10 @@ PyBuiltinFunction.class, "getSelf", null)); dict.__setitem__("__doc__", new PyGetSetDescr("__doc__", PyBuiltinFunction.class, "fastGetDoc", null)); + dict.__setitem__("__call__", new PyGetSetDescr("__call__", + PyBuiltinFunction.class, "makeCall", null)); } - //~ END GENERATED REGION -- DO NOT EDIT SEE gexpose.py - + public interface Info { String getName(); int getMaxargs(); @@ -156,4 +154,8 @@ public PyObject fastGetDoc() { return Py.None; } + + public PyObject makeCall(){ + return this; + } } Modified: trunk/jython/src/org/python/core/PyCallIter.java =================================================================== --- trunk/jython/src/org/python/core/PyCallIter.java 2006-08-12 18:56:26 UTC (rev 2883) +++ trunk/jython/src/org/python/core/PyCallIter.java 2006-08-12 19:13:39 UTC (rev 2884) @@ -6,6 +6,9 @@ private int idx; public PyCallIter(PyObject callable, PyObject sentinel) { + if(!__builtin__.callable(callable)) { + throw Py.TypeError("iter(v, w): v must be callable"); + } this.callable = callable; this.sentinel = sentinel; } @@ -15,8 +18,10 @@ try { val = callable.__call__(); } catch (PyException exc) { - if (Py.matchException(exc, Py.StopIteration)) + if (Py.matchException(exc, Py.StopIteration)){ + stopException = exc; return null; + } throw exc; } if (val._eq(sentinel).__nonzero__()) Modified: trunk/jython/src/org/python/core/PyClass.java =================================================================== --- trunk/jython/src/org/python/core/PyClass.java 2006-08-12 18:56:26 UTC (rev 2883) +++ trunk/jython/src/org/python/core/PyClass.java 2006-08-12 19:13:39 UTC (rev 2884) @@ -360,7 +360,7 @@ if (this == superclass) { return true; } - if (this.proxyClass != null && superclass.proxyClass != null) { + if (getProxyClass() != null && superclass.getProxyClass() != null) { if (superclass.proxyClass.isAssignableFrom(this.proxyClass)) { return true; } Modified: trunk/jython/src/org/python/core/PyEnumerate.java =================================================================== --- trunk/jython/src/org/python/core/PyEnumerate.java 2006-08-12 18:56:26 UTC (rev 2883) +++ trunk/jython/src/org/python/core/PyEnumerate.java 2006-08-12 19:13:39 UTC (rev 2884) @@ -107,8 +107,12 @@ PyObject next_index; next_item = en_sit.__iternext__(); - if(next_item == null) + if(next_item == null){ + if(en_sit instanceof PyIterator && ((PyIterator)en_sit).stopException != null){ + stopException = ((PyIterator)en_sit).stopException; + } return null; + } next_index = new PyInteger((int)en_index); en_index++; Modified: trunk/jython/src/org/python/core/PyGenerator.java =================================================================== --- trunk/jython/src/org/python/core/PyGenerator.java 2006-08-12 18:56:26 UTC (rev 2883) +++ trunk/jython/src/org/python/core/PyGenerator.java 2006-08-12 19:13:39 UTC (rev 2884) @@ -39,6 +39,13 @@ PyObject result = null; try { result = gi_frame.f_code.call(gi_frame, closure); + } catch(PyException e) { + if(!e.type.equals(Py.StopIteration)) { + throw e; + }else{ + stopException = e; + return null; + } } finally { gi_running = false; } Modified: trunk/jython/src/org/python/core/PyIterator.java =================================================================== --- trunk/jython/src/org/python/core/PyIterator.java 2006-08-12 18:56:26 UTC (rev 2883) +++ trunk/jython/src/org/python/core/PyIterator.java 2006-08-12 19:13:39 UTC (rev 2884) @@ -3,10 +3,14 @@ package org.python.core; /** - * An abstract helper class usefull when implementing an iterator object. - * This implementation supply a correct __iter__() and a next() method - * based on the __iternext__() implementation. - * The __iternext__() method must be supplied by the subclass. + * An abstract helper class usefull when implementing an iterator object. This + * implementation supply a correct __iter__() and a next() method based on the + * __iternext__() implementation. The __iternext__() method must be supplied by + * the subclass. + * + * If the implementation raises a StopIteration exception, it should be stored + * in stopException so the correct exception can be thrown to preserve the line + * numbers in the traceback. */ public abstract class PyIterator extends PyObject { public PyObject __iter__() { @@ -19,10 +23,18 @@ public PyObject next() { PyObject ret = __iternext__(); - if (ret == null) + if(ret == null) { + if(stopException != null) { + PyException toThrow = stopException; + stopException = null; + throw toThrow; + } throw Py.StopIteration(""); + } return ret; } - + public abstract PyObject __iternext__(); + + protected PyException stopException; } Modified: trunk/jython/src/org/python/core/PyJavaClass.java =================================================================== --- trunk/jython/src/org/python/core/PyJavaClass.java 2006-08-12 18:56:26 UTC (rev 2883) +++ trunk/jython/src/org/python/core/PyJavaClass.java 2006-08-12 19:13:39 UTC (rev 2884) @@ -159,9 +159,13 @@ setBeanInfoCustom(proxyClass, methods); setFields(proxyClass); setMethods(proxyClass, methods); - } catch (SecurityException se) {} + Class[] intfs = proxyClass.getInterfaces(); + for(int i = 0; i < intfs.length; i++) { + setMethods(intfs[i], intfs[i].getMethods()); + } + } catch(SecurityException se) {} } - + private synchronized void init__class__(Class c) { /* xxx disable opt, will need similar opt for types if (!PyObject.class.isAssignableFrom(c)) @@ -220,6 +224,7 @@ __bases__ = new PyTuple(bases); } + private void init(Class c) { init__class__(c); @@ -342,7 +347,6 @@ // See if any of my superclasses are using 'name' for something // else. Or if I'm already using it myself PyObject o = lookup(name, false); - // If it's being used as a function, then things get more // interesting... PyReflectedFunction func; @@ -356,8 +360,9 @@ some significant way, then return a duplicate and stick it in the __dict__ */ if (o1 != o) { - if (func.handles(meth)) + if (func.handles(meth)){ return; + } func = func.copy(); } func.addMethod(meth); @@ -376,8 +381,7 @@ } __dict__.__setitem__(name, func); } - - + /** * Return the list of all accessible methods for a class. This will * only the public methods unless Options.respectJavaAccessibility is @@ -415,7 +419,8 @@ continue; int mods = dc.getModifiers(); if(!(Modifier.isPublic(mods) || Modifier.isPrivate(mods) || Modifier.isProtected(mods))) { - // skip package protected classes such as AbstractStringBuilder or UNIXProcess + // skip package protected classes such as AbstractStringBuilder + // or UNIXProcess continue; } if (ignoreMethod(method)) @@ -551,7 +556,6 @@ getter = method; pname = decapitalize(name.substring(3)); myType = ret; - //System.out.println("get: "+name+", "+myType); } else { if (name.startsWith("is")) { if (args.length != 0 || ret != Boolean.TYPE) @@ -566,7 +570,6 @@ setter = method; pname = decapitalize(name.substring(3)); myType = args[0]; - //System.out.println("set: "+name+", "+myType); } else { continue; } @@ -584,7 +587,6 @@ addProperty(pname, myType, getter, setter); } } else { - //System.out.println("p: "+prop.myType+", "+myType); if (getter != null) prop.getMethod = getter; if (setter != null && (ret == Void.TYPE || prop.setMethod==null)) prop.setMethod = setter; @@ -744,7 +746,7 @@ if (newName != null) name = newName; } - return super.lookupGivingClass(name, stop_at_java); + return super.lookupGivingClass(name, stop_at_java); } public PyObject __dir__() { Modified: trunk/jython/src/org/python/core/PySystemState.java =================================================================== --- trunk/jython/src/org/python/core/PySystemState.java 2006-08-12 18:56:26 UTC (rev 2883) +++ trunk/jython/src/org/python/core/PySystemState.java 2006-08-12 19:13:39 UTC (rev 2884) @@ -236,6 +236,9 @@ } public void setrecursionlimit(int recursionlimit) { + if(recursionlimit <= 0) { + throw Py.ValueError("Recursion limit must be positive"); + } this.recursionlimit = recursionlimit; } @@ -246,11 +249,12 @@ argv = (PyList)defaultArgv.repeat(1); path = (PyList)defaultPath.repeat(1); + path.append(Py.newString("__classpath__")); meta_path = new PyList(); meta_path.append(new PrecompiledImporter()); - meta_path.append(new JavaImporter()); path_hooks = new PyList(); + path_hooks.append(new JavaImporter()); path_hooks.append(PyJavaClass.lookup(ZipFileImporter.class)); path_importer_cache = new PyDictionary(); Modified: trunk/jython/src/org/python/core/PyTableCode.java =================================================================== --- trunk/jython/src/org/python/core/PyTableCode.java 2006-08-12 18:56:26 UTC (rev 2883) +++ trunk/jython/src/org/python/core/PyTableCode.java 2006-08-12 19:13:39 UTC (rev 2884) @@ -218,7 +218,14 @@ //Add another traceback object to the exception if needed if (e.traceback.tb_frame != frame) { - PyTraceback tb = new PyTraceback(e.traceback.tb_frame.f_back); + PyTraceback tb; + // If f_back is null, we've jumped threads so use the current + // threadstate's frame. Bug #1533624 + if(e.traceback.tb_frame.f_back == null) { + tb = new PyTraceback(ts.frame); + } else { + tb = new PyTraceback(e.traceback.tb_frame.f_back); + } tb.tb_next = e.traceback; e.traceback = tb; } Modified: trunk/jython/src/org/python/core/PyTuple.java =================================================================== --- trunk/jython/src/org/python/core/PyTuple.java 2006-08-12 18:56:26 UTC (rev 2883) +++ trunk/jython/src/org/python/core/PyTuple.java 2006-08-12 19:13:39 UTC (rev 2884) @@ -22,6 +22,8 @@ public static final String exposed_name="tuple"; + public static final Class exposed_base=PyObject.class; + public static void typeSetup(PyObject dict,PyType.Newstyle marker) { class exposed___ne__ extends PyBuiltinFunctionNarrow { Modified: trunk/jython/src/org/python/core/PyType.java =================================================================== --- trunk/jython/src/org/python/core/PyType.java 2006-08-12 18:56:26 UTC (rev 2883) +++ trunk/jython/src/org/python/core/PyType.java 2006-08-12 19:13:39 UTC (rev 2884) @@ -928,278 +928,221 @@ private final static Class[] O = { PyObject.class }; private final static Class[] OO = { PyObject.class, PyObject.class }; - private static void fillFromClass( - PyType newtype, - String name, - Class c, - Class base, - boolean newstyle, - Method setup, - String[] exposed_methods) { + private static void fillFromClass(PyType newtype, + String name, + Class c, + Class base, + boolean newstyle, + Method setup, + String[] exposed_methods) { - if (base == null) { + if(base == null) { base = c.getSuperclass(); } - - if (name == null) { + if(name == null) { name = c.getName(); } - - if (name.startsWith("org.python.core.Py")) { + if(name.startsWith("org.python.core.Py")) { name = name.substring("org.python.core.Py".length()).toLowerCase(); } else { int lastdot = name.lastIndexOf('.'); - if (lastdot != -1) { - name = name.substring(lastdot+1); + if(lastdot != -1) { + name = name.substring(lastdot + 1); } } - newtype.name = name; - newtype.underlying_class = c; - boolean top = false; - // basic mro, base, bases PyType[] mro = null; - if (base == Object.class) { - mro = new PyType[] { newtype }; + if(base == Object.class) { + mro = new PyType[] {newtype}; top = true; } else { PyType basetype = fromClass(base); mro = new PyType[basetype.mro.length + 1]; System.arraycopy(basetype.mro, 0, mro, 1, basetype.mro.length); mro[0] = newtype; - newtype.base = basetype; - newtype.bases = new PyObject[] { basetype }; + newtype.bases = new PyObject[] {basetype}; } newtype.mro = mro; - - HashMap propnames = null; - if (!newstyle) - propnames = new HashMap(); - - boolean only_exposed_methods = newstyle; - PyObject dict = new PyStringMap(); - - if (only_exposed_methods) { - for (int i = 0; i < exposed_methods.length; i++) { - String methname = exposed_methods[i]; - dict.__setitem__( - normalize_name(methname), - new PyReflectedFunction(methname)); + if(newstyle) { + fillInNewstyle(newtype, setup, exposed_methods, dict); + } else { + fillInClassic(c, base, dict); + } + boolean has_set = false, has_delete = false; + if(!top) { + if(get_descr_method(c, "__set__", OO) != null || /* backw comp */ + get_descr_method(c, "_doset", OO) != null) { + has_set = true; } + if(get_descr_method(c, "__delete__", O) != null || /* backw comp */ + get_descr_method(c, "_dodel", O) != null) { + has_delete = true; + } } + newtype.has_set = has_set; + newtype.has_delete = has_delete; + newtype.dict = dict; + } + private static void fillInClassic(Class c, Class base, PyObject dict) { + HashMap propnames = new HashMap(); Method[] methods = c.getMethods(); - for (int i = 0; i < methods.length; i++) { + for(int i = 0; i < methods.length; i++) { Method meth = methods[i]; - Class declaring = meth.getDeclaringClass(); - if (declaring != base - && base.isAssignableFrom(declaring) - && !ignore(meth)) { + if(declaring != base && base.isAssignableFrom(declaring) + && !ignore(meth)) { String methname = meth.getName(); String nmethname = normalize_name(methname); - PyReflectedFunction reflfunc = - (PyReflectedFunction) dict.__finditem__(nmethname); + PyReflectedFunction reflfunc = (PyReflectedFunction)dict.__finditem__(nmethname); boolean added = false; - if (reflfunc == null) { - if (!only_exposed_methods) { - dict.__setitem__( - nmethname, - new PyReflectedFunction(meth)); - added = true; - } + if(reflfunc == null) { + dict.__setitem__(nmethname, new PyReflectedFunction(meth)); + added = true; } else { reflfunc.addMethod(meth); added = true; } - if (propnames != null - && added - && !Modifier.isStatic(meth.getModifiers())) { + if(added && !Modifier.isStatic(meth.getModifiers())) { // check for xxxX.* int n = meth.getParameterTypes().length; - if (methname.startsWith("get") && n == 0) { + if(methname.startsWith("get") && n == 0) { propnames.put(methname.substring(3), "getter"); - } else if ( - methname.startsWith("is") - && n == 0 + } else if(methname.startsWith("is") && n == 0 && meth.getReturnType() == Boolean.TYPE) { propnames.put(methname.substring(2), "getter"); - } else if (methname.startsWith("set") && n == 1) { + } else if(methname.startsWith("set") && n == 1) { propnames.put(methname.substring(3), meth); } } - } - } - - boolean has_set = false, has_delete = false; - if (!top) { - if (get_descr_method(c, "__set__", OO) != null || /*backw comp*/ - get_descr_method(c, "_doset", OO) != null) { - has_set = true; - } - - if (get_descr_method(c, "__delete__", O) != null || /*backw comp*/ - get_descr_method(c, "_dodel", O) != null) { - has_delete = true; - } - } - - for (int i = 0; i < methods.length; i++) { + for(int i = 0; i < methods.length; i++) { Method meth = methods[i]; - String nmethname = normalize_name(meth.getName()); - PyReflectedFunction reflfunc = - (PyReflectedFunction) dict.__finditem__(nmethname); - if (reflfunc != null) { + PyReflectedFunction reflfunc = (PyReflectedFunction)dict.__finditem__(nmethname); + if(reflfunc != null) { reflfunc.addMethod(meth); } - } - - if (!newstyle) { // backward compatibility - Field[] fields = c.getFields(); - - for (int i = 0; i < fields.length; i++) { - Field field = fields[i]; - Class declaring = field.getDeclaringClass(); - if (declaring != base && base.isAssignableFrom(declaring)) { - String fldname = field.getName(); - int fldmods = field.getModifiers(); - Class fldtype = field.getType(); - if (Modifier.isStatic(fldmods)) { - // ignore static PyClass __class__ - if (fldname.equals("__class__") - && fldtype == PyClass.class) { - continue; - } else if ( - fldname.startsWith("__doc__") - && fldname.length() > 7 - && fldtype == PyString.class) { - String fname = fldname.substring(7).intern(); - PyObject memb = dict.__finditem__(fname); - if (memb != null - && memb instanceof PyReflectedFunction) { - PyString doc = null; - try { - doc = (PyString) field.get(null); - } catch (IllegalAccessException e) { - throw error(e); - } - ((PyReflectedFunction) memb).__doc__ = doc; + Field[] fields = c.getFields(); + for(int i = 0; i < fields.length; i++) { + Field field = fields[i]; + Class declaring = field.getDeclaringClass(); + if(declaring != base && base.isAssignableFrom(declaring)) { + String fldname = field.getName(); + int fldmods = field.getModifiers(); + Class fldtype = field.getType(); + if(Modifier.isStatic(fldmods)) { + // ignore static PyClass __class__ + if(fldname.equals("__class__") && fldtype == PyClass.class) { + continue; + } else if(fldname.startsWith("__doc__") + && fldname.length() > 7 + && fldtype == PyString.class) { + String fname = fldname.substring(7).intern(); + PyObject memb = dict.__finditem__(fname); + if(memb != null && memb instanceof PyReflectedFunction) { + PyString doc = null; + try { + doc = (PyString)field.get(null); + } catch(IllegalAccessException e) { + throw error(e); } - + ((PyReflectedFunction)memb).__doc__ = doc; } } - dict.__setitem__( - normalize_name(fldname), - new PyReflectedField(field)); } - + dict.__setitem__(normalize_name(fldname), + new PyReflectedField(field)); } - - for (Iterator iter = propnames.keySet().iterator(); - iter.hasNext(); - ) { - String propname = (String) iter.next(); - String npropname = normalize_name(decapitalize(propname)); - PyObject prev = dict.__finditem__(npropname); - if (prev != null && prev instanceof PyReflectedFunction) { - continue; - } - Method getter = null; - Method setter = null; - Class proptype = null; - getter = - get_non_static_method(c, "get" + propname, new Class[] { - }); - if (getter == null) - getter = - get_non_static_method(c, "is" + propname, new Class[] { - }); - if (getter != null) { - proptype = getter.getReturnType(); - setter = - get_non_static_method( - c, - "set" + propname, - new Class[] { proptype }); - } else { - Object o = propnames.get(propname); - if (o instanceof Method) { - setter = (Method) o; - proptype = setter.getParameterTypes()[0]; - } - } - if (setter != null || getter != null) { - dict.__setitem__( - npropname, - new PyBeanProperty( - npropname, - proptype, - getter, - setter)); - - } else { - // xxx error - } + } + for(Iterator iter = propnames.keySet().iterator(); iter.hasNext();) { + String propname = (String)iter.next(); + String npropname = normalize_name(decapitalize(propname)); + PyObject prev = dict.__finditem__(npropname); + if(prev != null && prev instanceof PyReflectedFunction) { + continue; } - - Constructor[] ctrs = c.getConstructors(); - if (ctrs.length != 0) { - final PyReflectedConstructor reflctr = - new PyReflectedConstructor("_new_impl"); - for (int i = 0; i < ctrs.length; i++) { - reflctr.addConstructor(ctrs[i]); + Method getter = null; + Method setter = null; + Class proptype = null; + getter = get_non_static_method(c, "get" + propname, new Class[] {}); + if(getter == null) + getter = get_non_static_method(c, + "is" + propname, + new Class[] {}); + if(getter != null) { + proptype = getter.getReturnType(); + setter = get_non_static_method(c, + "set" + propname, + new Class[] {proptype}); + } else { + Object o = propnames.get(propname); + if(o instanceof Method) { + setter = (Method)o; + proptype = setter.getParameterTypes()[0]; } - PyObject new_ = new PyNewWrapper(c, "__new__", -1, -1) { - - public PyObject new_impl( - boolean init, - PyType subtype, - PyObject[] args, - String[] keywords) { - return reflctr.make(args, keywords); - } - }; - - dict.__setitem__("__new__", new_); } - - if (ClassDictInit.class.isAssignableFrom(c) - && c != ClassDictInit.class) { - try { - Method m = - c.getMethod( - "classDictInit", - new Class[] { PyObject.class }); - m.invoke(null, new Object[] { dict }); - } catch (Exception exc) { - throw error(exc); - } + if(setter != null || getter != null) { + dict.__setitem__(npropname, new PyBeanProperty(npropname, + proptype, + getter, + setter)); + } else { + // xxx error } + } + Constructor[] ctrs = c.getConstructors(); + if(ctrs.length != 0) { + final PyReflectedConstructor reflctr = new PyReflectedConstructor("_new_impl"); + for(int i = 0; i < ctrs.length; i++) { + reflctr.addConstructor(ctrs[i]); + } + PyObject new_ = new PyNewWrapper(c, "__new__", -1, -1) { - } else { - if (setup != null) { - try { - setup.invoke(null, new Object[] { dict, null }); - } catch (Exception e) { - throw error(e); + public PyObject new_impl(boolean init, + PyType subtype, + PyObject[] args, + String[] keywords) { + return reflctr.make(args, keywords); } + }; + dict.__setitem__("__new__", new_); + } + if(ClassDictInit.class.isAssignableFrom(c) && c != ClassDictInit.class) { + try { + Method m = c.getMethod("classDictInit", + new Class[] {PyObject.class}); + m.invoke(null, new Object[] {dict}); + } catch(Exception exc) { + throw error(exc); } - newtype.non_instantiable = dict.__finditem__("__new__") == null; - } + } - newtype.has_set = has_set; - newtype.has_delete = has_delete; - newtype.dict = dict; + private static void fillInNewstyle(PyType newtype, + Method setup, + String[] exposed_methods, + PyObject dict) { + for(int i = 0; i < exposed_methods.length; i++) { + String methname = exposed_methods[i]; + dict.__setitem__(normalize_name(methname), + new PyReflectedFunction(methname)); + } + if(setup != null) { + try { + setup.invoke(null, new Object[] {dict, null}); + } catch(Exception e) { + throw error(e); + } + } + newtype.non_instantiable = dict.__finditem__("__new__") == null; } private static HashMap class_to_type; Modified: trunk/jython/src/org/python/core/PythonTraceFunction.java =================================================================== --- trunk/jython/src/org/python/core/PythonTraceFunction.java 2006-08-12 18:56:26 UTC (rev 2883) +++ trunk/jython/src/org/python/core/PythonTraceFunction.java 2006-08-12 19:13:39 UTC (rev 2884) @@ -1,41 +1,42 @@ // Copyright (c) Corporation for National Research Initiatives package org.python.core; -class PythonTraceFunction extends TraceFunction -{ + +class PythonTraceFunction extends TraceFunction { + PyObject tracefunc; PythonTraceFunction(PyObject tracefunc) { this.tracefunc = tracefunc; } - private synchronized TraceFunction safeCall(PyFrame frame, String label, - PyObject arg) - { - ThreadState ts = Py.getThreadState(); - if (ts.tracing) - return null; - - if (tracefunc == null) - return null; - - PyObject ret = null; - try { - ts.tracing = true; - ret = tracefunc.__call__(frame, new PyString(label), arg); - } catch (PyException exc) { - frame.tracefunc = null; - ts.systemState.tracefunc = null; - ts.systemState.profilefunc = null; - throw exc; - } finally { - ts.tracing = false; + private TraceFunction safeCall(PyFrame frame, String label, PyObject arg) { + synchronized(imp.class) { + synchronized(this) { + ThreadState ts = Py.getThreadState(); + if(ts.tracing) + return null; + if(tracefunc == null) + return null; + PyObject ret = null; + try { + ts.tracing = true; + ret = tracefunc.__call__(frame, new PyString(label), arg); + } catch(PyException exc) { + frame.tracefunc = null; + ts.systemState.tracefunc = null; + ts.systemState.profilefunc = null; + throw exc; + } finally { + ts.tracing = false; + } + if(ret == tracefunc) + return this; + if(ret == Py.None) + return null; + return new PythonTraceFunction(ret); + } } - if (ret == tracefunc) - return this; - if (ret == Py.None) - return null; - return new PythonTraceFunction(ret); } public TraceFunction traceCall(PyFrame frame) { @@ -51,9 +52,10 @@ } public TraceFunction traceException(PyFrame frame, PyException exc) { - return safeCall(frame, "exception", - new PyTuple(new PyObject[] {exc.type, exc.value, - exc.traceback - })); + return safeCall(frame, + "exception", + new PyTuple(new PyObject[] {exc.type, + exc.value, + exc.traceback})); } } Modified: trunk/jython/src/org/python/core/SyspathJavaLoader.java =================================================================== --- trunk/jython/src/org/python/core/SyspathJavaLoader.java 2006-08-12 18:56:26 UTC (rev 2883) +++ trunk/jython/src/org/python/core/SyspathJavaLoader.java 2006-08-12 19:13:39 UTC (rev 2884) @@ -128,11 +128,17 @@ } try { byte[] buffer = FileUtil.readBytes(fis); - fis.close(); return loadClassFromBytes(name, buffer); - } catch (IOException e) { + } catch(IOException e) { continue; + } finally { + try { + fis.close(); + } catch(IOException e) { + continue; + } } + } } Modified: trunk/jython/src/org/python/core/imp.java =================================================================== --- trunk/jython/src/org/python/core/imp.java 2006-08-12 18:56:26 UTC (rev 2883) +++ trunk/jython/src/org/python/core/imp.java 2006-08-12 19:13:39 UTC (rev 2884) @@ -31,8 +31,12 @@ ; } + /** + * If the given name is found in sys.modules, the entry from there is + * returned. Otherwise a new PyModule is created for the name and added to + * sys.modules + */ public static PyModule addModule(String name) { - // System.err.println("AddModule:" + name); name = name.intern(); PyObject modules = Py.getSystemState().modules; PyModule module = (PyModule) modules.__finditem__(name); @@ -46,11 +50,15 @@ private static byte[] readBytes(InputStream fp) { try { - byte[] buf = FileUtil.readBytes(fp); - fp.close(); - return buf; - } catch (IOException ioe) { + return FileUtil.readBytes(fp); + } catch(IOException ioe) { throw Py.IOError(ioe); + } finally { + try { + fp.close(); + } catch(IOException e) { + throw Py.IOError(e); + } } } @@ -77,7 +85,6 @@ + APIVersion + ") in: " + name); } } - // System.err.println("APIVersion: "+api); PyCode code; try { code = BytecodeLoader.makeCode(name + "$py", data); @@ -98,29 +105,30 @@ return compileSource(name, file, null, null); } - public static byte[] compileSource(String name, File file, String filename, - String outFilename) { - if (filename == null) { - filename = file.toString(); + public static byte[] compileSource(String name, File file, String sourceFilename, + String compiledFilename) { + if (sourceFilename == null) { + sourceFilename = file.toString(); } - - if (outFilename == null) { - outFilename = filename.substring(0, filename.length() - 3) - + "$py.class"; + if (compiledFilename == null) { + compiledFilename = makeCompiledFilename(sourceFilename); } - - return compileSource(name, makeStream(file), filename, outFilename); + return compileSource(name, makeStream(file), sourceFilename, compiledFilename); } - static byte[] compileSource(String name, InputStream fp, String filename) { - String outFilename = null; - if (filename != null) { - outFilename = filename.substring(0, filename.length() - 3) - + "$py.class"; + static byte[] compileSource(String name, InputStream fp, String sourceFilename) { + String compiledFilename = null; + if (sourceFilename != null) { + compiledFilename = makeCompiledFilename(sourceFilename); } - return compileSource(name, fp, filename, outFilename); + return compileSource(name, fp, sourceFilename, compiledFilename); } + private static String makeCompiledFilename(String filename) { + return filename.substring(0, filename.length() - 3) + + "$py.class"; + } + static byte[] compileSource(String name, InputStream fp, String filename, String outFilename) { try { @@ -196,9 +204,8 @@ if (interfaces[i] == PyRunnable.class) { // System.err.println("is runnable"); try { - PyObject o = createFromCode(name, ((PyRunnable) c - .newInstance()).getMain()); - return o; + return createFromCode(name, + ((PyRunnable)c.newInstance()).getMain()); } catch (InstantiationException e) { throw Py.JavaError(e); } catch (IllegalAccessException e) { Modified: trunk/jython/src/org/python/parser/TreeBuilder.java =================================================================== --- trunk/jython/src/org/python/parser/TreeBuilder.java 2006-08-12 18:56:26 UTC (rev 2883) +++ trunk/jython/src/org/python/parser/TreeBuilder.java 2006-08-12 19:13:39 UTC (rev 2884) @@ -421,6 +421,10 @@ return new Slice(values[0], values[1], values[2]); } case JJTSUBSCRIPTLIST: + if (arity > 0 && peekNode().getId() == JJTCOMMA){ + arity--; + popNode(); + } sliceType[] dims = new sliceType[arity]; for (int i = arity - 1; i >= 0; i--) { dims[i] = (sliceType) popNode(); This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <otm...@us...> - 2006-08-22 22:44:29
|
Revision: 2904 Author: otmarhumbel Date: 2006-08-22 15:44:16 -0700 (Tue, 22 Aug 2006) ViewCVS: http://svn.sourceforge.net/jython/?rev=2904&view=rev Log Message: ----------- - improved java imports in case of incomplete or missing cachedir - standalone mode now explicitly disables the package scan - this makes test386.py pass Modified Paths: -------------- trunk/jython/src/org/python/core/PySystemState.java trunk/jython/src/org/python/core/__builtin__.java trunk/jython/src/org/python/core/imp.java Added Paths: ----------- trunk/jython/src/org/python/core/JavaImportHelper.java Added: trunk/jython/src/org/python/core/JavaImportHelper.java =================================================================== --- trunk/jython/src/org/python/core/JavaImportHelper.java (rev 0) +++ trunk/jython/src/org/python/core/JavaImportHelper.java 2006-08-22 22:44:16 UTC (rev 2904) @@ -0,0 +1,184 @@ +package org.python.core; + +import java.util.Iterator; +import java.util.Map; +import java.util.TreeMap; + +/** + * Helper class handling the VM specific java package detection. + */ +public class JavaImportHelper { + + /** + * Try to add the java package. + * <p> + * This is handy in cases where the package scan cannot run, or when the initial classpath does not contain all .jar + * files (such as in J2EE containers). + * <p> + * There is some self-healing in the sense that a correct, explicit import of a java class will succeed even if + * sys.modules already contains a Py.None entry for the corresponding java package. + * + * @param packageName The dotted name of the java package + * @param fromlist A tuple with the from names to import. Can be null or empty. + * + * @return <code>true</code> if a java package was doubtlessly identified and added, <code>false</code> + * otherwise. + */ + protected static boolean tryAddPackage(String packageName, PyObject fromlist) { + // build the actual map with the packages known to the VM + Map packages = buildLoadedPackages(); + + // make sure we do not turn off the added flag, once it is set + boolean packageAdded = false; + + // handle package name + if (isLoadedPackage(packageName, packages)) { + packageAdded = addPackage(packageName); + } + String parentPackageName = packageName; + int dotPos = 0; + do { + dotPos = parentPackageName.lastIndexOf("."); + if (dotPos > 0) { + parentPackageName = parentPackageName.substring(0, dotPos); + if (isLoadedPackage(parentPackageName, packages)) { + boolean parentAdded = addPackage(parentPackageName); + if (parentAdded) { + packageAdded = true; + } + } + } + } while (dotPos > 0); + + // handle fromlist + if (fromlist != null && fromlist != Py.EmptyTuple && fromlist instanceof PyTuple) { + Iterator iterator = ((PyTuple) fromlist).iterator(); + while (iterator.hasNext()) { + Object obj = iterator.next(); + if (obj instanceof String) { + String fromName = (String) obj; + if (!"*".equals(fromName)) { + boolean fromAdded = false; + if (isJavaClass(packageName, fromName)) { + fromAdded = addPackage(packageName); + if (fromAdded) { + packageAdded = true; + } + } else { + // handle cases like: from java import math + String fromPackageName = packageName + "." + fromName; + if (isLoadedPackage(fromPackageName, packages)) { + fromAdded = addPackage(fromPackageName); + if (fromAdded) { + packageAdded = true; + } + } + } + } + } + } + } + return packageAdded; + } + + /** + * Check if a java package is already known to the VM. + * <p> + * May return <code>false</code> even if the given package name is a valid java package ! + * + * @param packageName + * + * @return <code>true</code> if the package with the given name is already loaded by the VM, <code>false</code> + * otherwise. + */ + protected static boolean isLoadedPackage(String packageName) { + return isLoadedPackage(packageName, buildLoadedPackages()); + } + + /** + * Faster way to check if a java package is already known to the VM. + * <p> + * May return <code>false</code> even if the given package name is a valid java package ! + * + * @param packageName + * @param packages A Map containing all packages actually known to the VM. Such a Map can be obtained using + * {@link JavaImportHelper.buildLoadedPackagesTree()} + * + * @return <code>true</code> if the package with the given name is already loaded by the VM, <code>false</code> + * otherwise. + */ + private static boolean isLoadedPackage(String javaPackageName, Map packages) { + return packages.containsKey(javaPackageName); + } + + /** + * Build a <code>Map</code> of the currently known packages to the VM. + * <p> + * All parent packages appear as single entries like python modules, e.g. <code>java</code>, + * <code>java.lang</code>, <code>java.lang.reflect</code>, + */ + private static Map buildLoadedPackages() { + TreeMap packageMap = new TreeMap(); + Package[] packages = Package.getPackages(); + for (int i = 0; i < packages.length; i++) { + String packageName = packages[i].getName(); + packageMap.put(packageName, ""); + int dotPos = 0; + do { + dotPos = packageName.lastIndexOf("."); + if (dotPos > 0) { + packageName = packageName.substring(0, dotPos); + packageMap.put(packageName, ""); + } + } while (dotPos > 0); + } + return packageMap; + } + + /** + * Check a java class on VM level. + * + * @param packageName + * @param className + * + * @return <code>true</code> if the java class can be doubtlessly identified, <code>false</code> otherwise. + */ + private static boolean isJavaClass(String packageName, String className) { + if (className != null && className.length() > 0) { + className = packageName.replace('.', '/') + "/" + className + ".class"; + return Thread.currentThread().getContextClassLoader().getResource(className) != null; + } else { + return false; + } + } + + /** + * Add a java package to sys.modules, if not already done + * + * @return <code>true</code> if something was really added, <code>false</code> otherwise + */ + private static boolean addPackage(String packageName) { + boolean added = false; + PyObject module = Py.getSystemState().modules.__finditem__(packageName.intern()); + if (module == null || module == Py.None) { + PyObject modules = Py.getSystemState().modules; + int dotPos; + do { + String internedPackageName = packageName.intern(); + if (modules.__finditem__(internedPackageName) == Py.None) { + // a previously failed import could have created a Py.None entry in sys.modules + modules.__delitem__(internedPackageName); + } + PyJavaPackage p = PySystemState.add_package(packageName); + Py.getSystemState().modules.__setitem__(internedPackageName, p); + added = true; + dotPos = packageName.lastIndexOf("."); + if (dotPos > 0) { + packageName = packageName.substring(0, dotPos); + } + } while (dotPos > 0); + } + return added; + } + +} Modified: trunk/jython/src/org/python/core/PySystemState.java =================================================================== --- trunk/jython/src/org/python/core/PySystemState.java 2006-08-22 22:39:46 UTC (rev 2903) +++ trunk/jython/src/org/python/core/PySystemState.java 2006-08-22 22:44:16 UTC (rev 2904) @@ -17,6 +17,7 @@ import java.util.StringTokenizer; import java.util.jar.JarEntry; import java.util.jar.JarFile; + import org.python.modules.Setup; /** @@ -32,6 +33,10 @@ private static final String JAR_SEPARATOR = "!"; private static final String URL_BLANK_REPLACEMENT = "%20"; + private static final String PYTHON_CACHEDIR = "python.cachedir"; + protected static final String PYTHON_CACHEDIR_SKIP = "python.cachedir.skip"; + protected static final String CACHEDIR_DEFAULT_NAME = "cachedir"; + /** * The current version of Jython. */ @@ -331,8 +336,8 @@ return classpath.substring(start, jpy); } - private static void initRegistry(Properties preProperties, - Properties postProperties) + private static void initRegistry(Properties preProperties, Properties postProperties, + boolean standalone) { if (registry != null) { Py.writeError("systemState", "trying to reinitialize registry"); @@ -363,6 +368,12 @@ registry.put(key, value); } } + if (standalone) { + // set default standalone property (if not yet set) + if (!registry.containsKey(PYTHON_CACHEDIR_SKIP)) { + registry.put(PYTHON_CACHEDIR_SKIP, "true"); + } + } // Set up options from registry Options.setFromRegistry(); } @@ -396,6 +407,7 @@ return new Properties(); } } + public static synchronized void initialize() { if (initialized) return; @@ -428,15 +440,21 @@ } initialized = true; + boolean standalone = false; + String jarFileName = getJarFileName(); + if (jarFileName != null) { + standalone = isStandalone(jarFileName); + } + // initialize the JPython registry - initRegistry(preProperties, postProperties); + initRegistry(preProperties, postProperties, standalone); // other initializations initBuiltins(registry); initStaticFields(); // Initialize the path (and add system defaults) - defaultPath = initPath(registry); + defaultPath = initPath(registry, standalone, jarFileName); defaultArgv = initArgv(argv); // Set up the known Java packages @@ -501,12 +519,12 @@ cachedir = null; return; } - String skip = props.getProperty("python.cachedir.skip", "false"); + String skip = props.getProperty(PYTHON_CACHEDIR_SKIP, "false"); if (skip.equalsIgnoreCase("true")) { cachedir = null; return; } - cachedir = new File(props.getProperty("python.cachedir", "cachedir")); + cachedir = new File(props.getProperty(PYTHON_CACHEDIR, CACHEDIR_DEFAULT_NAME)); if (!cachedir.isAbsolute()) { cachedir = new File(PySystemState.prefix, cachedir.getPath()); } @@ -583,7 +601,7 @@ return (String)builtinNames.get(name); } - private static PyList initPath(Properties props) { + private static PyList initPath(Properties props, boolean standalone, String jarFileName) { PyList path = new PyList(); if (!Py.frozen) { addPaths(path, props.getProperty("python.prepath", ".")); @@ -595,26 +613,29 @@ addPaths(path, props.getProperty("python.path", "")); } - addJarLibPath(path); + if (standalone) { + // standalone jython: add the /Lib directory inside JYTHON_JAR to the path + addPaths(path, jarFileName + "/Lib"); + } return path; } /** - * standalone jython: add the /Lib directory inside JYTHON_JAR to the path (if present) + * Check if we are in standalone mode. * - * @param path the sys.path to be updated eventually + * @param jarFileName The name of the jar file + * + * @return <code>true</code> if we have a standalone .jar file, <code>false</code> otherwise. */ - private static void addJarLibPath(PyList path) { - String jarFileName = getJarFileName(); + private static boolean isStandalone(String jarFileName) { + boolean standalone = false; if (jarFileName != null) { JarFile jarFile = null; try { jarFile = new JarFile(jarFileName); JarEntry jarEntry = jarFile.getJarEntry("Lib/javaos.py"); - if (jarEntry != null) { - addPaths(path, jarFileName + "/Lib"); - } + standalone = jarEntry != null; } catch (IOException ioe) { } finally { if (jarFile != null) { @@ -625,6 +646,7 @@ } } } + return standalone; } /** Modified: trunk/jython/src/org/python/core/__builtin__.java =================================================================== --- trunk/jython/src/org/python/core/__builtin__.java 2006-08-22 22:39:46 UTC (rev 2903) +++ trunk/jython/src/org/python/core/__builtin__.java 2006-08-22 22:44:16 UTC (rev 2904) @@ -977,7 +977,7 @@ private PyObject load(String module, PyObject globals, PyObject fromlist) { PyObject mod = imp.importName(module.intern(), fromlist.__len__() == 0, - globals); + globals, fromlist); return mod; } Modified: trunk/jython/src/org/python/core/imp.java =================================================================== --- trunk/jython/src/org/python/core/imp.java 2006-08-22 22:39:46 UTC (rev 2903) +++ trunk/jython/src/org/python/core/imp.java 2006-08-22 22:44:16 UTC (rev 2904) @@ -7,6 +7,9 @@ import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; /** * Utility functions for "import" support. @@ -494,7 +497,7 @@ * @return null or None */ private static PyObject import_next(PyObject mod, - StringBuffer parentNameBuffer, String name) { + StringBuffer parentNameBuffer, String name, String outerFullName, PyObject fromlist) { if (parentNameBuffer.length() > 0) { parentNameBuffer.append('.'); } @@ -513,6 +516,9 @@ ret = mod.impAttr(name.intern()); } if (ret == null || ret == Py.None) { + if (JavaImportHelper.tryAddPackage(outerFullName, fromlist)) { + ret = modules.__finditem__(fullName); + } return ret; } if (modules.__finditem__(fullName) == null) { @@ -526,18 +532,33 @@ // never returns null or None private static PyObject import_first(String name, StringBuffer parentNameBuffer) { - PyObject ret = import_next(null, parentNameBuffer, name); + PyObject ret = import_next(null, parentNameBuffer, name, null, null); if (ret == null || ret == Py.None) { throw Py.ImportError("no module named " + name); } return ret; } + + + private static PyObject import_first(String name, StringBuffer parentNameBuffer, String fullName, PyObject fromlist) { + PyObject ret = import_next(null, parentNameBuffer, name, fullName, fromlist); + if (ret == null || ret == Py.None) { + if (JavaImportHelper.tryAddPackage(fullName, fromlist)) { + ret = import_next(null, parentNameBuffer, name, fullName, fromlist); + } + } + if (ret == null || ret == Py.None) { + throw Py.ImportError("no module named " + name); + } + return ret; + } + // Hierarchy-recursively search for dotted name in mod; // never returns null or None // ??pending: check if result is really a module/jpkg/jclass? private static PyObject import_logic(PyObject mod, - StringBuffer parentNameBuffer, String dottedName) { + StringBuffer parentNameBuffer, String dottedName, String fullName, PyObject fromlist) { int dot = 0; int last_dot = 0; @@ -549,9 +570,9 @@ } else { name = dottedName.substring(last_dot, dot); } - mod = import_next(mod, parentNameBuffer, name); + mod = import_next(mod, parentNameBuffer, name, fullName, fromlist); if (mod == null || mod == Py.None) { - throw Py.ImportError("No module named " + name); + throw Py.ImportError("no module named " + name); } last_dot = dot + 1; } while (dot != -1); @@ -568,7 +589,7 @@ * @return a module */ private static PyObject import_name(String name, boolean top, - PyObject modDict) { + PyObject modDict, PyObject fromlist) { // System.err.println("import_name " + name); if (name.length() == 0) { throw Py.ValueError("Empty module name"); @@ -593,7 +614,7 @@ } StringBuffer parentNameBuffer = new StringBuffer( pkgMod != null ? pkgName : ""); - PyObject topMod = import_next(pkgMod, parentNameBuffer, firstName); + PyObject topMod = import_next(pkgMod, parentNameBuffer, firstName, name, fromlist); if (topMod == Py.None || topMod == null) { if (topMod == null) { modules.__setitem__(parentNameBuffer.toString().intern(), @@ -601,13 +622,13 @@ } parentNameBuffer = new StringBuffer(""); // could throw ImportError - topMod = import_first(firstName, parentNameBuffer); + topMod = import_first(firstName, parentNameBuffer, name, fromlist); } PyObject mod = topMod; if (dot != -1) { // could throw ImportError mod = import_logic(topMod, parentNameBuffer, name - .substring(dot + 1)); + .substring(dot + 1), name, fromlist); } if (top) { return topMod; @@ -623,7 +644,7 @@ * @return an imported module (Java or Python) */ public static PyObject importName(String name, boolean top) { - return import_name(name, top, null); + return import_name(name, top, null, null); } /** @@ -635,13 +656,13 @@ * @param modDict the __dict__ of an already imported module * @return an imported module (Java or Python) */ - public synchronized static PyObject importName(String name, boolean top, - PyObject modDict) { - return import_name(name, top, modDict); + public synchronized static PyObject importName(String name, boolean top, + PyObject modDict, PyObject fromlist) { + return import_name(name, top, modDict, fromlist); } /** - * Called from jpython generated code when a statement like "import spam" is + * Called from jython generated code when a statement like "import spam" is * executed. */ public static PyObject importOne(String mod, PyFrame frame) { @@ -657,7 +678,7 @@ } /** - * Called from jpython generated code when a statement like "import spam as + * Called from jython generated code when a statement like "import spam as * foo" is executed. */ public static PyObject importOneAs(String mod, PyFrame frame) { @@ -669,7 +690,7 @@ } /** - * Called from jpython generated code when a stamenet like "from spam.eggs + * Called from jython generated code when a stamenet like "from spam.eggs * import foo, bar" is executed. */ public static PyObject[] importFrom(String mod, String[] names, @@ -678,7 +699,7 @@ } /** - * Called from jpython generated code when a stamenet like "from spam.eggs + * Called from jython generated code when a statement like "from spam.eggs * import foo as spam" is executed. */ public static PyObject[] importFromAs(String mod, String[] names, @@ -695,13 +716,38 @@ PyObject module = __builtin__.__import__(mod, frame.f_globals, frame .getf_locals(), new PyTuple(pynames)); PyObject[] submods = new PyObject[names.length]; + List wrongNames = new ArrayList(1); for (int i = 0; i < names.length; i++) { PyObject submod = module.__findattr__(names[i]); if (submod == null) { - throw Py.ImportError("cannot import name " + names[i]); + if (module instanceof PyJavaPackage) { + if (JavaImportHelper.tryAddPackage(mod + "." + names[i], null)) { + submod = module.__findattr__(names[i]); + } + } } - submods[i] = submod; + if (submod == null) { + wrongNames.add(names[i]); + } else { + submods[i] = submod; + } } + int size = wrongNames.size(); + if (size > 0) { + StringBuffer buf = new StringBuffer(20); + buf.append("cannot import name"); + if (size > 1) { + buf.append("s"); + } + Iterator wrongNamesIterator = wrongNames.iterator(); + buf.append(" "); + buf.append(wrongNamesIterator.next()); + while (wrongNamesIterator.hasNext()) { + buf.append(", "); + buf.append(wrongNamesIterator.next()); + } + throw Py.ImportError(buf.toString()); + } return submods; } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <cg...@us...> - 2006-10-14 03:16:58
|
Revision: 2952 http://svn.sourceforge.net/jython/?rev=2952&view=rev Author: cgroves Date: 2006-10-13 20:16:54 -0700 (Fri, 13 Oct 2006) Log Message: ----------- Added hasFreevars to PyTableCode and use from __builtin__ and Py when checking for use of freevars in eval and exec. Modified Paths: -------------- trunk/jython/src/org/python/core/Py.java trunk/jython/src/org/python/core/PyTableCode.java trunk/jython/src/org/python/core/__builtin__.java Modified: trunk/jython/src/org/python/core/Py.java =================================================================== --- trunk/jython/src/org/python/core/Py.java 2006-10-13 22:23:06 UTC (rev 2951) +++ trunk/jython/src/org/python/core/Py.java 2006-10-14 03:16:54 UTC (rev 2952) @@ -1216,7 +1216,7 @@ if(o instanceof PyCode) { code = (PyCode)o; if(locals == null && o instanceof PyTableCode - && ((PyTableCode)o).co_freevars.length > 0) { + && ((PyTableCode)o).hasFreevars()) { throw Py.TypeError("code object passed to exec may not contain free variables"); } }else { Modified: trunk/jython/src/org/python/core/PyTableCode.java =================================================================== --- trunk/jython/src/org/python/core/PyTableCode.java 2006-10-13 22:23:06 UTC (rev 2951) +++ trunk/jython/src/org/python/core/PyTableCode.java 2006-10-14 03:16:54 UTC (rev 2952) @@ -91,6 +91,10 @@ return new PyList(members); } + public boolean hasFreevars() { + return co_freevars != null && co_freevars.length > 0; + } + private void throwReadonly(String name) { for (int i = 0; i < __members__.length; i++) if (__members__[i] == name) Modified: trunk/jython/src/org/python/core/__builtin__.java =================================================================== --- trunk/jython/src/org/python/core/__builtin__.java 2006-10-13 22:23:06 UTC (rev 2951) +++ trunk/jython/src/org/python/core/__builtin__.java 2006-10-14 03:16:54 UTC (rev 2952) @@ -287,7 +287,7 @@ } public static PyObject eval(PyObject o) { - if(o instanceof PyTableCode && ((PyTableCode)o).co_freevars.length > 0) { + if(o instanceof PyTableCode && ((PyTableCode)o).hasFreevars()) { throw Py.TypeError("code object passed to eval() may not contain free variables"); } return eval(o, null, null); This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <cg...@us...> - 2006-11-19 17:00:45
|
Revision: 2975 http://svn.sourceforge.net/jython/?rev=2975&view=rev Author: cgroves Date: 2006-11-19 09:00:42 -0800 (Sun, 19 Nov 2006) Log Message: ----------- basic implementation of slots. still need to disallow slots on str, long and the like and go over the slot inheritance logic with a fine toothed comb Modified Paths: -------------- trunk/jython/src/org/python/core/PyClassMethodDerived.java trunk/jython/src/org/python/core/PyComplexDerived.java trunk/jython/src/org/python/core/PyDictionaryDerived.java trunk/jython/src/org/python/core/PyGetSetDescr.java trunk/jython/src/org/python/core/PyIntegerDerived.java trunk/jython/src/org/python/core/PyListDerived.java trunk/jython/src/org/python/core/PyObjectDerived.java trunk/jython/src/org/python/core/PyPropertyDerived.java trunk/jython/src/org/python/core/PyStringDerived.java trunk/jython/src/org/python/core/PySuperDerived.java trunk/jython/src/org/python/core/PyTupleDerived.java trunk/jython/src/org/python/core/PyType.java trunk/jython/src/org/python/core/PyTypeDerived.java trunk/jython/src/org/python/core/PyUnicodeDerived.java Added Paths: ----------- trunk/jython/src/org/python/core/PySlot.java trunk/jython/src/org/python/core/Slotted.java Modified: trunk/jython/src/org/python/core/PyClassMethodDerived.java =================================================================== --- trunk/jython/src/org/python/core/PyClassMethodDerived.java 2006-11-19 16:59:17 UTC (rev 2974) +++ trunk/jython/src/org/python/core/PyClassMethodDerived.java 2006-11-19 17:00:42 UTC (rev 2975) @@ -1,7 +1,17 @@ package org.python.core; -public class PyClassMethodDerived extends PyClassMethod { +public class PyClassMethodDerived extends PyClassMethod implements Slotted { + public PyObject getSlot(int index) { + return slots[index]; + } + + public void setSlot(int index,PyObject value) { + slots[index]=value; + } + + private PyObject[]slots; + private PyObject dict; public PyObject fastGetDict() { @@ -14,6 +24,7 @@ public PyClassMethodDerived(PyType subtype) { super(subtype); + slots=new PyObject[subtype.getNumSlots()]; dict=subtype.instDict(); } Modified: trunk/jython/src/org/python/core/PyComplexDerived.java =================================================================== --- trunk/jython/src/org/python/core/PyComplexDerived.java 2006-11-19 16:59:17 UTC (rev 2974) +++ trunk/jython/src/org/python/core/PyComplexDerived.java 2006-11-19 17:00:42 UTC (rev 2975) @@ -1,7 +1,17 @@ package org.python.core; -public class PyComplexDerived extends PyComplex { +public class PyComplexDerived extends PyComplex implements Slotted { + public PyObject getSlot(int index) { + return slots[index]; + } + + public void setSlot(int index,PyObject value) { + slots[index]=value; + } + + private PyObject[]slots; + private PyObject dict; public PyObject fastGetDict() { @@ -14,6 +24,7 @@ public PyComplexDerived(PyType subtype,double real,double imaginary) { super(subtype,real,imaginary); + slots=new PyObject[subtype.getNumSlots()]; dict=subtype.instDict(); } Modified: trunk/jython/src/org/python/core/PyDictionaryDerived.java =================================================================== --- trunk/jython/src/org/python/core/PyDictionaryDerived.java 2006-11-19 16:59:17 UTC (rev 2974) +++ trunk/jython/src/org/python/core/PyDictionaryDerived.java 2006-11-19 17:00:42 UTC (rev 2975) @@ -1,7 +1,17 @@ package org.python.core; -public class PyDictionaryDerived extends PyDictionary { +public class PyDictionaryDerived extends PyDictionary implements Slotted { + public PyObject getSlot(int index) { + return slots[index]; + } + + public void setSlot(int index,PyObject value) { + slots[index]=value; + } + + private PyObject[]slots; + private PyObject dict; public PyObject fastGetDict() { @@ -14,6 +24,7 @@ public PyDictionaryDerived(PyType subtype) { super(subtype); + slots=new PyObject[subtype.getNumSlots()]; dict=subtype.instDict(); } Modified: trunk/jython/src/org/python/core/PyGetSetDescr.java =================================================================== --- trunk/jython/src/org/python/core/PyGetSetDescr.java 2006-11-19 16:59:17 UTC (rev 2974) +++ trunk/jython/src/org/python/core/PyGetSetDescr.java 2006-11-19 17:00:42 UTC (rev 2975) @@ -7,87 +7,92 @@ public class PyGetSetDescr extends PyDescriptor { private Method get_meth; + private Method set_meth; + private Class getset_type; - public PyGetSetDescr(PyType dtype, String name, Class c, String get, String set) { + public PyGetSetDescr(PyType dtype, + String name, + Class c, + String get, + String set) { this.name = name; this.dtype = dtype; try { - get_meth = c.getMethod(get, new Class[] { - }); - } catch (NoSuchMethodException e) { + get_meth = c.getMethod(get, new Class[] {}); + } catch(NoSuchMethodException e) { throw Py.SystemError("bogus getset spec"); } - if (Modifier.isStatic(get_meth.getModifiers())) + if(Modifier.isStatic(get_meth.getModifiers())) throw Py.SystemError("static getset not supported"); getset_type = get_meth.getReturnType(); - if (set != null) { + if(set != null) { try { - set_meth = c.getMethod(set, new Class[] { getset_type }); - } catch (NoSuchMethodException e) { + set_meth = c.getMethod(set, new Class[] {getset_type}); + } catch(NoSuchMethodException e) { throw Py.SystemError("bogus getset spec"); } - if (Modifier.isStatic(set_meth.getModifiers())) + if(Modifier.isStatic(set_meth.getModifiers())) throw Py.SystemError("static getset not supported"); - } } public PyGetSetDescr(String name, Class c, String get, String set) { - this(PyType.fromClass(c),name,c,get,set); + this(PyType.fromClass(c), name, c, get, set); } - + public String toString() { - return "<attribute '"+name+"' of '"+dtype.fastGetName()+"' objects>"; + return "<attribute '" + name + "' of '" + dtype.fastGetName() + + "' objects>"; } - /** - * @see org.python.core.PyObject#__get__(org.python.core.PyObject, org.python.core.PyObject) + * @see org.python.core.PyObject#__get__(org.python.core.PyObject, + * org.python.core.PyObject) */ public PyObject __get__(PyObject obj, PyObject type) { try { - if (obj != null) { + if(obj != null) { PyType objtype = obj.getType(); - if (objtype != dtype && !objtype.isSubType(dtype)) + if(objtype != dtype && !objtype.isSubType(dtype)) throw get_wrongtype(objtype); Object v = get_meth.invoke(obj, new Object[0]); - if (v == null) { + if(v == null) { obj.noAttributeError(name); } return Py.java2py(v); } return this; - } catch (IllegalArgumentException e) { + } catch(IllegalArgumentException e) { throw Py.JavaError(e); - } catch (IllegalAccessException e) { + } catch(IllegalAccessException e) { throw Py.JavaError(e); // unexpected - } catch (InvocationTargetException e) { + } catch(InvocationTargetException e) { throw Py.JavaError(e); } } /** - * @see org.python.core.PyObject#__set__(org.python.core.PyObject, org.python.core.PyObject) + * @see org.python.core.PyObject#__set__(org.python.core.PyObject, + * org.python.core.PyObject) */ public void __set__(PyObject obj, PyObject value) { try { // obj != null PyType objtype = obj.getType(); - if (objtype != dtype && !objtype.isSubType(dtype)) + if(objtype != dtype && !objtype.isSubType(dtype)) throw get_wrongtype(objtype); Object converted = value.__tojava__(getset_type); - if (converted == Py.NoConversion) { + if(converted == Py.NoConversion) { throw Py.TypeError(""); // xxx } - set_meth.invoke(obj, new Object[] { converted }); - - } catch (IllegalArgumentException e) { + set_meth.invoke(obj, new Object[] {converted}); + } catch(IllegalArgumentException e) { throw Py.JavaError(e); - } catch (IllegalAccessException e) { + } catch(IllegalAccessException e) { throw Py.JavaError(e); // unexpected - } catch (InvocationTargetException e) { + } catch(InvocationTargetException e) { throw Py.JavaError(e); } } @@ -105,5 +110,4 @@ public boolean isDataDescr() { return true; } - } Modified: trunk/jython/src/org/python/core/PyIntegerDerived.java =================================================================== --- trunk/jython/src/org/python/core/PyIntegerDerived.java 2006-11-19 16:59:17 UTC (rev 2974) +++ trunk/jython/src/org/python/core/PyIntegerDerived.java 2006-11-19 17:00:42 UTC (rev 2975) @@ -1,7 +1,17 @@ package org.python.core; -public class PyIntegerDerived extends PyInteger { +public class PyIntegerDerived extends PyInteger implements Slotted { + public PyObject getSlot(int index) { + return slots[index]; + } + + public void setSlot(int index,PyObject value) { + slots[index]=value; + } + + private PyObject[]slots; + private PyObject dict; public PyObject fastGetDict() { @@ -14,6 +24,7 @@ public PyIntegerDerived(PyType subtype,int v) { super(subtype,v); + slots=new PyObject[subtype.getNumSlots()]; dict=subtype.instDict(); } Modified: trunk/jython/src/org/python/core/PyListDerived.java =================================================================== --- trunk/jython/src/org/python/core/PyListDerived.java 2006-11-19 16:59:17 UTC (rev 2974) +++ trunk/jython/src/org/python/core/PyListDerived.java 2006-11-19 17:00:42 UTC (rev 2975) @@ -1,7 +1,17 @@ package org.python.core; -public class PyListDerived extends PyList { +public class PyListDerived extends PyList implements Slotted { + public PyObject getSlot(int index) { + return slots[index]; + } + + public void setSlot(int index,PyObject value) { + slots[index]=value; + } + + private PyObject[]slots; + private PyObject dict; public PyObject fastGetDict() { @@ -14,6 +24,7 @@ public PyListDerived(PyType subtype) { super(subtype); + slots=new PyObject[subtype.getNumSlots()]; dict=subtype.instDict(); } Modified: trunk/jython/src/org/python/core/PyObjectDerived.java =================================================================== --- trunk/jython/src/org/python/core/PyObjectDerived.java 2006-11-19 16:59:17 UTC (rev 2974) +++ trunk/jython/src/org/python/core/PyObjectDerived.java 2006-11-19 17:00:42 UTC (rev 2975) @@ -1,7 +1,17 @@ package org.python.core; -public class PyObjectDerived extends PyObject { +public class PyObjectDerived extends PyObject implements Slotted { + public PyObject getSlot(int index) { + return slots[index]; + } + + public void setSlot(int index,PyObject value) { + slots[index]=value; + } + + private PyObject[]slots; + private PyObject dict; public PyObject fastGetDict() { @@ -14,6 +24,7 @@ public PyObjectDerived(PyType subtype) { super(subtype); + slots=new PyObject[subtype.getNumSlots()]; dict=subtype.instDict(); } Modified: trunk/jython/src/org/python/core/PyPropertyDerived.java =================================================================== --- trunk/jython/src/org/python/core/PyPropertyDerived.java 2006-11-19 16:59:17 UTC (rev 2974) +++ trunk/jython/src/org/python/core/PyPropertyDerived.java 2006-11-19 17:00:42 UTC (rev 2975) @@ -1,7 +1,17 @@ package org.python.core; -public class PyPropertyDerived extends PyProperty { +public class PyPropertyDerived extends PyProperty implements Slotted { + public PyObject getSlot(int index) { + return slots[index]; + } + + public void setSlot(int index,PyObject value) { + slots[index]=value; + } + + private PyObject[]slots; + private PyObject dict; public PyObject fastGetDict() { @@ -14,6 +24,7 @@ public PyPropertyDerived(PyType subtype) { super(subtype); + slots=new PyObject[subtype.getNumSlots()]; dict=subtype.instDict(); } Added: trunk/jython/src/org/python/core/PySlot.java =================================================================== --- trunk/jython/src/org/python/core/PySlot.java (rev 0) +++ trunk/jython/src/org/python/core/PySlot.java 2006-11-19 17:00:42 UTC (rev 2975) @@ -0,0 +1,43 @@ +package org.python.core; + +public class PySlot extends PyDescriptor { + + public PySlot(PyType dtype, String name, int index) { + this.name = name; + this.dtype = dtype; + this.index = index; + } + + public boolean implementsDescrSet() { + return true; + } + + public boolean isDataDescr() { + return true; + } + + public PyObject __get__(PyObject obj, PyObject type) { + if(obj != null) { + checkType((PyType)type); + return ((Slotted)obj).getSlot(index); + } + return this; + } + + public void __set__(PyObject obj, PyObject value) { + checkType(obj.getType()); + ((Slotted)obj).setSlot(index, value); + } + + public String toString() { + return "<member '" + name + "' of '" + dtype.fastGetName() + + "' objects>"; + } + + private void checkType(PyType type) { + if(type != dtype && !type.isSubType(dtype)) + throw get_wrongtype(type); + } + + private int index; +} Modified: trunk/jython/src/org/python/core/PyStringDerived.java =================================================================== --- trunk/jython/src/org/python/core/PyStringDerived.java 2006-11-19 16:59:17 UTC (rev 2974) +++ trunk/jython/src/org/python/core/PyStringDerived.java 2006-11-19 17:00:42 UTC (rev 2975) @@ -1,7 +1,17 @@ package org.python.core; -public class PyStringDerived extends PyString { +public class PyStringDerived extends PyString implements Slotted { + public PyObject getSlot(int index) { + return slots[index]; + } + + public void setSlot(int index,PyObject value) { + slots[index]=value; + } + + private PyObject[]slots; + private PyObject dict; public PyObject fastGetDict() { @@ -14,6 +24,7 @@ public PyStringDerived(PyType subtype,String v) { super(subtype,v); + slots=new PyObject[subtype.getNumSlots()]; dict=subtype.instDict(); } Modified: trunk/jython/src/org/python/core/PySuperDerived.java =================================================================== --- trunk/jython/src/org/python/core/PySuperDerived.java 2006-11-19 16:59:17 UTC (rev 2974) +++ trunk/jython/src/org/python/core/PySuperDerived.java 2006-11-19 17:00:42 UTC (rev 2975) @@ -1,7 +1,17 @@ package org.python.core; -public class PySuperDerived extends PySuper { +public class PySuperDerived extends PySuper implements Slotted { + public PyObject getSlot(int index) { + return slots[index]; + } + + public void setSlot(int index,PyObject value) { + slots[index]=value; + } + + private PyObject[]slots; + private PyObject dict; public PyObject fastGetDict() { @@ -14,6 +24,7 @@ public PySuperDerived(PyType subtype) { super(subtype); + slots=new PyObject[subtype.getNumSlots()]; dict=subtype.instDict(); } Modified: trunk/jython/src/org/python/core/PyTupleDerived.java =================================================================== --- trunk/jython/src/org/python/core/PyTupleDerived.java 2006-11-19 16:59:17 UTC (rev 2974) +++ trunk/jython/src/org/python/core/PyTupleDerived.java 2006-11-19 17:00:42 UTC (rev 2975) @@ -1,7 +1,17 @@ package org.python.core; -public class PyTupleDerived extends PyTuple { +public class PyTupleDerived extends PyTuple implements Slotted { + public PyObject getSlot(int index) { + return slots[index]; + } + + public void setSlot(int index,PyObject value) { + slots[index]=value; + } + + private PyObject[]slots; + private PyObject dict; public PyObject fastGetDict() { @@ -14,6 +24,7 @@ public PyTupleDerived(PyType subtype,PyObject[]elements) { super(subtype,elements); + slots=new PyObject[subtype.getNumSlots()]; dict=subtype.instDict(); } Modified: trunk/jython/src/org/python/core/PyType.java =================================================================== --- trunk/jython/src/org/python/core/PyType.java 2006-11-19 16:59:17 UTC (rev 2974) +++ trunk/jython/src/org/python/core/PyType.java 2006-11-19 17:00:42 UTC (rev 2975) @@ -382,26 +382,21 @@ return null; } - public List getSlotnames() { - return slotnames; - } - - private String name; private PyType base; private PyObject[] bases; private PyObject dict; private PyObject[] mro; private Class underlying_class; - private List slotnames; private boolean non_instantiable = false; - boolean has_set, has_delete, hide_dict; + boolean has_set, has_delete; private boolean needs_finalizer; - private int nuserslots; + private int numSlots; + private PyObject userslots; private boolean needs_userdict; private java.lang.ref.ReferenceQueue subclasses_refq = new java.lang.ref.ReferenceQueue(); @@ -602,7 +597,7 @@ PyObject parent = mro[i]; if (parent instanceof PyType) { PyType parent_type =(PyType)parent; - if (parent_type.underlying_class != null || parent_type.nuserslots != 0) + if (parent_type.underlying_class != null || parent_type.numSlots != 0) return parent_type; } } @@ -679,23 +674,7 @@ // xxx can be subclassed ? - boolean needs_userdict = base.needs_userdict; - if (!needs_userdict) { - for (int i=0; i<bases_list.length;i++) { - PyObject cur = bases_list[i]; - if (cur != base) { - if ((cur instanceof PyType && ((PyType)cur).needs_userdict) || cur instanceof PyClass) { - needs_userdict = true; - break; - } - } - } - } - int nuserslots = base.nuserslots; - - needs_userdict = true; - if (dict.__finditem__("__module__") == null) { PyFrame frame = Py.getFrame(); if (frame != null) { @@ -708,37 +687,43 @@ } // xxx also __doc__ __module__ - List slotnames = null; - boolean hide_dict = false; + PyType newtype; + if (new_.for_type == metatype) { + newtype = new PyType(); // xxx set metatype + } else { + newtype = new PyTypeDerived(metatype); + } + + int nuserslots = base.numSlots; PyObject slots = dict.__finditem__("__slots__"); - if (slots != null) { - hide_dict = true; - if (base.nuserslots > 0) { - nuserslots = base.nuserslots; - slotnames = new ArrayList(base.getSlotnames()); - } - else { - slotnames = new ArrayList(); - } + boolean needs_userdict = true; + if(slots != null) { + needs_userdict = false; PyObject iter = slots.__iter__(); PyObject slotname; - for (; (slotname = iter.__iternext__())!= null; ) { + for(; (slotname = iter.__iternext__()) != null;) { confirmIdentifier(slotname); - String slotstring = slotname.toString(); - if (slotstring.equals("__dict__")) { - hide_dict = false; + String slotstring = mangleName(name, slotname.toString()); + if(slotstring.equals("__dict__")) { + needs_userdict = true; + } else { + dict.__setitem__(slotstring, new PySlot(newtype, + slotstring, + nuserslots)); + nuserslots += 1; } - slotnames.add(mangleName(name, slotstring)); - nuserslots += 1; } } - - PyType newtype; - if (new_.for_type == metatype) { - newtype = new PyType(); // xxx set metatype - } else { - newtype = new PyTypeDerived(metatype); + if(!needs_userdict) { + for(int i = 0; i < bases_list.length; i++) { + PyObject cur = bases_list[i]; + if((cur instanceof PyType && ((PyType)cur).needs_userdict) + || cur instanceof PyClass) { + needs_userdict = true; + break; + } + } } newtype.name = name; @@ -746,13 +731,10 @@ newtype.bases = bases_list; newtype.needs_userdict = needs_userdict; - newtype.nuserslots = nuserslots; - newtype.hide_dict = hide_dict; + newtype.numSlots = nuserslots; newtype.dict = dict; - newtype.slotnames = slotnames; - // special case __new__, if function => static method PyObject tmp = dict.__finditem__("__new__"); if (tmp != null && tmp instanceof PyFunction) { // xxx java functions? @@ -788,7 +770,6 @@ if (cur instanceof PyType) ((PyType)cur).attachSubclass(newtype); } - return newtype; } @@ -807,19 +788,18 @@ } /** - * INTERNAL - * lookup for name through mro objects' dicts - * - * @param name attribute name (must be interned) + * INTERNAL lookup for name through mro objects' dicts + * + * @param name + * attribute name (must be interned) * @return found object or null */ public PyObject lookup(String name) { - PyObject[] mro = this.mro; - for (int i = 0; i < mro.length; i++) { + for(int i = 0; i < mro.length; i++) { PyObject dict = mro[i].fastGetDict(); - if (dict != null) { + if(dict != null) { PyObject obj = dict.__finditem__(name); - if (obj != null) + if(obj != null) return obj; } } @@ -1344,6 +1324,10 @@ return new PyString("__builtin__"); return dict.__finditem__("__module__"); } + + public int getNumSlots(){ + return numSlots; + } public String getFullName () { if (underlying_class != null) Modified: trunk/jython/src/org/python/core/PyTypeDerived.java =================================================================== --- trunk/jython/src/org/python/core/PyTypeDerived.java 2006-11-19 16:59:17 UTC (rev 2974) +++ trunk/jython/src/org/python/core/PyTypeDerived.java 2006-11-19 17:00:42 UTC (rev 2975) @@ -1,7 +1,17 @@ package org.python.core; -public class PyTypeDerived extends PyType { +public class PyTypeDerived extends PyType implements Slotted { + public PyObject getSlot(int index) { + return slots[index]; + } + + public void setSlot(int index,PyObject value) { + slots[index]=value; + } + + private PyObject[]slots; + private PyObject dict; public PyObject fastGetDict() { @@ -14,6 +24,7 @@ public PyTypeDerived(PyType subtype) { super(subtype); + slots=new PyObject[subtype.getNumSlots()]; dict=subtype.instDict(); } Modified: trunk/jython/src/org/python/core/PyUnicodeDerived.java =================================================================== --- trunk/jython/src/org/python/core/PyUnicodeDerived.java 2006-11-19 16:59:17 UTC (rev 2974) +++ trunk/jython/src/org/python/core/PyUnicodeDerived.java 2006-11-19 17:00:42 UTC (rev 2975) @@ -1,7 +1,17 @@ package org.python.core; -public class PyUnicodeDerived extends PyUnicode { +public class PyUnicodeDerived extends PyUnicode implements Slotted { + public PyObject getSlot(int index) { + return slots[index]; + } + + public void setSlot(int index,PyObject value) { + slots[index]=value; + } + + private PyObject[]slots; + private PyObject dict; public PyObject fastGetDict() { @@ -14,6 +24,7 @@ public PyUnicodeDerived(PyType subtype,String string) { super(subtype,string); + slots=new PyObject[subtype.getNumSlots()]; dict=subtype.instDict(); } Added: trunk/jython/src/org/python/core/Slotted.java =================================================================== --- trunk/jython/src/org/python/core/Slotted.java (rev 0) +++ trunk/jython/src/org/python/core/Slotted.java 2006-11-19 17:00:42 UTC (rev 2975) @@ -0,0 +1,8 @@ +package org.python.core; + +public interface Slotted { + + public PyObject getSlot(int index); + + public void setSlot(int index, PyObject value); +} This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <cg...@us...> - 2006-11-28 04:18:14
|
Revision: 2999 http://svn.sourceforge.net/jython/?rev=2999&view=rev Author: cgroves Date: 2006-11-27 20:18:13 -0800 (Mon, 27 Nov 2006) Log Message: ----------- make keyword args to constructor line up with those from CPython Modified Paths: -------------- trunk/jython/src/org/python/core/PyList.java trunk/jython/src/org/python/core/PyTuple.java trunk/jython/src/org/python/core/PyUnicode.java Modified: trunk/jython/src/org/python/core/PyList.java =================================================================== --- trunk/jython/src/org/python/core/PyList.java 2006-11-28 01:55:36 UTC (rev 2998) +++ trunk/jython/src/org/python/core/PyList.java 2006-11-28 04:18:13 UTC (rev 2999) @@ -1126,20 +1126,17 @@ } final void list_init(PyObject[] args,String[] kwds) { - int nargs = args.length - kwds.length; - if (nargs > 1) { - throw PyBuiltinFunction.DefaultInfo.unexpectedCall(nargs,false,exposed_name,0,1); - } - if (nargs == 0) { + ArgParser ap = new ArgParser("list", args, kwds, new String[] { "sequence"}, 0); + PyObject seq = ap.getPyObject(0, null); + if (seq == null) { return; } - PyObject o = args[0]; - if (o instanceof PySequenceList) { - PySequenceList p = (PySequenceList) o.__getslice__(Py.None, Py.None, Py.One); + if (seq instanceof PySequenceList) { + PySequenceList p = (PySequenceList) seq.__getslice__(Py.None, Py.None, Py.One); this.list = p.list; } else { - PyObject iter = o.__iter__(); + PyObject iter = seq.__iter__(); for (PyObject item = null; (item = iter.__iternext__()) != null; ) { append(item); } Modified: trunk/jython/src/org/python/core/PyTuple.java =================================================================== --- trunk/jython/src/org/python/core/PyTuple.java 2006-11-28 01:55:36 UTC (rev 2998) +++ trunk/jython/src/org/python/core/PyTuple.java 2006-11-28 04:18:13 UTC (rev 2999) @@ -416,7 +416,7 @@ final static PyObject tuple_new(PyNewWrapper new_, boolean init, PyType subtype, PyObject[] args, String[] keywords) { - ArgParser ap = new ArgParser("tuple", args, keywords, new String[] { "S" }, 0); + ArgParser ap = new ArgParser("tuple", args, keywords, new String[] { "sequence" }, 0); PyObject S = ap.getPyObject(0, null); if (new_.for_type == subtype) { if (S == null) { Modified: trunk/jython/src/org/python/core/PyUnicode.java =================================================================== --- trunk/jython/src/org/python/core/PyUnicode.java 2006-11-28 01:55:36 UTC (rev 2998) +++ trunk/jython/src/org/python/core/PyUnicode.java 2006-11-28 04:18:13 UTC (rev 2999) @@ -2701,7 +2701,7 @@ final static PyObject unicode_new(PyNewWrapper new_, boolean init, PyType subtype, PyObject[] args, String[] keywords) { - ArgParser ap = new ArgParser("unicode", args, keywords, new String[] { "S", "encoding", "errors" }, 0); + ArgParser ap = new ArgParser("unicode", args, keywords, new String[] { "string", "encoding", "errors" }, 0); PyObject S = ap.getPyObject(0, null); String encoding = ap.getString(1, null); String errors = ap.getString(2, null); This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <ped...@us...> - 2006-12-09 21:00:02
|
Revision: 3018 http://svn.sourceforge.net/jython/?rev=3018&view=rev Author: pedronis Date: 2006-12-09 13:00:01 -0800 (Sat, 09 Dec 2006) Log Message: ----------- umph, my Eclipse was using tabs... fixing that Modified Paths: -------------- trunk/jython/src/org/python/core/PyObject.java trunk/jython/src/org/python/core/PyType.java Modified: trunk/jython/src/org/python/core/PyObject.java =================================================================== --- trunk/jython/src/org/python/core/PyObject.java 2006-12-09 20:40:17 UTC (rev 3017) +++ trunk/jython/src/org/python/core/PyObject.java 2006-12-09 21:00:01 UTC (rev 3018) @@ -1583,7 +1583,7 @@ PyType t2 = o.getType(); if (t1 != t2 && t2.isSubType(t1)) { - return o._eq(this); + return o._eq(this); } ThreadState ts = Py.getThreadState(); @@ -1622,7 +1622,7 @@ PyType t2 = o.getType(); if (t1 != t2 && t2.isSubType(t1)) { - return o._ne(this); + return o._ne(this); } ThreadState ts = Py.getThreadState(); @@ -1656,7 +1656,7 @@ PyType t2 = o.getType(); if (t1 != t2 && t2.isSubType(t1)) { - return o._ge(this); + return o._ge(this); } ThreadState ts = Py.getThreadState(); @@ -1690,7 +1690,7 @@ PyType t2 = o.getType(); if (t1 != t2 && t2.isSubType(t1)) { - return o._gt(this); + return o._gt(this); } ThreadState ts = Py.getThreadState(); @@ -1724,7 +1724,7 @@ PyType t2 = o.getType(); if (t1 != t2 && t2.isSubType(t1)) { - return o._le(this); + return o._le(this); } ThreadState ts = Py.getThreadState(); @@ -1758,7 +1758,7 @@ PyType t2 = o.getType(); if (t1 != t2 && t2.isSubType(t1)) { - return o._lt(this); + return o._lt(this); } ThreadState ts = Py.getThreadState(); @@ -2004,53 +2004,51 @@ } - private PyObject _binop_rule(PyType t1, PyObject o2, PyType t2, - String left, - String right, - String op) { - /* this is the general rule for binary operation dispatching - * try first __xxx__ with this and then __rxxx__ with o2 - * unless o2 is an instance of subclass of the type of this, - * and further __xxx__ and __rxxx__ are unrelated ( - * checked here by looking at where in the hierarchy they - * are defined), in that case try them in the reverse order. - * This is the same formulation as used by PyPy, - * see also test_descr.subclass_right_op. - */ - PyObject o1 = this; - PyObject[] where = new PyObject[1]; - PyObject where1=null, where2=null; - PyObject impl1 = t1.lookup_where(left, where); - where1 = where[0]; - PyObject impl2 = t2.lookup_where(right, where); - where2 = where[0]; - if (impl2 !=null && where1 != where2 && t2.isSubType(t1)) { - PyObject tmp = o1; - o1 = o2; - o2 = tmp; - tmp = impl1; - impl1 = impl2; - impl2 = tmp; - PyType ttmp; - ttmp = t1; - t1 = t2; - t2 = ttmp; - } - PyObject res = null; - if (impl1 != null) { - res = impl1.__get__(o1, t1).__call__(o2); - if (res != Py.NotImplemented) { - return res; - } - } - if (impl2 != null) { - res = impl2.__get__(o2, t2).__call__(o1); - if (res != Py.NotImplemented) { - return res; - } - } - throw Py.TypeError(_unsupportedop(op,o2)); - } + private PyObject _binop_rule(PyType t1, PyObject o2, PyType t2, + String left, String right, String op) { + /* + * this is the general rule for binary operation dispatching try first + * __xxx__ with this and then __rxxx__ with o2 unless o2 is an instance + * of subclass of the type of this, and further __xxx__ and __rxxx__ are + * unrelated ( checked here by looking at where in the hierarchy they + * are defined), in that case try them in the reverse order. This is the + * same formulation as used by PyPy, see also + * test_descr.subclass_right_op. + */ + PyObject o1 = this; + PyObject[] where = new PyObject[1]; + PyObject where1 = null, where2 = null; + PyObject impl1 = t1.lookup_where(left, where); + where1 = where[0]; + PyObject impl2 = t2.lookup_where(right, where); + where2 = where[0]; + if (impl2 != null && where1 != where2 && t2.isSubType(t1)) { + PyObject tmp = o1; + o1 = o2; + o2 = tmp; + tmp = impl1; + impl1 = impl2; + impl2 = tmp; + PyType ttmp; + ttmp = t1; + t1 = t2; + t2 = ttmp; + } + PyObject res = null; + if (impl1 != null) { + res = impl1.__get__(o1, t1).__call__(o2); + if (res != Py.NotImplemented) { + return res; + } + } + if (impl2 != null) { + res = impl2.__get__(o2, t2).__call__(o1); + if (res != Py.NotImplemented) { + return res; + } + } + throw Py.TypeError(_unsupportedop(op, o2)); + } // Generated by make_binops.py (Begin) Modified: trunk/jython/src/org/python/core/PyType.java =================================================================== --- trunk/jython/src/org/python/core/PyType.java 2006-12-09 20:40:17 UTC (rev 3017) +++ trunk/jython/src/org/python/core/PyType.java 2006-12-09 21:00:01 UTC (rev 3018) @@ -798,13 +798,13 @@ public PyObject lookup_where(String name, PyObject[] where) { PyObject[] mro = this.mro; - for(int i = 0; i < mro.length; i++) { - PyObject t = mro[i]; + for (int i = 0; i < mro.length; i++) { + PyObject t = mro[i]; PyObject dict = t.fastGetDict(); - if(dict != null) { + if (dict != null) { PyObject obj = dict.__finditem__(name); - if(obj != null) { - where[0] = t; + if (obj != null) { + where[0] = t; return obj; } } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <cg...@us...> - 2007-01-20 17:49:50
|
Revision: 3053 http://svn.sourceforge.net/jython/?rev=3053&view=rev Author: cgroves Date: 2007-01-20 09:49:47 -0800 (Sat, 20 Jan 2007) Log Message: ----------- remove returnString method in favor of letting subclasses of PyString use their __str__ method when passed to PyString' constructor. Fixes bug #1604264 Modified Paths: -------------- trunk/jython/src/org/python/core/PyString.java trunk/jython/src/org/python/core/PyUnicode.java Modified: trunk/jython/src/org/python/core/PyString.java =================================================================== --- trunk/jython/src/org/python/core/PyString.java 2007-01-19 08:36:01 UTC (rev 3052) +++ trunk/jython/src/org/python/core/PyString.java 2007-01-20 17:49:47 UTC (rev 3053) @@ -2822,8 +2822,11 @@ PyObject[] args, String[] keywords) { ArgParser ap = new ArgParser("str", args, keywords, new String[] { "object" }, 0); PyObject S = ap.getPyObject(0, null); - if (new_.for_type == subtype) { - return returnString(S); + if(new_.for_type == subtype) { + if(S == null) { + return new PyString(""); + } + return S.__str__(); } else { if (S == null) { return new PyStringDerived(subtype, ""); @@ -2832,18 +2835,6 @@ } } - private static PyString returnString(PyObject S) { - if (S == null) { - return new PyString(""); - } - if (S instanceof PyStringDerived || S instanceof PyUnicode) { - return new PyString(S.toString()); - } if (S instanceof PyString) { - return (PyString)S; - } - return S.__str__(); - } - /** <i>Internal use only. Do not call this method explicit.</i> */ public static void classDictInit(PyObject dict) throws PyIgnoreMethodTag {} @@ -2856,7 +2847,7 @@ } final PyString str___str__() { - return returnString(this); + return this; } public PyUnicode __unicode__() { Modified: trunk/jython/src/org/python/core/PyUnicode.java =================================================================== --- trunk/jython/src/org/python/core/PyUnicode.java 2007-01-19 08:36:01 UTC (rev 3052) +++ trunk/jython/src/org/python/core/PyUnicode.java 2007-01-20 17:49:47 UTC (rev 3053) @@ -2741,7 +2741,7 @@ } public PyString unicode___str__() { - return str___str__(); + return new PyString(toString()); } final int unicode___len__() { This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <cg...@us...> - 2007-04-29 08:58:38
|
Revision: 3196 http://svn.sourceforge.net/jython/?rev=3196&view=rev Author: cgroves Date: 2007-04-29 01:58:37 -0700 (Sun, 29 Apr 2007) Log Message: ----------- go ahead and make sys.builtins static since that's effectively what we were doing Modified Paths: -------------- trunk/jython/src/org/python/core/PySystemState.java trunk/jython/src/org/python/core/__builtin__.java Modified: trunk/jython/src/org/python/core/PySystemState.java =================================================================== --- trunk/jython/src/org/python/core/PySystemState.java 2007-04-29 08:47:24 UTC (rev 3195) +++ trunk/jython/src/org/python/core/PySystemState.java 2007-04-29 08:58:37 UTC (rev 3196) @@ -108,9 +108,9 @@ exit(Py.None); } - public PyObject modules; // = new PyStringMap(); + public PyObject modules; public PyList path; - public PyObject builtins; + public static PyObject builtins; public PyList meta_path; public PyList path_hooks; @@ -277,8 +277,6 @@ if(builtins == null){ builtins = new PyStringMap(); __builtin__.fillWithBuiltins(builtins); - }else{ - builtins = Py.defaultSystemState.builtins; } PyModule __builtin__ = new PyModule("__builtin__", builtins); modules.__setitem__("__builtin__", __builtin__); @@ -475,7 +473,7 @@ if (classLoader != null) Py.defaultSystemState.setClassLoader(classLoader); - Py.initClassExceptions(Py.defaultSystemState.builtins); + Py.initClassExceptions(PySystemState.builtins); // Make sure that Exception classes have been loaded new PySyntaxError("", 1,1,"", ""); } Modified: trunk/jython/src/org/python/core/__builtin__.java =================================================================== --- trunk/jython/src/org/python/core/__builtin__.java 2007-04-29 08:47:24 UTC (rev 3195) +++ trunk/jython/src/org/python/core/__builtin__.java 2007-04-29 08:58:37 UTC (rev 3196) @@ -302,7 +302,6 @@ public class __builtin__ { public static void fillWithBuiltins(PyObject dict) { /* newstyle */ - dict.__setitem__("object", PyType.fromClass(PyObject.class)); dict.__setitem__("type", PyType.fromClass(PyType.class)); dict.__setitem__("int", PyType.fromClass(PyInteger.class)); This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <kz...@us...> - 2007-05-04 05:51:16
|
Revision: 3203 http://svn.sourceforge.net/jython/?rev=3203&view=rev Author: kzuberi Date: 2007-05-03 22:51:14 -0700 (Thu, 03 May 2007) Log Message: ----------- PyFloat _pow, __builtin__ hex and vars fixes from patch #1628469 by lantz moore Modified Paths: -------------- trunk/jython/src/org/python/core/PyFloat.java trunk/jython/src/org/python/core/__builtin__.java Modified: trunk/jython/src/org/python/core/PyFloat.java =================================================================== --- trunk/jython/src/org/python/core/PyFloat.java 2007-04-30 07:08:57 UTC (rev 3202) +++ trunk/jython/src/org/python/core/PyFloat.java 2007-05-04 05:51:14 UTC (rev 3203) @@ -950,6 +950,9 @@ return new PyFloat(0); } + if (value < 0 && iw != Math.floor(iw)) + throw Py.ValueError("negative number cannot be raised to a fractional power"); + double ret = Math.pow(value, iw); if (modulo == null) { return new PyFloat(ret); Modified: trunk/jython/src/org/python/core/__builtin__.java =================================================================== --- trunk/jython/src/org/python/core/__builtin__.java 2007-04-30 07:08:57 UTC (rev 3202) +++ trunk/jython/src/org/python/core/__builtin__.java 2007-05-04 05:51:14 UTC (rev 3203) @@ -627,7 +627,13 @@ } public static PyString hex(PyObject o) { - return o.__hex__(); + try { + return o.__hex__(); + } catch (PyException e) { + if (Py.matchException(e, Py.AttributeError)) + throw Py.TypeError("hex() argument can't be converted to hex"); + throw e; + } } public static long id(PyObject o) { @@ -1035,7 +1041,13 @@ } public static PyObject vars(PyObject o) { - return o.__getattr__("__dict__"); + try { + return o.__getattr__("__dict__"); + } catch (PyException e) { + if (Py.matchException(e, Py.AttributeError)) + throw Py.TypeError("vars() argument must have __dict__ attribute"); + throw e; + } } public static PyObject vars() { This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <cg...@us...> - 2007-05-06 06:09:28
|
Revision: 3209 http://svn.sourceforge.net/jython/?rev=3209&view=rev Author: cgroves Date: 2007-05-05 23:09:25 -0700 (Sat, 05 May 2007) Log Message: ----------- added PyObjectAdapters to allow Py.py2java to be extended with custom object wrappers Modified Paths: -------------- trunk/jython/src/org/python/core/Py.java trunk/jython/src/org/python/core/PySystemState.java Added Paths: ----------- trunk/jython/src/org/python/core/adapter/ trunk/jython/src/org/python/core/adapter/ClassAdapter.java trunk/jython/src/org/python/core/adapter/ClassicPyObjectAdapter.java trunk/jython/src/org/python/core/adapter/ExtensiblePyObjectAdapter.java trunk/jython/src/org/python/core/adapter/PyObjectAdapter.java Modified: trunk/jython/src/org/python/core/Py.java =================================================================== --- trunk/jython/src/org/python/core/Py.java 2007-05-05 23:33:26 UTC (rev 3208) +++ trunk/jython/src/org/python/core/Py.java 2007-05-06 06:09:25 UTC (rev 3209) @@ -14,6 +14,8 @@ import java.lang.reflect.InvocationTargetException; import org.python.compiler.Module; +import org.python.core.adapter.ClassicPyObjectAdapter; +import org.python.core.adapter.ExtensiblePyObjectAdapter; import org.python.parser.ast.modType; public final class Py @@ -1480,49 +1482,27 @@ } return letters[c]; } - - // Needs rewriting for efficiency and extensibility - public static PyObject java2py(Object o) { - if (o instanceof PyObject) - return (PyObject)o; - - if (o instanceof PyProxy) - return ((PyProxy)o)._getPyInstance(); - - if (o instanceof Number) { - if (o instanceof Double || o instanceof Float) { - return new PyFloat(((Number)o).doubleValue()); - } - else if (o instanceof Long) { - return new PyLong(((Number)o).longValue()); - } - else if (o instanceof Integer || - o instanceof Byte || - o instanceof Short) - { - return new PyInteger(((Number)o).intValue()); - } - } - if (o instanceof Boolean) { - return ((Boolean)o).booleanValue() ? Py.One : Py.Zero; - } - if (o == null) return Py.None; - if (o instanceof String) return new PyString((String)o); - if (o instanceof Character) return makeCharacter((Character)o); - if (o instanceof Class) { - Class cls = (Class)o; - if (PyObject.class.isAssignableFrom(cls)) { - return PyType.fromClass(cls); - } - return PyJavaClass.lookup(cls); - } - - Class c = o.getClass(); - if (c.isArray()) { - return new PyArray(c.getComponentType(), o); - } - return new PyJavaInstance(o); + + /** + * Uses the PyObjectAdapter passed to {@link PySystemState#initialize} to turn o into a PyObject. + * + * @see ClassicPyObjectAdapter - default PyObjectAdapter type + */ + public static PyObject java2py(Object o) { + return adapter.adapt(o); + } + + /** + * @return the ExtensiblePyObjectAdapter used by java2py. + */ + public static ExtensiblePyObjectAdapter getAdapter(){ + return adapter; } + + /** + * Handles wrapping Java objects in PyObject to expose them to jython. + */ + protected static ExtensiblePyObjectAdapter adapter; public static PyObject makeClass(String name, PyObject[] bases, PyCode code, PyObject doc) Modified: trunk/jython/src/org/python/core/PySystemState.java =================================================================== --- trunk/jython/src/org/python/core/PySystemState.java 2007-05-05 23:33:26 UTC (rev 3208) +++ trunk/jython/src/org/python/core/PySystemState.java 2007-05-06 06:09:25 UTC (rev 3209) @@ -19,6 +19,8 @@ import java.util.jar.JarEntry; import java.util.jar.JarFile; +import org.python.core.adapter.ClassicPyObjectAdapter; +import org.python.core.adapter.ExtensiblePyObjectAdapter; import org.python.modules.Setup; /** @@ -433,6 +435,14 @@ String[] argv, ClassLoader classLoader) { + initialize(preProperties, postProperties, argv, classLoader, new ClassicPyObjectAdapter()); + } + public static synchronized void initialize(Properties preProperties, + Properties postProperties, + String[] argv, + ClassLoader classLoader, + ExtensiblePyObjectAdapter adapter) + { //System.err.println("initializing system state"); //Thread.currentThread().dumpStack(); @@ -447,6 +457,7 @@ } initialized = true; + Py.adapter = adapter; boolean standalone = false; String jarFileName = getJarFileName(); if (jarFileName != null) { Added: trunk/jython/src/org/python/core/adapter/ClassAdapter.java =================================================================== --- trunk/jython/src/org/python/core/adapter/ClassAdapter.java (rev 0) +++ trunk/jython/src/org/python/core/adapter/ClassAdapter.java 2007-05-06 06:09:25 UTC (rev 3209) @@ -0,0 +1,19 @@ +package org.python.core.adapter; + +public abstract class ClassAdapter implements PyObjectAdapter { + + public ClassAdapter(Class adaptedClass) { + this.adaptedClass = adaptedClass; + } + + public Class getAdaptedClass() { + return adaptedClass; + } + + public boolean canAdapt(Object o) { + return adaptedClass.getClass().equals(adaptedClass); + } + + private Class adaptedClass; + +} Property changes on: trunk/jython/src/org/python/core/adapter/ClassAdapter.java ___________________________________________________________________ Name: svn:executable + * Added: trunk/jython/src/org/python/core/adapter/ClassicPyObjectAdapter.java =================================================================== --- trunk/jython/src/org/python/core/adapter/ClassicPyObjectAdapter.java (rev 0) +++ trunk/jython/src/org/python/core/adapter/ClassicPyObjectAdapter.java 2007-05-06 06:09:25 UTC (rev 3209) @@ -0,0 +1,154 @@ +package org.python.core.adapter; + +import org.python.core.Py; +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.PyLong; +import org.python.core.PyObject; +import org.python.core.PyProxy; +import org.python.core.PyString; +import org.python.core.PyType; + +/** + * 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 { + + public ClassicPyObjectAdapter() { + addPreClass(new PyObjectAdapter() { + + public PyObject adapt(Object o) { + return (PyObject) o; + } + + public boolean canAdapt(Object o) { + return o instanceof PyObject; + } + }); + addPreClass(new PyObjectAdapter() { + + public PyObject adapt(Object o) { + return ((PyProxy) o)._getPyInstance(); + } + + public boolean canAdapt(Object o) { + return o instanceof PyProxy; + } + }); + addPreClass(new PyObjectAdapter() { + + public boolean canAdapt(Object o) { + return o == null; + } + + public PyObject adapt(Object o) { + return Py.None; + } + }); + + add(new ClassAdapter(String.class) { + + public PyObject adapt(Object o) { + return new PyString((String) o); + } + + }); + add(new ClassAdapter(Character.class) { + + public PyObject adapt(Object 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); + } + + }); + add(new NumberToPyFloat(Double.class)); + add(new NumberToPyFloat(Float.class)); + add(new NumberToPyInteger(Integer.class)); + add(new NumberToPyInteger(Byte.class)); + add(new NumberToPyInteger(Short.class)); + add(new ClassAdapter(Long.class) { + + public PyObject adapt(Object o) { + return new PyLong(((Number) o).longValue()); + } + + }); + add(new ClassAdapter(Boolean.class) { + + public PyObject adapt(Object o) { + return ((Boolean) o).booleanValue() ? Py.One : Py.Zero; + } + + }); + addPostClass(new PyObjectAdapter() { + + public PyObject adapt(Object o) { + return new PyArray(o.getClass().getComponentType(), o); + } + + public boolean canAdapt(Object o) { + return o.getClass().isArray(); + } + }); + } + + /** + * Always returns true as we just return new PyJavaInstance(o) if the + * adapters added to the superclass can't handle o. + */ + public boolean canAdapt(Object o) { + return true; + } + + public PyObject adapt(Object o) { + PyObject result = super.adapt(o); + if (result != null) { + return result; + } + return new PyJavaInstance(o); + } + + private static class NumberToPyInteger extends ClassAdapter { + + public NumberToPyInteger(Class c) { + super(c); + } + + public PyObject adapt(Object o) { + return new PyInteger(((Number) o).intValue()); + } + + } + + private static class NumberToPyFloat extends ClassAdapter { + public NumberToPyFloat(Class c) { + super(c); + } + + public PyObject adapt(Object o) { + return new PyFloat(((Number) o).doubleValue()); + } + + } +} Property changes on: trunk/jython/src/org/python/core/adapter/ClassicPyObjectAdapter.java ___________________________________________________________________ Name: svn:executable + * Added: trunk/jython/src/org/python/core/adapter/ExtensiblePyObjectAdapter.java =================================================================== --- trunk/jython/src/org/python/core/adapter/ExtensiblePyObjectAdapter.java (rev 0) +++ trunk/jython/src/org/python/core/adapter/ExtensiblePyObjectAdapter.java 2007-05-06 06:09:25 UTC (rev 3209) @@ -0,0 +1,94 @@ +package org.python.core.adapter; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; + +import org.python.core.PyObject; + +/** + * A PyObjectAdapter attempts to adapt a Java Object with three user fillable + * groups of adapters: preClass, class and postClass. + * + */ +public class ExtensiblePyObjectAdapter implements PyObjectAdapter { + + /** + * @return true if a preClass, postClass or class adapter can handle this + */ + public boolean canAdapt(Object o) { + return findAdapter(preClassAdapters, o) != null || classAdapters.containsKey(o.getClass()) + || findAdapter(postClassAdapters, o) != null; + } + + /** + * Attempts to adapt o using the preClass, class and postClass adapters. + * + * First each of the preClass adapters is asked in the order of addition if + * they can adapt o. If so, they adapt it. Otherwise, if o.getClass() is + * equal to one of the classes from the added ClassAdapters, that class + * adapter is used. Finally, each of the post class adapters are asked in + * turn if they can adapt o. If so, that adapter handles it. If none can, + * null is returned. + */ + public PyObject adapt(Object o) { + PyObjectAdapter adapter = findAdapter(preClassAdapters, o); + if (adapter != null) { + return adapter.adapt(o); + } + + adapter = (PyObjectAdapter) classAdapters.get(o.getClass()); + if (adapter != null) { + return adapter.adapt(o); + } + + adapter = findAdapter(postClassAdapters, o); + if (adapter != null) { + return adapter.adapt(o); + } + return null; + } + + /** + * Adds an adapter to the list of adapters to be tried before the + * ClassAdapters. + */ + public void addPreClass(PyObjectAdapter adapter) { + preClassAdapters.add(adapter); + } + + /** + * Adds a Class handling adapter that will adapt any objects of its Class if + * that object hasn't already been handled by one of the pre class adapters. + */ + public void add(ClassAdapter adapter) { + classAdapters.put(adapter.getAdaptedClass(), adapter); + } + + /** + * Adds an adapter to the list of adapters to be tried after the + * ClassAdapters. + */ + public void addPostClass(PyObjectAdapter converter) { + postClassAdapters.add(converter); + } + + private static PyObjectAdapter findAdapter(List l, Object o) { + for (Iterator iter = l.iterator(); iter.hasNext();) { + PyObjectAdapter adapter = (PyObjectAdapter) iter.next(); + if (adapter.canAdapt(o)) { + return adapter; + } + } + return null; + } + + private List preClassAdapters = new ArrayList(); + + private List postClassAdapters = new ArrayList(); + + private Map classAdapters = new HashMap(); + +} Property changes on: trunk/jython/src/org/python/core/adapter/ExtensiblePyObjectAdapter.java ___________________________________________________________________ Name: svn:executable + * Added: trunk/jython/src/org/python/core/adapter/PyObjectAdapter.java =================================================================== --- trunk/jython/src/org/python/core/adapter/PyObjectAdapter.java (rev 0) +++ trunk/jython/src/org/python/core/adapter/PyObjectAdapter.java 2007-05-06 06:09:25 UTC (rev 3209) @@ -0,0 +1,20 @@ +package org.python.core.adapter; + +import org.python.core.PyObject; + +/** + * PyObjectAdapters turn Java Objects into PyObjects. + */ +public interface PyObjectAdapter { + + /** + * @return 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); + +} \ No newline at end of file Property changes on: trunk/jython/src/org/python/core/adapter/PyObjectAdapter.java ___________________________________________________________________ Name: svn:executable + * This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <pj...@us...> - 2007-10-02 18:26:39
|
Revision: 3552 http://jython.svn.sourceforge.net/jython/?rev=3552&view=rev Author: pjenvey Date: 2007-10-02 11:26:37 -0700 (Tue, 02 Oct 2007) Log Message: ----------- kill the pollStandardIn option; it was made for green threads, which are gone as of Java 1.4 Modified Paths: -------------- trunk/jython/src/org/python/core/Options.java trunk/jython/src/org/python/core/PySystemState.java Modified: trunk/jython/src/org/python/core/Options.java =================================================================== --- trunk/jython/src/org/python/core/Options.java 2007-10-02 06:37:03 UTC (rev 3551) +++ trunk/jython/src/org/python/core/Options.java 2007-10-02 18:26:37 UTC (rev 3552) @@ -26,12 +26,6 @@ public static boolean showPythonProxyExceptions = false; /** - * Setting this to true will cause the console to poll standard in. This - * might be helpful on systems without system-level threads. - */ - public static boolean pollStandardIn = false; - - /** * If true, Jython respects Java the accessibility flag for fields, * methods, and constructors. This means you can only access public members. * Set this to false to access all members by toggling the accessible flag @@ -126,9 +120,6 @@ Options.deprecatedKeywordMangling = getBooleanOption( "deprecated.keywordMangling", Options.deprecatedKeywordMangling); - Options.pollStandardIn = getBooleanOption("console.poll", - Options.pollStandardIn); - Options.respectJavaAccessibility = getBooleanOption( "security.respectJavaAccessibility", Options.respectJavaAccessibility); Modified: trunk/jython/src/org/python/core/PySystemState.java =================================================================== --- trunk/jython/src/org/python/core/PySystemState.java 2007-10-02 06:37:03 UTC (rev 3551) +++ trunk/jython/src/org/python/core/PySystemState.java 2007-10-02 18:26:37 UTC (rev 3552) @@ -278,7 +278,7 @@ // Set up the initial standard ins and outs __stdout__ = stdout = new PyFile(System.out, "<stdout>"); __stderr__ = stderr = new PyFile(System.err, "<stderr>"); - __stdin__ = stdin = new PyFile(getSystemIn(), "<stdin>"); + __stdin__ = stdin = new PyFile(System.in, "<stdin>"); __displayhook__ = new PySystemStateFunctions("displayhook", 10, 1, 1); __excepthook__ = new PySystemStateFunctions("excepthook", 30, 3, 3); @@ -802,14 +802,6 @@ } } - private InputStream getSystemIn() { - if (Options.pollStandardIn) { - return new PollingInputStream(System.in); - } else { - return System.in; - } - } - public String getdefaultencoding() { return codecs.getDefaultEncoding(); } @@ -855,37 +847,6 @@ } } - -// This class is based on a suggestion from Yunho Jeon -class PollingInputStream extends FilterInputStream { - public PollingInputStream(InputStream s) { - super(s); - } - - private void waitForBytes() throws IOException { - try { - while(available()==0) { - //System.err.println("waiting..."); - Thread.sleep(100); - } - } catch (InterruptedException e) { - throw new PyException(Py.KeyboardInterrupt, - "interrupt waiting on <stdin>"); - } - } - - public int read() throws IOException { - waitForBytes(); - return super.read(); - } - - public int read(byte b[], int off, int len) throws IOException { - waitForBytes(); - return super.read(b, off, len); - } -} - - class PySystemStateFunctions extends PyBuiltinFunctionSet { PySystemStateFunctions(String name, int index, int minargs, int maxargs) { This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <cg...@us...> - 2007-12-16 00:02:18
|
Revision: 3810 http://jython.svn.sourceforge.net/jython/?rev=3810&view=rev Author: cgroves Date: 2007-12-15 16:02:14 -0800 (Sat, 15 Dec 2007) Log Message: ----------- Create resized arrays for PyObjectList as new PyObject[] rather than using reflection. This leads to a significant speedup for creating lists(halves the time for SmallLists in pybench). Modified Paths: -------------- trunk/jython/src/org/python/core/AbstractArray.java trunk/jython/src/org/python/core/PyArray.java trunk/jython/src/org/python/core/PyObjectArray.java Modified: trunk/jython/src/org/python/core/AbstractArray.java =================================================================== --- trunk/jython/src/org/python/core/AbstractArray.java 2007-12-15 21:20:35 UTC (rev 3809) +++ trunk/jython/src/org/python/core/AbstractArray.java 2007-12-16 00:02:14 UTC (rev 3810) @@ -242,7 +242,7 @@ * @return array containing a shallow copy of the data. */ public Object copyArray() { - Object copy = Array.newInstance(getArray().getClass().getComponentType(), this.size); + Object copy = createArray(this.size); System.arraycopy(getArray(), 0, copy, 0, this.size); return copy; } @@ -494,8 +494,7 @@ private void setNewBase(int newCapacity) { this.modCountIncr = 1; Object base = getArray(); - Class baseType = base.getClass().getComponentType(); - Object newBase = Array.newInstance(baseType, newCapacity); + Object newBase = createArray(newCapacity); System.arraycopy(base, 0, newBase, 0, this.capacity); setArray(newBase); } @@ -586,4 +585,9 @@ public int getModCountIncr() { return this.modCountIncr; } + + /** + * @return an array of the given size for the type used by this abstract array. + */ + protected abstract Object createArray(int size); } Modified: trunk/jython/src/org/python/core/PyArray.java =================================================================== --- trunk/jython/src/org/python/core/PyArray.java 2007-12-15 21:20:35 UTC (rev 3809) +++ trunk/jython/src/org/python/core/PyArray.java 2007-12-16 00:02:14 UTC (rev 3810) @@ -631,32 +631,24 @@ // PyArray can't extend anymore, so delegate private class ArrayDelegate extends AbstractArray { - final PyArray pyArray; - private ArrayDelegate(PyArray pyArray) { - super((pyArray.data == null) ? 0 : Array.getLength(pyArray.data)); - this.pyArray = pyArray; + private ArrayDelegate() { + super(data == null ? 0 : Array.getLength(data)); } protected Object getArray() { - return pyArray.data; + return data; } protected void setArray(Object array) { - pyArray.data = array; + data = array; } - protected void makeInsertSpace(int index) { - super.makeInsertSpace(index, 1); + @Override + protected Object createArray(int size) { + Class baseType = data.getClass().getComponentType(); + return Array.newInstance(baseType, size); } - - protected void makeInsertSpace(int index, int length) { - super.makeInsertSpace(index, length); - } - - public void remove(int index) { - super.remove(index); - } } private PyArray() { @@ -669,14 +661,14 @@ public PyArray(PyArray toCopy) { data = toCopy.delegate.copyArray(); - delegate = new ArrayDelegate(this); + delegate = new ArrayDelegate(); type = toCopy.type; } public PyArray(Class type, Object data) { this.type = type; this.data = data; - delegate = new ArrayDelegate(this); + delegate = new ArrayDelegate(); } public PyArray(Class type, int n) { @@ -702,7 +694,7 @@ typecode = type.getName(); } data = Array.newInstance(type, 0); - delegate = new ArrayDelegate(this); + delegate = new ArrayDelegate(); PyObject seq = ap.getPyObject(1, null); if(seq == null){ Modified: trunk/jython/src/org/python/core/PyObjectArray.java =================================================================== --- trunk/jython/src/org/python/core/PyObjectArray.java 2007-12-15 21:20:35 UTC (rev 3809) +++ trunk/jython/src/org/python/core/PyObjectArray.java 2007-12-16 00:02:14 UTC (rev 3810) @@ -204,5 +204,10 @@ public void ensureCapacity(int minCapacity) { super.ensureCapacity(minCapacity); } + + @Override + protected PyObject[] createArray(int size) { + return new PyObject[size]; + } } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <cg...@us...> - 2008-01-01 21:33:06
|
Revision: 3942 http://jython.svn.sourceforge.net/jython/?rev=3942&view=rev Author: cgroves Date: 2008-01-01 13:33:03 -0800 (Tue, 01 Jan 2008) Log Message: ----------- formatting and cleanup Modified Paths: -------------- trunk/jython/src/org/python/core/PyList.java trunk/jython/src/org/python/core/PySequence.java trunk/jython/src/org/python/core/PySequenceList.java Modified: trunk/jython/src/org/python/core/PyList.java =================================================================== --- trunk/jython/src/org/python/core/PyList.java 2008-01-01 21:10:41 UTC (rev 3941) +++ trunk/jython/src/org/python/core/PyList.java 2008-01-01 21:33:03 UTC (rev 3942) @@ -1,8 +1,6 @@ // Copyright (c) Corporation for National Research Initiatives - -// Implementation of the standard Python list objects - package org.python.core; + import java.util.Collection; import java.util.Iterator; import java.util.List; @@ -15,7 +13,6 @@ /** * A builtin python list. */ - @ExposedType(name = "list", base = PyObject.class) public class PyList extends PySequenceList { @@ -48,28 +45,26 @@ public PyList(PyObject o) { this(TYPE); PyObject iter = o.__iter__(); - for (PyObject item = null; (item = iter.__iternext__()) != null; ) { + for(PyObject item = null; (item = iter.__iternext__()) != null;) { append(item); } } @ExposedNew @ExposedMethod - final void list___init__(PyObject[] args,String[] kwds) { - ArgParser ap = new ArgParser("list", args, kwds, new String[] { "sequence"}, 0); + final void list___init__(PyObject[] args, String[] kwds) { + ArgParser ap = new ArgParser("list", args, kwds, new String[] {"sequence"}, 0); PyObject seq = ap.getPyObject(0, null); - clear(); - if (seq == null) { + if(seq == null) { return; } - - if (seq instanceof PySequenceList) { - PySequenceList p = (PySequenceList) seq.__getslice__(Py.None, Py.None, Py.One); + if(seq instanceof PySequenceList) { + PySequenceList p = (PySequenceList)seq.__getslice__(Py.None, Py.None, Py.One); this.list = p.list; } else { PyObject iter = seq.__iter__(); - for (PyObject item = null; (item = iter.__iternext__()) != null; ) { + for(PyObject item = null; (item = iter.__iternext__()) != null;) { append(item); } } @@ -89,18 +84,18 @@ } protected PyObject getslice(int start, int stop, int step) { - if (step > 0 && stop < start) + if(step > 0 && stop < start) { stop = start; + } int n = sliceLength(start, stop, step); PyObject[] newList = new PyObject[n]; PyObject[] array = getArray(); - - if (step == 1) { - System.arraycopy(array, start, newList, 0, stop-start); + if(step == 1) { + System.arraycopy(array, start, newList, 0, stop - start); return new PyList(newList); } int j = 0; - for (int i=start; j<n; i+=step) { + for(int i = start; j < n; i += step) { newList[j] = array[i]; j++; } @@ -112,18 +107,16 @@ } protected void delRange(int start, int stop, int step) { - if (step == 1) { + if(step == 1) { remove(start, stop); - } - else if (step > 1) { - for(int i=start;i<stop;i+=step) { + } 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) { + } else if(step < 0) { + for(int i = start; i >= 0 && i >= stop; i += step) { remove(i); } } @@ -134,75 +127,68 @@ } protected void setslice(int start, int stop, int step, PyObject value) { - if (stop < start) + if(stop < start) { stop = start; - - if (value instanceof PySequence) { + } + if(value instanceof PySequence) { PySequence sequence = (PySequence)value; setslicePySequence(start, stop, step, sequence); - } - else if (value instanceof List) { + } else if(value instanceof List) { List list = (List)value.__tojava__(List.class); - if (list != null && list != Py.NoConversion) { + if(list != null && list != Py.NoConversion) { setsliceList(start, stop, step, list); } - } - else { + } else { setsliceIterable(start, stop, step, value); } } protected void setslicePySequence(int start, int stop, int step, PySequence value) { - if (step == 1) { - PyObject[] otherArray = null; - PyObject[] array = getArray(); - - if (value instanceof PySequenceList) { + if(step == 1) { + PyObject[] otherArray; + PyObject[] array = getArray(); + if(value instanceof PySequenceList) { PySequenceList seqList = (PySequenceList)value; otherArray = seqList.getArray(); - if (otherArray == array) { + if(otherArray == array) { otherArray = otherArray.clone(); } list.replaceSubArray(start, stop, otherArray, 0, seqList.size()); - } - else { + } else { int n = value.__len__(); list.ensureCapacity(start + n); - for (int i=0; i < n; i++) { + for(int i = 0; i < n; i++) { list.add(i + start, value.pyget(i)); } } - } - else if (step > 1) { + } else if(step > 1) { int n = value.__len__(); - for (int i=0, j=0; i < n; i++, j += step) { + for(int i = 0, j = 0; i < n; i++, j += step) { list.pyset(j + start, value.pyget(i)); } - } - else if (step < 0) { + } else if(step < 0) { int n = value.__len__(); - if (value == this) { + if(value == this) { PyList newseq = new PyList(); PyObject iter = value.__iter__(); - for (PyObject item = null; (item = iter.__iternext__()) != null;) { + for(PyObject item = null; (item = iter.__iternext__()) != null;) { newseq.append(item); } value = newseq; } - for (int i=0, j=list.size() - 1; i < n; i++, j += step) { + for(int i = 0, j = list.size() - 1; i < n; i++, j += step) { list.pyset(j, value.pyget(i)); } } } protected void setsliceList(int start, int stop, int step, List value) { - if (step != 1) { - throw Py.TypeError("setslice with java.util.List and step != 1 not " + - "supported yet"); + if(step != 1) { + throw Py.TypeError("setslice with java.util.List and step != 1 not " + "supported yet"); } int n = value.size(); list.ensureCapacity(start + n); - for(int i=0; i < n; i++) { + for(int i = 0; i < n; i++) { list.add(i + start, value.get(i)); } } @@ -211,32 +197,30 @@ PyObject iter; try { iter = value.__iter__(); - } - catch (PyException pye) { - if (Py.matchException(pye, Py.TypeError)) { + } catch(PyException pye) { + if(Py.matchException(pye, Py.TypeError)) { throw Py.TypeError("can only assign an iterable"); } throw pye; } PyObject next; - for (int j = 0; (next = iter.__iternext__()) != null; j += step) { - if (step < 0) { + for(int j = 0; (next = iter.__iternext__()) != null; j += step) { + if(step < 0) { list.pyset(start + j, next); - } - else { + } else { list.add(start + j, next); } } } protected PyObject repeat(int count) { - if (count < 0) { + if(count < 0) { count = 0; } int l = size(); - PyObject[] newList = new PyObject[l*count]; - for (int i=0; i<count; i++) { - System.arraycopy(getArray(), 0, newList, i*l, l); + PyObject[] newList = new PyObject[l * count]; + for(int i = 0; i < count; i++) { + System.arraycopy(getArray(), 0, newList, i * l, l); } return new PyList(newList); } @@ -270,32 +254,31 @@ final PyObject list___ge__(PyObject o) { return seq___ge__(o); } - + public PyObject __imul__(PyObject o) { PyObject result = list___imul__(o); - if (result == null) { + if(result == null) { // We can't perform an in-place multiplication on o's - // type, so let o try to rmul this list. A new list will + // type, so let o try to rmul this list. A new list will // be created instead of modifying this one, but that's // preferable to just blowing up on this operation. result = o.__rmul__(this); - if (result == null) { + if(result == null) { throw Py.TypeError(_unsupportedop("*", o)); } } return result; } - + @ExposedMethod final PyObject list___imul__(PyObject o) { - if (!(o instanceof PyInteger || o instanceof PyLong)) + if(!(o instanceof PyInteger || o instanceof PyLong)) { return null; + } int l = size(); int count = ((PyInteger)o.__int__()).getValue(); - int newSize = l * count; list.setSize(newSize); - PyObject[] array = getArray(); for(int i = 1; i < count; i++) { System.arraycopy(array, 0, array, i * l, l); @@ -305,16 +288,18 @@ @ExposedMethod(type = MethodType.BINARY) final PyObject list___mul__(PyObject o) { - if(!(o instanceof PyInteger || o instanceof PyLong)) + if(!(o instanceof PyInteger || o instanceof PyLong)) { return null; + } int count = ((PyInteger)o.__int__()).getValue(); return repeat(count); } @ExposedMethod(type = MethodType.BINARY) final PyObject list___rmul__(PyObject o) { - if(!(o instanceof PyInteger || o instanceof PyLong)) + if(!(o instanceof PyInteger || o instanceof PyLong)) { return null; + } int count = ((PyInteger)o.__int__()).getValue(); return repeat(count); } @@ -322,43 +307,43 @@ public PyObject __add__(PyObject o) { return list___add__(o); } - - @ExposedMethod(type=MethodType.BINARY) + + @ExposedMethod(type = MethodType.BINARY) final PyObject list___add__(PyObject o) { PyList sum = null; - if (o instanceof PyList) { - PyList other = (PyList)o; + if(o instanceof PyList) { + PyList other = (PyList)o; int thisLen = size(); int otherLen = other.size(); - PyObject[] newList = new PyObject[thisLen+otherLen]; + PyObject[] newList = new PyObject[thisLen + otherLen]; System.arraycopy(getArray(), 0, newList, 0, thisLen); System.arraycopy(other.getArray(), 0, newList, thisLen, otherLen); sum = new PyList(newList); - } else if ( !(o instanceof PySequenceList) ) { + } else if(!(o instanceof PySequenceList)) { // also support adding java lists (but not PyTuple!) Object oList = o.__tojava__(List.class); - if (oList != Py.NoConversion && oList != null) { + if(oList != Py.NoConversion && oList != null) { List otherList = (List)oList; sum = new PyList(); sum.list_extend(this); - for (Iterator i = otherList.iterator(); i.hasNext(); ) { + for(Iterator i = otherList.iterator(); i.hasNext();) { sum.add(i.next()); } } } return sum; } - + public PyObject __radd__(PyObject o) { return list___radd__(o); } - @ExposedMethod(type=MethodType.BINARY) + @ExposedMethod(type = MethodType.BINARY) final PyObject list___radd__(PyObject o) { // Support adding java.util.List, but prevent adding PyTuple. // 'o' should never be a PyList since __add__ is defined. PyList sum = null; - if (o instanceof PySequence) { + if(o instanceof PySequence) { return null; } Object oList = o.__tojava__(List.class); @@ -400,8 +385,7 @@ } @ExposedMethod(defaults = "null") - final PyObject list___getslice__(PyObject start, PyObject stop, PyObject step) - { + final PyObject list___getslice__(PyObject start, PyObject stop, PyObject step) { return seq___getslice__(start, stop, step); } @@ -418,45 +402,44 @@ final void list___delslice__(PyObject start, PyObject stop, PyObject step) { seq___delslice__(start, stop, step); } - + protected String unsupportedopMessage(String op, PyObject o2) { - if (op.equals("+")) { + if(op.equals("+")) { return "can only concatenate list (not \"{2}\") to list"; } return super.unsupportedopMessage(op, o2); } - + public String toString() { return list_toString(); } - @ExposedMethod(names="__repr__") + @ExposedMethod(names = "__repr__") final String list_toString() { ThreadState ts = Py.getThreadState(); - if (!ts.enterRepr(this)) { + if(!ts.enterRepr(this)) { return "[...]"; } - StringBuffer buf = new StringBuffer("["); int length = size(); PyObject[] array = getArray(); - - for (int i=0; i<length-1; i++) { + for(int i = 0; i < length - 1; i++) { buf.append((array[i]).__repr__().toString()); buf.append(", "); } - if (length > 0) - buf.append((array[length-1]).__repr__().toString()); + if(length > 0) { + buf.append((array[length - 1]).__repr__().toString()); + } buf.append("]"); - ts.exitRepr(this); return buf.toString(); } /** * Add a single element to the end of list. - * - * @param o the element to add. + * + * @param o + * the element to add. */ public void append(PyObject o) { list_append(o); @@ -469,9 +452,9 @@ /** * 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. + * + * @param o + * the argument to test for. Testing is done with the <code>==</code> operator. */ public int count(PyObject o) { return list_count(o); @@ -481,94 +464,91 @@ final int list_count(PyObject o) { int count = 0; PyObject[] array = getArray(); - for (int i=0, n = size(); i<n; i++) { - if (array[i].equals(o)) + for(int i = 0, n = size(); i < n; i++) { + if(array[i].equals(o)) { count++; + } } return count; } /** - * 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. + * 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. */ public int index(PyObject o) { return index(o, 0); } - + public int index(PyObject o, int start) { return list_index(o, start, null); } - + public int index(PyObject o, int start, int stop) { return list_index(o, start, Py.newInteger(stop)); } - @ExposedMethod(defaults={"0", "null"}) + @ExposedMethod(defaults = {"0", "null"}) final int list_index(PyObject o, int start, PyObject stop) { int iStop; - if(stop == null){ + if(stop == null) { iStop = size(); - }else{ + } else { iStop = stop.asInt(); } return _index(o, "list.index(x): x not in list", start, iStop); } - + final int list_index(PyObject o, int start) { return _index(o, "list.index(x): x not in list", start, size()); } - + final int list_index(PyObject o) { return _index(o, "list.index(x): x not in list", 0, size()); } private int _index(PyObject o, String message, int start, int stop) { - - //Follow Python 2.3+ behavior + // Follow Python 2.3+ behavior int validStop = calculateIndex(stop); int validStart = calculateIndex(start); - PyObject[] array = getArray(); - int i = validStart; - for (; i < validStop && i < size(); i++) { - if (array[i].equals(o)) + for(int i = validStart; i < validStop && i < size(); i++) { + if(array[i].equals(o)) { return i; + } } throw Py.ValueError(message); - } + } - //This is closely related to fixindex in PySequence, but less strict - //fixindex returns -1 if index += length < 0 or if index >= length - //where this function returns 0 in former case and length in the latter. - //I think both are needed in different cases, but if this method turns - //out to be needed in other sequence subclasses, it should be moved to - //PySequence. + // This is closely related to fixindex in PySequence, but less strict + // fixindex returns -1 if index += length < 0 or if index >= length + // where this function returns 0 in former case and length in the latter. + // I think both are needed in different cases, but if this method turns + // out to be needed in other sequence subclasses, it should be moved to + // PySequence. private int calculateIndex(int index) { int length = size(); - if (index < 0) { + if(index < 0) { index = index += length; - if (index < 0) { + if(index < 0) { index = 0; } - } else if (index > length) { + } else if(index > length) { index = length; } return index; } - /** - * Insert the argument element into the list at the specified - * index. - * <br> + * 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 the element to insert. + * + * @param index + * the position where the element will be inserted. + * @param o + * the element to insert. */ public void insert(int index, PyObject o) { list_insert(index, o); @@ -576,18 +556,22 @@ @ExposedMethod final void list_insert(int index, PyObject o) { - if (index < 0) index = Math.max(0, size() + index); - if (index > size()) index = size(); + if(index < 0) { + index = Math.max(0, size() + index); + } + if(index > size()) { + index = size(); + } list.pyadd(index, o); } /** - * Remove the first occurence of the argument from the list. - * The elements arecompared with the <code>==</code> operator. - * <br> + * 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. + * + * @param o + * the element to search for and remove. */ public void remove(PyObject o) { list_remove(o); @@ -599,10 +583,9 @@ } /** - * Reverses the items of s in place. - * The reverse() methods modify the list in place for economy - * of space when reversing a large list. It doesn't return the - * reversed list to remind you of this side effect. + * Reverses the items of s in place. The reverse() methods modify the list in place for economy + * of space when reversing a large list. It doesn't return the reversed list to remind you of + * this side effect. */ public void reverse() { list_reverse(); @@ -613,8 +596,8 @@ PyObject tmp; int n = size(); PyObject[] array = getArray(); - int j = n-1; - for (int i=0; i<n/2; i++, j--) { + int j = n - 1; + for(int i = 0; i < n / 2; i++, j--) { tmp = array[i]; array[i] = array[j]; array[j] = tmp; @@ -629,37 +612,38 @@ } /** - * Removes and return the <code>n</code> indexed element in the - * list. - * - * @param n the index of the element to remove and return. + * Removes and return the <code>n</code> indexed element in the list. + * + * @param n + * the index of the element to remove and return. */ public PyObject pop(int n) { return list_pop(n); } - @ExposedMethod(defaults="-1") + @ExposedMethod(defaults = "-1") final PyObject list_pop(int n) { int length = size(); - if (length==0) { + if(length == 0) { throw Py.IndexError("pop from empty list"); } - if (n < 0) + if(n < 0) { n += length; - if (n < 0 || n >= length) + } + if(n < 0 || n >= length) { throw Py.IndexError("pop index out of range"); + } PyObject v = pyget(n); - - setslice(n, n+1, 1, Py.EmptyTuple); + setslice(n, n + 1, 1, Py.EmptyTuple); return v; } /** - * Append the elements in the argument sequence to the end of the list. - * <br> + * 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. + * + * @param o + * the sequence of items to append to the list. */ public void extend(PyObject o) { list_extend(o); @@ -682,31 +666,29 @@ } /** - * Sort the items of the list in place. The compare argument is a - * function of two arguments (list items) which should return - * -1, 0 or 1 depending on whether the first argument is - * considered smaller than, equal to, or larger than the second - * argument. Note that this slows 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. The compare argument is a function of two arguments + * (list items) which should return -1, 0 or 1 depending on whether the first argument is + * considered smaller than, equal to, or larger than the second argument. Note that this slows + * 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. */ public synchronized void sort(PyObject compare) { list_sort(compare); } - @ExposedMethod(defaults="null") + @ExposedMethod(defaults = "null") final synchronized void list_sort(PyObject compare) { MergeState ms = new MergeState(getArray(), size(), compare); ms.sort(); } /** - * Sort the items of the list in place. Items is compared with the - * normal relative comparison operators. + * Sort the items of the list in place. Items is compared with the normal relative comparison + * operators. */ public void sort() { list_sort(null); Modified: trunk/jython/src/org/python/core/PySequence.java =================================================================== --- trunk/jython/src/org/python/core/PySequence.java 2008-01-01 21:10:41 UTC (rev 3941) +++ trunk/jython/src/org/python/core/PySequence.java 2008-01-01 21:33:03 UTC (rev 3942) @@ -2,18 +2,18 @@ package org.python.core; /** - * The abstract superclass of PyObjects that implements a Sequence. - * Minimize the work in creating such objects. - * - * Method names are designed to make it possible for PySequence to - * implement java.util.List interface when JDK 1.2 is ubiquitous. - * + * The abstract superclass of PyObjects that implements a Sequence. Minimize the work in creating + * such objects. + * + * Method names are designed to make it possible for subclasses of PySequence to implement + * java.util.List. + * * Subclasses must also implement get, getslice, and repeat methods. - * - * Subclasses that are mutable should also implement: set, setslice, del, - * and delRange. + * + * Subclasses that are mutable should also implement: set, setslice, del, and delRange. */ public abstract class PySequence extends PyObject { + /** * This constructor is used by PyJavaClass.init() */ @@ -24,38 +24,43 @@ } // These methods must be defined for any sequence - /** - * @param index index of element to return. + * @param index + * index of element to return. * @return the element at the given position in the list. */ abstract protected PyObject pyget(int index); /** * Returns a range of elements from the sequence. - * - * @param start the position of the first element. - * @param stop one more than the position of the last element. - * @param step the step size. + * + * @param start + * the position of the first element. + * @param stop + * one more than the position of the last element. + * @param step + * the step size. * @return a sequence corresponding the the given range of elements. */ abstract protected PyObject getslice(int start, int stop, int step); /** * Repeats the given sequence. - * - * @param count the number of times to repeat the sequence. + * + * @param count + * the number of times to repeat the sequence. * @return this sequence repeated count times. */ abstract protected PyObject repeat(int count); // These methods only apply to mutable sequences - /** * Sets the given element of the sequence. - * - * @param index index of the element to set. - * @param value the value to set this element to. + * + * @param index + * index of the element to set. + * @param value + * the value to set this element to. */ protected void set(int index, PyObject value) { throw Py.TypeError("can't assign to immutable object"); @@ -71,6 +76,7 @@ protected void del(int i) throws PyException { throw Py.TypeError("can't remove from immutable object"); } + protected void delRange(int start, int stop, int step) { throw Py.TypeError("can't remove from immutable object"); } @@ -96,13 +102,14 @@ } final synchronized PyObject seq___eq__(PyObject o) { - if (!(getType() == o.getType()) && !(getType().isSubType(o.getType()))) { + if(!(getType() == o.getType()) && !(getType().isSubType(o.getType()))) { return null; } int tl = __len__(); int ol = o.__len__(); - if (tl != ol) + if(tl != ol) { return Py.Zero; + } int i = cmp(this, tl, o, ol); return (i < 0) ? Py.One : Py.Zero; } @@ -112,71 +119,75 @@ } final synchronized PyObject seq___ne__(PyObject o) { - if (!(getType() == o.getType()) && !(getType().isSubType(o.getType()))) { + if(!(getType() == o.getType()) && !(getType().isSubType(o.getType()))) { return null; } int tl = __len__(); int ol = o.__len__(); - if (tl != ol) + if(tl != ol) { return Py.One; + } int i = cmp(this, tl, o, ol); return (i < 0) ? Py.Zero : Py.One; } public synchronized PyObject __lt__(PyObject o) { - if (!(getType() == o.getType()) && !(getType().isSubType(o.getType()))) { + if(!(getType() == o.getType()) && !(getType().isSubType(o.getType()))) { return null; } int i = cmp(this, -1, o, -1); - if (i < 0) + if(i < 0) { return (i == -1) ? Py.One : Py.Zero; + } return __finditem__(i)._lt(o.__finditem__(i)); } - - final synchronized PyObject seq___lt__(PyObject o){ - return __lt__(o); + + final synchronized PyObject seq___lt__(PyObject o) { + return __lt__(o); } public synchronized PyObject __le__(PyObject o) { - if (!(getType() == o.getType()) && !(getType().isSubType(o.getType()))) { + if(!(getType() == o.getType()) && !(getType().isSubType(o.getType()))) { return null; } int i = cmp(this, -1, o, -1); - if (i < 0) + if(i < 0) { return (i == -1 || i == -2) ? Py.One : Py.Zero; + } return __finditem__(i)._le(o.__finditem__(i)); } - - final synchronized PyObject seq___le__(PyObject o){ - return __le__(o); + + final synchronized PyObject seq___le__(PyObject o) { + return __le__(o); } public synchronized PyObject __gt__(PyObject o) { - if (!(getType() == o.getType()) && !(getType().isSubType(o.getType()))) { + if(!(getType() == o.getType()) && !(getType().isSubType(o.getType()))) { return null; } int i = cmp(this, -1, o, -1); - if (i < 0) + if(i < 0) return (i == -3) ? Py.One : Py.Zero; return __finditem__(i)._gt(o.__finditem__(i)); } - - final synchronized PyObject seq___gt__(PyObject o){ - return __gt__(o); + + final synchronized PyObject seq___gt__(PyObject o) { + return __gt__(o); } public synchronized PyObject __ge__(PyObject o) { - if (!(getType() == o.getType()) && !(getType().isSubType(o.getType()))) { + if(!(getType() == o.getType()) && !(getType().isSubType(o.getType()))) { return null; } int i = cmp(this, -1, o, -1); - if (i < 0) + if(i < 0) { return (i == -3 || i == -2) ? Py.One : Py.Zero; + } return __finditem__(i)._ge(o.__finditem__(i)); } - - final synchronized PyObject seq___ge__(PyObject o){ - return __ge__(o); + + final synchronized PyObject seq___ge__(PyObject o) { + return __ge__(o); } // Return value >= 0 is the index where the sequences differs. @@ -184,30 +195,32 @@ // -2: reached the end of both seqeunces without a difference // -3: reached the end of o2 without a difference protected static int cmp(PyObject o1, int ol1, PyObject o2, int ol2) { - if (ol1 < 0) + if(ol1 < 0) { ol1 = o1.__len__(); - if (ol2 < 0) + } + if(ol2 < 0) { ol2 = o2.__len__(); - int i = 0; - for ( ; i < ol1 && i < ol2; i++) { - if (!o1.__getitem__(i)._eq(o2.__getitem__(i)).__nonzero__()) + } + for(int i = 0; i < ol1 && i < ol2; i++) { + if(!o1.__getitem__(i)._eq(o2.__getitem__(i)).__nonzero__()) { return i; + } } - if (ol1 == ol2) + if(ol1 == ol2) { return -2; + } return (ol1 < ol2) ? -1 : -3; } - // Return a copy of a sequence where the __len__() method is // telling the thruth. protected static PyObject fastSequence(PyObject seq, String msg) { - if (seq instanceof PyList || seq instanceof PyTuple) + if(seq instanceof PyList || seq instanceof PyTuple) { return seq; - + } PyList list = new PyList(); PyObject iter = Py.iter(seq, msg); - for (PyObject item = null; (item = iter.__iternext__()) != null; ) { + for(PyObject item = null; (item = iter.__iternext__()) != null;) { list.append(item); } return list; @@ -215,7 +228,6 @@ // make step a long in case adding the start, stop and step together overflows an int protected static final int sliceLength(int start, int stop, long step) { - //System.err.println("slice: "+start+", "+stop+", "+step); int ret; if(step > 0) { ret = (int)((stop - start + step - 1) / step); @@ -230,20 +242,23 @@ protected int fixindex(int index) { int l = __len__(); - if (index < 0) + if(index < 0) { index += l; - if (index < 0 || index >= l) + } + if(index < 0 || index >= l) { return -1; - //throw Py.IndexError("index out of range"); - else return index; + } else { + return index; + } } public synchronized PyObject __finditem__(int index) { index = fixindex(index); - if (index == -1) + if(index == -1) { return null; - else + } else { return pyget(index); + } } public PyObject __finditem__(PyObject index) { @@ -251,15 +266,14 @@ } final PyObject seq___finditem__(PyObject index) { - if (index instanceof PyInteger) - return __finditem__(((PyInteger)index).getValue()); - else if (index instanceof PySlice) { + if(index instanceof PyInteger || index instanceof PyLong) { + return __finditem__(index.asInt()); + } else if(index instanceof PySlice) { PySlice s = (PySlice)index; return __getslice__(s.start, s.stop, s.step); - } else if (index instanceof PyLong) - return __finditem__(((PyInteger)index.__int__()).getValue()); - else + } else { throw Py.TypeError("sequence subscript must be integer or slice"); + } } public PyObject __getitem__(PyObject index) { @@ -268,87 +282,81 @@ final PyObject seq___getitem__(PyObject index) { PyObject ret = __finditem__(index); - if (ret == null) { - throw Py.IndexError("index out of range: "+index); + if(ret == null) { + throw Py.IndexError("index out of range: " + index); } return ret; } - public boolean isMappingType() throws PyIgnoreMethodTag { return false; } - public boolean isNumberType() throws PyIgnoreMethodTag { return false; } + public boolean isMappingType() throws PyIgnoreMethodTag { + return false; + } - public synchronized PyObject __getslice__(PyObject s_start, - PyObject s_stop, - PyObject s_step) { - return seq___getslice__(s_start,s_stop,s_step); + public boolean isNumberType() throws PyIgnoreMethodTag { + return false; } - final synchronized PyObject seq___getslice__(PyObject s_start, - PyObject s_stop) - { - return seq___getslice__(s_start,s_stop,null); + public synchronized PyObject __getslice__(PyObject start, PyObject stop, PyObject step) { + return seq___getslice__(start, stop, step); } - final synchronized PyObject seq___getslice__(PyObject s_start, - PyObject s_stop, - PyObject s_step) - { - int[] slice = new PySlice(s_start, s_stop, s_step).indices(__len__()); + 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[] slice = new PySlice(start, stop, step).indices(__len__()); return getslice(slice[0], slice[1], slice[2]); } - public synchronized void __setslice__(PyObject s_start, PyObject s_stop, - PyObject s_step, PyObject value) { - seq___setslice__(s_start,s_stop,s_step,value); + public synchronized void __setslice__(PyObject start, + PyObject stop, + PyObject step, + PyObject value) { + seq___setslice__(start, stop, step, value); } - final synchronized void seq___setslice__(PyObject s_start, PyObject s_stop, - PyObject value) - { - seq___setslice__(s_start,s_stop,null,value); + + final synchronized void seq___setslice__(PyObject start, PyObject stop, PyObject value) { + seq___setslice__(start, stop, null, value); } - final synchronized void seq___setslice__(PyObject s_start, PyObject s_stop, - PyObject s_step, PyObject value) - { - int[] slice = new PySlice(s_start, s_stop, s_step).indices(__len__()); + + final synchronized void seq___setslice__(PyObject start, + PyObject stop, + PyObject step, + PyObject value) { + int[] slice = new PySlice(start, stop, step).indices(__len__()); setslice(slice[0], slice[1], slice[2], value); } - public synchronized void __delslice__(PyObject s_start, PyObject s_stop, - PyObject s_step) { - seq___delslice__(s_start,s_stop,s_step); + public synchronized void __delslice__(PyObject start, PyObject stop, PyObject step) { + seq___delslice__(start, stop, step); } - final synchronized void seq___delslice__(PyObject s_start, PyObject s_stop, - PyObject s_step) - { - int[] slice = new PySlice(s_start, s_stop, s_step).indices(__len__()); + final synchronized void seq___delslice__(PyObject start, PyObject stop, PyObject step) { + int[] slice = new PySlice(start, stop, step).indices(__len__()); delRange(slice[0], slice[1], slice[2]); } public synchronized void __setitem__(int index, PyObject value) { int i = fixindex(index); - if (i == -1) - throw Py.IndexError("index out of range: "+i); + if(i == -1) { + throw Py.IndexError("index out of range: " + i); + } set(i, value); } public void __setitem__(PyObject index, PyObject value) { - seq___setitem__(index,value); + seq___setitem__(index, value); } final void seq___setitem__(PyObject index, PyObject value) { - if (index instanceof PyInteger) - __setitem__(((PyInteger)index).getValue(), value); - else { - if (index instanceof PySlice) { - PySlice s = (PySlice)index; - __setslice__(s.start, s.stop, s.step, value); - } else if (index instanceof PyLong) { - __setitem__(((PyInteger)index.__int__()).getValue(), value); - } else { - throw Py.TypeError( - "sequence subscript must be integer or slice"); - } + if(index instanceof PyInteger || index instanceof PyLong) { + __setitem__(index.asInt(), value); + } else if(index instanceof PySlice) { + PySlice s = (PySlice)index; + __setslice__(s.start, s.stop, s.step, value); + } else { + throw Py.TypeError("sequence subscript must be integer or slice"); } } @@ -357,43 +365,35 @@ } final synchronized void seq___delitem__(PyObject index) { - if (index instanceof PyInteger) { - int i = fixindex(((PyInteger)index).getValue()); - if (i == -1) - throw Py.IndexError("index out of range: "+i); + if(index instanceof PyInteger || index instanceof PyLong) { + int i = fixindex(index.asInt()); + if(i == -1) { + throw Py.IndexError("index out of range: " + i); + } del(i); + } else if(index instanceof PySlice) { + PySlice s = (PySlice)index; + __delslice__(s.start, s.stop, s.step); + } else { + throw Py.TypeError("sequence subscript must be integer or slice"); } - else { - if (index instanceof PySlice) { - PySlice s = (PySlice)index; - __delslice__(s.start, s.stop, s.step); - } else if (index instanceof PyLong) { - int i = fixindex(((PyInteger)index.__int__()).getValue()); - if (i == -1) - throw Py.IndexError("index out of range: "+i); - del(i); - } else { - throw Py.TypeError( - "sequence subscript must be integer or slice"); - } - } } public synchronized Object __tojava__(Class c) throws PyIgnoreMethodTag { - if (c.isArray()) { + if(c.isArray()) { Class component = c.getComponentType(); - //System.out.println("getting: "+component); + // System.out.println("getting: "+component); try { int n = __len__(); PyArray array = new PyArray(component, n); - for (int i=0; i<n; i++) { + for(int i = 0; i < n; i++) { PyObject o = pyget(i); array.set(i, o); } - //System.out.println("getting: "+component+", "+array.data); + // System.out.println("getting: "+component+", "+array.data); return array.getArray(); - } catch (Throwable t) { - ;//System.out.println("failed to get: "+component.getName()); + } catch(Throwable t) { + ;// System.out.println("failed to get: "+component.getName()); } } return super.__tojava__(c); @@ -401,27 +401,23 @@ /** * Return sequence-specific error messages suitable for substitution. - * - * {0} is the op name. - * {1} is the left operand type. - * {2} is the right operand type. + * + * {0} is the op name. {1} is the left operand type. {2} is the right operand type. */ protected String unsupportedopMessage(String op, PyObject o2) { - if (op.equals("*")) { + if(op.equals("*")) { return "can''t multiply sequence by non-int of type ''{2}''"; } return null; } - + /** * Return sequence-specific error messages suitable for substitution. - * - * {0} is the op name. - * {1} is the left operand type. - * {2} is the right operand type. + * + * {0} is the op name. {1} is the left operand type. {2} is the right operand type. */ protected String runsupportedopMessage(String op, PyObject o2) { - if (op.equals("*")) { + if(op.equals("*")) { return "can''t multiply sequence by non-int of type ''{1}''"; } return null; Modified: trunk/jython/src/org/python/core/PySequenceList.java =================================================================== --- trunk/jython/src/org/python/core/PySequenceList.java 2008-01-01 21:10:41 UTC (rev 3941) +++ trunk/jython/src/org/python/core/PySequenceList.java 2008-01-01 21:33:03 UTC (rev 3942) @@ -1,7 +1,3 @@ -/* - * Created: Apr 18, 2005 - * By: updikca1 - */ package org.python.core; import java.util.Collection; @@ -9,13 +5,6 @@ import java.util.List; import java.util.ListIterator; - -/** - * @author updikca1 - * - * To change the template for this generated type comment go to - * Window>Preferences>Java>Code Generation>Code and Comments - */ public abstract class PySequenceList extends PySequence implements List { protected PyObjectList list; @@ -28,7 +17,7 @@ super(type); list = new PyObjectList(); } - + protected PySequenceList(PyType type, PyObject[] elements) { super(type); list = new PyObjectList(elements); @@ -36,7 +25,6 @@ /** * Creates an instance directly backed by the array of PyObject elements. - * @param elements */ public PySequenceList(PyObject[] elements) { list = new PyObjectList(elements); @@ -50,87 +38,115 @@ public void add(int index, Object element) { list.add(index, element); } + public boolean add(Object o) { return list.add(o); } + public boolean addAll(int index, Collection c) { return list.addAll(index, c); } + public boolean addAll(Collection c) { return list.addAll(c); } + public void clear() { list.clear(); } + public boolean contains(Object o) { return list.contains(o); } + public boolean containsAll(Collection c) { return list.containsAll(c); } + public Object get(int index) { return list.get(index); } + public int indexOf(Object o) { return list.indexOf(o); } + public boolean isEmpty() { return list.isEmpty(); } + public Iterator iterator() { return list.iterator(); } + public int lastIndexOf(Object o) { return list.lastIndexOf(o); } + public ListIterator listIterator() { return list.listIterator(); } + public ListIterator listIterator(int index) { return list.listIterator(index); } + public void pyadd(int index, PyObject element) { list.pyadd(index, element); } + public PyObject pyget(int index) { return list.pyget(index); } + public PyObject pyset(int index, PyObject element) { return list.pyset(index, element); } + public Object remove(int index) { return list.remove(index); } + public void remove(int start, int stop) { list.remove(start, stop); } + public boolean remove(Object o) { return list.remove(o); } + public boolean removeAll(Collection c) { return list.removeAll(c); } + public boolean retainAll(Collection c) { return list.retainAll(c); } + public Object set(int index, Object element) { return list.set(index, element); } + public int size() { return list.size(); } + public List subList(int fromIndex, int toIndex) { return list.subList(fromIndex, toIndex); } + public Object[] toArray() { return list.toArray(); } + public Object[] toArray(Object[] a) { return list.toArray(a); } + public String toString() { return list.toString(); } + public boolean pyadd(PyObject o) { return list.pyadd(o); } @@ -149,19 +165,10 @@ return list.hashCode(); } -// /** -// * @param list The list to set. -// */ -// public void setList(PyObjectList list) { -// this.list = list; -// } - - /** - * Get the backing array. The array should not be modified. - * To get a copy of the array, see {@link #toArray()}. - * - * @return backing array object - */ + /** + * Get the backing array. The array should not be modified. To get a copy of the array, see + * {@link #toArray()}. + */ public PyObject[] getArray() { return list.getArray(); } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <pj...@us...> - 2008-01-15 05:23:29
|
Revision: 4033 http://jython.svn.sourceforge.net/jython/?rev=4033&view=rev Author: pjenvey Date: 2008-01-14 21:23:27 -0800 (Mon, 14 Jan 2008) Log Message: ----------- match basic ImportError and UnboundLocalError exception messages with CPython fixes #1871739 thanks tristanlk Modified Paths: -------------- trunk/jython/src/org/python/core/PyFrame.java trunk/jython/src/org/python/core/imp.java Modified: trunk/jython/src/org/python/core/PyFrame.java =================================================================== --- trunk/jython/src/org/python/core/PyFrame.java 2008-01-15 01:35:35 UTC (rev 4032) +++ trunk/jython/src/org/python/core/PyFrame.java 2008-01-15 05:23:27 UTC (rev 4033) @@ -25,6 +25,9 @@ // an interface to functions suitable for tracing, e.g. via sys.settrace() public TraceFunction tracefunc; + private static final String UNBOUNDLOCAL_ERROR_MSG = + "local variable '%.200s' referenced before assignment"; + private static final String[] __members__ = { "f_back", "f_code", "f_locals", "f_globals", "f_lineno", "f_builtins", "f_trace" @@ -191,7 +194,7 @@ if (ret != null) return ret; - throw Py.UnboundLocalError("local: '" + index + "'"); + throw Py.UnboundLocalError(String.format(UNBOUNDLOCAL_ERROR_MSG, index)); //return getglobal(index); } @@ -240,7 +243,8 @@ public void dellocal(int index) { if (f_fastlocals != null) { if (f_fastlocals[index] == null) { - throw Py.UnboundLocalError("local: '" + f_code.co_varnames[index] + "'"); + throw Py.UnboundLocalError(String.format(UNBOUNDLOCAL_ERROR_MSG, + f_code.co_varnames[index])); } f_fastlocals[index] = null; } else @@ -254,7 +258,7 @@ f_locals.__delitem__(index); } catch (PyException e) { if (!Py.matchException(e, Py.KeyError)) throw e; - throw Py.UnboundLocalError("local: '" + index + "'"); + throw Py.UnboundLocalError(String.format(UNBOUNDLOCAL_ERROR_MSG, index)); } } @@ -274,7 +278,7 @@ String name; if (index >= f_ncells) name = f_code.co_freevars[index - f_ncells]; else name = f_code.co_cellvars[index]; - throw Py.UnboundLocalError("local: '" + name + "'"); + throw Py.UnboundLocalError(String.format(UNBOUNDLOCAL_ERROR_MSG, name)); } public void setderef(int index, PyObject value) { Modified: trunk/jython/src/org/python/core/imp.java =================================================================== --- trunk/jython/src/org/python/core/imp.java 2008-01-15 01:35:35 UTC (rev 4032) +++ trunk/jython/src/org/python/core/imp.java 2008-01-15 05:23:27 UTC (rev 4033) @@ -583,7 +583,7 @@ StringBuffer parentNameBuffer) { PyObject ret = import_next(null, parentNameBuffer, name, null, null); if (ret == null || ret == Py.None) { - throw Py.ImportError("no module named " + name); + throw Py.ImportError("No module named " + name); } return ret; } @@ -597,7 +597,7 @@ } } if (ret == null || ret == Py.None) { - throw Py.ImportError("no module named " + name); + throw Py.ImportError("No module named " + name); } return ret; } @@ -621,7 +621,7 @@ } mod = import_next(mod, parentNameBuffer, name, fullName, fromlist); if (mod == null || mod == Py.None) { - throw Py.ImportError("no module named " + name); + throw Py.ImportError("No module named " + name); } last_dot = dot + 1; } while (dot != -1); This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |