From: <fwi...@us...> - 2006-04-09 13:28:54
|
Revision: 2710 Author: fwierzbicki Date: 2006-04-09 06:28:44 -0700 (Sun, 09 Apr 2006) ViewCVS: http://svn.sourceforge.net/jython/?rev=2710&view=rev Log Message: ----------- Created src directory. Added Paths: ----------- trunk/jython/src/ trunk/jython/src/com/ trunk/jython/src/org/ Removed Paths: ------------- trunk/jython/com/ trunk/jython/org/ Copied: trunk/jython/src/com (from rev 2707, trunk/jython/com) Copied: trunk/jython/src/org (from rev 2707, trunk/jython/org) This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <fwi...@us...> - 2006-04-09 16:14:26
|
Revision: 2711 Author: fwierzbicki Date: 2006-04-09 09:14:16 -0700 (Sun, 09 Apr 2006) ViewCVS: http://svn.sourceforge.net/jython/?rev=2711&view=rev Log Message: ----------- First pass to get ant working again. Modified Paths: -------------- trunk/jython/Lib/test/javatests/AnonInner.java trunk/jython/build.xml Modified: trunk/jython/Lib/test/javatests/AnonInner.java =================================================================== --- trunk/jython/Lib/test/javatests/AnonInner.java 2006-04-09 13:28:44 UTC (rev 2710) +++ trunk/jython/Lib/test/javatests/AnonInner.java 2006-04-09 16:14:16 UTC (rev 2711) @@ -9,6 +9,11 @@ public int hashCode() { return 2000; } + //XXX: stuck compareTo to make the compiler happier. + // hopefully this doesn't mess up the test. + public int compareTo(Object x) { + return 0; + } }; return d.hashCode(); } Modified: trunk/jython/build.xml =================================================================== --- trunk/jython/build.xml 2006-04-09 13:28:44 UTC (rev 2710) +++ trunk/jython/build.xml 2006-04-09 16:14:16 UTC (rev 2711) @@ -155,11 +155,8 @@ <pathelement path="${java.class.path}" /> </path> - <available property="java2collection.present" classname="java.util.List" /> <available property="threadlocal.present" classname="java.lang.ThreadLocal" /> <available property="secureclassloader.present" classname="java.security.SecureClassLoader" /> - <available property="java2accessible.present" classname="java.lang.reflect.AccessibleObject" /> - <available property="weakref.present" classname="java.lang.ref.WeakReference" /> <available property="servlet.present" classname="javax.servlet.Servlet" classpath="${servlet.jar}" /> <available property="readline.present" classname="org.gnu.readline.Readline" classpath="${readline.jar}" /> <available property="informix.present" classname="com.informix.jdbc.IfxDriver" classpath="${informix.jar}" /> @@ -175,7 +172,7 @@ <!-- init properties for the developer build --> <target name="developer-init" depends="pre-init"> <property name="work.dir" value="${basedir}" /> - <property name="source.dir" value="${basedir}" /> + <property name="source.dir" value="${basedir}/src" /> <property name="python.lib" value="${python.home}/Lib" /> </target> @@ -191,7 +188,7 @@ <property name="work.dir" value="${basedir}/../full_build_${cvs.tag}" /> <property name="cvs.checkout.dir" value="${work.dir}/checkout" /> - <property name="source.dir" value="${cvs.checkout.dir}/jython" /> + <property name="source.dir" value="${cvs.checkout.dir}/jython/src" /> <property name="has.cvs.connection" value="true" /> <property name="python.module" value="python/dist/src/Lib" /> <property name="python.lib" value="${cvs.checkout.dir}/${python.module}" /> @@ -211,10 +208,7 @@ <echo>Build environment for ${ant.project.name}</echo> <echo>(Note: if ${propertyname} is displayed, then the property is not set)</echo> <echo>--- optional libraries ---</echo> - <echo>collections = '${java2collection.present}'</echo> - <echo>weakref = '${weakref.present}'</echo> <echo>threadlocal = '${threadlocal.present}'</echo> - <echo>java2 access = '${java2accessible.present}'</echo> <echo>secureclassloader = '${secureclassloader.present}'</echo> <echo>servlet = '${servlet.present}'</echo> <echo>readline = '${readline.present}'</echo> @@ -355,21 +349,9 @@ deprecation="${deprecation}" nowarn="${nowarn}" > - <include name="org/**" /> <exclude name="org/python/parser/python.java" /> - - <include name="com/ziclix/python/sql/**" if="java2collection.present" /> - <!-- +++ TODO: the following java files could be removed from cvs since we are targeting jdk 1.2 --> - <exclude name="**/CollectionProxy2.java" unless="java2collection.present" /> - <exclude name="**/Java2Accessibility.java" unless="java2accessible.present" /> - <exclude name="**/BytecodeLoader2.java" unless="secureclassloader.present" /> - <exclude name="**/ThreadStateMapping2.java" unless="threadlocal.present" /> - <exclude name="**/InternalTables2.java" unless="weakref.present" /> - <exclude name="**/WeakInternalTables.java" unless="weakref.present" /> - <exclude name="**/AutoInternalTables.java" unless="weakref.present" /> - <exclude name="**/SoftIInternalTables.java" unless="weakref.present" /> - <exclude name="**/_weakref.java" unless="weakref.present" /> <!-- end of java files to be removed from cvs --> + <exclude name="**/PyServlet.java" unless="servlet.present" /> <exclude name="**/ReadlineConsole.java" unless="readline.present" /> <exclude name="**/handler/InformixDataHandler.java" unless="informix.present" /> @@ -383,7 +365,7 @@ <classpath refid="main.classpath" /> </javac> - <javac srcdir="${source.dir}/Lib" + <javac srcdir="${basedir}/Lib" includes="jxxload_help/**" destdir="${output.dir}/" target="${jdk.target.version}" @@ -395,7 +377,7 @@ /> <!-- java files used by tests --> - <javac srcdir="${source.dir}/Lib/test/" + <javac srcdir="${basedir}/Lib/test/" includes="javatests/**" destdir="${output.dir}/" target="${jdk.target.version}" @@ -406,14 +388,14 @@ nowarn="${nowarn}" /> - <copy file="org/python/modules/ucnhash.dat" + <copy file="${source.dir}/org/python/modules/ucnhash.dat" todir="${output.dir}/org/python/modules" preservelastmodified="true" /> <copy todir="${output.dir}/com" preservelastmodified="true"> <fileset dir="${source.dir}/com"> - <include name="**/*.properties" if="java2collection.present" /> + <include name="**/*.properties" /> </fileset> </copy> </target> @@ -435,10 +417,7 @@ <section name="Build-Info"> <attribute name="version" value="${cvs.tag}" /> <attribute name="cvs-build" value="${do.checkout}" /> - <attribute name="collections" value="${java2collection.present}" /> - <attribute name="weakref" value="${weakref.present}" /> <attribute name="threadlocal" value="${threadlocal.present}" /> - <attribute name="java2-accessibility" value="${java2accessible.present}" /> <attribute name="secureclassloader" value="${secureclassloader.present}" /> <attribute name="servlet" value="${servlet.present}" /> <attribute name="readline" value="${readline.present}" /> @@ -467,7 +446,7 @@ </copy> <!-- Create .html files in Doc --> <apply executable="${python.exe}" dir="Doc"> - <env key="PYTHONPATH" path="${source.dir}/Misc/htgen" /> + <env key="PYTHONPATH" path="${basedir}/Misc/htgen" /> <arg line="${ht2html.dir}/ht2html.py" /> <arg line="-s JyLocalGenerator" /> <fileset dir="${dist.dir}/Doc"> @@ -499,9 +478,9 @@ <!-- copy for full distribution --> <target name="copy-full" if="full-build"> <!-- Misc files --> - <echo>copy misc files from ${source.dir}</echo> + <echo>copy misc files from ${basedir}</echo> <copy todir="${dist.dir}" preservelastmodified="true"> - <fileset dir="${source.dir}" + <fileset dir="${basedir}" includes="ACKNOWLEDGMENTS, build.xml, build.Lib.include.properties, NEWS, LICENSE.txt, README.txt, registry" /> </copy> @@ -512,24 +491,23 @@ <copy file="${python.home}/LICENSE.txt" tofile="${dist.dir}/LICENSE_CPython.txt" preservelastmodified="true" /> <!-- sources: todir has to correspond with installer/**/JarInstaller.java --> - <echo>copy sources from ${source.dir}</echo> + <echo>copy sources from ${basedir}</echo> <copy todir="${dist.dir}/src/java" preservelastmodified="true"> - <fileset dir="${source.dir}"> - <include name="org/**/*.java" /> - <include name="com/**/*.java" /> - <include name="com/**/*.properties" /> + <fileset dir="${basedir}"> + <include name="src/**/*.java" /> + <include name="src/com/**/*.properties" /> <include name="Lib/jxxload_help/*.java" /> <include name="Lib/test/javatests/*.java" /> - <include name="org/**/ucnhash.dat" /> - <include name="org/python/parser/build.xml" /> - <exclude name="org/python/parser/python.java" /> + <include name="src/org/**/ucnhash.dat" /> + <include name="src/org/python/parser/build.xml" /> + <exclude name="src/org/python/parser/python.java" /> </fileset> </copy> <!-- The demo files --> - <echo>copy the demo files from ${source.dir}/Demo</echo> + <echo>copy the demo files from ${basedir}/Demo</echo> <copy todir="${dist.dir}/Demo" preservelastmodified="true"> - <fileset dir="${source.dir}/Demo"> + <fileset dir="${basedir}/Demo"> <include name="**/*.java" /> <include name="**/*.html" /> <include name="**/*.py" /> @@ -546,9 +524,9 @@ <!-- copy for distribution --> <target name="copy-dist" depends="jar, doc, javadoc, copy-full"> <!-- Tools: jythonc and freeze --> - <echo>copy Tools from ${source.dir}/Tools</echo> + <echo>copy Tools from ${basedir}/Tools</echo> <copy todir="${dist.dir}" preservelastmodified="true"> - <fileset dir="${source.dir}" includes="Tools/**/*.py" /> + <fileset dir="${basedir}" includes="Tools/**/*.py" /> </copy> <!-- Copy the CPython standard library files --> @@ -556,15 +534,15 @@ <copy todir="${dist.dir}/Lib" preservelastmodified="true"> <fileset dir="${python.lib}" excludes="**/*.pyc, **/*.pyo"> <patternset> - <includesfile name="${source.dir}/build.Lib.include.properties" /> + <includesfile name="${basedir}/build.Lib.include.properties" /> </patternset> </fileset> </copy> <!-- The jython .py modules: important to overwrite the above CPython .py files --> - <echo>copy the jython *.py modules from ${source.dir}/Lib</echo> + <echo>copy the jython *.py modules from ${basedir}/Lib</echo> <copy todir="${dist.dir}/Lib" preservelastmodified="true" overwrite="true"> - <fileset dir="${source.dir}/Lib" excludes="**/*.class"/> + <fileset dir="${basedir}/Lib" excludes="**/*.class"/> </copy> </target> @@ -572,7 +550,7 @@ <!-- wrap the build into the installer --> <target name="install" depends="copy-dist"> <fail unless="cvs.tag" message="no cvs.tag specified" /> - <property name="install.src.dir" value="${source.dir}/../installer/src/java" /> + <property name="install.src.dir" value="${basedir}/../installer/src/java" /> <echo>compiling installer from ${install.src.dir}</echo> <javac srcdir="${install.src.dir}" includes="org/**" @@ -608,10 +586,7 @@ <section name="Build-Info"> <attribute name="cvs-build" value="${do.checkout}" /> <attribute name="cpython-version" value="${python.cvs.tag}" /> - <attribute name="collections" value="${java2collection.present}" /> - <attribute name="weakref" value="${weakref.present}" /> <attribute name="threadlocal" value="${threadlocal.present}" /> - <attribute name="java2-accessibility" value="${java2accessible.present}" /> <attribute name="secureclassloader" value="${secureclassloader.present}" /> <attribute name="servlet" value="${servlet.present}" /> <attribute name="readline" value="${readline.present}" /> This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <fwi...@us...> - 2006-05-17 20:55:09
|
Revision: 2732 Author: fwierzbicki Date: 2006-05-17 13:55:02 -0700 (Wed, 17 May 2006) ViewCVS: http://svn.sourceforge.net/jython/?rev=2732&view=rev Log Message: ----------- Replaced a couple of long deprecated String methods. Modified Paths: -------------- trunk/jython/src/org/python/core/PyString.java trunk/jython/src/org/python/modules/SHA1.java Property Changed: ---------------- trunk/jython/ Property changes on: trunk/jython ___________________________________________________________________ Name: svn:ignore - .classpath .project *.ipr *.iws *.iml build dist ant.properties bin cachedir + .classpath .project *.ipr *.iws *.iml build dist ant.properties bin cachedir .settings Modified: trunk/jython/src/org/python/core/PyString.java =================================================================== --- trunk/jython/src/org/python/core/PyString.java 2006-05-15 17:48:20 UTC (rev 2731) +++ trunk/jython/src/org/python/core/PyString.java 2006-05-17 20:55:02 UTC (rev 2732) @@ -3039,9 +3039,7 @@ } private byte[] getBytes() { - byte[] buf = new byte[string.length()]; - string.getBytes(0, string.length(), buf, 0); - return buf; + return string.getBytes(); } public Object __tojava__(Class c) { Modified: trunk/jython/src/org/python/modules/SHA1.java =================================================================== --- trunk/jython/src/org/python/modules/SHA1.java 2006-05-15 17:48:20 UTC (rev 2731) +++ trunk/jython/src/org/python/modules/SHA1.java 2006-05-17 20:55:02 UTC (rev 2732) @@ -496,7 +496,7 @@ public String digest() { if (digestBits == null) digestBits = engineDigest(); - return new String(digestBits, 0, 0, digestBits.length); + return new String(digestBits); } // XXX should become PyObject and use Py.idstr? This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <otm...@us...> - 2006-10-13 21:59:04
|
Revision: 2950 http://svn.sourceforge.net/jython/?rev=2950&view=rev Author: otmarhumbel Date: 2006-10-13 14:58:52 -0700 (Fri, 13 Oct 2006) Log Message: ----------- bugfix 1565644: improved version handling for snapshot builds Modified Paths: -------------- trunk/jython/build.xml trunk/jython/src/org/python/core/PySystemState.java Modified: trunk/jython/build.xml =================================================================== --- trunk/jython/build.xml 2006-10-09 01:35:44 UTC (rev 2949) +++ trunk/jython/build.xml 2006-10-13 21:58:52 UTC (rev 2950) @@ -67,9 +67,10 @@ - jdk.target.version (target: pre-init) 4. if new CPython .py files should be distributed, add them to build.Lib.include.properties 5. adjust the public static String version in PySystemState.java - 6. check in all the changes - 7. apply the new tag to the jython svn (all projects) - 8. call target 'full-build' + 6. adjust the version strings in target 'version' of this build.xml + 7. check in all the changes + 8. apply the new tag to the jython svn (all projects) + 9. call target 'full-build' @@ -110,6 +111,10 @@ #svn.tag=Release_2_2alpha2 svn.tag=HEAD +# - the revision; defaults to svn.tag; only needed for full-build +# (uncomment and indicate the correct revision to do a snapshot build) +#svn.revision=2948 + # - the directory containing libsvnjavahl-1.dll (on windows) and svnjavahl.jar; only needed for full-build # how to get these: # - download http://subversion.tigris.org/files/documents/15/31073/svn-win32-1.3.1_javahl.zip (or newer) @@ -209,6 +214,9 @@ <property name="svn.tag" value="HEAD" /> <property name="python.cvs.tag" value="r223" /> + <!-- revision handling --> + <property name="svn.revison" value="${svn.tag}" /> + <property name="work.dir" value="${basedir}/../full_build_${svn.tag}" /> <property name="svn.checkout.dir" value="${work.dir}/checkout" /> <property name="jython.base.dir" value="${svn.checkout.dir}/jython" /> @@ -220,6 +228,11 @@ <condition property="do.checkout" value="true"> <istrue value="${has.repositories.connection}" /> </condition> + <condition property="do.snapshot.build" value="true"> + <not> + <equals arg1="${svn.revison}" arg2="${svn.tag}" /> + </not> + </condition> <!-- classpath for svn ant task --> <path id="svn.classpath"> @@ -230,7 +243,6 @@ </path> <!-- taskdef for svn ant task --> <taskdef name="svn" classname="org.tigris.subversion.svnant.SvnTask" classpathref="svn.classpath" /> - </target> @@ -279,6 +291,8 @@ <echo>svn.checkout.dir = '${svn.checkout.dir}'</echo> <echo>javahl.dir = '${javahl.dir}'</echo> <echo>svnant.jar.dir = '${svnant.jar.dir}'</echo> + <echo>svn.revison = '${svn.revison}'</echo> + <echo>do.snapshot.build = '${do.snapshot.build}'</echo> <echo>do.checkout = '${do.checkout}'</echo> </target> @@ -344,8 +358,8 @@ </condition> <property name="svn.main.dir" value="tags/${svn.tag}" /> <svn javahl="${javahl.dir}" > - <checkout url="https://svn.sourceforge.net/svnroot/jython/${svn.main.dir}/jython" destPath="${svn.checkout.dir}/jython" /> - <checkout url="https://svn.sourceforge.net/svnroot/jython/${svn.main.dir}/installer" destPath="${svn.checkout.dir}/installer" /> + <checkout url="https://svn.sourceforge.net/svnroot/jython/${svn.main.dir}/jython" revision="${svn.revison}" destPath="${svn.checkout.dir}/jython" /> + <checkout url="https://svn.sourceforge.net/svnroot/jython/${svn.main.dir}/installer" revision="${svn.revison}" destPath="${svn.checkout.dir}/installer" /> </svn> <!-- cpython --> @@ -359,6 +373,15 @@ <cvs command="${python.checkout.command} ${python.module}" dest="${svn.checkout.dir}" /> </target> + <!-- change the version string, if so defined: used for snapshot builds --> + <!-- the following replacements have to be updated if the version strings in PySystemState.java change --> + <target name="version" depends="checkout" if="do.snapshot.build" > + <property name="replace.value.version" value='version = "2.2a${svn.revison}"' /> + <replace file="${source.dir}/org/python/core/PySystemState.java" token='version = "2.2a1"' value="${replace.value.version}" /> + <replace file="${source.dir}/org/python/core/PySystemState.java" token="PY_RELEASE_LEVEL = 0x0A" value="PY_RELEASE_LEVEL = 0xAA" /> + <property name="replace.value.serial" value="PY_RELEASE_SERIAL = ${svn.revison}" /> + <replace file="${source.dir}/org/python/core/PySystemState.java" token="PY_RELEASE_SERIAL = 1" value="${replace.value.serial}" /> + </target> <!-- separate build.xml for parser grammar --> <!-- we use settings as in developer-build - at the moment all properties will already be set if we do a full build --> @@ -369,7 +392,7 @@ <!-- compile java sources --> - <target name="compile" depends="checkout, parser"> + <target name="compile" depends="version, parser"> <javac srcdir="${source.dir}/" destdir="${output.dir}/" target="${jdk.target.version}" @@ -443,7 +466,7 @@ <attribute name="Built-By" value="${user.name}" /> <!-- info section. ATTN: no blanks, no '.' in the names --> <section name="Build-Info"> - <attribute name="version" value="${svn.tag}" /> + <attribute name="version" value="${svn.revison}" /> <attribute name="svn-build" value="${do.checkout}" /> <attribute name="threadlocal" value="${threadlocal.present}" /> <attribute name="secureclassloader" value="${secureclassloader.present}" /> @@ -603,13 +626,13 @@ <fileset dir="${install.src.dir}" includes="**/*.png" excludes="bin/**" /> </copy> <echo>building installer .jar file</echo> - <jar destfile="${work.dir}/jython_${svn.tag}.jar" basedir="${dist.dir}" update="true"> + <jar destfile="${work.dir}/jython_${svn.revison}.jar" basedir="${dist.dir}" update="true"> <manifest> <attribute name="Main-Class" value="org.python.util.install.Installation" /> <attribute name="Built-By" value="${user.name}" /> <!-- section for the install program --> <section name="Jython"> - <attribute name="version" value="${svn.tag}" /> + <attribute name="version" value="${svn.revison}" /> <attribute name="exclude-dirs" value="org;META-INF" /> </section> <!-- info section. ATTN: no blanks, no '.' in the names --> Modified: trunk/jython/src/org/python/core/PySystemState.java =================================================================== --- trunk/jython/src/org/python/core/PySystemState.java 2006-10-09 01:35:44 UTC (rev 2949) +++ trunk/jython/src/org/python/core/PySystemState.java 2006-10-13 21:58:52 UTC (rev 2950) @@ -39,13 +39,18 @@ /** * The current version of Jython. + * <p> + * Usually updated by hand.<br> + * Replaced by ant when doing a snapshot build. + * <p> + * This also applies for the <code>PY_*</code> integer values below */ public static String version = "2.2a1"; private static int PY_MAJOR_VERSION = 2; private static int PY_MINOR_VERSION = 2; private static int PY_MICRO_VERSION = 0; - private static int PY_RELEASE_LEVEL = 0xA; + private static int PY_RELEASE_LEVEL = 0x0A; private static int PY_RELEASE_SERIAL = 1; public static int hexversion = ((PY_MAJOR_VERSION << 24) | @@ -503,6 +508,8 @@ s = "candidate"; else if (PY_RELEASE_LEVEL == 0x0F) s = "final"; + else if (PY_RELEASE_LEVEL == 0xAA) + s = "snapshot"; version_info = new PyTuple(new PyObject[] { Py.newInteger(PY_MAJOR_VERSION), Py.newInteger(PY_MINOR_VERSION), This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <ped...@us...> - 2006-10-16 00:50:38
|
Revision: 2958 http://svn.sourceforge.net/jython/?rev=2958&view=rev Author: pedronis Date: 2006-10-15 17:50:16 -0700 (Sun, 15 Oct 2006) Log Message: ----------- - tweak dict.get to not consider an overriden __getitem__ (we should use dict___finditem__ instead of __finditem__ much more, we are not consistent enough to make a point of being different from cpython here) - incorporate the up-to-date result from the templates, we should try not to have any manual tweaks. I haven't checked if it is the case for all .expose too. I did for the .derived. - changed PyString/Unicode/Tuple to match the adaptation in the .expose files. - disable a test exploding with a null-pointer exception in test_descr now we finish test_descr without exploding, although with quite a bit of failure. corresponding changes should be done on the 2.3 branch too. Modified Paths: -------------- trunk/jython/Lib/test/test_descr.py trunk/jython/src/org/python/core/PyBaseString.java trunk/jython/src/org/python/core/PyClassMethodDerived.java trunk/jython/src/org/python/core/PyComplexDerived.java trunk/jython/src/org/python/core/PyDictionary.java trunk/jython/src/org/python/core/PyDictionaryDerived.java trunk/jython/src/org/python/core/PyFileDerived.java trunk/jython/src/org/python/core/PyFloatDerived.java trunk/jython/src/org/python/core/PyIntegerDerived.java trunk/jython/src/org/python/core/PyListDerived.java trunk/jython/src/org/python/core/PyLongDerived.java trunk/jython/src/org/python/core/PyObjectDerived.java trunk/jython/src/org/python/core/PyPropertyDerived.java trunk/jython/src/org/python/core/PyString.java trunk/jython/src/org/python/core/PyStringDerived.java trunk/jython/src/org/python/core/PySuperDerived.java trunk/jython/src/org/python/core/PyTuple.java trunk/jython/src/org/python/core/PyTupleDerived.java trunk/jython/src/org/python/core/PyTypeDerived.java trunk/jython/src/org/python/core/PyUnicode.java trunk/jython/src/org/python/core/PyUnicodeDerived.java Modified: trunk/jython/Lib/test/test_descr.py =================================================================== --- trunk/jython/Lib/test/test_descr.py 2006-10-16 00:43:44 UTC (rev 2957) +++ trunk/jython/Lib/test/test_descr.py 2006-10-16 00:50:16 UTC (rev 2958) @@ -3927,7 +3927,7 @@ testrmul, testipow, test_mutable_bases, - test_mutable_bases_with_failing_mro, + #test_mutable_bases_with_failing_mro, test_mutable_bases_catch_mro_conflict, mutable_names, subclass_right_op, Modified: trunk/jython/src/org/python/core/PyBaseString.java =================================================================== --- trunk/jython/src/org/python/core/PyBaseString.java 2006-10-16 00:43:44 UTC (rev 2957) +++ trunk/jython/src/org/python/core/PyBaseString.java 2006-10-16 00:50:16 UTC (rev 2958) @@ -5,8 +5,17 @@ */ public abstract class PyBaseString extends PySequence { - public static final String exposed_name="unicode"; - + //~ BEGIN GENERATED REGION -- DO NOT EDIT SEE gexpose.py + /* type info */ + + public static final String exposed_name="basestring"; + + public static final Class exposed_base=PyObject.class; + + public static void typeSetup(PyObject dict,PyType.Newstyle marker) { + } + //~ END GENERATED REGION -- DO NOT EDIT SEE gexpose.py + public PyBaseString() { super(); } Modified: trunk/jython/src/org/python/core/PyClassMethodDerived.java =================================================================== --- trunk/jython/src/org/python/core/PyClassMethodDerived.java 2006-10-16 00:43:44 UTC (rev 2957) +++ trunk/jython/src/org/python/core/PyClassMethodDerived.java 2006-10-16 00:50:16 UTC (rev 2958) @@ -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__"); @@ -77,18 +65,6 @@ 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__"); @@ -157,6 +133,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__"); @@ -669,6 +653,18 @@ return super.__ixor__(other); } + 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 PyInteger||res instanceof PyLong) + return(PyObject)res; + throw Py.TypeError("__int__"+" should return an integer"); + } + return super.__int__(); + } + public String toString() { PyType self_type=getType(); PyObject impl=self_type.lookup("__repr__"); @@ -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__"); @@ -790,6 +800,20 @@ super.__setitem__(key,value); } + public PyObject __getslice__(PyObject start,PyObject stop,PyObject step) { // ??? + PyType self_type=getType(); + PyObject impl=self_type.lookup("__getslice__"); + if (impl!=null) + try { + return impl.__get__(this,self_type).__call__(start,stop); + } catch (PyException exc) { + if (Py.matchException(exc,Py.LookupError)) + return null; + throw exc; + } + return super.__getslice__(start,stop,step); + } + public void __delitem__(PyObject key) { // ??? PyType self_type=getType(); PyObject impl=self_type.lookup("__delitem__"); Modified: trunk/jython/src/org/python/core/PyComplexDerived.java =================================================================== --- trunk/jython/src/org/python/core/PyComplexDerived.java 2006-10-16 00:43:44 UTC (rev 2957) +++ trunk/jython/src/org/python/core/PyComplexDerived.java 2006-10-16 00:50:16 UTC (rev 2958) @@ -12,8 +12,8 @@ return dict; } - public PyComplexDerived(PyType subtype, double real, double imaginary) { - super(subtype, real, imaginary); + public PyComplexDerived(PyType subtype,double real,double imaginary) { + super(subtype,real,imaginary); dict=subtype.instDict(); } @@ -65,18 +65,6 @@ 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__"); @@ -145,6 +133,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__"); @@ -657,6 +653,18 @@ return super.__ixor__(other); } + 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 PyInteger||res instanceof PyLong) + return(PyObject)res; + throw Py.TypeError("__int__"+" should return an integer"); + } + return super.__int__(); + } + public String toString() { PyType self_type=getType(); PyObject impl=self_type.lookup("__repr__"); @@ -683,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__"); @@ -778,6 +800,20 @@ super.__setitem__(key,value); } + public PyObject __getslice__(PyObject start,PyObject stop,PyObject step) { // ??? + PyType self_type=getType(); + PyObject impl=self_type.lookup("__getslice__"); + if (impl!=null) + try { + return impl.__get__(this,self_type).__call__(start,stop); + } catch (PyException exc) { + if (Py.matchException(exc,Py.LookupError)) + return null; + throw exc; + } + return super.__getslice__(start,stop,step); + } + public void __delitem__(PyObject key) { // ??? PyType self_type=getType(); PyObject impl=self_type.lookup("__delitem__"); Modified: trunk/jython/src/org/python/core/PyDictionary.java =================================================================== --- trunk/jython/src/org/python/core/PyDictionary.java 2006-10-16 00:43:44 UTC (rev 2957) +++ trunk/jython/src/org/python/core/PyDictionary.java 2006-10-16 00:50:16 UTC (rev 2958) @@ -1174,7 +1174,7 @@ } final PyObject dict_get(PyObject key, PyObject default_object) { - PyObject o = __finditem__(key); + PyObject o = dict___finditem__(key); if (o == null) return default_object; else Modified: trunk/jython/src/org/python/core/PyDictionaryDerived.java =================================================================== --- trunk/jython/src/org/python/core/PyDictionaryDerived.java 2006-10-16 00:43:44 UTC (rev 2957) +++ trunk/jython/src/org/python/core/PyDictionaryDerived.java 2006-10-16 00:50:16 UTC (rev 2958) @@ -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__"); @@ -77,18 +65,6 @@ 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__"); @@ -157,6 +133,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__"); @@ -669,6 +653,18 @@ return super.__ixor__(other); } + 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 PyInteger||res instanceof PyLong) + return(PyObject)res; + throw Py.TypeError("__int__"+" should return an integer"); + } + return super.__int__(); + } + public String toString() { PyType self_type=getType(); PyObject impl=self_type.lookup("__repr__"); @@ -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__"); @@ -790,21 +800,6 @@ super.__setitem__(key,value); } - public PyObject __getitem__(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.__getitem__(key); - } - public PyObject __getslice__(PyObject start,PyObject stop,PyObject step) { // ??? PyType self_type=getType(); PyObject impl=self_type.lookup("__getslice__"); Modified: trunk/jython/src/org/python/core/PyFileDerived.java =================================================================== --- trunk/jython/src/org/python/core/PyFileDerived.java 2006-10-16 00:43:44 UTC (rev 2957) +++ trunk/jython/src/org/python/core/PyFileDerived.java 2006-10-16 00:50:16 UTC (rev 2958) @@ -65,18 +65,6 @@ 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 PyInteger) - return(PyInteger)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__"); @@ -145,6 +133,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__"); @@ -657,6 +653,18 @@ return super.__ixor__(other); } + 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 PyInteger||res instanceof PyLong) + return(PyObject)res; + throw Py.TypeError("__int__"+" should return an integer"); + } + return super.__int__(); + } + public String toString() { PyType self_type=getType(); PyObject impl=self_type.lookup("__repr__"); @@ -683,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__"); @@ -778,6 +800,20 @@ super.__setitem__(key,value); } + public PyObject __getslice__(PyObject start,PyObject stop,PyObject step) { // ??? + PyType self_type=getType(); + PyObject impl=self_type.lookup("__getslice__"); + if (impl!=null) + try { + return impl.__get__(this,self_type).__call__(start,stop); + } catch (PyException exc) { + if (Py.matchException(exc,Py.LookupError)) + return null; + throw exc; + } + return super.__getslice__(start,stop,step); + } + public void __delitem__(PyObject key) { // ??? PyType self_type=getType(); PyObject impl=self_type.lookup("__delitem__"); Modified: trunk/jython/src/org/python/core/PyFloatDerived.java =================================================================== --- trunk/jython/src/org/python/core/PyFloatDerived.java 2006-10-16 00:43:44 UTC (rev 2957) +++ trunk/jython/src/org/python/core/PyFloatDerived.java 2006-10-16 00:50:16 UTC (rev 2958) @@ -12,9 +12,8 @@ return dict; } - //XXX: hand modified to pass v into super - public PyFloatDerived(PyType subtype, double v) { - super(subtype, v); + public PyFloatDerived(PyType subtype,double v) { + super(subtype,v); dict=subtype.instDict(); } @@ -66,18 +65,6 @@ 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__"); @@ -146,6 +133,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__"); @@ -658,6 +653,18 @@ return super.__ixor__(other); } + 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 PyInteger||res instanceof PyLong) + return(PyObject)res; + throw Py.TypeError("__int__"+" should return an integer"); + } + return super.__int__(); + } + public String toString() { PyType self_type=getType(); PyObject impl=self_type.lookup("__repr__"); @@ -684,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__"); @@ -779,6 +800,20 @@ super.__setitem__(key,value); } + public PyObject __getslice__(PyObject start,PyObject stop,PyObject step) { // ??? + PyType self_type=getType(); + PyObject impl=self_type.lookup("__getslice__"); + if (impl!=null) + try { + return impl.__get__(this,self_type).__call__(start,stop); + } catch (PyException exc) { + if (Py.matchException(exc,Py.LookupError)) + return null; + throw exc; + } + return super.__getslice__(start,stop,step); + } + public void __delitem__(PyObject key) { // ??? PyType self_type=getType(); PyObject impl=self_type.lookup("__delitem__"); Modified: trunk/jython/src/org/python/core/PyIntegerDerived.java =================================================================== --- trunk/jython/src/org/python/core/PyIntegerDerived.java 2006-10-16 00:43:44 UTC (rev 2957) +++ trunk/jython/src/org/python/core/PyIntegerDerived.java 2006-10-16 00:50:16 UTC (rev 2958) @@ -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__"); @@ -77,18 +65,6 @@ 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__"); @@ -162,12 +138,7 @@ PyObject impl=self_type.lookup("__reduce__"); if (impl!=null) return impl.__get__(this,self_type).__call__(); - return new PyTuple(new PyObject[]{ - getType(), - new PyTuple(new PyObject[]{ - new PyString("x") - }) - }); + return super.__reduce__(); } public PyObject __add__(PyObject other) { @@ -682,6 +653,18 @@ return super.__ixor__(other); } + 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 PyInteger||res instanceof PyLong) + return(PyObject)res; + throw Py.TypeError("__int__"+" should return an integer"); + } + return super.__int__(); + } + public String toString() { PyType self_type=getType(); PyObject impl=self_type.lookup("__repr__"); @@ -708,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__"); @@ -803,21 +800,6 @@ super.__setitem__(key,value); } - public PyObject __getitem__(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.__getitem__(key); - } - public PyObject __getslice__(PyObject start,PyObject stop,PyObject step) { // ??? PyType self_type=getType(); PyObject impl=self_type.lookup("__getslice__"); Modified: trunk/jython/src/org/python/core/PyListDerived.java =================================================================== --- trunk/jython/src/org/python/core/PyListDerived.java 2006-10-16 00:43:44 UTC (rev 2957) +++ trunk/jython/src/org/python/core/PyListDerived.java 2006-10-16 00:50:16 UTC (rev 2958) @@ -65,18 +65,6 @@ 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__"); @@ -665,6 +653,18 @@ return super.__ixor__(other); } + 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 PyInteger||res instanceof PyLong) + return(PyObject)res; + throw Py.TypeError("__int__"+" should return an integer"); + } + return super.__int__(); + } + public String toString() { PyType self_type=getType(); PyObject impl=self_type.lookup("__repr__"); @@ -800,21 +800,6 @@ super.__setitem__(key,value); } - public PyObject __getitem__(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.__getitem__(key); - } - public PyObject __getslice__(PyObject start,PyObject stop,PyObject step) { // ??? PyType self_type=getType(); PyObject impl=self_type.lookup("__getslice__"); Modified: trunk/jython/src/org/python/core/PyLongDerived.java =================================================================== --- trunk/jython/src/org/python/core/PyLongDerived.java 2006-10-16 00:43:44 UTC (rev 2957) +++ trunk/jython/src/org/python/core/PyLongDerived.java 2006-10-16 00:50:16 UTC (rev 2958) @@ -12,9 +12,8 @@ return dict; } - //XXX: hand modified to pass v into super - public PyLongDerived(PyType subtype, java.math.BigInteger v) { - super(subtype, v); + public PyLongDerived(PyType subtype,java.math.BigInteger v) { + super(subtype,v); dict=subtype.instDict(); } @@ -66,18 +65,6 @@ 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__"); @@ -146,6 +133,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__"); @@ -658,6 +653,18 @@ return super.__ixor__(other); } + 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 PyInteger||res instanceof PyLong) + return(PyObject)res; + throw Py.TypeError("__int__"+" should return an integer"); + } + return super.__int__(); + } + public String toString() { PyType self_type=getType(); PyObject impl=self_type.lookup("__repr__"); @@ -684,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__"); @@ -779,6 +800,20 @@ super.__setitem__(key,value); } + public PyObject __getslice__(PyObject start,PyObject stop,PyObject step) { // ??? + PyType self_type=getType(); + PyObject impl=self_type.lookup("__getslice__"); + if (impl!=null) + try { + return impl.__get__(this,self_type).__call__(start,stop); + } catch (PyException exc) { + if (Py.matchException(exc,Py.LookupError)) + return null; + throw exc; + } + return super.__getslice__(start,stop,step); + } + public void __delitem__(PyObject key) { // ??? PyType self_type=getType(); PyObject impl=self_type.lookup("__delitem__"); Modified: trunk/jython/src/org/python/core/PyObjectDerived.java =================================================================== --- trunk/jython/src/org/python/core/PyObjectDerived.java 2006-10-16 00:43:44 UTC (rev 2957) +++ trunk/jython/src/org/python/core/PyObjectDerived.java 2006-10-16 00:50:16 UTC (rev 2958) @@ -65,18 +65,6 @@ 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__"); @@ -665,6 +653,18 @@ return super.__ixor__(other); } + 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 PyInteger||res instanceof PyLong) + return(PyObject)res; + throw Py.TypeError("__int__"+" should return an integer"); + } + return super.__int__(); + } + public String toString() { PyType self_type=getType(); PyObject impl=self_type.lookup("__repr__"); @@ -800,21 +800,6 @@ super.__setitem__(key,value); } - public PyObject __getitem__(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.__getitem__(key); - } - public PyObject __getslice__(PyObject start,PyObject stop,PyObject step) { // ??? PyType self_type=getType(); PyObject impl=self_type.lookup("__getslice__"); Modified: trunk/jython/src/org/python/core/PyPropertyDerived.java =================================================================== --- trunk/jython/src/org/python/core/PyPropertyDerived.java 2006-10-16 00:43:44 UTC (rev 2957) +++ trunk/jython/src/org/python/core/PyPropertyDerived.java 2006-10-16 00:50:16 UTC (rev 2958) @@ -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__"); @@ -77,18 +65,6 @@ 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__"); @@ -157,6 +133,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__"); @@ -669,6 +653,18 @@ return super.__ixor__(other); } + 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 PyInteger||res instanceof PyLong) + return(PyObject)res; + throw Py.TypeError("__int__"+" should return an integer"); + } + return super.__int__(); + } + public String toString() { PyType self_type=getType(); PyObject impl=self_type.lookup("__repr__"); @@ -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__"); @@ -790,6 +800,20 @@ super.__setitem__(key,value); } + public PyObject __getslice__(PyObject start,PyObject stop,PyObject step) { // ??? + PyType self_type=getType(); + PyObject impl=self_type.lookup("__getslice__"); + if (impl!=null) + try { + return impl.__get__(this,self_type).__call__(start,stop); + } catch (PyException exc) { + if (Py.matchException(exc,Py.LookupError)) + return null; + throw exc; + } + return super.__getslice__(start,stop,step); + } + public void __delitem__(PyObject key) { // ??? PyType self_type=getType(); PyObject impl=self_type.lookup("__delitem__"); Modified: trunk/jython/src/org/python/core/PyString.java =================================================================== --- trunk/jython/src/org/python/core/PyString.java 2006-10-16 00:43:44 UTC (rev 2957) +++ trunk/jython/src/org/python/core/PyString.java 2006-10-16 00:50:16 UTC (rev 2958) @@ -80,7 +80,7 @@ } dict.__setitem__("__eq__",new PyMethodDescr("__eq__",PyString.class,1,1,new exposed___eq__(null,null))); - class exposed___contains__ extends PyBuiltinFunctionNarrow { + class exposed___getitem__ extends PyBuiltinFunctionNarrow { private PyString self; @@ -88,27 +88,35 @@ return self; } - exposed___contains__(PyString self,PyBuiltinFunction.Info info) { + exposed___getitem__(PyString self,PyBuiltinFunction.Info info) { super(info); this.self=self; } public PyBuiltinFunction makeBound(PyObject self) { - return new exposed___contains__((PyString)self,info); + return new exposed___getitem__((PyString)self,info); } public PyObject __call__(PyObject arg0) { - return Py.newBoolean(self.str___contains__(arg0)); + PyObject ret=self.seq___finditem__(arg0); + if (ret==null) { + throw Py.IndexError("index out of range: "+arg0); + } + return ret; } public PyObject inst_call(PyObject gself,PyObject arg0) { PyString self=(PyString)gself; - return Py.newBoolean(self.str___contains__(arg0)); + PyObject ret=self.seq___finditem__(arg0); + if (ret==null) { + throw Py.IndexError("index out of range: "+arg0); + } + return ret; } } - dict.__setitem__("__contains__",new PyMethodDescr("__contains__",PyString.class,1,1,new exposed___contains__(null,null))); - class exposed___len__ extends PyBuiltinFunctionNarrow { + dict.__setitem__("__getitem__",new PyMethodDescr("__getitem__",PyString.class,1,1,new exposed___getitem__(null,null))); + class exposed___getslice__ extends PyBuiltinFunctionNarrow { private PyString self; @@ -116,55 +124,36 @@ return self; } - exposed___len__(PyString self,PyBuiltinFunction.Info info) { + exposed___getslice__(PyString self,PyBuiltinFunction.Info info) { super(info); this.self=self; } public PyBuiltinFunction makeBound(PyObject self) { - return new exposed___len__((PyString)self,info); + return new exposed___getslice__((PyString)self,info); } - public PyObject __call__() { - return Py.newInteger(self.str___len__()); + public PyObject __call__(PyObject arg0,PyObject arg1,PyObject arg2) { + return self.seq___getslice__(arg0,arg1,arg2); } - public PyObject inst_call(PyObject gself) { + public PyObject inst_call(PyObject gself,PyObject arg0,PyObject arg1,PyObject arg2) { PyString self=(PyString)gself; - return Py.newInteger(self.str___len__()); + return self.seq___getslice__(arg0,arg1,arg2); } - } - dict.__setitem__("__len__",new PyMethodDescr("__len__",PyString.class,0,0,new exposed___len__(null,null))); - class exposed___add__ extends PyBuiltinFunctionNarrow { - - private PyString self; - - public PyObject getSelf() { - return self; + public PyObject __call__(PyObject arg0,PyObject arg1) { + return self.seq___getslice__(arg0,arg1); } - exposed___add__(PyString self,PyBuiltinFunction.Info info) { - super(info); - this.self=self; - } - - public PyBuiltinFunction makeBound(PyObject self) { - return new exposed___add__((PyString)self,info); - } - - public PyObject __call__(PyObject arg0) { - return self.str___add__(arg0); - } - - public PyObject inst_call(PyObject gself,PyObject arg0) { + public PyObject inst_call(PyObject gself,PyObject arg0,PyObject arg1) { PyString self=(PyString)gself; - return self.str___add__(arg0); + return self.seq___getslice__(arg0,arg1); } } - dict.__setitem__("__add__",new PyMethodDescr("__add__",PyString.class,1,1,new exposed___add__(null,null))); - class exposed___getitem__ extends PyBuiltinFunctionNarrow { + dict.__setitem__("__getslice__",new PyMethodDescr("__getslice__",PyString.class,2,3,new exposed___getslice__(null,null))); + class exposed___contains__ extends PyBuiltinFunctionNarrow { private PyString self; @@ -172,27 +161,27 @@ return self; } - exposed___getitem__(PyString self,PyBuiltinFunction.Info info) { + exposed___contains__(PyString self,PyBuiltinFunction.Info info) { super(info); this.self=self; } public PyBuiltinFunction makeBound(PyObject self) { - return new exposed___getitem__((PyString)self,info); + return new exposed___contains__((PyString)self,info); } public PyObject __call__(PyObject arg0) { - return self.str___getitem__(arg0); + return Py.newBoolean(self.str___contains__(arg0)); } public PyObject inst_call(PyObject gself,PyObject arg0) { PyString self=(PyString)gself; - return self.str___getitem__(arg0); + return Py.newBoolean(self.str___contains__(arg0)); } } - dict.__setitem__("__getitem__",new PyMethodDescr("__getitem__",PyString.class,1,1,new exposed___getitem__(null,null))); - class exposed___getslice__ extends PyBuiltinFunctionNarrow { + dict.__setitem__("__contains__",new PyMethodDescr("__contains__",PyString.class,1,1,new exposed___contains__(null,null))); + class exposed___len__ extends PyBuiltinFunctionNarrow { private PyString self; @@ -200,36 +189,27 @@ return self; } - exposed___getslice__(PyString self,PyBuiltinFunction.Info info) { + exposed___len__(PyString self,PyBuiltinFunction.Info info) { super(info); this.self=self; } public PyBuiltinFunction makeBound(PyObject self) { - return new exposed___getslice__((PyString)self,info); + return new exposed___len__((PyString)self,info); } - public PyObject __call__(PyObject arg0,PyObject arg1,PyObject arg2) { - return self.str___getslice__(arg0,arg1,arg2); + public PyObject __call__() { + return Py.newInteger(self.str___len__()); } - public PyObject inst_call(PyObject gself,PyObject arg0,PyObject arg1,PyObject arg2) { + public PyObject inst_call(PyObject gself) { PyString self=(PyString)gself; - return self.str___getslice__(arg0,arg1,arg2); + return Py.newInteger(self.str___len__()); } - public PyObject __call__(PyObject arg0,PyObject arg1) { - return self.str___getslice__(arg0,arg1); - } - - public PyObject inst_call(PyObject gself,PyObject arg0,PyObject arg1) { - PyString self=(PyString)gself; - return self.str___getslice__(arg0,arg1); - } - } - dict.__setitem__("__getslice__",new PyMethodDescr("__getslice__",PyString.class,2,3,new exposed___getslice__(null,null))); - class exposed___iter__ extends PyBuiltinFunctionNarrow { + dict.__setitem__("__len__",new PyMethodDescr("__len__",PyString.class,0,0,new exposed___len__(null,null))); + class exposed___add__ extends PyBuiltinFunctionNarrow { private PyString self; @@ -237,26 +217,26 @@ return self; } - exposed___iter__(PyString self,PyBuiltinFunction.Info info) { + exposed___add__(PyString self,PyBuiltinFunction.Info info) { super(info); this.self=self; } public PyBuiltinFunction makeBound(PyObject self) { - return new exposed___iter__((PyString)self,info); + return new exposed___add__((PyString)self,info); } - public PyObject __call__() { - return self.str___iter__(); + public PyObject __call__(PyObject arg0) { + return self.str___add__(arg0); } - public PyObject inst_call(PyObject gself) { + public PyObject inst_call(PyObject gself,PyObject arg0) { PyString self=(PyString)gself; - return self.str___iter__(); + return self.str___add__(arg0); } } - dict.__setitem__("__iter__",new PyMethodDescr("__iter__",PyString.class,0,0,new exposed___iter__(null,null))); + dict.__setitem__("__add__",new PyMethodDescr("__add__",PyString.class,1,1,new exposed___add__(null,null))); class exposed___mul__ extends PyBuiltinFunctionNarrow { private PyString self; @@ -3343,34 +3323,6 @@ else return null; } - public PyObject __getslice__(PyObject s_start, PyObject s_stop) { - return str___getslice__(s_start,s_stop,null); - } - - public PyObject __getslice__(PyObject s_start, PyObject s_stop, PyObject s_step) { - return str___getslice__(s_start,s_stop,s_step); - } - - final PyObject str___getslice__(PyObject s_start, PyObject s_stop) { - return seq___getslice__(s_start,s_stop,null); - } - - final PyObject str___getslice__(PyObject s_start, PyObject s_stop, PyObject s_step) { - return seq___getslice__(s_start,s_stop,s_step); - } - - public PyObject __iter__() { - return str___iter__(); - } - - final PyObject str___iter__() { - return seq___iter__(); - } - - final PyObject str___getitem__(PyObject index) { - return seq___getitem__(index); - } - /** * Used for pickling. * Modified: trunk/jython/src/org/python/core/PyStringDerived.java =================================================================== --- trunk/jython/src/org/python/core/PyStringDerived.java 2006-10-16 00:43:44 UTC (rev 2957) +++ trunk/jython/src/org/python/core/PyStringDerived.java 2006-10-16 00:50:16 UTC (rev 2958) @@ -65,18 +65,6 @@ 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__"); @@ -665,6 +653,18 @@ return super.__ixor__(other); } + 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 PyInteger||res instanceof PyLong) + return(PyObject)res; + throw Py.TypeError("__int__"+" should return an integer"); + } + return super.__int__(); + } + public String toString() { PyType self_type=getType(); PyObject impl=self_type.lookup("__repr__"); @@ -800,21 +800,6 @@ super.__setitem__(key,value); } - public PyObject __getitem__(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.__getitem__(key); - } - public PyObject __getslice__(PyObject start,PyObject stop,PyObject step) { // ??? PyType self_type=getType(); PyObject impl=self_type.lookup("__getslice__"); Modified: trunk/jython/src/org/python/core/PySuperDerived.java =================================================================== --- trunk/jython/src/org/python/core/PySuperDerived.java 2006-10-16 00:43:44 UTC (rev 2957) +++ trunk/jython/src/org/python/core/PySuperDerived.java 2006-10-16 00:50:16 UTC (rev 2958) @@ -65,18 +65,6 @@ 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__"); @@ -665,6 +653,18 @@ return super.__ixor__(other); } + 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 PyInteger||res instanceof PyLong) + return(PyObject)res; + throw Py.TypeError("__int__"+" should return an integer"); + } + return super.__int__(); + } + public String toString() { PyType self_type=getType(); PyObject impl=self_type.lookup("__repr__"); @@ -800,21 +800,6 @@ super.__setitem__(key,value); } - public PyObject __getitem__(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.__getitem__(key); - } - public PyObject __getslice__(PyObject start,PyObject stop,PyObject step) { // ??? PyType self_type=getType(); PyObject impl=self_type.lookup("__getslice__"); Modified: trunk/jython/src/org/python/core/PyTuple.java =================================================================== --- trunk/jython/src/org/python/core/PyTuple.java 2006-10-16 00:43:44 UTC (rev 2957) +++ trunk/jython/src/org/python/core/PyTuple.java 2006-10-16 00:50:16 UTC (rev 2958) @@ -93,7 +93,7 @@ } dict.__setitem__("__eq__",new PyMethodDescr("__eq__",PyTuple.class,1,1,new exposed___eq__(null,null))); - class exposed___contains__ extends PyBuiltinFunctionNarrow { + class exposed___getitem__ extends PyBuiltinFunctionNarrow { private PyTuple self; @@ -101,27 +101,35 @@ return self; } - exposed___contains__(PyTuple self,PyBuiltinFunction.Info info) { + exposed___getitem__(PyTuple self,PyBuiltinFunction.Info info) { super(info); this.self=self; } public PyBuiltinFunction makeBound(PyObject self) { - return new exposed___contains__((PyTuple)self,info); + return new exposed___getitem__((PyTuple)self,info); } public PyObject __call__(PyObject arg0) { - return Py.newBoolean(self.tuple___contains__(arg0)); + PyObject ret=self.seq___finditem__(arg0); + if (ret==null) { + throw Py.IndexError("index out of range: "+arg0); + } + return ret; } public PyObject inst_call(PyObject gself,PyObject arg0) { PyTuple self=(PyTuple)gself; - return Py.newBoolean(self.tuple___contains__(arg0)); + PyObject ret=self.seq___finditem__(arg0); + if (ret==null) { + throw Py.IndexError("index out of range: "+arg0); + } + return ret; } } - dict.__setitem__("__contains__",new PyMethodDescr("__contains__",PyTuple.class,1,1,new exposed___contains__(null,null))); - class exposed___len__ extends PyBuiltinFunctionNarrow { + dict.__setitem__("__getitem__",new PyMethodDescr("__getitem__",PyTuple.class,1,1,new exposed___getitem__(null,null))); + class exposed___getslice__ extends PyBuiltinFunctionNarrow { private PyTuple self; @@ -129,27 +137,36 @@ return self; } - exposed___len__(PyTuple self,PyBuiltinFunction.Info info) { + exposed___getslice__(PyTuple self,PyBuiltinFunction.Info info) { super(info); this.self=self; } public PyBuiltinFunction makeBound(PyObject self) { - return new exposed___len__((PyTuple)self,info); + return new exposed___getslice__((PyTuple)self,info); } - public PyObject __call__() { - return Py.newInteger(self.tuple___len__()); + public PyObject __call__(PyObject arg0,PyObject arg1,PyObject arg2) { + return self.seq___getslice__(arg0,arg1,arg2); } - public PyObject inst_call(PyObject gself) { + public PyObject inst_call(PyObject gself,PyObject arg0,PyObject arg1,PyObject arg2) { PyTuple self=(PyTuple)gself; - return Py.newInteger(self.tuple___len__()); + return self.seq___getslice__(arg0,arg1,arg2); } + public PyObject __call__(PyObject arg0,PyObject arg1) { + return self.seq___getslice__(arg0,arg1); + } + + public PyObject inst_call(PyObject gself,PyObject arg0,PyObject arg1) { + PyTuple self=(PyTuple)gself; + return self.seq___getslice__(arg0,arg1); + } + } - dict.__setitem__("__len__",new PyMethodDescr("__len__",PyTuple.class,0,0,new exposed___len__(null,null))); - class exposed___add__ extends PyBuiltinFunctionNarrow { + dict.__setitem__("__getslice__",new PyMethodDescr("__getslice__",PyTuple.class,2,3,new exposed___getslice__(null,null))); + class exposed___contains__ extends PyBuiltinFunctionNarrow { private PyTuple self; @@ -157,27 +174,27 @@ return self; } - exposed___add__(PyTuple self,PyBuiltinFunction.Info info) { + exposed___contains__(PyTuple self,PyBuiltinFunction.Info info) { super(info); this.self=self; } public PyBuiltinFunction makeBound(PyObject self) { - return new exposed___add__((PyTuple)self,info); + return new exposed___contains__((PyTuple)self,info); } public PyObject __call__(PyObject arg0) { - return self.tuple___add__(arg0); + return Py.newBoolean(self.tuple___contains__(arg0)); } public PyObject inst_call(PyObject gself,PyObject arg0) { PyTuple self=(PyTuple)gself; - return self.tuple___add__(arg0); + return Py.newBoolean(se... [truncated message content] |
From: <fwi...@us...> - 2006-10-23 00:50:52
|
Revision: 2965 http://svn.sourceforge.net/jython/?rev=2965&view=rev Author: fwierzbicki Date: 2006-10-22 17:50:43 -0700 (Sun, 22 Oct 2006) Log Message: ----------- Added Matt's template task to trunk. I did not make it part of the main build at this point, it needs to be executed like: ant template This is probably the best way to go for now since the task is a little time consuming. Modified Paths: -------------- trunk/jython/build.xml Added Paths: ----------- trunk/jython/src/org/python/util/TemplateAntTask.java Modified: trunk/jython/build.xml =================================================================== --- trunk/jython/build.xml 2006-10-17 02:43:45 UTC (rev 2964) +++ trunk/jython/build.xml 2006-10-23 00:50:43 UTC (rev 2965) @@ -201,6 +201,7 @@ <property name="work.dir" value="${basedir}" /> <property name="jython.base.dir" value="${basedir}" /> <property name="source.dir" value="${basedir}/src" /> + <property name="templates.dir" value="${basedir}/../sandbox/jt" /> <property name="python.lib" value="${python.home}/Lib" /> </target> @@ -393,6 +394,50 @@ </target> + <!-- prepare template ant task --> + <target name="template-init" depends="prepare"> + <javac srcdir="${source.dir}/" + destdir="${output.dir}/" + target="${jdk.target.version}" + source="${jdk.source.version}" + debug="${debug}" + optimize="${optimize}" + deprecation="${deprecation}" + nowarn="${nowarn}" + > + <include name="org/python/util/TemplateAntTask.java" /> + </javac> + </target> + + + <!-- run templates --> + <target name="template" depends="checkout, template-init"> + <taskdef name="gentempl" classname="org.python.util.TemplateAntTask" + classpath="${output.dir}" /> + <gentempl mappingFile="${templates.dir}/mappings" + srcdir="${templates.dir}" + destdir="${source.dir}" + scriptdir="${templates.dir}" + verbose="true"> + <include name="*.expose" /> + <include name="*.derived" /> + + <!-- these have custom modifications --> + <exclude name="float.derived" /> + <exclude name="long.derived" /> + <exclude name="str.expose" /> + <exclude name="random.derived" /> + + <!-- unfinished --> + <exclude name="function.expose" /> + + <!-- sequence.expose is to be used as a parent expose; extended, + but not used directly --> + <exclude name="sequence.expose" /> + </gentempl> + </target> + + <!-- compile java sources --> <target name="compile" depends="version, parser"> <javac srcdir="${source.dir}/" Added: trunk/jython/src/org/python/util/TemplateAntTask.java =================================================================== --- trunk/jython/src/org/python/util/TemplateAntTask.java (rev 0) +++ trunk/jython/src/org/python/util/TemplateAntTask.java 2006-10-23 00:50:43 UTC (rev 2965) @@ -0,0 +1,312 @@ +/* + * The Apache Software License, Version 1.1 + * + * Copyright (c) 2002 The Apache Software Foundation. All rights + * reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. The end-user documentation included with the redistribution, if + * any, must include the following acknowlegement: + * "This product includes software developed by the + * Apache Software Foundation (http://www.apache.org/)." + * Alternately, this acknowlegement may appear in the software itself, + * if and wherever such third-party acknowlegements normally appear. + * + * 4. The names "The Jakarta Project", "Ant", and "Apache Software + * Foundation" must not be used to endorse or promote products derived + * from this software without prior written permission. For written + * permission, please contact ap...@ap.... + * + * 5. Products derived from this software may not be called "Apache" + * nor may "Apache" appear in their names without prior written + * permission of the Apache Group. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR + * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF + * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT + * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * ==================================================================== + * + * This software consists of voluntary contributions made by many + * individuals on behalf of the Apache Software Foundation. For more + * information on the Apache Software Foundation, please see + * <http://www.apache.org/>. + */ + +package org.python.util; + +import org.apache.tools.ant.taskdefs.MatchingTask; +import org.apache.tools.ant.taskdefs.Execute; +import org.apache.tools.ant.BuildException; +import org.apache.tools.ant.taskdefs.Java; +import org.apache.tools.ant.types.Path; +import org.apache.tools.ant.DirectoryScanner; + +import java.io.File; +import java.io.BufferedReader; +import java.io.InputStreamReader; +import java.io.FileInputStream; +import java.io.Reader; +import java.io.IOException; + +import java.util.Map; +import java.util.HashMap; + +/** + * Template is an Ant task for generating new-style object definitions based + * on template files. These template files come in two flavors; *.expose and + * *.derived, both are supported by this task. + * + * @author Matt Small - ms...@ac... + * @version 1.0 + */ +public class TemplateAntTask extends MatchingTask { + + /** + * Specifies the mapping file, for template short name to Python class + * name. + */ + protected File mappingFile; + + /** + * Specifies the mapping file, for template short name to Python class + * name. + */ + public void setMappingFile(String aMappingFile) { + String amp=getProject().replaceProperties(aMappingFile); + mappingFile=new File(amp); + } + + /** + * Specifies the Python interpreter. + */ + protected String python; + + /** + * Specifies the Python interpreter. + */ + public void setPython(String aPE) { + python=aPE; + } + + /** + * Specifies the destination directory; this should usually be the source + * tree, as the templates modify source files in-place. + */ + protected File destdir; + + /** + * Specifies the destination directory; this should usually be the source + * tree, as the templates modify source files in-place. + */ + public void setDestdir(String in) { + destdir=new File(getProject().replaceProperties(in)); + } + + /** + * Source paths. + */ + protected Path src; + + public Path createSrc() { + if (null==src) { + src=new Path(getProject()); + } + return src.createPath(); + } + + /** + * Source paths. + */ + public void setSrcdir(Path srcDir) { + if (null==src) { + src=srcDir; + } else { + src.append(srcDir); + } + } + + /** + * Path to find scripts (gexpose.py & gderived.py). + */ + protected File scriptDir; + + /** + * Path to find scripts (gexpose.py & gderived.py). + */ + public void setScriptdir(String in) { + scriptDir=new File(getProject().replaceProperties(in)); + } + + /** + * Verbose flag. + */ + protected boolean verbose=false; + + /** + * Verbose flag. + */ + public void setVerbose(String in) { + verbose=(new Boolean(getProject().replaceProperties(in))).booleanValue(); + } + + public void execute() { + if (null==mappingFile) { + throw new BuildException("no mappingFile specified"); + } else if (!mappingFile.canRead()) { + throw new BuildException("Can't read mappingFile: "+mappingFile); + } + if (null==python) { + // throw new BuildException("no python executable specified"); + python="python"; + } + if (null==destdir) { + throw new BuildException("no destdir specified"); + } else if (!destdir.exists()) { + throw new BuildException("destdir '"+destdir+"' doesn't exist"); + } + + Map mapping; + try { + mapping=fileToMap(mappingFile); + } catch (IOException e) { + throw new BuildException(e.toString(), e); + } + + if (null==scriptDir) { + throw new BuildException("no scriptdir specified"); + } else if (!scriptDir.exists()) { + throw new BuildException("scriptdir '"+scriptDir+"' doesn't exist"); + } + File gexposeScript=new File(scriptDir.getAbsolutePath()+File.separator+ + "gexpose.py"); + File gderiveScript=new File(scriptDir.getAbsolutePath()+File.separator+ + "gderived.py"); + if (!gexposeScript.exists()) { + throw new BuildException("no gexpose.py script found at: "+ + gexposeScript); + } + if (!gderiveScript.exists()) { + throw new BuildException("no gderive.py script found at: "+ + gderiveScript); + } + + + String[] list=src.list(); + for (int i=0;i<list.length;i++) { + File srcDir=getProject().resolveFile(list[i]); + if (!srcDir.exists()) { + throw new BuildException("srcDir '"+list[i]+"' does not exist"); + } + + DirectoryScanner ds=getDirectoryScanner(srcDir); + String[] files=ds.getIncludedFiles(); + + for (int j=0;j<files.length;j++) { + // TODO - use FileNameMapper, SourceFileScanner to only update + // changed files + // + + if (null==mapping.get(files[j])) { + if (verbose) { + log("ignoring file ("+files[j]+") with no mapping"); + } + continue; + } + + String fromFile=srcDir.getAbsolutePath()+File.separator+ + files[j]; + String mapFile=(String)mapping.get(files[j]); + String mapFileName=mapFile.replace('.', File.separatorChar)+".java"; + String toFile=destdir.getAbsolutePath()+File.separator+ + mapFileName; + + if (! (new File(fromFile)).exists() ) { + throw new BuildException("source file '"+fromFile+ + "' does not exist"); + } + if (! (new File(toFile)).exists() ) { + throw new BuildException("destination file '"+toFile+ + "' (from class named "+mapFile+") does not exist"); + } + + String[] cmd; + if (fromFile.endsWith(".expose")) { + cmd=new String[] {python, gexposeScript.getAbsolutePath(), + fromFile, toFile}; + } else if (fromFile.endsWith(".derived")) { + cmd=new String[] {python, gderiveScript.getAbsolutePath(), + fromFile, toFile}; + } else { + throw new BuildException("source file: '"+fromFile+ + "' has unknown extension; expected .derived or .expose"); + } + + Execute e=new Execute(); + e.setWorkingDirectory(scriptDir); + e.setCommandline(cmd); + if (verbose) { + String out=""; + for (int k=0;k<e.getCommandline().length;k++) { + out+=(e.getCommandline()[k]+" "); + } + log("executing: "+out); + } + + try { + e.execute(); + } catch (IOException e2) { + throw new BuildException(e2.toString(), e2); + } + } + } + } + + protected Map fileToMap (File mapFile) throws IOException, BuildException { + HashMap ret=new HashMap(); + BufferedReader in=new BufferedReader(new InputStreamReader( + new FileInputStream(mapFile))); + String line; + int idx; + String key; + String val; + + while (null!=(line=in.readLine())) { + if (line.trim().startsWith("#")) { + continue; + } else if (0==line.trim().compareTo("")) { + continue; + } + + idx=line.indexOf(":"); + if (-1==idx) { + throw new BuildException("invalid mapping syntax; no ':' on line: '"+line+"'"); + } + key=line.substring(0, idx); + val=line.substring(idx+1, line.length()); + + ret.put(key, val); + } + + return ret; + } +} This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <cg...@us...> - 2006-11-21 03:06:50
|
Revision: 2980 http://svn.sourceforge.net/jython/?rev=2980&view=rev Author: cgroves Date: 2006-11-20 19:06:48 -0800 (Mon, 20 Nov 2006) Log Message: ----------- added CPython's release22-maint/Lib to svn:externals as CPythonLib Modified Paths: -------------- trunk/jython/build.xml Property Changed: ---------------- trunk/jython/ Property changes on: trunk/jython ___________________________________________________________________ Name: svn:externals + CPythonLib http://svn.python.org/projects/python/branches/release22-maint/Lib/ Modified: trunk/jython/build.xml =================================================================== --- trunk/jython/build.xml 2006-11-20 16:14:17 UTC (rev 2979) +++ trunk/jython/build.xml 2006-11-21 03:06:48 UTC (rev 2980) @@ -201,8 +201,8 @@ <property name="work.dir" value="${basedir}" /> <property name="jython.base.dir" value="${basedir}" /> <property name="source.dir" value="${basedir}/src" /> - <property name="templates.dir" value="${basedir}/../sandbox/jt" /> - <property name="python.lib" value="${python.home}/Lib" /> + <property name="templates.dir" value="${basedir}/../sandbox/jt" /> + <property name="python.lib" value="${basedir}/CPythonLib" /> </target> This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <cg...@us...> - 2006-11-22 05:30:18
|
Revision: 2986 http://svn.sourceforge.net/jython/?rev=2986&view=rev Author: cgroves Date: 2006-11-21 21:30:17 -0800 (Tue, 21 Nov 2006) Log Message: ----------- no hand modified generated files, so don't exclude any templates from ant template Modified Paths: -------------- trunk/jython/build.xml trunk/jython/src/org/python/core/PyFileDerived.java trunk/jython/src/org/python/core/PyFloatDerived.java Modified: trunk/jython/build.xml =================================================================== --- trunk/jython/build.xml 2006-11-22 05:26:56 UTC (rev 2985) +++ trunk/jython/build.xml 2006-11-22 05:30:17 UTC (rev 2986) @@ -408,12 +408,6 @@ <include name="*.expose" /> <include name="*.derived" /> - <!-- these have custom modifications --> - <exclude name="float.derived" /> - <exclude name="long.derived" /> - <exclude name="str.expose" /> - <exclude name="random.derived" /> - <!-- unfinished --> <exclude name="function.expose" /> Modified: trunk/jython/src/org/python/core/PyFileDerived.java =================================================================== --- trunk/jython/src/org/python/core/PyFileDerived.java 2006-11-22 05:26:56 UTC (rev 2985) +++ trunk/jython/src/org/python/core/PyFileDerived.java 2006-11-22 05:30:17 UTC (rev 2986) @@ -1,7 +1,17 @@ package org.python.core; -public class PyFileDerived extends PyFile { +public class PyFileDerived extends PyFile 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 PyFileDerived(PyType subtype) { super(subtype); + slots=new PyObject[subtype.getNumSlots()]; dict=subtype.instDict(); } Modified: trunk/jython/src/org/python/core/PyFloatDerived.java =================================================================== --- trunk/jython/src/org/python/core/PyFloatDerived.java 2006-11-22 05:26:56 UTC (rev 2985) +++ trunk/jython/src/org/python/core/PyFloatDerived.java 2006-11-22 05:30:17 UTC (rev 2986) @@ -1,7 +1,17 @@ package org.python.core; -public class PyFloatDerived extends PyFloat { +public class PyFloatDerived extends PyFloat 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 PyFloatDerived(PyType subtype,double v) { super(subtype,v); + slots=new PyObject[subtype.getNumSlots()]; dict=subtype.instDict(); } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <ped...@us...> - 2006-12-09 20:35:52
|
Revision: 3016 http://svn.sourceforge.net/jython/?rev=3016&view=rev Author: pedronis Date: 2006-12-09 12:35:50 -0800 (Sat, 09 Dec 2006) Log Message: ----------- - disable old code that was once used to generate the non-comparison binary op code in PyObject. - changed the new version of the same to generate code that follow the correct rule (as fo 2.3) for binary op dispatching Modified Paths: -------------- trunk/jython/Misc/make_binops.py trunk/jython/src/templates/make_binops.py Modified: trunk/jython/Misc/make_binops.py =================================================================== --- trunk/jython/Misc/make_binops.py 2006-12-09 18:25:49 UTC (rev 3015) +++ trunk/jython/Misc/make_binops.py 2006-12-09 20:35:50 UTC (rev 3016) @@ -6,80 +6,83 @@ ('mod', '%'), ('divmod', 'divmod'), ('pow', '**'), ('lshift', '<<'), ('rshift', '>>'), ('and', '&'), ('or', '|'), ('xor', '^')] -template = """\ - /** - * Equivalent to the standard Python __%(name)s__ method - * @param other the object to perform this binary operation with - * (the right-hand operand). - * @return the result of the %(name)s, or null if this operation - * is not defined - **/ - public PyObject __%(name)s__(PyObject other) { %(function)s } +# +# this bit is superseded by src/templates/make_binops.py +# +## template = """\ +## /** +## * Equivalent to the standard Python __%(name)s__ method +## * @param other the object to perform this binary operation with +## * (the right-hand operand). +## * @return the result of the %(name)s, or null if this operation +## * is not defined +## **/ +## public PyObject __%(name)s__(PyObject other) { %(function)s } - /** - * Equivalent to the standard Python __r%(name)s__ method - * @param other the object to perform this binary operation with - * (the left-hand operand). - * @return the result of the %(name)s, or null if this operation - * is not defined. - **/ - public PyObject __r%(name)s__(PyObject other) { %(rfunction)s } +## /** +## * Equivalent to the standard Python __r%(name)s__ method +## * @param other the object to perform this binary operation with +## * (the left-hand operand). +## * @return the result of the %(name)s, or null if this operation +## * is not defined. +## **/ +## public PyObject __r%(name)s__(PyObject other) { %(rfunction)s } - /** - * Equivalent to the standard Python __i%(name)s__ method - * @param other the object to perform this binary operation with - * (the right-hand operand). - * @return the result of the %(name)s, or null if this operation - * is not defined - **/ - public PyObject __i%(name)s__(PyObject other) { return _%(name)s(other); } +## /** +## * Equivalent to the standard Python __i%(name)s__ method +## * @param other the object to perform this binary operation with +## * (the right-hand operand). +## * @return the result of the %(name)s, or null if this operation +## * is not defined +## **/ +## public PyObject __i%(name)s__(PyObject other) { return _%(name)s(other); } - /** - * Implements the Python expression <code>this %(op)s other</code> - * @param other the object to perform this binary operation with. - * @return the result of the %(name)s. - * @exception PyTypeError if this operation can't be performed - * with these operands. - **/ - public final PyObject _%(name)s(PyObject o2) {%(divhook)s - PyObject x = __%(name)s__(o2); - if (x != null) - return x; - x = o2.__r%(name)s__(this); - if (x != null) - return x; - throw Py.TypeError( - "__%(name)s__ nor __r%(name)s__ defined for these operands"); - } +## /** +## * Implements the Python expression <code>this %(op)s other</code> +## * @param other the object to perform this binary operation with. +## * @return the result of the %(name)s. +## * @exception PyTypeError if this operation can't be performed +## * with these operands. +## **/ +## public final PyObject _%(name)s(PyObject o2) {%(divhook)s +## PyObject x = __%(name)s__(o2); +## if (x != null) +## return x; +## x = o2.__r%(name)s__(this); +## if (x != null) +## return x; +## throw Py.TypeError( +## "__%(name)s__ nor __r%(name)s__ defined for these operands"); +## } -""" +## """ -fp = open('binops.txt', 'w') +## fp = open('binops.txt', 'w') -fp.write(' // Generated by make_binops.py (Begin)\n\n') +## fp.write(' // Generated by make_binops.py (Begin)\n\n') -for name, op in binops: - rfunction = function = 'return null;' - divhook = "" +## for name, op in binops: +## rfunction = function = 'return null;' +## divhook = "" - if name == 'pow': - function = 'return __pow__(other, null);' - if name == 'div': - divhook = ''' - if (Options.Qnew) - return _truediv(o2);''' +## if name == 'pow': +## function = 'return __pow__(other, null);' +## if name == 'div': +## divhook = ''' +## if (Options.Qnew) +## return _truediv(o2);''' - fp.write(template % { - 'name':name, - 'op':op, - 'function':function, - 'rfunction':rfunction, - 'divhook':divhook - }) +## fp.write(template % { +## 'name':name, +## 'op':op, +## 'function':function, +## 'rfunction':rfunction, +## 'divhook':divhook +## }) -fp.write(' // Generated by make_binops.py (End)\n\n') +## fp.write(' // Generated by make_binops.py (End)\n\n') -fp.close() +## fp.close() Modified: trunk/jython/src/templates/make_binops.py =================================================================== --- trunk/jython/src/templates/make_binops.py 2006-12-09 18:25:49 UTC (rev 3015) +++ trunk/jython/src/templates/make_binops.py 2006-12-09 20:35:50 UTC (rev 3016) @@ -1,6 +1,6 @@ """generates code for binops in PyObject and for all "simple" ops in PyInstance""" -from java_templating import JavaTemplate as jt, concat, csub +from java_templating import JavaTemplate as jt, concat, csub, strfy binops = \ [('add', '+'), ('sub', '-'), ('mul', '*'), ('div', '/'), @@ -45,15 +45,36 @@ } `csub`( + /** + * Implements the Python expression <code>this %(bareop)s o2</code> + * @param o2 the object to perform this binary operation with. + * @return the result of the %(name)s. + * @exception Py.TypeError if this operation can't be performed + * with these operands. + **/ + ); + public final PyObject `concat`(_, `name)(PyObject o2) { + PyType t1 = this.getType(); + PyType t2 = o2.getType(); + if (t1 == t2 || t1.builtin && t2.builtin) { + return this.`concat`(_basic_, `name)(o2); + } + return _binop_rule(t1, o2, t2, `strfy`(`concat`(__,`name,__)), + `strfy`(`concat`(__r,`name,__)), + `op); + } + + `csub`( /** - * Implements the Python expression <code>this %(bareop)s other</code> + * Implements the Python expression <code>this %(bareop)s o2</code> + * when this and o2 have the same type or are builtin types. * @param o2 the object to perform this binary operation with. * @return the result of the %(name)s. * @exception Py.TypeError if this operation can't be performed * with these operands. **/ ); - public final PyObject `concat`(_, `name)(PyObject o2) { + final PyObject `concat`(_basic_, `name)(PyObject o2) { `divhook; PyObject x = `concat`(__,`name,__)(o2); if (x != null) @@ -63,7 +84,9 @@ return x; throw Py.TypeError(_unsupportedop(`op, o2)); } -""", bindings={'csub': csub, 'concat': concat }, start='ClassBodyDeclarations') + +""", bindings={'csub': csub, 'concat': concat, + 'strfy': strfy}, start='ClassBodyDeclarations') def main(): fp = open('binops.txt', 'w') This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <ped...@us...> - 2006-12-09 20:40:19
|
Revision: 3017 http://svn.sourceforge.net/jython/?rev=3017&view=rev Author: pedronis Date: 2006-12-09 12:40:17 -0800 (Sat, 09 Dec 2006) Log Message: ----------- use the ouput generated from templates/make_binop.txt and introduce the needed helpers in PyObject and PyType. Now we pass test_descr.subclass_right_op! This solution is a compromise between speed and simplicity, is still trying tough to make the fast path not too bad. We can rethink this after 2.2. Add a test to test_descr: subclass_cmp_right_op to check for the dispatch rules for comparisons, this rule is more direct and less subtle than the general one. This test pass as is both on top jython (with the fixes in _eq, _gt etc) and on top of Python 2.4, so we are reasonably implementing the Python behavior as it stands today. Modified Paths: -------------- trunk/jython/Lib/test/test_descr.py trunk/jython/src/org/python/core/PyObject.java trunk/jython/src/org/python/core/PyType.java Modified: trunk/jython/Lib/test/test_descr.py =================================================================== --- trunk/jython/Lib/test/test_descr.py 2006-12-09 20:35:50 UTC (rev 3016) +++ trunk/jython/Lib/test/test_descr.py 2006-12-09 20:40:17 UTC (rev 3017) @@ -3681,6 +3681,55 @@ vereq(E() // C(), "C.__floordiv__") vereq(C() // E(), "C.__floordiv__") # This one would fail +def subclass_cmp_right_op(): + if verbose: + print "Testing correct dispatch of subclass overloading for comp ops" + + # Case 1: subclass of int + + class B(int): + def __ge__(self, other): + return "B.__ge__" + def __le__(self, other): + return "B.__le__" + + vereq(B(1) >= 1, "B.__ge__") + vereq(1 >= B(1), "B.__le__") + + # Case 2: subclass of object + + class C(object): + def __ge__(self, other): + return "C.__ge__" + def __le__(self, other): + return "C.__le__" + + vereq(C() >= 1, "C.__ge__") + vereq(1 >= C(), "C.__le__") + + # Case 3: subclass of new-style class; here it gets interesting + + class D(C): + def __ge__(self, other): + return "D.__ge__" + def __le__(self, other): + return "D.__le__" + + vereq(D() >= C(), "D.__ge__") + vereq(C() >= D(), "D.__le__") + + # Case 4: comparison is different than other binops + + class E(C): + pass + + vereq(E.__le__, C.__le__) + + vereq(E() >= 1, "C.__ge__") + vereq(1 >= E(), "C.__le__") + vereq(E() >= C(), "C.__ge__") + vereq(C() >= E(), "C.__le__") # different + def dict_type_with_metaclass(): if verbose: print "Testing type of __dict__ when __metaclass__ set..." @@ -3932,6 +3981,7 @@ test_mutable_bases_catch_mro_conflict, mutable_names, subclass_right_op, + subclass_cmp_right_op, dict_type_with_metaclass, meth_class_get, isinst_isclass, Modified: trunk/jython/src/org/python/core/PyObject.java =================================================================== --- trunk/jython/src/org/python/core/PyObject.java 2006-12-09 20:35:50 UTC (rev 3016) +++ trunk/jython/src/org/python/core/PyObject.java 2006-12-09 20:40:17 UTC (rev 3017) @@ -1579,6 +1579,12 @@ **/ public final PyObject _eq(PyObject o) { PyObject token = null; + PyType t1 = this.getType(); + PyType t2 = o.getType(); + + if (t1 != t2 && t2.isSubType(t1)) { + return o._eq(this); + } ThreadState ts = Py.getThreadState(); try { @@ -1612,6 +1618,12 @@ **/ public final PyObject _ne(PyObject o) { PyObject token = null; + PyType t1 = this.getType(); + PyType t2 = o.getType(); + + if (t1 != t2 && t2.isSubType(t1)) { + return o._ne(this); + } ThreadState ts = Py.getThreadState(); try { @@ -1640,6 +1652,12 @@ **/ public final PyObject _le(PyObject o) { PyObject token = null; + PyType t1 = this.getType(); + PyType t2 = o.getType(); + + if (t1 != t2 && t2.isSubType(t1)) { + return o._ge(this); + } ThreadState ts = Py.getThreadState(); try { @@ -1668,6 +1686,12 @@ **/ public final PyObject _lt(PyObject o) { PyObject token = null; + PyType t1 = this.getType(); + PyType t2 = o.getType(); + + if (t1 != t2 && t2.isSubType(t1)) { + return o._gt(this); + } ThreadState ts = Py.getThreadState(); try { @@ -1696,6 +1720,12 @@ **/ public final PyObject _ge(PyObject o) { PyObject token = null; + PyType t1 = this.getType(); + PyType t2 = o.getType(); + + if (t1 != t2 && t2.isSubType(t1)) { + return o._le(this); + } ThreadState ts = Py.getThreadState(); try { @@ -1724,6 +1754,12 @@ **/ public final PyObject _gt(PyObject o) { PyObject token = null; + PyType t1 = this.getType(); + PyType t2 = o.getType(); + + if (t1 != t2 && t2.isSubType(t1)) { + return o._lt(this); + } ThreadState ts = Py.getThreadState(); try { @@ -1967,6 +2003,55 @@ return null; } + + 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) /** @@ -2003,13 +2088,30 @@ } /** - * Implements the Python expression <code>this + other</code> + * Implements the Python expression <code>this + o2</code> + * @param o2 the object to perform this binary operation with. + * @return the result of the add. + * @exception Py.TypeError if this operation can't be performed + * with these operands. + **/ + public final PyObject _add(PyObject o2) { + PyType t1=this.getType(); + PyType t2=o2.getType(); + if (t1==t2||t1.builtin&&t2.builtin) { + return this._basic_add(o2); + } + return _binop_rule(t1,o2,t2,"__add__","__radd__","+"); + } + + /** + * Implements the Python expression <code>this + o2</code> + * when this and o2 have the same type or are builtin types. * @param o2 the object to perform this binary operation with. * @return the result of the add. * @exception Py.TypeError if this operation can't be performed * with these operands. **/ - public final PyObject _add(PyObject o2) { + final PyObject _basic_add(PyObject o2) { PyObject x=__add__(o2); if (x!=null) return x; @@ -2053,13 +2155,30 @@ } /** - * Implements the Python expression <code>this - other</code> + * Implements the Python expression <code>this - o2</code> + * @param o2 the object to perform this binary operation with. + * @return the result of the sub. + * @exception Py.TypeError if this operation can't be performed + * with these operands. + **/ + public final PyObject _sub(PyObject o2) { + PyType t1=this.getType(); + PyType t2=o2.getType(); + if (t1==t2||t1.builtin&&t2.builtin) { + return this._basic_sub(o2); + } + return _binop_rule(t1,o2,t2,"__sub__","__rsub__","-"); + } + + /** + * Implements the Python expression <code>this - o2</code> + * when this and o2 have the same type or are builtin types. * @param o2 the object to perform this binary operation with. * @return the result of the sub. * @exception Py.TypeError if this operation can't be performed * with these operands. **/ - public final PyObject _sub(PyObject o2) { + final PyObject _basic_sub(PyObject o2) { PyObject x=__sub__(o2); if (x!=null) return x; @@ -2103,13 +2222,30 @@ } /** - * Implements the Python expression <code>this * other</code> + * Implements the Python expression <code>this * o2</code> + * @param o2 the object to perform this binary operation with. + * @return the result of the mul. + * @exception Py.TypeError if this operation can't be performed + * with these operands. + **/ + public final PyObject _mul(PyObject o2) { + PyType t1=this.getType(); + PyType t2=o2.getType(); + if (t1==t2||t1.builtin&&t2.builtin) { + return this._basic_mul(o2); + } + return _binop_rule(t1,o2,t2,"__mul__","__rmul__","*"); + } + + /** + * Implements the Python expression <code>this * o2</code> + * when this and o2 have the same type or are builtin types. * @param o2 the object to perform this binary operation with. * @return the result of the mul. * @exception Py.TypeError if this operation can't be performed * with these operands. **/ - public final PyObject _mul(PyObject o2) { + final PyObject _basic_mul(PyObject o2) { PyObject x=__mul__(o2); if (x!=null) return x; @@ -2153,13 +2289,30 @@ } /** - * Implements the Python expression <code>this / other</code> + * Implements the Python expression <code>this / o2</code> + * @param o2 the object to perform this binary operation with. + * @return the result of the div. + * @exception Py.TypeError if this operation can't be performed + * with these operands. + **/ + public final PyObject _div(PyObject o2) { + PyType t1=this.getType(); + PyType t2=o2.getType(); + if (t1==t2||t1.builtin&&t2.builtin) { + return this._basic_div(o2); + } + return _binop_rule(t1,o2,t2,"__div__","__rdiv__","/"); + } + + /** + * Implements the Python expression <code>this / o2</code> + * when this and o2 have the same type or are builtin types. * @param o2 the object to perform this binary operation with. * @return the result of the div. * @exception Py.TypeError if this operation can't be performed * with these operands. **/ - public final PyObject _div(PyObject o2) { + final PyObject _basic_div(PyObject o2) { if (Options.Qnew) return _truediv(o2); PyObject x=__div__(o2); @@ -2205,13 +2358,30 @@ } /** - * Implements the Python expression <code>this // other</code> + * Implements the Python expression <code>this // o2</code> + * @param o2 the object to perform this binary operation with. + * @return the result of the floordiv. + * @exception Py.TypeError if this operation can't be performed + * with these operands. + **/ + public final PyObject _floordiv(PyObject o2) { + PyType t1=this.getType(); + PyType t2=o2.getType(); + if (t1==t2||t1.builtin&&t2.builtin) { + return this._basic_floordiv(o2); + } + return _binop_rule(t1,o2,t2,"__floordiv__","__rfloordiv__","//"); + } + + /** + * Implements the Python expression <code>this // o2</code> + * when this and o2 have the same type or are builtin types. * @param o2 the object to perform this binary operation with. * @return the result of the floordiv. * @exception Py.TypeError if this operation can't be performed * with these operands. **/ - public final PyObject _floordiv(PyObject o2) { + final PyObject _basic_floordiv(PyObject o2) { PyObject x=__floordiv__(o2); if (x!=null) return x; @@ -2255,13 +2425,30 @@ } /** - * Implements the Python expression <code>this / other</code> + * Implements the Python expression <code>this / o2</code> + * @param o2 the object to perform this binary operation with. + * @return the result of the truediv. + * @exception Py.TypeError if this operation can't be performed + * with these operands. + **/ + public final PyObject _truediv(PyObject o2) { + PyType t1=this.getType(); + PyType t2=o2.getType(); + if (t1==t2||t1.builtin&&t2.builtin) { + return this._basic_truediv(o2); + } + return _binop_rule(t1,o2,t2,"__truediv__","__rtruediv__","/"); + } + + /** + * Implements the Python expression <code>this / o2</code> + * when this and o2 have the same type or are builtin types. * @param o2 the object to perform this binary operation with. * @return the result of the truediv. * @exception Py.TypeError if this operation can't be performed * with these operands. **/ - public final PyObject _truediv(PyObject o2) { + final PyObject _basic_truediv(PyObject o2) { PyObject x=__truediv__(o2); if (x!=null) return x; @@ -2305,13 +2492,30 @@ } /** - * Implements the Python expression <code>this % other</code> + * Implements the Python expression <code>this % o2</code> + * @param o2 the object to perform this binary operation with. + * @return the result of the mod. + * @exception Py.TypeError if this operation can't be performed + * with these operands. + **/ + public final PyObject _mod(PyObject o2) { + PyType t1=this.getType(); + PyType t2=o2.getType(); + if (t1==t2||t1.builtin&&t2.builtin) { + return this._basic_mod(o2); + } + return _binop_rule(t1,o2,t2,"__mod__","__rmod__","%"); + } + + /** + * Implements the Python expression <code>this % o2</code> + * when this and o2 have the same type or are builtin types. * @param o2 the object to perform this binary operation with. * @return the result of the mod. * @exception Py.TypeError if this operation can't be performed * with these operands. **/ - public final PyObject _mod(PyObject o2) { + final PyObject _basic_mod(PyObject o2) { PyObject x=__mod__(o2); if (x!=null) return x; @@ -2355,13 +2559,30 @@ } /** - * Implements the Python expression <code>this divmod other</code> + * Implements the Python expression <code>this divmod o2</code> + * @param o2 the object to perform this binary operation with. + * @return the result of the divmod. + * @exception Py.TypeError if this operation can't be performed + * with these operands. + **/ + public final PyObject _divmod(PyObject o2) { + PyType t1=this.getType(); + PyType t2=o2.getType(); + if (t1==t2||t1.builtin&&t2.builtin) { + return this._basic_divmod(o2); + } + return _binop_rule(t1,o2,t2,"__divmod__","__rdivmod__","divmod"); + } + + /** + * Implements the Python expression <code>this divmod o2</code> + * when this and o2 have the same type or are builtin types. * @param o2 the object to perform this binary operation with. * @return the result of the divmod. * @exception Py.TypeError if this operation can't be performed * with these operands. **/ - public final PyObject _divmod(PyObject o2) { + final PyObject _basic_divmod(PyObject o2) { PyObject x=__divmod__(o2); if (x!=null) return x; @@ -2405,13 +2626,30 @@ } /** - * Implements the Python expression <code>this ** other</code> + * Implements the Python expression <code>this ** o2</code> + * @param o2 the object to perform this binary operation with. + * @return the result of the pow. + * @exception Py.TypeError if this operation can't be performed + * with these operands. + **/ + public final PyObject _pow(PyObject o2) { + PyType t1=this.getType(); + PyType t2=o2.getType(); + if (t1==t2||t1.builtin&&t2.builtin) { + return this._basic_pow(o2); + } + return _binop_rule(t1,o2,t2,"__pow__","__rpow__","**"); + } + + /** + * Implements the Python expression <code>this ** o2</code> + * when this and o2 have the same type or are builtin types. * @param o2 the object to perform this binary operation with. * @return the result of the pow. * @exception Py.TypeError if this operation can't be performed * with these operands. **/ - public final PyObject _pow(PyObject o2) { + final PyObject _basic_pow(PyObject o2) { PyObject x=__pow__(o2); if (x!=null) return x; @@ -2455,13 +2693,30 @@ } /** - * Implements the Python expression <code>this << other</code> + * Implements the Python expression <code>this << o2</code> + * @param o2 the object to perform this binary operation with. + * @return the result of the lshift. + * @exception Py.TypeError if this operation can't be performed + * with these operands. + **/ + public final PyObject _lshift(PyObject o2) { + PyType t1=this.getType(); + PyType t2=o2.getType(); + if (t1==t2||t1.builtin&&t2.builtin) { + return this._basic_lshift(o2); + } + return _binop_rule(t1,o2,t2,"__lshift__","__rlshift__","<<"); + } + + /** + * Implements the Python expression <code>this << o2</code> + * when this and o2 have the same type or are builtin types. * @param o2 the object to perform this binary operation with. * @return the result of the lshift. * @exception Py.TypeError if this operation can't be performed * with these operands. **/ - public final PyObject _lshift(PyObject o2) { + final PyObject _basic_lshift(PyObject o2) { PyObject x=__lshift__(o2); if (x!=null) return x; @@ -2505,13 +2760,30 @@ } /** - * Implements the Python expression <code>this >> other</code> + * Implements the Python expression <code>this >> o2</code> + * @param o2 the object to perform this binary operation with. + * @return the result of the rshift. + * @exception Py.TypeError if this operation can't be performed + * with these operands. + **/ + public final PyObject _rshift(PyObject o2) { + PyType t1=this.getType(); + PyType t2=o2.getType(); + if (t1==t2||t1.builtin&&t2.builtin) { + return this._basic_rshift(o2); + } + return _binop_rule(t1,o2,t2,"__rshift__","__rrshift__",">>"); + } + + /** + * Implements the Python expression <code>this >> o2</code> + * when this and o2 have the same type or are builtin types. * @param o2 the object to perform this binary operation with. * @return the result of the rshift. * @exception Py.TypeError if this operation can't be performed * with these operands. **/ - public final PyObject _rshift(PyObject o2) { + final PyObject _basic_rshift(PyObject o2) { PyObject x=__rshift__(o2); if (x!=null) return x; @@ -2555,13 +2827,30 @@ } /** - * Implements the Python expression <code>this & other</code> + * Implements the Python expression <code>this & o2</code> + * @param o2 the object to perform this binary operation with. + * @return the result of the and. + * @exception Py.TypeError if this operation can't be performed + * with these operands. + **/ + public final PyObject _and(PyObject o2) { + PyType t1=this.getType(); + PyType t2=o2.getType(); + if (t1==t2||t1.builtin&&t2.builtin) { + return this._basic_and(o2); + } + return _binop_rule(t1,o2,t2,"__and__","__rand__","&"); + } + + /** + * Implements the Python expression <code>this & o2</code> + * when this and o2 have the same type or are builtin types. * @param o2 the object to perform this binary operation with. * @return the result of the and. * @exception Py.TypeError if this operation can't be performed * with these operands. **/ - public final PyObject _and(PyObject o2) { + final PyObject _basic_and(PyObject o2) { PyObject x=__and__(o2); if (x!=null) return x; @@ -2605,13 +2894,30 @@ } /** - * Implements the Python expression <code>this | other</code> + * Implements the Python expression <code>this | o2</code> + * @param o2 the object to perform this binary operation with. + * @return the result of the or. + * @exception Py.TypeError if this operation can't be performed + * with these operands. + **/ + public final PyObject _or(PyObject o2) { + PyType t1=this.getType(); + PyType t2=o2.getType(); + if (t1==t2||t1.builtin&&t2.builtin) { + return this._basic_or(o2); + } + return _binop_rule(t1,o2,t2,"__or__","__ror__","|"); + } + + /** + * Implements the Python expression <code>this | o2</code> + * when this and o2 have the same type or are builtin types. * @param o2 the object to perform this binary operation with. * @return the result of the or. * @exception Py.TypeError if this operation can't be performed * with these operands. **/ - public final PyObject _or(PyObject o2) { + final PyObject _basic_or(PyObject o2) { PyObject x=__or__(o2); if (x!=null) return x; @@ -2655,13 +2961,30 @@ } /** - * Implements the Python expression <code>this ^ other</code> + * Implements the Python expression <code>this ^ o2</code> + * @param o2 the object to perform this binary operation with. + * @return the result of the xor. + * @exception Py.TypeError if this operation can't be performed + * with these operands. + **/ + public final PyObject _xor(PyObject o2) { + PyType t1=this.getType(); + PyType t2=o2.getType(); + if (t1==t2||t1.builtin&&t2.builtin) { + return this._basic_xor(o2); + } + return _binop_rule(t1,o2,t2,"__xor__","__rxor__","^"); + } + + /** + * Implements the Python expression <code>this ^ o2</code> + * when this and o2 have the same type or are builtin types. * @param o2 the object to perform this binary operation with. * @return the result of the xor. * @exception Py.TypeError if this operation can't be performed * with these operands. **/ - public final PyObject _xor(PyObject o2) { + final PyObject _basic_xor(PyObject o2) { PyObject x=__xor__(o2); if (x!=null) return x; Modified: trunk/jython/src/org/python/core/PyType.java =================================================================== --- trunk/jython/src/org/python/core/PyType.java 2006-12-09 20:35:50 UTC (rev 3016) +++ trunk/jython/src/org/python/core/PyType.java 2006-12-09 20:40:17 UTC (rev 3017) @@ -388,6 +388,8 @@ private PyObject dict; private PyObject[] mro; private Class underlying_class; + + boolean builtin = false; private boolean non_instantiable = false; @@ -782,6 +784,7 @@ * @return found object or null */ public PyObject lookup(String name) { + PyObject[] mro = this.mro; for(int i = 0; i < mro.length; i++) { PyObject dict = mro[i].fastGetDict(); if(dict != null) { @@ -793,6 +796,22 @@ return null; } + public PyObject lookup_where(String name, PyObject[] where) { + PyObject[] mro = this.mro; + for(int i = 0; i < mro.length; i++) { + PyObject t = mro[i]; + PyObject dict = t.fastGetDict(); + if(dict != null) { + PyObject obj = dict.__finditem__(name); + if(obj != null) { + where[0] = t; + return obj; + } + } + } + return null; + } + public PyObject super_lookup(PyType ref,String name) { PyObject[] mro = this.mro; int i; @@ -919,6 +938,7 @@ } newtype.name = name; newtype.underlying_class = c; + newtype.builtin = true; boolean top = false; // basic mro, base, bases PyType[] mro = null; This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <cg...@us...> - 2006-12-10 06:36:08
|
Revision: 3019 http://svn.sourceforge.net/jython/?rev=3019&view=rev Author: cgroves Date: 2006-12-09 22:36:06 -0800 (Sat, 09 Dec 2006) Log Message: ----------- Add setBases mostly from descr_set__bases__ in typetype.py from pypy. Add layoutAligns(PyType) to check if the actual structure of two types are compatible and use in PyObject.setType to make sure the new type is acceptable. Initialize mro to an empty array so __dict__ is usable from __new__ on metatypes. Modified Paths: -------------- trunk/jython/Lib/test/test_descr.py trunk/jython/src/org/python/core/PyObject.java trunk/jython/src/org/python/core/PyType.java trunk/jython/src/templates/type.expose Modified: trunk/jython/Lib/test/test_descr.py =================================================================== --- trunk/jython/Lib/test/test_descr.py 2006-12-09 21:00:01 UTC (rev 3018) +++ trunk/jython/Lib/test/test_descr.py 2006-12-10 06:36:06 UTC (rev 3019) @@ -3977,7 +3977,7 @@ testrmul, testipow, test_mutable_bases, - #test_mutable_bases_with_failing_mro, + test_mutable_bases_with_failing_mro, test_mutable_bases_catch_mro_conflict, mutable_names, subclass_right_op, Modified: trunk/jython/src/org/python/core/PyObject.java =================================================================== --- trunk/jython/src/org/python/core/PyObject.java 2006-12-09 21:00:01 UTC (rev 3018) +++ trunk/jython/src/org/python/core/PyObject.java 2006-12-10 06:36:06 UTC (rev 3019) @@ -395,10 +395,8 @@ } public void setType(PyType type) { - PyType objectType = PyType.fromClass(PyObject.class); - if(PyObjectDerived.class.isAssignableFrom(getClass()) - && type.getStatic().equals(objectType) && - !type.equals(objectType)) { + if(getType().layoutAligns(type) && + !type.equals(PyType.fromClass(PyObject.class))){ this.objtype = type; } else { throw Py.TypeError("Can only assign subtypes of object to __class__ on subclasses of object"); Modified: trunk/jython/src/org/python/core/PyType.java =================================================================== --- trunk/jython/src/org/python/core/PyType.java 2006-12-09 21:00:01 UTC (rev 3018) +++ trunk/jython/src/org/python/core/PyType.java 2006-12-10 06:36:06 UTC (rev 3019) @@ -24,7 +24,7 @@ dict.__setitem__("__dict__",new PyGetSetDescr("__dict__",PyType.class,"getDict","setDict","delDict")); dict.__setitem__("__name__",new PyGetSetDescr("__name__",PyType.class,"fastGetName",null,null)); dict.__setitem__("__base__",new PyGetSetDescr("__base__",PyType.class,"getBase",null,null)); - dict.__setitem__("__bases__",new PyGetSetDescr("__bases__",PyType.class,"getBases",null,null)); + dict.__setitem__("__bases__",new PyGetSetDescr("__bases__",PyType.class,"getBases","setBases","delBases")); dict.__setitem__("__mro__",new PyGetSetDescr("__mro__",PyType.class,"getMro",null,null)); class exposed_mro extends PyBuiltinFunctionNarrow { @@ -362,6 +362,29 @@ } return cur; } + + /** + * Checks that the physical layout between this type and <code>other</code> + * are compatible. + */ + public boolean layoutAligns(PyType other) { + return getLayout().equals(other.getLayout()) + && needs_userdict == other.needs_userdict + && needs_finalizer == other.needs_finalizer; + } + + /** + * Gets the most parent PyType that determines the layout of this type ie + * has slots or an underlying_class. Can by this PyType. + */ + private PyType getLayout(){ + if(underlying_class != null){ + return this; + }else if(numSlots != base.numSlots){ + return this; + } + return base.getLayout(); + } public PyObject getBase() { if (base == null) @@ -375,6 +398,96 @@ return new PyTuple(bases); } + public void delBases() { + throw Py.TypeError("Can't delete __bases__ attribute"); + } + + public void setBases(PyObject newBasesTuple) { + if(!(newBasesTuple instanceof PyTuple)){ + throw Py.TypeError("bases must be a tuple"); + } + PyObject[] newBases = ((PyTuple)newBasesTuple).getArray(); + if (newBases.length == 0) { + throw Py.TypeError("can only assign non-empty tuple to __bases__, not " + newBasesTuple); + } + for(int i = 0; i < newBases.length; i++) { + if(!(newBases[i] instanceof PyType)){ + if(!(newBases[i] instanceof PyClass)){ + throw Py.TypeError(name + ".__bases__ must be a tuple of old- or new-style classes, not " + newBases[i]); + } + }else{ + if(((PyType)newBases[i]).isSubType(this)){ + throw Py.TypeError("a __bases__ item causes an inheritance cycle"); + } + } + } + PyType newBase = best_base(newBases); + if(!newBase.layoutAligns(base)) { + throw Py.TypeError("'" + base + "' layout differs from '" + newBase + + "'"); + } + PyObject[] savedBases = bases; + PyType savedBase = base; + PyObject[] savedMro = mro; + List savedSubMros = new ArrayList(); + try { + bases = newBases; + base = newBase; + mro_internal(); + mro_subclasses(savedSubMros); + for(int i = 0; i < savedBases.length; i++) { + if(savedBases[i] instanceof PyType) { + ((PyType)savedBases[i]).detachSubclass(this); + } + } + for(int i = 0; i < newBases.length; i++) { + if(newBases[i] instanceof PyType) { + ((PyType)newBases[i]).attachSubclass(this); + } + } + } catch(PyException t) { + for(Iterator it = savedSubMros.iterator(); it.hasNext(); ){ + PyType subtype = (PyType)it.next(); + PyObject[] subtypeSavedMro = (PyObject[])it.next(); + subtype.mro = subtypeSavedMro; + } + bases = savedBases; + base = savedBase; + mro = savedMro; + throw t; + } + + } + + private void mro_internal() { + if(getType().underlying_class != PyType.class + && getType().lookup("mro") != null) { + mro = Py.make_array(getType().lookup("mro") + .__get__(null, getType()) + .__call__(this)); + }else{ + mro = compute_mro(); + } + } + + /** + * Collects the subclasses and current mro of this type in currentMroSaver. If + * this type has subclasses C and D, and D has a subclass E current mro saver will equal + * [C, C.__mro__, D, D.__mro__, E, E.__mro__] after this call. + */ + private void mro_subclasses(List mroCollector){ + for (java.util.Iterator iter =subclasses.iterator(); iter.hasNext();) { + java.lang.ref.WeakReference type_ref = (java.lang.ref.WeakReference)iter.next(); + PyType subtype = (PyType)type_ref.get(); + if (subtype == null) + continue; + mroCollector.add(subtype); + mroCollector.add(subtype.mro); + subtype.mro_internal(); + subtype.mro_subclasses(mroCollector); + } + } + public PyObject instDict() { if (needs_userdict) { return new PyStringMap(); @@ -386,7 +499,7 @@ private PyType base; private PyObject[] bases; private PyObject dict; - private PyObject[] mro; + private PyObject[] mro = new PyObject[0]; private Class underlying_class; boolean builtin = false; @@ -432,6 +545,18 @@ new java.lang.ref.WeakReference(subtype, subclasses_refq)); } + private synchronized void detachSubclass(PyType subtype) { + cleanup_subclasses(); + for (java.util.Iterator iter =subclasses.iterator(); iter.hasNext();) { + java.lang.ref.WeakReference type_ref = (java.lang.ref.WeakReference)iter.next(); + PyType refType = (PyType)type_ref.get(); + if(refType == subtype){ + subclasses.remove(type_ref); + break; + } + } + } + private interface OnType { boolean onType(PyType type); } @@ -582,74 +707,68 @@ throw mro_error(to_merge,remain); } + /** + * Finds the parent of base with an underlying_class or with slots + * + * @raises Py.TypeError if there is no solid base for base + */ private static PyType solid_base(PyType base) { PyObject[] mro = base.mro; for (int i=0; i<mro.length; i++) { PyObject parent = mro[i]; if (parent instanceof PyType) { PyType parent_type =(PyType)parent; - if (parent_type.underlying_class != null || parent_type.numSlots != 0) + if (isSolidBase(parent_type)) return parent_type; } } throw Py.TypeError("base without solid base"); } - private static PyType best_base(PyObject[] bases_list) { + private static boolean isSolidBase(PyType type) { + return type.underlying_class != null || type.numSlots != 0; + } + + /** + * Finds the base in bases with the most derived solid_base, ie the most base type + * + * @throws Py.TypeError if the bases don't all derive from the same solid_base + * @throws Py.TypeError if at least one of the bases isn't a new-style class + */ + private static PyType best_base(PyObject[] bases) { PyType winner=null; PyType candidate=null; - PyType base=null; - for (int i=0; i < bases_list.length;i++) { - PyObject base_proto = bases_list[i]; + PyType best=null; + for (int i=0; i < bases.length;i++) { + PyObject base_proto = bases[i]; if (base_proto instanceof PyClass) continue; if (!(base_proto instanceof PyType)) throw Py.TypeError("bases must be types"); - PyType base_i = (PyType)base_proto; - candidate = solid_base(base_i); + PyType base = (PyType)base_proto; + candidate = solid_base(base); if (winner == null) { winner = candidate; - base = base_i; + best = base; } else if (winner.isSubType(candidate)) { ; } else if (candidate.isSubType(winner)) { winner = candidate; - base = base_i; + best = base; } else { throw Py.TypeError("multiple bases have instance lay-out conflict"); } } - if (base == null) + if (best == null) throw Py.TypeError("a new-style class can't have only classic bases"); - return base; + return best; } public static PyObject newType(PyNewWrapper new_,PyType metatype,String name,PyTuple bases,PyObject dict) { PyType object_type = fromClass(PyObject.class); PyObject[] bases_list = bases.getArray(); - PyType winner = metatype; - for (int i=0; i<bases_list.length; i++) { - PyObject bases_i = bases_list[i]; - if (bases_i instanceof PyJavaClass) - throw Py.TypeError("can't mix new-style and java classes"); - if (bases_i instanceof PyClass) { - if (((PyClass)bases_i).proxyClass != null) - throw Py.TypeError("can't mix new-style and java classes"); - continue; - } - PyType curtype = bases_i.getType(); - if (winner.isSubType(curtype)) - continue; - if (curtype.isSubType(winner)) { - winner = curtype; - continue; - } - throw Py.TypeError("metaclass conflict: "+ - "the metaclass of a derived class "+ - "must be a (non-strict) subclass "+ - "of the metaclasses of all its bases"); - } + PyType winner = findMostDerivedMetatype(bases_list, metatype); if (winner != metatype) { PyObject winner_new_ = winner.lookup("__new__"); if (winner_new_ !=null && winner_new_ != new_) { @@ -661,11 +780,7 @@ bases_list = new PyObject[] {object_type}; } - PyType base = best_base(bases_list); - // xxx can be subclassed ? - - if (dict.__finditem__("__module__") == null) { PyFrame frame = Py.getFrame(); if (frame != null) { @@ -676,7 +791,6 @@ } } } - // xxx also __doc__ __module__ PyType newtype; @@ -686,9 +800,9 @@ newtype = new PyTypeDerived(metatype); } newtype.dict = dict; - newtype.numSlots = base.numSlots; newtype.name = name; - newtype.base = base; + newtype.base = best_base(bases_list); + newtype.numSlots = newtype.base.numSlots; newtype.bases = bases_list; PyObject slots = dict.__finditem__("__slots__"); @@ -702,36 +816,19 @@ for(; (slotname = iter.__iternext__()) != null;) { addSlot(newtype, slotname); } - } } if(!newtype.needs_userdict) { - for(int i = 0; i < bases_list.length; i++) { - PyObject cur = bases_list[i]; - if((cur instanceof PyType && ((PyType)cur).needs_userdict && ((PyType)cur).numSlots > 0) - || cur instanceof PyClass) { - newtype.needs_userdict = true; - break; - } - } + newtype.needs_userdict = necessitatesUserdict(bases_list); } - - - // special case __new__, if function => static method PyObject tmp = dict.__finditem__("__new__"); if (tmp != null && tmp instanceof PyFunction) { // xxx java functions? dict.__setitem__("__new__",new PyStaticMethod(tmp)); } - newtype.mro = newtype.compute_mro(); - if(metatype.underlying_class != PyType.class - && metatype.lookup("mro") != null) { - newtype.mro = Py.make_array(metatype.lookup("mro") - .__get__(null, metatype) - .__call__(newtype)); - } + newtype.mro_internal(); // __dict__ descriptor if (newtype.needs_userdict && newtype.lookup("__dict__")==null) { dict.__setitem__("__dict__",new PyGetSetDescr(newtype,"__dict__",PyObject.class,"getDict","setDict","delDict")); @@ -739,7 +836,6 @@ newtype.has_set = newtype.lookup("__set__") != null; newtype.has_delete = newtype.lookup("__delete__") != null; - newtype.needs_finalizer = newtype.lookup("__del__") != null; for (int i=0; i<bases_list.length;i++) { @@ -750,6 +846,50 @@ return newtype; } + private static boolean necessitatesUserdict(PyObject[] bases_list) { + for(int i = 0; i < bases_list.length; i++) { + PyObject cur = bases_list[i]; + if((cur instanceof PyType && ((PyType)cur).needs_userdict && ((PyType)cur).numSlots > 0) + || cur instanceof PyClass) { + return true; + } + } + return false; + } + + /** + * Finds the most derived subtype of initialMetatype in the types of bases, or initialMetatype if + * it is already the most derived. + * + * @raises Py.TypeError if the all the metaclasses don't descend from the same base + * @raises Py.TypeError if one of the bases is a PyJavaClass or a PyClass with no proxyClass + */ + private static PyType findMostDerivedMetatype(PyObject[] bases_list, PyType initialMetatype) { + PyType winner = initialMetatype; + for (int i=0; i<bases_list.length; i++) { + PyObject bases_i = bases_list[i]; + if (bases_i instanceof PyJavaClass) + throw Py.TypeError("can't mix new-style and java classes"); + if (bases_i instanceof PyClass) { + if (((PyClass)bases_i).proxyClass != null) + throw Py.TypeError("can't mix new-style and java classes"); + continue; + } + PyType curtype = bases_i.getType(); + if (winner.isSubType(curtype)) + continue; + if (curtype.isSubType(winner)) { + winner = curtype; + continue; + } + throw Py.TypeError("metaclass conflict: "+ + "the metaclass of a derived class "+ + "must be a (non-strict) subclass "+ + "of the metaclasses of all its bases"); + } + return winner; + } + private static void addSlot(PyType newtype, PyObject slotname) { confirmIdentifier(slotname); String slotstring = mangleName(newtype.name, slotname.toString()); Modified: trunk/jython/src/templates/type.expose =================================================================== --- trunk/jython/src/templates/type.expose 2006-12-09 21:00:01 UTC (rev 3018) +++ trunk/jython/src/templates/type.expose 2006-12-10 06:36:06 UTC (rev 3019) @@ -5,7 +5,7 @@ expose_getset: __dict__ getDict setDict delDict expose_getset: __name__ fastGetName expose_getset: __base__ getBase -expose_getset: __bases__ getBases +expose_getset: __bases__ getBases setBases delBases expose_getset: __mro__ getMro # exposed methods expose_meth: :o mro o? This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <cg...@us...> - 2007-01-24 05:07:33
|
Revision: 3061 http://svn.sourceforge.net/jython/?rev=3061&view=rev Author: cgroves Date: 2007-01-23 21:07:31 -0800 (Tue, 23 Jan 2007) Log Message: ----------- handle iterators as * args Modified Paths: -------------- trunk/jython/Lib/test/output/test_extcall trunk/jython/src/org/python/core/PyObject.java Modified: trunk/jython/Lib/test/output/test_extcall =================================================================== --- trunk/jython/Lib/test/output/test_extcall 2007-01-24 02:42:33 UTC (rev 3060) +++ trunk/jython/Lib/test/output/test_extcall 2007-01-24 05:07:31 UTC (rev 3061) @@ -17,6 +17,7 @@ 1 (2, 3) {} 1 (2, 3, 4, 5) {} 0 (1, 2) {} +0 (1, 2, 3) {} 1 () {'a': 1, 'b': 2, 'c': 3, 'd': 4} {'a': 1, 'b': 2, 'c': 3} {'a': 1, 'b': 2, 'c': 3} Modified: trunk/jython/src/org/python/core/PyObject.java =================================================================== --- trunk/jython/src/org/python/core/PyObject.java 2007-01-24 02:42:33 UTC (rev 3060) +++ trunk/jython/src/org/python/core/PyObject.java 2007-01-24 05:07:31 UTC (rev 3061) @@ -2,6 +2,9 @@ package org.python.core; import java.text.MessageFormat; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; /** * All objects known to the Jython runtime system are represented @@ -699,14 +702,12 @@ } /** @deprecated **/ - public PyObject _callextra( // xxx fix, should work with iterators too - PyObject[] args, - String[] keywords, - PyObject starargs, - PyObject kwargs) { + public PyObject _callextra(PyObject[] args, + String[] keywords, + PyObject starargs, + PyObject kwargs) { int argslen = args.length; - int nstar = 0; String name = ""; if (this instanceof PyFunction) { @@ -716,9 +717,9 @@ } if (kwargs != null) { PyObject keys = kwargs.__findattr__("keys"); - if (keys == null) - throw Py.TypeError( - name + "argument after ** must be " + "a dictionary"); + if(keys == null) + throw Py.TypeError(name + + "argument after ** must be a dictionary"); for (int i = 0; i < keywords.length; i++) if (kwargs.__finditem__(keywords[i]) != null) throw Py.TypeError( @@ -729,49 +730,48 @@ + "'"); argslen += kwargs.__len__(); } - if (starargs != null) { - if (!(starargs instanceof PySequence - || starargs instanceof PyInstance)) // xxx - throw Py.TypeError( - name + "argument after * must " + "be a sequence"); - try { - nstar = starargs.__len__(); - } catch (PyException e) { - if (Py.matchException(e, Py.AttributeError)) { - throw Py.TypeError( - name + "argument after * must " + "be a sequence"); + List starObjs = null; + if(starargs != null) { + if(starargs.__findattr__("__iter__") != null){ + PyObject iter = starargs.__iter__(); + starObjs = new ArrayList(); + PyObject cur; + while((cur = iter.__iternext__()) != null) { + starObjs.add(cur); } - throw e; + } else { + try { + int nstar = starargs.__len__(); + PyObject cur; + starObjs = new ArrayList(nstar); + for(int i = 0; (cur = starargs.__finditem__(i)) != null + && i < nstar; i++) { + starObjs.add(cur); + } + } catch(PyException e) { + if(Py.matchException(e, Py.AttributeError)) { + throw Py.TypeError(name + "argument after * must " + + "be a sequence"); + } + throw e; + } } - argslen += nstar; + argslen += starObjs.size(); } - PyObject[] newargs = new PyObject[argslen]; int argidx = args.length - keywords.length; System.arraycopy(args, 0, newargs, 0, argidx); - - if (starargs != null) { - PyObject a; - try { - for (int i = 0; - (a = starargs.__finditem__(i)) != null && i < nstar; - i++) { - newargs[argidx++] = a; - } - } catch (PyException e) { - if (Py.matchException(e, Py.AttributeError)) { - throw Py.TypeError( - name + "argument after * must " + "be a sequence"); - } - throw e; + if(starObjs != null) { + Iterator it = starObjs.iterator(); + while(it.hasNext()) { + newargs[argidx++] = (PyObject)it.next(); } } - System.arraycopy( - args, - args.length - keywords.length, - newargs, - argidx, - keywords.length); + System.arraycopy(args, + args.length - keywords.length, + newargs, + argidx, + keywords.length); argidx += keywords.length; if (kwargs != null) { This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <cg...@us...> - 2007-02-06 07:09:45
|
Revision: 3090 http://svn.sourceforge.net/jython/?rev=3090&view=rev Author: cgroves Date: 2007-02-05 23:09:43 -0800 (Mon, 05 Feb 2007) Log Message: ----------- bump versions to 2.2b1 Modified Paths: -------------- trunk/jython/build.xml trunk/jython/src/org/python/core/PySystemState.java Modified: trunk/jython/build.xml =================================================================== --- trunk/jython/build.xml 2007-02-06 06:47:31 UTC (rev 3089) +++ trunk/jython/build.xml 2007-02-06 07:09:43 UTC (rev 3090) @@ -108,8 +108,8 @@ #deprecation=off # - the svn tag to build from; only needed for full-build -#svn.tag=Release_2_2alpha2 -svn.tag=HEAD +svn.tag=Release_2_2beta1 +#svn.tag=HEAD # - the revision; defaults to svn.tag; only needed for full-build # (uncomment and indicate the correct revision to do a snapshot build) @@ -380,7 +380,7 @@ <target name="version" depends="checkout" if="do.snapshot.build" > <property name="replace.value.version" value='version = "2.2a${svn.revision}"' /> <replace file="${source.dir}/org/python/core/PySystemState.java" token='version = "2.2a1"' value="${replace.value.version}" /> - <replace file="${source.dir}/org/python/core/PySystemState.java" token="PY_RELEASE_LEVEL = 0x0A" value="PY_RELEASE_LEVEL = 0xAA" /> + <replace file="${source.dir}/org/python/core/PySystemState.java" token="PY_RELEASE_LEVEL = 0x0B" value="PY_RELEASE_LEVEL = 0xAA" /> <property name="replace.value.serial" value="PY_RELEASE_SERIAL = ${svn.revision}" /> <replace file="${source.dir}/org/python/core/PySystemState.java" token="PY_RELEASE_SERIAL = 1" value="${replace.value.serial}" /> </target> Modified: trunk/jython/src/org/python/core/PySystemState.java =================================================================== --- trunk/jython/src/org/python/core/PySystemState.java 2007-02-06 06:47:31 UTC (rev 3089) +++ trunk/jython/src/org/python/core/PySystemState.java 2007-02-06 07:09:43 UTC (rev 3090) @@ -45,12 +45,12 @@ * <p> * This also applies for the <code>PY_*</code> integer values below */ - public static String version = "2.2a1"; + public static String version = "2.2b1"; private static int PY_MAJOR_VERSION = 2; private static int PY_MINOR_VERSION = 2; private static int PY_MICRO_VERSION = 0; - private static int PY_RELEASE_LEVEL = 0x0A; + private static int PY_RELEASE_LEVEL = 0x0B; private static int PY_RELEASE_SERIAL = 1; public static int hexversion = ((PY_MAJOR_VERSION << 24) | This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <cg...@us...> - 2007-02-07 07:19:54
|
Revision: 3092 http://svn.sourceforge.net/jython/?rev=3092&view=rev Author: cgroves Date: 2007-02-06 23:19:53 -0800 (Tue, 06 Feb 2007) Log Message: ----------- bump target to java 1.4, fix some version replacement issues for snapshots, set the right svn.tag and update the copyright Modified Paths: -------------- trunk/jython/build.xml trunk/jython/src/org/python/core/PySystemState.java Modified: trunk/jython/build.xml =================================================================== --- trunk/jython/build.xml 2007-02-07 07:18:20 UTC (rev 3091) +++ trunk/jython/build.xml 2007-02-07 07:19:53 UTC (rev 3092) @@ -15,7 +15,7 @@ Use case 2: full build for a release (using svn checkout) --------------------------------------------------------- - - make sure you have access to the jython subversion repository (https://svn.sourceforge.net/svnroot/jython) + - make sure you have access to the jython subversion repository (https://jython.svn.sourceforge.net/svnroot/jython/trunk) - override svn.tag in ant.properties (if necessary) - call target 'full-build' This build will create a working directory named full_build_${svn.tag} at the same @@ -67,7 +67,7 @@ 5. adjust the public static String version in PySystemState.java 6. adjust the version strings in target 'version' of this build.xml (this is for upcoming snapshot builds only) - 7, adjust the url for the cpython maintenance branch in target 'checkout' of this build.xml + 7. adjust the url for the cpython maintenance branch in target 'checkout' of this build.xml 8. check in all the changes 9. apply the new tag to the jython svn (all projects) 10. call target 'full-build' @@ -102,13 +102,13 @@ # - option for javac (build.compiler=modern is a global option to use standard jdk 1.3/1.4/1.5) #build.compiler=modern -#jdk.target.version=1.2 +#jdk.target.version=1.4 #debug=false #optimize=off #deprecation=off # - the svn tag to build from; only needed for full-build -svn.tag=Release_2_2beta1 +#svn.tag=Release_2_2beta1 #svn.tag=HEAD # - the revision; defaults to svn.tag; only needed for full-build @@ -162,8 +162,8 @@ <property file="${basedir}/ant.properties" /> <property name="build.compiler" value="modern" /> - <property name="jdk.target.version" value="1.2" /> - <property name="jdk.source.version" value="1.3" /> + <property name="jdk.target.version" value="1.4" /> + <property name="jdk.source.version" value="1.4" /> <property name="deprecation" value="off" /> <property name="debug" value="off" /> <property name="optimize" value="on" /> @@ -213,7 +213,7 @@ <property name="full-build" value="true" /> <!-- predefined tags for jython and cpython --> - <property name="svn.tag" value="HEAD" /> + <property name="svn.tag" value="Release_2_2beta1" /> <!-- revision handling --> <property name="svn.revision" value="${svn.tag}" /> @@ -364,8 +364,8 @@ </condition> <property name="svn.main.dir" value="tags/${svn.tag}" /> <svn javahl="${javahl.dir}" > - <checkout url="https://svn.sourceforge.net/svnroot/jython/${svn.main.dir}/jython" revision="${svn.revision}" destPath="${svn.checkout.dir}/jython" /> - <checkout url="https://svn.sourceforge.net/svnroot/jython/${svn.main.dir}/installer" revision="${svn.revision}" destPath="${svn.checkout.dir}/installer" /> + <checkout url="https://jython.svn.sourceforge.net/svnroot/jython/${svn.main.dir}/jython" revision="${svn.revision}" destPath="${svn.checkout.dir}/jython" /> + <checkout url="https://jython.svn.sourceforge.net/svnroot/jython/${svn.main.dir}/installer" revision="${svn.revision}" destPath="${svn.checkout.dir}/installer" /> </svn> <!-- checkout cpython license from the correct python maintenance branch --> @@ -378,8 +378,8 @@ <!-- change the version string, if so defined: used for snapshot builds --> <!-- the following replacements have to be updated if the version strings in PySystemState.java change --> <target name="version" depends="checkout" if="do.snapshot.build" > - <property name="replace.value.version" value='version = "2.2a${svn.revision}"' /> - <replace file="${source.dir}/org/python/core/PySystemState.java" token='version = "2.2a1"' value="${replace.value.version}" /> + <property name="replace.value.version" value='version = "2.2b${svn.revision}"' /> + <replace file="${source.dir}/org/python/core/PySystemState.java" token='version = "2.2b1"' value="${replace.value.version}" /> <replace file="${source.dir}/org/python/core/PySystemState.java" token="PY_RELEASE_LEVEL = 0x0B" value="PY_RELEASE_LEVEL = 0xAA" /> <property name="replace.value.serial" value="PY_RELEASE_SERIAL = ${svn.revision}" /> <replace file="${source.dir}/org/python/core/PySystemState.java" token="PY_RELEASE_SERIAL = 1" value="${replace.value.serial}" /> Modified: trunk/jython/src/org/python/core/PySystemState.java =================================================================== --- trunk/jython/src/org/python/core/PySystemState.java 2007-02-07 07:18:20 UTC (rev 3091) +++ trunk/jython/src/org/python/core/PySystemState.java 2007-02-07 07:19:53 UTC (rev 3092) @@ -68,7 +68,7 @@ */ // TBD: should we use \u00a9 Unicode c-inside-circle? public static String copyright = - "Copyright (c) 2000, Jython Developers\n" + + "Copyright (c) 2000-2007, Jython Developers\n" + "All rights reserved.\n\n" + "Copyright (c) 2000 BeOpen.com.\n" + This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <cg...@us...> - 2007-02-20 07:54:54
|
Revision: 3111 http://svn.sourceforge.net/jython/?rev=3111&view=rev Author: cgroves Date: 2007-02-19 23:54:48 -0800 (Mon, 19 Feb 2007) Log Message: ----------- Finish work to expose classmethods from the templates. new-style class classmethods now call the given method in the template with the type and any specified arguments. Get dict.fromkeys to correctly function as a classmethod that works on dict, an instance of dict and a subtype of dict. Just need to fix __cmp__ on dict and all of the fromkeys stuff in test_types will pass. Modified Paths: -------------- trunk/jython/Lib/test/test_types.py trunk/jython/src/org/python/core/PyDictionary.java trunk/jython/src/org/python/core/PyMethodDescr.java trunk/jython/src/templates/dict.expose trunk/jython/src/templates/gexpose-defs trunk/jython/src/templates/gexpose.py Added Paths: ----------- trunk/jython/src/org/python/core/PyClassMethodDescr.java Modified: trunk/jython/Lib/test/test_types.py =================================================================== --- trunk/jython/Lib/test/test_types.py 2007-02-16 05:57:23 UTC (rev 3110) +++ trunk/jython/Lib/test/test_types.py 2007-02-20 07:54:48 UTC (rev 3111) @@ -596,10 +596,9 @@ try: d.update(FailingUserDict()) except ValueError: pass else: raise TestFailed, 'dict.update(), __getitem__ expected ValueError' -#XXX fromkeys not a classmethod yet. # dict.fromkeys() -#if dict.fromkeys('abc') != {'a':None, 'b':None, 'c':None}: -# raise TestFailed, 'dict.fromkeys did not work as a class method' +if dict.fromkeys('abc') != {'a':None, 'b':None, 'c':None}: + raise TestFailed, 'dict.fromkeys did not work as a class method' d = {} if d.fromkeys('abc') is d: raise TestFailed, 'dict.fromkeys did not return a new dict' @@ -616,21 +615,19 @@ try: {}.fromkeys(3) except TypeError: pass else: raise TestFailed, 'dict.fromkeys failed to raise TypeError' -#XXX fromkeys in a subclass doesn't work yet. class dictlike(dict): pass #if dictlike.fromkeys('a') != {'a':None}: # raise TestFailed, 'dictsubclass.fromkeys did not inherit' -if dictlike().fromkeys('a') != {'a':None}: - raise TestFailed, 'dictsubclass.fromkeys did not inherit' -#if type(dictlike.fromkeys('a')) is not dictlike: -# raise TestFailed, 'dictsubclass.fromkeys created wrong type' -#if type(dictlike().fromkeys('a')) is not dictlike: -# raise TestFailed, 'dictsubclass.fromkeys created wrong type' +#if dictlike().fromkeys('a') != {'a':None}: +# raise TestFailed, 'dictsubclass.fromkeys did not inherit' +if type(dictlike.fromkeys('a')) is not dictlike: + raise TestFailed, 'dictsubclass.fromkeys created wrong type' +if type(dictlike().fromkeys('a')) is not dictlike: + raise TestFailed, 'dictsubclass.fromkeys created wrong type' from UserDict import UserDict class mydict(dict): def __new__(cls): return UserDict() -#XXX fromkeys in a subclass doesn't work yet. #ud = mydict.fromkeys('ab') #if ud != {'a':None, 'b':None} or not isinstance(ud,UserDict): # raise TestFailed, 'fromkeys did not instantiate using __new__' Added: trunk/jython/src/org/python/core/PyClassMethodDescr.java =================================================================== --- trunk/jython/src/org/python/core/PyClassMethodDescr.java (rev 0) +++ trunk/jython/src/org/python/core/PyClassMethodDescr.java 2007-02-20 07:54:48 UTC (rev 3111) @@ -0,0 +1,28 @@ +package org.python.core; + +public class PyClassMethodDescr extends PyMethodDescr { + + public PyClassMethodDescr(String name, + Class c, + int minargs, + int maxargs, + PyBuiltinFunction func) { + super(name, c, minargs, maxargs, func); + } + + protected void checkCallerType(PyObject obj) { + if((PyType)obj != dtype && !((PyType)obj).isSubType(dtype)) + throw get_wrongtype((PyType)obj); + } + + public PyObject __get__(PyObject obj, PyObject type) { + if (obj != null) { + checkCallerType(obj.getType()); + return func.makeBound(obj.getType()); + }else if(type != null){ + checkCallerType(type); + return func.makeBound(type); + } + return this; + } +} Modified: trunk/jython/src/org/python/core/PyDictionary.java =================================================================== --- trunk/jython/src/org/python/core/PyDictionary.java 2007-02-16 05:57:23 UTC (rev 3110) +++ trunk/jython/src/org/python/core/PyDictionary.java 2007-02-20 07:54:48 UTC (rev 3111) @@ -156,41 +156,31 @@ dict.__setitem__("__getitem__",new PyMethodDescr("__getitem__",PyDictionary.class,1,1,new exposed___getitem__(null,null))); class exposed_fromkeys extends PyBuiltinFunctionNarrow { - private PyDictionary self; + private PyType self; public PyObject getSelf() { return self; } - exposed_fromkeys(PyDictionary self,PyBuiltinFunction.Info info) { + exposed_fromkeys(PyType self,PyBuiltinFunction.Info info) { super(info); this.self=self; } public PyBuiltinFunction makeBound(PyObject self) { - return new exposed_fromkeys((PyDictionary)self,info); + return new exposed_fromkeys((PyType)self,info); } public PyObject __call__(PyObject arg0,PyObject arg1) { - return self.dict_fromkeys(arg0,arg1); + return dict_fromkeys(self,arg0,arg1); } - public PyObject inst_call(PyObject gself,PyObject arg0,PyObject arg1) { - PyDictionary self=(PyDictionary)gself; - return self.dict_fromkeys(arg0,arg1); - } - public PyObject __call__(PyObject arg0) { - return self.dict_fromkeys(arg0); + return dict_fromkeys(self,arg0); } - public PyObject inst_call(PyObject gself,PyObject arg0) { - PyDictionary self=(PyDictionary)gself; - return self.dict_fromkeys(arg0); - } - } - dict.__setitem__("fromkeys",new PyMethodDescr("fromkeys",PyDictionary.class,1,2,new exposed_fromkeys(null,null))); + dict.__setitem__("fromkeys",new PyClassMethodDescr("fromkeys",PyDictionary.class,1,2,new exposed_fromkeys(null,null))); class exposed_get extends PyBuiltinFunctionNarrow { private PyDictionary self; @@ -950,22 +940,22 @@ } } public PyObject fromkeys(PyObject keys) { - return dict_fromkeys(keys, null); + return fromkeys(keys, null); } public PyObject fromkeys(PyObject keys, PyObject value) { - return dict_fromkeys(keys, value); + return dict_fromkeys(PyType.fromClass(PyDictionary.class), keys, value); } - final PyObject dict_fromkeys(PyObject keys) { - return dict_fromkeys(keys, null); + final static PyObject dict_fromkeys(PyType type, PyObject keys) { + return dict_fromkeys(type, keys, null); } - final PyObject dict_fromkeys(PyObject keys, PyObject value) { + final static PyObject dict_fromkeys(PyType type, PyObject keys, PyObject value) { if (value == null) { value = Py.None; } - PyDictionary d = new PyDictionary(); + PyObject d = type.__call__(); PyIterator iter = (PyIterator)keys.__iter__(); for (PyObject o = iter.__iternext__();o != null;o = iter.__iternext__()) { d.__setitem__(o, value); Modified: trunk/jython/src/org/python/core/PyMethodDescr.java =================================================================== --- trunk/jython/src/org/python/core/PyMethodDescr.java 2007-02-16 05:57:23 UTC (rev 3110) +++ trunk/jython/src/org/python/core/PyMethodDescr.java 2007-02-20 07:54:48 UTC (rev 3111) @@ -34,27 +34,22 @@ } public PyObject __call__(PyObject[] args) { - PyObject self = args[0]; - PyType objtype = self.getType(); - if (objtype != dtype && !objtype.isSubType(dtype)) - throw call_wrongtype(objtype); - int n = args.length; - PyObject[] rest = new PyObject[n-1]; - System.arraycopy(args,1,rest,0,n-1); - return func.inst_call(self,rest); + return extractSelfAndCall(args); } public PyObject __call__(PyObject[] args, String[] kws) { - int n = args.length; if (kws.length == args.length) throw Py.TypeError(blurb()+" needs an argument"); + return extractSelfAndCall(args); + } + + private PyObject extractSelfAndCall(PyObject[] args) { PyObject self = args[0]; - PyType objtype = self.getType(); - if (objtype != dtype && !objtype.isSubType(dtype)) - throw call_wrongtype(objtype); + checkCallerType(self); + int n = args.length; PyObject[] rest = new PyObject[n-1]; System.arraycopy(args,1,rest,0,n-1); - return func.inst_call(self,rest,kws); + return func.inst_call(self,rest); } public PyObject __call__() { @@ -62,32 +57,24 @@ } public PyObject __call__(PyObject arg1) { - PyType objtype = arg1.getType(); - if (objtype != dtype && !objtype.isSubType(dtype)) - throw call_wrongtype(objtype); + checkCallerType(arg1); return func.inst_call(arg1); } public PyObject __call__(PyObject arg1, PyObject arg2) { - PyType objtype = arg1.getType(); - if (objtype != dtype && !objtype.isSubType(dtype)) - throw call_wrongtype(objtype); + checkCallerType(arg1); return func.inst_call(arg1,arg2); } public PyObject __call__(PyObject arg1, PyObject arg2, PyObject arg3) { - PyType objtype = arg1.getType(); - if (objtype != dtype && !objtype.isSubType(dtype)) - throw call_wrongtype(objtype); + checkCallerType(arg1); return func.inst_call(arg1,arg2,arg3); } public PyObject __call__(PyObject arg1, PyObject arg2, PyObject arg3, PyObject arg4) { - PyType objtype = arg1.getType(); - if (objtype != dtype && !objtype.isSubType(dtype)) - throw call_wrongtype(objtype); + checkCallerType(arg1); return func.inst_call(arg1,arg2,arg3,arg4); } @@ -97,12 +84,16 @@ public PyObject __get__(PyObject obj, PyObject type) { if (obj != null) { - PyType objtype = obj.getType(); - if (objtype != dtype && !objtype.isSubType(dtype)) - throw get_wrongtype(objtype); + checkCallerType(obj); return func.makeBound(obj); } return this; } + protected void checkCallerType(PyObject obj) { + PyType objtype = obj.getType(); + if (objtype != dtype && !objtype.isSubType(dtype)) + throw get_wrongtype(objtype); + } + } Modified: trunk/jython/src/templates/dict.expose =================================================================== --- trunk/jython/src/templates/dict.expose 2007-02-16 05:57:23 UTC (rev 3110) +++ trunk/jython/src/templates/dict.expose 2007-02-20 07:54:48 UTC (rev 3111) @@ -4,7 +4,7 @@ # exposed methods expose_binary: __ne__ __eq__ expose_vanilla_cmp: -expose_meth: fromkeys o o? +expose_cmeth: fromkeys o o? expose_key_getitem: expose_meth: get oo? expose_meth: setdefault oo? Modified: trunk/jython/src/templates/gexpose-defs =================================================================== --- trunk/jython/src/templates/gexpose-defs 2007-02-16 05:57:23 UTC (rev 3110) +++ trunk/jython/src/templates/gexpose-defs 2007-02-20 07:54:48 UTC (rev 3111) @@ -19,6 +19,11 @@ `strfy`(`name), new PyGetSetDescr(`strfy`(`name), `typ.class, `get, `set, `del)); +define: (ClassBodyDeclarations)call_cmeths args body + public PyObject __call__(`args) { + `body; + } + define: (ClassBodyDeclarations)call_meths args body public PyObject __call__(`args) { `body; @@ -28,6 +33,7 @@ `typ self = (`typ)gself; `body; } + define: expose_wide_meth class `concat`(exposed_,`name) extends PyBuiltinFunctionWide { private `typ self; @@ -99,19 +105,19 @@ define: expose_narrow_cmeth typ name minargs maxargs call_meths class `concat`(exposed_,`name) extends PyBuiltinFunctionNarrow { - private `typ self; + private PyType self; public PyObject getSelf() { return self; } - `concat`(exposed_,`name)(`typ self, PyBuiltinFunction.Info info) { + `concat`(exposed_,`name)(PyType self, PyBuiltinFunction.Info info) { super(info); this.self = self; } public PyBuiltinFunction makeBound(PyObject self) { - return new `concat`(exposed_,`name)((`typ)self, info); + return new `concat`(exposed_,`name)((PyType)self, info); } `call_meths; @@ -120,13 +126,12 @@ dict.__setitem__( `strfy`(`name), - new PyClassMethod( - new PyMethodDescr( + new PyClassMethodDescr( `strfy`(`name), `typ.class, `minargs, `maxargs, - new `concat`(exposed_,`name)(null, null)))); + new `concat`(exposed_,`name)(null, null))); define: conv_error_handling unsafe_body try { Modified: trunk/jython/src/templates/gexpose.py =================================================================== --- trunk/jython/src/templates/gexpose.py 2007-02-16 05:57:23 UTC (rev 3110) +++ trunk/jython/src/templates/gexpose.py 2007-02-20 07:54:48 UTC (rev 3111) @@ -10,7 +10,6 @@ import java_templating from java_templating import JavaTemplate,jast_make,jast, make_id, make_literal - # Some examples for modif_re # (one)two -> group 1 = "one" # group 2 = "two" @@ -24,7 +23,7 @@ # k = one character key ("o","i" and "s" in "ois") # opt = optional (the "?" in "o?") # dfl = default for optional (the "blah" in o?(blah) ) -# tg = ? (the "anything_can_go_here in o{anything_can_go_here} ) +# tg = descriptive argument name (the "I'm anything but a curly brace in o{I'm anything but a curly brace} ) ktg_re = re.compile("(?P<k>\w)(?P<opt>\?(:?\((?P<dfl>[^)]*)\))?)?(?:\{(?P<tg>[^}]*)\})?") def make_name(n): @@ -99,7 +98,6 @@ naked = False if templ_kind is None: templ_kind = 'Fragment' - templ = JavaTemplate(body, parms=':'.join(parms[1:]), bindings = self.global_bindings, @@ -358,15 +356,13 @@ self.statements.append(expose.tbind(expose_bindings)) - #XXX: First pass is a c&p and modify of dire_expose_meth: do better. def dire_expose_cmeth(self,name,parm,body): + if body is None: + body = 'return `concat`(`deleg_prefix,`name)(self,`all);' parm, prefix, body = self.expose_meth_body(name, parm, body) expose = self.get_aux('expose_narrow_cmeth') + type_class = getattr(self, 'type_class', None) - type_class = getattr(self,'type_class',None) - type_name = getattr(self,'type_name',None) - if type_class is None or type_name is None: - raise Exception,"type_class or type_name not defined" parms = parm.strip().split(None,1) if len(parms) not in (1,2): self.invalid(name,parm) @@ -382,15 +378,15 @@ body_bindings = self.global_bindings.copy() body_bindings.update(expose_bindings) - - call_meths_bindings['call_meths'] = self.get_aux('call_meths').tbind({'typ': type_class}) + call_meths_bindings['call_meths'] = self.get_aux('call_cmeths').tbind({'typ': type_class}) + inst_call_meths,minargs,maxargs = self.handle_expose_meth_sig(parms[1],call_meths_bindings,body,body_bindings) expose_bindings['call_meths'] = inst_call_meths expose_bindings['minargs'] = JavaTemplate(str(minargs)) expose_bindings['maxargs'] = JavaTemplate(str(maxargs)) - + self.statements.append(expose.tbind(expose_bindings)) def dire_expose_unary(self,name,parm,body): @@ -558,19 +554,19 @@ return typeinfo.tnaked().texpand({'basic': basic.tbind(bindings), 'setup': setup},nindent=1) -def process(fn, mergefile=None): +def process(fn, mergefile=None, lazy=False): + if lazy and mergefile and os.stat(fn).st_mtime < os.stat(mergefile).st_mtime: + return gen = Gen() directives.execute(directives.load(fn),gen) result = gen.generate() if mergefile is None: print result else: + print 'Merging %s into %s' % (fn, mergefile) result = merge(mergefile, result) #gen.debug() -def usage(): - print "Usage: python %s infile [mergefile]" % sys.argv[0] - def merge(filename, generated): in_generated = False start_found = False @@ -600,10 +596,48 @@ f.write("".join(output)) f.close() +def load_mappings(): + scriptdir = os.path.dirname(os.path.abspath(__file__)) + srcdir = os.path.dirname(scriptdir) + mappings = {} + + for line in open(os.path.join(scriptdir, 'mappings')): + if line.strip() is '' or line.startswith('#'): + continue + tmpl, klass = line.strip().split(':') + + mappings[tmpl] = (os.path.join(scriptdir, tmpl), + os.path.join(srcdir, *klass.split('.')) + '.java') + return mappings + + +def usage(): + print """Usage: python %s [--lazy|--help] <template> <outfile> + +If lazy is given, a template is only processed if its modtime is +greater than outfile. If outfile isn't specified, the outfile from +mappings for the given template is used. If template isn't given, all +templates from mappings are processed.""" % sys.argv[0] + if __name__ == '__main__': - if (len(sys.argv) < 2 or len(sys.argv) > 3): + lazy = False + if len(sys.argv) > 4: usage() - elif (len(sys.argv) == 2): - process(sys.argv[1]) - elif (len(sys.argv) == 3): - process(sys.argv[1], sys.argv[2]) + sys.exit(1) + if len(sys.argv) >= 2: + if '--help' in sys.argv: + usage() + sys.exit(0) + elif '--lazy' in sys.argv: + lazy = True + sys.argv.remove('--lazy') + mappings = load_mappings() + if len(sys.argv) == 1: + for template, mapping in mappings.items(): + if template.endswith('expose'): + process(mapping[0], mapping[1], lazy) + elif len(sys.argv) == 2: + mapping = mappings[sys.argv[1]] + process(mapping[0], mapping[1], lazy) + else: + process(sys.argv[1], sys.argv[2], lazy) This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <cg...@us...> - 2007-02-20 07:55:41
|
Revision: 3112 http://svn.sourceforge.net/jython/?rev=3112&view=rev Author: cgroves Date: 2007-02-19 23:55:39 -0800 (Mon, 19 Feb 2007) Log Message: ----------- build templates in from developer and full builds. use new --lazy flag to only build changed templates in the developer build Modified Paths: -------------- trunk/jython/build.xml trunk/jython/src/org/python/util/TemplateAntTask.java trunk/jython/src/templates/gderived.py trunk/jython/src/templates/mappings Modified: trunk/jython/build.xml =================================================================== --- trunk/jython/build.xml 2007-02-20 07:54:48 UTC (rev 3111) +++ trunk/jython/build.xml 2007-02-20 07:55:39 UTC (rev 3112) @@ -138,7 +138,7 @@ <!-- developer build --> <target name="developer-build" - depends="developer-build-called, developer-init, post-init, copy-dist" + depends="developer-build-called, developer-init, post-init, template, copy-dist" description="a local build for developers" /> @@ -204,6 +204,7 @@ <property name="templates.dir" value="${basedir}/src/templates" /> <property name="python.lib" value="${basedir}/CPythonLib" /> <property name="bugtests.dir" value="${basedir}/bugtests" /> + <property name="templates.lazy" value="true" /> </target> @@ -395,6 +396,7 @@ <!-- prepare template ant task --> <target name="template-init" depends="prepare"> + <javac srcdir="${source.dir}/" destdir="${output.dir}/" target="${jdk.target.version}" @@ -413,21 +415,8 @@ <target name="template" depends="checkout, template-init"> <taskdef name="gentempl" classname="org.python.util.TemplateAntTask" classpath="${output.dir}" /> - <gentempl mappingFile="${templates.dir}/mappings" - srcdir="${templates.dir}" - destdir="${source.dir}" - scriptdir="${templates.dir}" - verbose="true"> - <include name="*.expose" /> - <include name="*.derived" /> - - <!-- unfinished --> - <exclude name="function.expose" /> - - <!-- sequence.expose is to be used as a parent expose; extended, - but not used directly --> - <exclude name="sequence.expose" /> - </gentempl> + <gentempl srcdir="${templates.dir}" verbose="true" + lazy="${templates.lazy}"/> </target> Modified: trunk/jython/src/org/python/util/TemplateAntTask.java =================================================================== --- trunk/jython/src/org/python/util/TemplateAntTask.java 2007-02-20 07:54:48 UTC (rev 3111) +++ trunk/jython/src/org/python/util/TemplateAntTask.java 2007-02-20 07:55:39 UTC (rev 3112) @@ -1,57 +1,49 @@ /* * The Apache Software License, Version 1.1 - * - * Copyright (c) 2002 The Apache Software Foundation. All rights - * reserved. - * + * + * Copyright (c) 2002 The Apache Software Foundation. All rights reserved. + * * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in - * the documentation and/or other materials provided with the - * distribution. - * - * 3. The end-user documentation included with the redistribution, if - * any, must include the following acknowlegement: - * "This product includes software developed by the - * Apache Software Foundation (http://www.apache.org/)." - * Alternately, this acknowlegement may appear in the software itself, - * if and wherever such third-party acknowlegements normally appear. - * - * 4. The names "The Jakarta Project", "Ant", and "Apache Software - * Foundation" must not be used to endorse or promote products derived - * from this software without prior written permission. For written - * permission, please contact ap...@ap.... - * - * 5. Products derived from this software may not be called "Apache" - * nor may "Apache" appear in their names without prior written - * permission of the Apache Group. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES - * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR - * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF - * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, - * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT - * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF - * SUCH DAMAGE. + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. The end-user documentation included with the redistribution, if any, must + * include the following acknowlegement: "This product includes software + * developed by the Apache Software Foundation (http://www.apache.org/)." + * Alternately, this acknowlegement may appear in the software itself, if and + * wherever such third-party acknowlegements normally appear. + * + * 4. The names "The Jakarta Project", "Ant", and "Apache Software Foundation" + * must not be used to endorse or promote products derived from this software + * without prior written permission. For written permission, please contact + * ap...@ap.... + * + * 5. Products derived from this software may not be called "Apache" nor may + * "Apache" appear in their names without prior written permission of the Apache + * Group. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, + * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND + * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE APACHE + * SOFTWARE FOUNDATION OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, + * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, + * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * <http://www.apache.org/>. + * + * This software consists of voluntary contributions made by many individuals on + * behalf of the Apache Software Foundation. For more information on the Apache + * Software Foundation, please see <http://www.apache.org/>. */ - package org.python.util; import org.apache.tools.ant.taskdefs.MatchingTask; @@ -60,43 +52,26 @@ import org.apache.tools.ant.taskdefs.Java; import org.apache.tools.ant.types.Path; import org.apache.tools.ant.DirectoryScanner; - import java.io.File; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.FileInputStream; import java.io.Reader; import java.io.IOException; - import java.util.Map; import java.util.HashMap; /** - * Template is an Ant task for generating new-style object definitions based - * on template files. These template files come in two flavors; *.expose and + * Template is an Ant task for generating new-style object definitions based on + * template files. These template files come in two flavors; *.expose and * *.derived, both are supported by this task. - * + * * @author Matt Small - ms...@ac... * @version 1.0 */ public class TemplateAntTask extends MatchingTask { /** - * Specifies the mapping file, for template short name to Python class - * name. - */ - protected File mappingFile; - - /** - * Specifies the mapping file, for template short name to Python class - * name. - */ - public void setMappingFile(String aMappingFile) { - String amp=getProject().replaceProperties(aMappingFile); - mappingFile=new File(amp); - } - - /** * Specifies the Python interpreter. */ protected String python; @@ -105,208 +80,91 @@ * Specifies the Python interpreter. */ public void setPython(String aPE) { - python=aPE; + python = aPE; } /** - * Specifies the destination directory; this should usually be the source - * tree, as the templates modify source files in-place. - */ - protected File destdir; - - /** - * Specifies the destination directory; this should usually be the source - * tree, as the templates modify source files in-place. - */ - public void setDestdir(String in) { - destdir=new File(getProject().replaceProperties(in)); - } - - /** * Source paths. */ - protected Path src; + private File srcDir; - public Path createSrc() { - if (null==src) { - src=new Path(getProject()); - } - return src.createPath(); - } - /** * Source paths. */ - public void setSrcdir(Path srcDir) { - if (null==src) { - src=srcDir; - } else { - src.append(srcDir); - } + public void setSrcdir(String in) { + srcDir = new File(project.replaceProperties(in)); } /** - * Path to find scripts (gexpose.py & gderived.py). + * Verbose flag. */ - protected File scriptDir; + protected boolean verbose = false; /** - * Path to find scripts (gexpose.py & gderived.py). + * Verbose flag. */ - public void setScriptdir(String in) { - scriptDir=new File(getProject().replaceProperties(in)); + public void setVerbose(String in) { + verbose = (new Boolean(getProject().replaceProperties(in))).booleanValue(); } /** - * Verbose flag. + * Lazy flag. */ - protected boolean verbose=false; + protected boolean lazy = false; /** - * Verbose flag. + * Lazy flag. */ - public void setVerbose(String in) { - verbose=(new Boolean(getProject().replaceProperties(in))).booleanValue(); + public void setLazy(String in) { + lazy = (new Boolean(getProject().replaceProperties(in))).booleanValue(); } public void execute() { - if (null==mappingFile) { - throw new BuildException("no mappingFile specified"); - } else if (!mappingFile.canRead()) { - throw new BuildException("Can't read mappingFile: "+mappingFile); + if(null == srcDir) { + throw new BuildException("no srcdir specified"); + } else if(!srcDir.exists()) { + throw new BuildException("srcdir '" + srcDir + "' doesn't exist"); } - if (null==python) { - // throw new BuildException("no python executable specified"); - python="python"; + File gexposeScript = new File(srcDir.getAbsolutePath() + File.separator + + "gexpose.py"); + File gderiveScript = new File(srcDir.getAbsolutePath() + File.separator + + "gderived.py"); + if(!gexposeScript.exists()) { + throw new BuildException("no gexpose.py script found at: " + + gexposeScript); } - if (null==destdir) { - throw new BuildException("no destdir specified"); - } else if (!destdir.exists()) { - throw new BuildException("destdir '"+destdir+"' doesn't exist"); + if(!gderiveScript.exists()) { + throw new BuildException("no gderive.py script found at: " + + gderiveScript); } + runPythonScript(gexposeScript.getAbsolutePath()); + runPythonScript(gderiveScript.getAbsolutePath()); + } - Map mapping; - try { - mapping=fileToMap(mappingFile); - } catch (IOException e) { - throw new BuildException(e.toString(), e); + private void runPythonScript(String script) throws BuildException { + if(null == python) { + python = "python"; } - - if (null==scriptDir) { - throw new BuildException("no scriptdir specified"); - } else if (!scriptDir.exists()) { - throw new BuildException("scriptdir '"+scriptDir+"' doesn't exist"); + Execute e = new Execute(); + e.setWorkingDirectory(srcDir); + String[] command; + if(lazy) { + command = new String[] {python, script, "--lazy"}; + } else { + command = new String[] {python, script}; } - File gexposeScript=new File(scriptDir.getAbsolutePath()+File.separator+ - "gexpose.py"); - File gderiveScript=new File(scriptDir.getAbsolutePath()+File.separator+ - "gderived.py"); - if (!gexposeScript.exists()) { - throw new BuildException("no gexpose.py script found at: "+ - gexposeScript); - } - if (!gderiveScript.exists()) { - throw new BuildException("no gderive.py script found at: "+ - gderiveScript); - } - - - String[] list=src.list(); - for (int i=0;i<list.length;i++) { - File srcDir=getProject().resolveFile(list[i]); - if (!srcDir.exists()) { - throw new BuildException("srcDir '"+list[i]+"' does not exist"); + e.setCommandline(command); + if(verbose) { + String out = ""; + for(int k = 0; k < e.getCommandline().length; k++) { + out += (e.getCommandline()[k] + " "); } - - DirectoryScanner ds=getDirectoryScanner(srcDir); - String[] files=ds.getIncludedFiles(); - - for (int j=0;j<files.length;j++) { - // TODO - use FileNameMapper, SourceFileScanner to only update - // changed files - // - - if (null==mapping.get(files[j])) { - if (verbose) { - log("ignoring file ("+files[j]+") with no mapping"); - } - continue; - } - - String fromFile=srcDir.getAbsolutePath()+File.separator+ - files[j]; - String mapFile=(String)mapping.get(files[j]); - String mapFileName=mapFile.replace('.', File.separatorChar)+".java"; - String toFile=destdir.getAbsolutePath()+File.separator+ - mapFileName; - - if (! (new File(fromFile)).exists() ) { - throw new BuildException("source file '"+fromFile+ - "' does not exist"); - } - if (! (new File(toFile)).exists() ) { - throw new BuildException("destination file '"+toFile+ - "' (from class named "+mapFile+") does not exist"); - } - - String[] cmd; - if (fromFile.endsWith(".expose")) { - cmd=new String[] {python, gexposeScript.getAbsolutePath(), - fromFile, toFile}; - } else if (fromFile.endsWith(".derived")) { - cmd=new String[] {python, gderiveScript.getAbsolutePath(), - fromFile, toFile}; - } else { - throw new BuildException("source file: '"+fromFile+ - "' has unknown extension; expected .derived or .expose"); - } - - Execute e=new Execute(); - e.setWorkingDirectory(scriptDir); - e.setCommandline(cmd); - if (verbose) { - String out=""; - for (int k=0;k<e.getCommandline().length;k++) { - out+=(e.getCommandline()[k]+" "); - } - log("executing: "+out); - } - - try { - e.execute(); - } catch (IOException e2) { - throw new BuildException(e2.toString(), e2); - } - } + log("executing: " + out); } - } - - protected Map fileToMap (File mapFile) throws IOException, BuildException { - HashMap ret=new HashMap(); - BufferedReader in=new BufferedReader(new InputStreamReader( - new FileInputStream(mapFile))); - String line; - int idx; - String key; - String val; - - while (null!=(line=in.readLine())) { - if (line.trim().startsWith("#")) { - continue; - } else if (0==line.trim().compareTo("")) { - continue; - } - - idx=line.indexOf(":"); - if (-1==idx) { - throw new BuildException("invalid mapping syntax; no ':' on line: '"+line+"'"); - } - key=line.substring(0, idx); - val=line.substring(idx+1, line.length()); - - ret.put(key, val); + try { + e.execute(); + } catch(IOException e2) { + throw new BuildException(e2.toString(), e2); } - - return ret; } } Modified: trunk/jython/src/templates/gderived.py =================================================================== --- trunk/jython/src/templates/gderived.py 2007-02-20 07:54:48 UTC (rev 3111) +++ trunk/jython/src/templates/gderived.py 2007-02-20 07:55:39 UTC (rev 3112) @@ -177,21 +177,37 @@ derived_templ = self.get_aux('derived_class') return derived_templ.texpand({'base': self.base_class, 'decls': self.decls }) -def process(fn, outfile=sys.stdout): +def process(fn, outfile, lazy=False): + if lazy and os.stat(fn).st_mtime < os.stat(outfile).st_mtime: + return + print 'Processing %s into %s' % (fn, outfile) gen = Gen() directives.execute(directives.load(fn),gen) result = gen.generate() - print >> outfile, result + print >> open(outfile, 'w'), result #gen.debug() - -def usage(): - print "Usage: python %s infile [outfile]" % sys.argv[0] if __name__ == '__main__': - if (len(sys.argv) < 2 or len(sys.argv) > 3): + from gexpose import load_mappings, usage + lazy = False + if len(sys.argv) > 4: usage() - elif (len(sys.argv) == 2): - process(sys.argv[1]) - elif (len(sys.argv) == 3): - process(sys.argv[1], file(sys.argv[2], 'w')) + sys.exit(1) + if len(sys.argv) >= 2: + if '--help' in sys.argv: + usage() + sys.exit(0) + elif '--lazy' in sys.argv: + lazy = True + sys.argv.remove('--lazy') + if len(sys.argv) == 1: + for template, mapping in load_mappings().items(): + if template.endswith('derived'): + process(mapping[0], mapping[1], lazy) + elif len(sys.argv) == 2: + mapping = load_mappings()[sys.argv[1]] + process(mapping[0], mapping[1], lazy) + else: + process(sys.argv[1], sys.argv[2], lazy) + Modified: trunk/jython/src/templates/mappings =================================================================== --- trunk/jython/src/templates/mappings 2007-02-20 07:54:48 UTC (rev 3111) +++ trunk/jython/src/templates/mappings 2007-02-20 07:55:39 UTC (rev 3112) @@ -22,7 +22,7 @@ #file.expose:org.python.core.PyFile float.derived:org.python.core.PyFloatDerived float.expose:org.python.core.PyFloat -function.expose:org.python.core.PyFunction +#function.expose:org.python.core.PyFunction #immutableset.expose int.derived:org.python.core.PyIntegerDerived int.expose:org.python.core.PyInteger @@ -35,9 +35,9 @@ object.expose:org.python.core.PyObject property.derived:org.python.core.PyPropertyDerived property.expose:org.python.core.PyProperty -sequence.expose:org.python.core.PySequence -random.derived:org.python.modules.random.PyRandomDerived -random.expose:org.python.modules.random.PyRandom +#sequence.expose:org.python.core.PySequence +#random.derived:org.python.modules.random.PyRandomDerived +#random.expose:org.python.modules.random.PyRandom #set.expose str.expose:org.python.core.PyString str.derived:org.python.core.PyStringDerived This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <cg...@us...> - 2007-02-28 19:06:37
|
Revision: 3127 http://svn.sourceforge.net/jython/?rev=3127&view=rev Author: cgroves Date: 2007-02-28 10:55:19 -0800 (Wed, 28 Feb 2007) Log Message: ----------- Fix for bug #1659819 from Pekka Laukkanen. Makes replace and join return unicode if given unicode in their arguments Modified Paths: -------------- trunk/jython/src/org/python/core/PyString.java trunk/jython/src/org/python/core/PyUnicode.java trunk/jython/src/templates/str.expose trunk/jython/src/templates/unicode.expose Added Paths: ----------- trunk/jython/Lib/test/test_str2unicode.py Added: trunk/jython/Lib/test/test_str2unicode.py =================================================================== --- trunk/jython/Lib/test/test_str2unicode.py (rev 0) +++ trunk/jython/Lib/test/test_str2unicode.py 2007-02-28 18:55:19 UTC (rev 3127) @@ -0,0 +1,19 @@ +import unittest + +class TestStrReturnsUnicode(unittest.TestCase): + def test_join(self): + self.assertEquals(unicode, type(''.join([u'blah']))) + + def test_replace(self): + self.assertEquals(unicode, type('hello'.replace('o', u'o'))) + + +class TestStrReturnsStr(unittest.TestCase): + def test_join(self): + self.assertEquals(str, type(''.join(['blah']))) + + def test_replace(self): + self.assertEquals(str, type('hello'.replace('o', 'oo'))) + +if __name__ == '__main__': + unittest.main() Modified: trunk/jython/src/org/python/core/PyString.java =================================================================== --- trunk/jython/src/org/python/core/PyString.java 2007-02-28 18:52:43 UTC (rev 3126) +++ trunk/jython/src/org/python/core/PyString.java 2007-02-28 18:55:19 UTC (rev 3127) @@ -879,13 +879,7 @@ } public PyObject __call__(PyObject arg0) { - String result=((PyString)self).str_join(arg0); - //XXX: do we really need to check self? - if (self instanceof PyUnicode||arg0 instanceof PyUnicode) { - return new PyUnicode(result); - } else { - return new PyString(result); - } + return((PyString)self).str_join(arg0); } } @@ -978,17 +972,13 @@ public PyObject __call__(PyObject arg0,PyObject arg1,PyObject arg2) { try { - return new PyString(((PyString)self).str_replace(arg0.asString(0),arg1.asString(1),arg2.asInt(2))); + return((PyString)self).str_replace(arg0,arg1,arg2.asInt(2)); } catch (PyObject.ConversionException e) { String msg; switch (e.index) { case 2: msg="expected an integer"; break; - case 0: - case 1: - msg="expected a string"; - break; default: msg="xxx"; } @@ -997,20 +987,7 @@ } public PyObject __call__(PyObject arg0,PyObject arg1) { - try { - return new PyString(((PyString)self).str_replace(arg0.asString(0),arg1.asString(1))); - } catch (PyObject.ConversionException e) { - String msg; - switch (e.index) { - case 0: - case 1: - msg="expected a string"; - break; - default: - msg="xxx"; - } - throw Py.TypeError(msg); - } + return((PyString)self).str_replace(arg0,arg1); } } @@ -2981,42 +2958,45 @@ return first.concat(string.substring(1).toLowerCase()); } - public String replace(String oldPiece, String newPiece) { - return str_replace(oldPiece, newPiece); - } - - final String str_replace(String oldPiece, String newPiece) { + final PyString str_replace(PyObject oldPiece, PyObject newPiece) { return str_replace(oldPiece, newPiece, string.length()); } - - public String replace(String oldPiece, String newPiece, int maxsplit) { - return str_replace(oldPiece, newPiece, maxsplit); + + final PyString str_replace(PyObject oldPiece, PyObject newPiece, int maxsplit) { + if(!(oldPiece instanceof PyString) || !(newPiece instanceof PyString)){ + throw Py.TypeError("str or unicode required for replace"); + } + return ((PyString)newPiece).str_join(str_split(((PyString)oldPiece).string, maxsplit)); } - final String str_replace(String oldPiece, String newPiece, int maxsplit) { - PyString newstr = createInstance(newPiece); - return newstr.join(split(oldPiece, maxsplit)); - } - public String join(PyObject seq) { - return str_join(seq); + return str_join(seq).string; } - final String str_join(PyObject seq) { + final PyString str_join(PyObject seq) { StringBuffer buf = new StringBuffer(); PyObject iter = seq.__iter__(); PyObject obj = null; + boolean needsUnicode = false; for (int i = 0; (obj = iter.__iternext__()) != null; i++) { - if (!(obj instanceof PyString)) + if (!(obj instanceof PyString)){ throw Py.TypeError( "sequence item " + i + ": expected string, " + obj.safeRepr() + " found"); - if (i > 0) + } + if(obj instanceof PyUnicode){ + needsUnicode = true; + } + if (i > 0){ buf.append(string); + } buf.append(obj.__str__()); } - return buf.toString(); + if(needsUnicode || this instanceof PyUnicode){ + return new PyUnicode(buf.toString()); + } + return new PyString(buf.toString()); } Modified: trunk/jython/src/org/python/core/PyUnicode.java =================================================================== --- trunk/jython/src/org/python/core/PyUnicode.java 2007-02-28 18:52:43 UTC (rev 3126) +++ trunk/jython/src/org/python/core/PyUnicode.java 2007-02-28 18:55:19 UTC (rev 3127) @@ -943,17 +943,13 @@ public PyObject __call__(PyObject arg0,PyObject arg1,PyObject arg2) { try { - return new PyUnicode(((PyUnicode)self).unicode_replace(arg0.asString(0),arg1.asString(1),arg2.asInt(2))); + return((PyUnicode)self).unicode_replace(arg0,arg1,arg2.asInt(2)); } catch (PyObject.ConversionException e) { String msg; switch (e.index) { case 2: msg="expected an integer"; break; - case 0: - case 1: - msg="expected a string"; - break; default: msg="xxx"; } @@ -962,20 +958,7 @@ } public PyObject __call__(PyObject arg0,PyObject arg1) { - try { - return new PyUnicode(((PyUnicode)self).unicode_replace(arg0.asString(0),arg1.asString(1))); - } catch (PyObject.ConversionException e) { - String msg; - switch (e.index) { - case 0: - case 1: - msg="expected a string"; - break; - default: - msg="xxx"; - } - throw Py.TypeError(msg); - } + return((PyUnicode)self).unicode_replace(arg0,arg1); } } @@ -1710,15 +1693,15 @@ return str_capitalize(); } - final String unicode_replace(String oldPiece, String newPiece) { + final PyObject unicode_replace(PyObject oldPiece, PyObject newPiece) { return str_replace(oldPiece, newPiece); } - final String unicode_replace(String oldPiece, String newPiece, int maxsplit) { + final PyObject unicode_replace(PyObject oldPiece, PyObject newPiece, int maxsplit) { return str_replace(oldPiece, newPiece, maxsplit); } - final String unicode_join(PyObject seq) { + final PyString unicode_join(PyObject seq) { return str_join(seq); } Modified: trunk/jython/src/templates/str.expose =================================================================== --- trunk/jython/src/templates/str.expose 2007-02-28 18:52:43 UTC (rev 3126) +++ trunk/jython/src/templates/str.expose 2007-02-28 18:55:19 UTC (rev 3127) @@ -39,17 +39,10 @@ expose_meth: :b isunicode expose_meth: :b isupper expose_meth: join o - String result = ((PyString)self).str_join(arg0); - //XXX: do we really need to check self? - if (self instanceof PyUnicode || arg0 instanceof PyUnicode) { - return new PyUnicode(result); - } else { - return new PyString(result); - } expose_meth: :s ljust i expose_meth: :s lower expose_meth: :s lstrip S? -expose_meth: :s replace s s i? +expose_meth: replace o o i? expose_meth: :i rfind s i? i? expose_meth: :i rindex s i? i? expose_meth: :s rjust i Modified: trunk/jython/src/templates/unicode.expose =================================================================== --- trunk/jython/src/templates/unicode.expose 2007-02-28 18:52:43 UTC (rev 3126) +++ trunk/jython/src/templates/unicode.expose 2007-02-28 18:55:19 UTC (rev 3127) @@ -40,7 +40,7 @@ expose_meth: :u ljust i expose_meth: :u lower expose_meth: :u lstrip S? -expose_meth: :u replace s s i? +expose_meth: replace o o i? expose_meth: :i rfind s i? i? expose_meth: :i rindex s i? i? expose_meth: :u rjust i This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <cg...@us...> - 2007-03-09 17:20:34
|
Revision: 3135 http://svn.sourceforge.net/jython/?rev=3135&view=rev Author: cgroves Date: 2007-03-09 09:20:29 -0800 (Fri, 09 Mar 2007) Log Message: ----------- >From patch #1671304 for bug #1671134 from Pekka Laukkanen. Returns unicode from '%s' % u'x' and other usages of string formatting with unicode arguments Modified Paths: -------------- trunk/jython/Lib/test/test_str2unicode.py trunk/jython/src/org/python/core/PyString.java trunk/jython/src/org/python/core/PyUnicode.java Modified: trunk/jython/Lib/test/test_str2unicode.py =================================================================== --- trunk/jython/Lib/test/test_str2unicode.py 2007-03-02 07:20:08 UTC (rev 3134) +++ trunk/jython/Lib/test/test_str2unicode.py 2007-03-09 17:20:29 UTC (rev 3135) @@ -1,19 +1,90 @@ import unittest + class TestStrReturnsUnicode(unittest.TestCase): + def test_join(self): - self.assertEquals(unicode, type(''.join([u'blah']))) + self.assertEquals(unicode, type(''.join([u'blah']))) def test_replace(self): - self.assertEquals(unicode, type('hello'.replace('o', u'o'))) + self.assertEquals(unicode, type('hello'.replace('o', u'o'))) + def test_string_formatting_s(self): + self.assertEquals(unicode, type('%s' % u'x')) + self.assertEquals(unicode, type('%s %s' % (u'x', 'y'))) + self.assertEquals(unicode, type('%(x)s' % {'x' : u'x'})) + def test_string_formatting_r(self): + self.assertEquals(unicode, type('%r' % u'x')) + self.assertEquals(unicode, type('%r %r' % (u'x', 'y'))) + self.assertEquals(unicode, type('%(x)r' % {'x' : u'x'})) + + def test_string_formatting_c(self): + self.assertEquals(unicode, type('%c' % u'x')) + self.assertEquals(unicode, type('%c %c' % (u'x', 'y'))) + self.assertEquals(unicode, type('%(x)c' % {'x' : u'x'})) + + class TestStrReturnsStr(unittest.TestCase): + def test_join(self): - self.assertEquals(str, type(''.join(['blah']))) + self.assertEquals(str, type(''.join(['blah']))) def test_replace(self): - self.assertEquals(str, type('hello'.replace('o', 'oo'))) + self.assertEquals(str, type('hello'.replace('o', 'oo'))) + def test_string_formatting_s(self): + self.assertEquals(str, type('%s' % 'x')) + self.assertEquals(str, type('%s %s' % ('x', 'y'))) + self.assertEquals(str, type('%(x)s' % {'x' : 'xxx'})) + + def test_string_formatting_r(self): + self.assertEquals(str, type('%r' % 'x')) + self.assertEquals(str, type('%r %r' % ('x', 'y'))) + self.assertEquals(str, type('%(x)r' % {'x' : 'x'})) + + def test_string_formatting_c(self): + self.assertEquals(str, type('%c' % 'x')) + self.assertEquals(str, type('%c %c' % ('x', 'y'))) + self.assertEquals(str, type('%(x)c' % {'x' : 'x'})) + + +class TestUnicodeReturnsUnicode(unittest.TestCase): + + def test_join(self): + self.assertEquals(unicode, type(u''.join([u'blah']))) + self.assertEquals(unicode, type(u''.join(['blah']))) + + def test_replace(self): + self.assertEquals(unicode, type(u'hello'.replace('o', u'o'))) + self.assertEquals(unicode, type(u'hello'.replace(u'o', 'o'))) + self.assertEquals(unicode, type(u'hello'.replace(u'o', u'o'))) + self.assertEquals(unicode, type(u'hello'.replace('o', 'o'))) + + def test_string_formatting_s(self): + self.assertEquals(unicode, type(u'%s' % u'x')) + self.assertEquals(unicode, type(u'%s' % 'x')) + self.assertEquals(unicode, type(u'%s %s' % (u'x', 'y'))) + self.assertEquals(unicode, type(u'%s %s' % ('x', 'y'))) + self.assertEquals(unicode, type(u'%(x)s' % {'x' : u'x'})) + self.assertEquals(unicode, type(u'%(x)s' % {'x' : 'x'})) + + def test_string_formatting_r(self): + self.assertEquals(unicode, type(u'%r' % u'x')) + self.assertEquals(unicode, type(u'%r' % 'x')) + self.assertEquals(unicode, type(u'%r %r' % (u'x', 'y'))) + self.assertEquals(unicode, type(u'%r %r' % ('x', 'y'))) + self.assertEquals(unicode, type(u'%(x)r' % {'x' : u'x'})) + self.assertEquals(unicode, type(u'%(x)r' % {'x' : 'x'})) + + def test_string_formatting_c(self): + self.assertEquals(unicode, type(u'%c' % u'x')) + self.assertEquals(unicode, type(u'%c' % 'x')) + self.assertEquals(unicode, type(u'%c %c' % (u'x', 'y'))) + self.assertEquals(unicode, type(u'%c %c' % ('x', 'y'))) + self.assertEquals(unicode, type(u'%(x)c' % {'x' : u'x'})) + self.assertEquals(unicode, type(u'%(x)c' % {'x' : 'x'})) + + if __name__ == '__main__': unittest.main() Modified: trunk/jython/src/org/python/core/PyString.java =================================================================== --- trunk/jython/src/org/python/core/PyString.java 2007-03-02 07:20:08 UTC (rev 3134) +++ trunk/jython/src/org/python/core/PyString.java 2007-03-09 17:20:29 UTC (rev 3135) @@ -2045,7 +2045,7 @@ public PyObject str___mod__(PyObject other){ StringFormatter fmt = new StringFormatter(string); - return createInstance(fmt.format(other)); + return fmt.format(other); } public PyObject __int__() { @@ -3535,7 +3535,7 @@ } - public String formatLong(PyString arg, char type, boolean altFlag) { + private String formatLong(PyString arg, char type, boolean altFlag) { checkPrecision("long"); String s = arg.toString(); int end = s.length(); @@ -3589,11 +3589,11 @@ return s; } - public String formatInteger(PyObject arg, int radix, boolean unsigned) { + private String formatInteger(PyObject arg, int radix, boolean unsigned) { return formatInteger(((PyInteger)arg.__int__()).getValue(), radix, unsigned); } - public String formatInteger(long v, int radix, boolean unsigned) { + private String formatInteger(long v, int radix, boolean unsigned) { checkPrecision("integer"); if (unsigned) { if (v < 0) @@ -3611,11 +3611,11 @@ return s; } - public String formatFloatDecimal(PyObject arg, boolean truncate) { + private String formatFloatDecimal(PyObject arg, boolean truncate) { return formatFloatDecimal(arg.__float__().getValue(), truncate); } - public String formatFloatDecimal(double v, boolean truncate) { + private String formatFloatDecimal(double v, boolean truncate) { checkPrecision("decimal"); java.text.NumberFormat format = java.text.NumberFormat.getInstance( java.util.Locale.US); @@ -3638,7 +3638,7 @@ return ret; } - public String formatFloatExponential(PyObject arg, char e, + private String formatFloatExponential(PyObject arg, char e, boolean truncate) { StringBuffer buf = new StringBuffer(); @@ -3681,9 +3681,10 @@ return buf.toString(); } - public String format(PyObject args) { + public PyString format(PyObject args) { PyObject dict = null; this.args = args; + boolean needUnicode = false; if (args instanceof PyTuple) { argIndex = 0; } else { @@ -3786,6 +3787,9 @@ if (precision >= 0 && string.length() > precision) { string = string.substring(0, precision); } + if (arg instanceof PyUnicode) { + needUnicode = true; + } break; case 'i': case 'd': @@ -3877,6 +3881,9 @@ string = ((PyString)arg).toString(); if (string.length() != 1) throw Py.TypeError("%c requires int or char"); + if (arg instanceof PyUnicode) { + needUnicode = true; + } break; } char tmp = (char)((PyInteger)arg.__int__()).getValue(); @@ -3949,7 +3956,10 @@ { throw Py.TypeError("not all arguments converted"); } - return buffer.toString(); + if (needUnicode) { + return new PyUnicode(buffer.toString()); + } + return new PyString(buffer.toString()); } } Modified: trunk/jython/src/org/python/core/PyUnicode.java =================================================================== --- trunk/jython/src/org/python/core/PyUnicode.java 2007-03-02 07:20:08 UTC (rev 3134) +++ trunk/jython/src/org/python/core/PyUnicode.java 2007-03-09 17:20:29 UTC (rev 3135) @@ -1483,6 +1483,10 @@ return new PyUnicode(str); } + public PyObject __mod__(PyObject other) { + return str___mod__(other).__unicode__(); + } + final PyUnicode unicode___unicode__() { return str___unicode__(); } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <cg...@us...> - 2007-03-09 17:23:05
|
Revision: 3136 http://svn.sourceforge.net/jython/?rev=3136&view=rev Author: cgroves Date: 2007-03-09 09:23:03 -0800 (Fri, 09 Mar 2007) Log Message: ----------- >From patch #1672800 from Philip Jenvey. Makes __import__('module', None) work. Modified Paths: -------------- trunk/jython/Lib/test/test_importhooks.py trunk/jython/src/org/python/core/imp.java Modified: trunk/jython/Lib/test/test_importhooks.py =================================================================== --- trunk/jython/Lib/test/test_importhooks.py 2007-03-09 17:20:29 UTC (rev 3135) +++ trunk/jython/Lib/test/test_importhooks.py 2007-03-09 17:23:03 UTC (rev 3136) @@ -186,7 +186,7 @@ else: self.fail("'%s' was not supposed to be importable" % mname) - def testImpWrapper(self): + def doTestImpWrapper(self, globals_func=globals, locals_func=locals): i = ImpWrapper() sys.meta_path.append(i) sys.path_hooks.append(ImpWrapper) @@ -198,9 +198,15 @@ if n.startswith(parent): del sys.modules[n] for mname in mnames: - m = __import__(mname, globals(), locals(), ["__dummy__"]) + m = __import__(mname, globals_func(), locals_func(), ["__dummy__"]) m.__loader__ # to make sure we actually handled the import + def testImpWrapper(self): + self.doTestImpWrapper() + + def testImpWrapperNoContext(self): + self.doTestImpWrapper(lambda: None, lambda: None) + def test_main(): test_support.run_unittest(ImportHooksTestCase) Modified: trunk/jython/src/org/python/core/imp.java =================================================================== --- trunk/jython/src/org/python/core/imp.java 2007-03-09 17:20:29 UTC (rev 3135) +++ trunk/jython/src/org/python/core/imp.java 2007-03-09 17:23:03 UTC (rev 3136) @@ -636,7 +636,7 @@ PyObject modules = Py.getSystemState().modules; PyObject pkgMod = null; String pkgName = null; - if (modDict != null) { + if (modDict != null && !(modDict instanceof PyNone)) { pkgName = getParent(modDict); pkgMod = modules.__finditem__(pkgName); // System.err.println("GetParent: " + pkgName + " => " + pkgMod); This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <cg...@us...> - 2007-04-13 06:37:56
|
Revision: 3150 http://svn.sourceforge.net/jython/?rev=3150&view=rev Author: cgroves Date: 2007-04-12 23:37:55 -0700 (Thu, 12 Apr 2007) Log Message: ----------- Exposed rich comparison methods to fix bugs 1658688, 1658687, 1658685, and 1658683 Modified Paths: -------------- trunk/jython/Lib/test/test_descrtut.py trunk/jython/src/org/python/core/PyArray.java trunk/jython/src/org/python/core/PyDictionary.java trunk/jython/src/org/python/core/PyList.java trunk/jython/src/org/python/core/PySequence.java trunk/jython/src/org/python/core/PyString.java trunk/jython/src/org/python/core/PyTuple.java trunk/jython/src/templates/dict.expose trunk/jython/src/templates/sequence.expose trunk/jython/src/templates/str.expose trunk/jython/src/templates/tuple.expose Modified: trunk/jython/Lib/test/test_descrtut.py =================================================================== --- trunk/jython/Lib/test/test_descrtut.py 2007-04-13 06:36:46 UTC (rev 3149) +++ trunk/jython/Lib/test/test_descrtut.py 2007-04-13 06:37:55 UTC (rev 3150) @@ -189,14 +189,18 @@ '__delslice__', '__doc__', '__eq__', + '__ge__', '__getattribute__', '__getitem__', '__getslice__', + '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', + '__le__', '__len__', + '__lt__', '__mul__', '__ne__', '__new__', Modified: trunk/jython/src/org/python/core/PyArray.java =================================================================== --- trunk/jython/src/org/python/core/PyArray.java 2007-04-13 06:36:46 UTC (rev 3149) +++ trunk/jython/src/org/python/core/PyArray.java 2007-04-13 06:37:55 UTC (rev 3150) @@ -67,6 +67,82 @@ } dict.__setitem__("__eq__",new PyMethodDescr("__eq__",PyArray.class,1,1,new exposed___eq__(null,null))); + class exposed___lt__ extends PyBuiltinMethodNarrow { + + exposed___lt__(PyObject self,PyBuiltinFunction.Info info) { + super(self,info); + } + + public PyBuiltinFunction bind(PyObject self) { + return new exposed___lt__(self,info); + } + + public PyObject __call__(PyObject arg0) { + PyObject ret=((PyArray)self).seq___lt__(arg0); + if (ret==null) + return Py.NotImplemented; + return ret; + } + + } + dict.__setitem__("__lt__",new PyMethodDescr("__lt__",PyArray.class,1,1,new exposed___lt__(null,null))); + class exposed___le__ extends PyBuiltinMethodNarrow { + + exposed___le__(PyObject self,PyBuiltinFunction.Info info) { + super(self,info); + } + + public PyBuiltinFunction bind(PyObject self) { + return new exposed___le__(self,info); + } + + public PyObject __call__(PyObject arg0) { + PyObject ret=((PyArray)self).seq___le__(arg0); + if (ret==null) + return Py.NotImplemented; + return ret; + } + + } + dict.__setitem__("__le__",new PyMethodDescr("__le__",PyArray.class,1,1,new exposed___le__(null,null))); + class exposed___gt__ extends PyBuiltinMethodNarrow { + + exposed___gt__(PyObject self,PyBuiltinFunction.Info info) { + super(self,info); + } + + public PyBuiltinFunction bind(PyObject self) { + return new exposed___gt__(self,info); + } + + public PyObject __call__(PyObject arg0) { + PyObject ret=((PyArray)self).seq___gt__(arg0); + if (ret==null) + return Py.NotImplemented; + return ret; + } + + } + dict.__setitem__("__gt__",new PyMethodDescr("__gt__",PyArray.class,1,1,new exposed___gt__(null,null))); + class exposed___ge__ extends PyBuiltinMethodNarrow { + + exposed___ge__(PyObject self,PyBuiltinFunction.Info info) { + super(self,info); + } + + public PyBuiltinFunction bind(PyObject self) { + return new exposed___ge__(self,info); + } + + public PyObject __call__(PyObject arg0) { + PyObject ret=((PyArray)self).seq___ge__(arg0); + if (ret==null) + return Py.NotImplemented; + return ret; + } + + } + dict.__setitem__("__ge__",new PyMethodDescr("__ge__",PyArray.class,1,1,new exposed___ge__(null,null))); class exposed___getitem__ extends PyBuiltinMethodNarrow { exposed___getitem__(PyObject self,PyBuiltinFunction.Info info) { Modified: trunk/jython/src/org/python/core/PyDictionary.java =================================================================== --- trunk/jython/src/org/python/core/PyDictionary.java 2007-04-13 06:36:46 UTC (rev 3149) +++ trunk/jython/src/org/python/core/PyDictionary.java 2007-04-13 06:37:55 UTC (rev 3150) @@ -54,6 +54,82 @@ } dict.__setitem__("__eq__",new PyMethodDescr("__eq__",PyDictionary.class,1,1,new exposed___eq__(null,null))); + class exposed___lt__ extends PyBuiltinMethodNarrow { + + exposed___lt__(PyObject self,PyBuiltinFunction.Info info) { + super(self,info); + } + + public PyBuiltinFunction bind(PyObject self) { + return new exposed___lt__(self,info); + } + + public PyObject __call__(PyObject arg0) { + PyObject ret=((PyDictionary)self).dict___lt__(arg0); + if (ret==null) + return Py.NotImplemented; + return ret; + } + + } + dict.__setitem__("__lt__",new PyMethodDescr("__lt__",PyDictionary.class,1,1,new exposed___lt__(null,null))); + class exposed___gt__ extends PyBuiltinMethodNarrow { + + exposed___gt__(PyObject self,PyBuiltinFunction.Info info) { + super(self,info); + } + + public PyBuiltinFunction bind(PyObject self) { + return new exposed___gt__(self,info); + } + + public PyObject __call__(PyObject arg0) { + PyObject ret=((PyDictionary)self).dict___gt__(arg0); + if (ret==null) + return Py.NotImplemented; + return ret; + } + + } + dict.__setitem__("__gt__",new PyMethodDescr("__gt__",PyDictionary.class,1,1,new exposed___gt__(null,null))); + class exposed___ge__ extends PyBuiltinMethodNarrow { + + exposed___ge__(PyObject self,PyBuiltinFunction.Info info) { + super(self,info); + } + + public PyBuiltinFunction bind(PyObject self) { + return new exposed___ge__(self,info); + } + + public PyObject __call__(PyObject arg0) { + PyObject ret=((PyDictionary)self).dict___ge__(arg0); + if (ret==null) + return Py.NotImplemented; + return ret; + } + + } + dict.__setitem__("__ge__",new PyMethodDescr("__ge__",PyDictionary.class,1,1,new exposed___ge__(null,null))); + class exposed___le__ extends PyBuiltinMethodNarrow { + + exposed___le__(PyObject self,PyBuiltinFunction.Info info) { + super(self,info); + } + + public PyBuiltinFunction bind(PyObject self) { + return new exposed___le__(self,info); + } + + public PyObject __call__(PyObject arg0) { + PyObject ret=((PyDictionary)self).dict___le__(arg0); + if (ret==null) + return Py.NotImplemented; + return ret; + } + + } + dict.__setitem__("__le__",new PyMethodDescr("__le__",PyDictionary.class,1,1,new exposed___le__(null,null))); class exposed___cmp__ extends PyBuiltinMethodNarrow { exposed___cmp__(PyObject self,PyBuiltinFunction.Info info) { @@ -735,6 +811,38 @@ if (eq_result == null) return null; return eq_result == Py.One?Py.Zero:Py.One; } + + final PyObject dict___lt__(PyObject ob_other){ + int result = __cmp__(ob_other); + if(result == -2){ + return null; + } + return result < 0 ? Py.One : Py.Zero; + } + + final PyObject dict___gt__(PyObject ob_other){ + int result = __cmp__(ob_other); + if(result == -2){ + return null; + } + return result > 0 ? Py.One : Py.Zero; + } + + final PyObject dict___le__(PyObject ob_other){ + int result = __cmp__(ob_other); + if(result == -2){ + return null; + } + return result <= 0 ? Py.One : Py.Zero; + } + + final PyObject dict___ge__(PyObject ob_other){ + int result = __cmp__(ob_other); + if(result == -2){ + return null; + } + return result >= 0 ? Py.One : Py.Zero; + } public int __cmp__(PyObject ob_other) { return dict___cmp__(ob_other); Modified: trunk/jython/src/org/python/core/PyList.java =================================================================== --- trunk/jython/src/org/python/core/PyList.java 2007-04-13 06:36:46 UTC (rev 3149) +++ trunk/jython/src/org/python/core/PyList.java 2007-04-13 06:37:55 UTC (rev 3150) @@ -62,6 +62,82 @@ } dict.__setitem__("__eq__",new PyMethodDescr("__eq__",PyList.class,1,1,new exposed___eq__(null,null))); + class exposed___lt__ extends PyBuiltinMethodNarrow { + + exposed___lt__(PyObject self,PyBuiltinFunction.Info info) { + super(self,info); + } + + public PyBuiltinFunction bind(PyObject self) { + return new exposed___lt__(self,info); + } + + public PyObject __call__(PyObject arg0) { + PyObject ret=((PyList)self).seq___lt__(arg0); + if (ret==null) + return Py.NotImplemented; + return ret; + } + + } + dict.__setitem__("__lt__",new PyMethodDescr("__lt__",PyList.class,1,1,new exposed___lt__(null,null))); + class exposed___le__ extends PyBuiltinMethodNarrow { + + exposed___le__(PyObject self,PyBuiltinFunction.Info info) { + super(self,info); + } + + public PyBuiltinFunction bind(PyObject self) { + return new exposed___le__(self,info); + } + + public PyObject __call__(PyObject arg0) { + PyObject ret=((PyList)self).seq___le__(arg0); + if (ret==null) + return Py.NotImplemented; + return ret; + } + + } + dict.__setitem__("__le__",new PyMethodDescr("__le__",PyList.class,1,1,new exposed___le__(null,null))); + class exposed___gt__ extends PyBuiltinMethodNarrow { + + exposed___gt__(PyObject self,PyBuiltinFunction.Info info) { + super(self,info); + } + + public PyBuiltinFunction bind(PyObject self) { + return new exposed___gt__(self,info); + } + + public PyObject __call__(PyObject arg0) { + PyObject ret=((PyList)self).seq___gt__(arg0); + if (ret==null) + return Py.NotImplemented; + return ret; + } + + } + dict.__setitem__("__gt__",new PyMethodDescr("__gt__",PyList.class,1,1,new exposed___gt__(null,null))); + class exposed___ge__ extends PyBuiltinMethodNarrow { + + exposed___ge__(PyObject self,PyBuiltinFunction.Info info) { + super(self,info); + } + + public PyBuiltinFunction bind(PyObject self) { + return new exposed___ge__(self,info); + } + + public PyObject __call__(PyObject arg0) { + PyObject ret=((PyList)self).seq___ge__(arg0); + if (ret==null) + return Py.NotImplemented; + return ret; + } + + } + dict.__setitem__("__ge__",new PyMethodDescr("__ge__",PyList.class,1,1,new exposed___ge__(null,null))); class exposed___getitem__ extends PyBuiltinMethodNarrow { exposed___getitem__(PyObject self,PyBuiltinFunction.Info info) { Modified: trunk/jython/src/org/python/core/PySequence.java =================================================================== --- trunk/jython/src/org/python/core/PySequence.java 2007-04-13 06:36:46 UTC (rev 3149) +++ trunk/jython/src/org/python/core/PySequence.java 2007-04-13 06:37:55 UTC (rev 3150) @@ -137,6 +137,10 @@ return (i == -1) ? Py.One : Py.Zero; return __finditem__(i)._lt(o.__finditem__(i)); } + + final synchronized PyObject seq___lt__(PyObject o){ + return __lt__(o); + } public synchronized PyObject __le__(PyObject o) { if (!(getType() == o.getType()) && !(getType().isSubType(o.getType()))) { @@ -147,6 +151,10 @@ 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); + } public synchronized PyObject __gt__(PyObject o) { if (!(getType() == o.getType()) && !(getType().isSubType(o.getType()))) { @@ -157,6 +165,10 @@ return (i == -3) ? Py.One : Py.Zero; return __finditem__(i)._gt(o.__finditem__(i)); } + + final synchronized PyObject seq___gt__(PyObject o){ + return __gt__(o); + } public synchronized PyObject __ge__(PyObject o) { if (!(getType() == o.getType()) && !(getType().isSubType(o.getType()))) { @@ -167,6 +179,10 @@ 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); + } // Return value >= 0 is the index where the sequences differs. // -1: reached the end of o1 without a difference Modified: trunk/jython/src/org/python/core/PyString.java =================================================================== --- trunk/jython/src/org/python/core/PyString.java 2007-04-13 06:36:46 UTC (rev 3149) +++ trunk/jython/src/org/python/core/PyString.java 2007-04-13 06:37:55 UTC (rev 3150) @@ -50,6 +50,82 @@ } dict.__setitem__("__eq__",new PyMethodDescr("__eq__",PyString.class,1,1,new exposed___eq__(null,null))); + class exposed___lt__ extends PyBuiltinMethodNarrow { + + exposed___lt__(PyObject self,PyBuiltinFunction.Info info) { + super(self,info); + } + + public PyBuiltinFunction bind(PyObject self) { + return new exposed___lt__(self,info); + } + + public PyObject __call__(PyObject arg0) { + PyObject ret=((PyString)self).str___lt__(arg0); + if (ret==null) + return Py.NotImplemented; + return ret; + } + + } + dict.__setitem__("__lt__",new PyMethodDescr("__lt__",PyString.class,1,1,new exposed___lt__(null,null))); + class exposed___le__ extends PyBuiltinMethodNarrow { + + exposed___le__(PyObject self,PyBuiltinFunction.Info info) { + super(self,info); + } + + public PyBuiltinFunction bind(PyObject self) { + return new exposed___le__(self,info); + } + + public PyObject __call__(PyObject arg0) { + PyObject ret=((PyString)self).str___le__(arg0); + if (ret==null) + return Py.NotImplemented; + return ret; + } + + } + dict.__setitem__("__le__",new PyMethodDescr("__le__",PyString.class,1,1,new exposed___le__(null,null))); + class exposed___gt__ extends PyBuiltinMethodNarrow { + + exposed___gt__(PyObject self,PyBuiltinFunction.Info info) { + super(self,info); + } + + public PyBuiltinFunction bind(PyObject self) { + return new exposed___gt__(self,info); + } + + public PyObject __call__(PyObject arg0) { + PyObject ret=((PyString)self).str___gt__(arg0); + if (ret==null) + return Py.NotImplemented; + return ret; + } + + } + dict.__setitem__("__gt__",new PyMethodDescr("__gt__",PyString.class,1,1,new exposed___gt__(null,null))); + class exposed___ge__ extends PyBuiltinMethodNarrow { + + exposed___ge__(PyObject self,PyBuiltinFunction.Info info) { + super(self,info); + } + + public PyBuiltinFunction bind(PyObject self) { + return new exposed___ge__(self,info); + } + + public PyObject __call__(PyObject arg0) { + PyObject ret=((PyString)self).str___ge__(arg0); + if (ret==null) + return Py.NotImplemented; + return ret; + } + + } + dict.__setitem__("__ge__",new PyMethodDescr("__ge__",PyString.class,1,1,new exposed___ge__(null,null))); class exposed___getitem__ extends PyBuiltinMethodNarrow { exposed___getitem__(PyObject self,PyBuiltinFunction.Info info) { @@ -1859,13 +1935,17 @@ return null; return string.equals(s) ? Py.Zero : Py.One; } - + public PyObject __lt__(PyObject other) { String s = coerce(other); if (s == null) return null; return string.compareTo(s) < 0 ? Py.One : Py.Zero; } + + final PyObject str___lt__(PyObject other){ + return __lt__(other); + } public PyObject __le__(PyObject other) { String s = coerce(other); @@ -1873,6 +1953,10 @@ return null; return string.compareTo(s) <= 0 ? Py.One : Py.Zero; } + + final PyObject str___le__(PyObject other){ + return __le__(other); + } public PyObject __gt__(PyObject other) { String s = coerce(other); @@ -1880,6 +1964,10 @@ return null; return string.compareTo(s) > 0 ? Py.One : Py.Zero; } + + final PyObject str___gt__(PyObject other){ + return __gt__(other); + } public PyObject __ge__(PyObject other) { String s = coerce(other); @@ -1887,6 +1975,10 @@ return null; return string.compareTo(s) >= 0 ? Py.One : Py.Zero; } + + final PyObject str___ge__(PyObject other){ + return __ge__(other); + } private static String coerce(PyObject o) { if (o instanceof PyString) Modified: trunk/jython/src/org/python/core/PyTuple.java =================================================================== --- trunk/jython/src/org/python/core/PyTuple.java 2007-04-13 06:36:46 UTC (rev 3149) +++ trunk/jython/src/org/python/core/PyTuple.java 2007-04-13 06:37:55 UTC (rev 3150) @@ -63,6 +63,82 @@ } dict.__setitem__("__eq__",new PyMethodDescr("__eq__",PyTuple.class,1,1,new exposed___eq__(null,null))); + class exposed___lt__ extends PyBuiltinMethodNarrow { + + exposed___lt__(PyObject self,PyBuiltinFunction.Info info) { + super(self,info); + } + + public PyBuiltinFunction bind(PyObject self) { + return new exposed___lt__(self,info); + } + + public PyObject __call__(PyObject arg0) { + PyObject ret=((PyTuple)self).tuple___lt__(arg0); + if (ret==null) + return Py.NotImplemented; + return ret; + } + + } + dict.__setitem__("__lt__",new PyMethodDescr("__lt__",PyTuple.class,1,1,new exposed___lt__(null,null))); + class exposed___le__ extends PyBuiltinMethodNarrow { + + exposed___le__(PyObject self,PyBuiltinFunction.Info info) { + super(self,info); + } + + public PyBuiltinFunction bind(PyObject self) { + return new exposed___le__(self,info); + } + + public PyObject __call__(PyObject arg0) { + PyObject ret=((PyTuple)self).tuple___le__(arg0); + if (ret==null) + return Py.NotImplemented; + return ret; + } + + } + dict.__setitem__("__le__",new PyMethodDescr("__le__",PyTuple.class,1,1,new exposed___le__(null,null))); + class exposed___gt__ extends PyBuiltinMethodNarrow { + + exposed___gt__(PyObject self,PyBuiltinFunction.Info info) { + super(self,info); + } + + public PyBuiltinFunction bind(PyObject self) { + return new exposed___gt__(self,info); + } + + public PyObject __call__(PyObject arg0) { + PyObject ret=((PyTuple)self).tuple___gt__(arg0); + if (ret==null) + return Py.NotImplemented; + return ret; + } + + } + dict.__setitem__("__gt__",new PyMethodDescr("__gt__",PyTuple.class,1,1,new exposed___gt__(null,null))); + class exposed___ge__ extends PyBuiltinMethodNarrow { + + exposed___ge__(PyObject self,PyBuiltinFunction.Info info) { + super(self,info); + } + + public PyBuiltinFunction bind(PyObject self) { + return new exposed___ge__(self,info); + } + + public PyObject __call__(PyObject arg0) { + PyObject ret=((PyTuple)self).tuple___ge__(arg0); + if (ret==null) + return Py.NotImplemented; + return ret; + } + + } + dict.__setitem__("__ge__",new PyMethodDescr("__ge__",PyTuple.class,1,1,new exposed___ge__(null,null))); class exposed___getitem__ extends PyBuiltinMethodNarrow { exposed___getitem__(PyObject self,PyBuiltinFunction.Info info) { @@ -344,6 +420,22 @@ return super.__eq__(o); } + final PyObject tuple___gt__(PyObject o) { + return super.__gt__(o); + } + + final PyObject tuple___ge__(PyObject o) { + return super.__ge__(o); + } + + final PyObject tuple___lt__(PyObject o) { + return super.__lt__(o); + } + + final PyObject tuple___le__(PyObject o) { + return super.__le__(o); + } + public PyObject __add__(PyObject generic_other) { return tuple___add__(generic_other); } Modified: trunk/jython/src/templates/dict.expose =================================================================== --- trunk/jython/src/templates/dict.expose 2007-04-13 06:36:46 UTC (rev 3149) +++ trunk/jython/src/templates/dict.expose 2007-04-13 06:37:55 UTC (rev 3150) @@ -2,7 +2,7 @@ type_name: dict type_class: PyDictionary # exposed methods -expose_binary: __ne__ __eq__ +expose_binary: __ne__ __eq__ __lt__ __gt__ __ge__ __le__ expose_vanilla_cmp: expose_cmeth: fromkeys o o? expose_key_getitem: @@ -35,5 +35,4 @@ `void; # TODO: # ('__getattribute__'), -# '__lt__', '__gt__', '__ge__', __le__' # (__doc__) Modified: trunk/jython/src/templates/sequence.expose =================================================================== --- trunk/jython/src/templates/sequence.expose 2007-04-13 06:36:46 UTC (rev 3149) +++ trunk/jython/src/templates/sequence.expose 2007-04-13 06:37:55 UTC (rev 3150) @@ -1,7 +1,7 @@ # sequence itself is not python visible # exposed methods -expose_binary: seq_> __ne__ __eq__ +expose_binary: seq_> __ne__ __eq__ __lt__ __le__ __gt__ __ge__ expose_meth: object_> :b __contains__ o expose_meth: seq_> :- __delitem__ o expose_meth: seq_> :- __setitem__ oo Modified: trunk/jython/src/templates/str.expose =================================================================== --- trunk/jython/src/templates/str.expose 2007-04-13 06:36:46 UTC (rev 3149) +++ trunk/jython/src/templates/str.expose 2007-04-13 06:37:55 UTC (rev 3150) @@ -5,7 +5,7 @@ expose_index_getitem: seq_> expose_meth: seq_> __getslice__ ooo? # -expose_binary: __ne__ __eq__ +expose_binary: __ne__ __eq__ __lt__ __le__ __gt__ __ge__ expose_meth: :b __contains__ o expose_meth: :i __len__ expose_meth: __add__ o Modified: trunk/jython/src/templates/tuple.expose =================================================================== --- trunk/jython/src/templates/tuple.expose 2007-04-13 06:36:46 UTC (rev 3149) +++ trunk/jython/src/templates/tuple.expose 2007-04-13 06:37:55 UTC (rev 3150) @@ -7,7 +7,7 @@ expose_meth: seq_> __getslice__ ooo? #expose_meth: seq_> __iter__ # -expose_binary: __ne__ __eq__ +expose_binary: __ne__ __eq__ __lt__ __le__ __gt__ __ge__ expose_meth: :b __contains__ o expose_meth: :i __len__ expose_meth: __add__ o This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <cg...@us...> - 2007-04-13 06:04:09
|
Revision: 3148 http://svn.sourceforge.net/jython/?rev=3148&view=rev Author: cgroves Date: 2007-04-12 23:04:05 -0700 (Thu, 12 Apr 2007) Log Message: ----------- Make all builtin functions newstyle functions so they're of the same type as CPython. This also speeds calls to them up significantly over the old reflected arg matching versions. Make open an alias to PyFile and handle the bufsize argument in PyFile.__init__ so it will actually function as open. Modified Paths: -------------- trunk/jython/Lib/test/output/test_extcall trunk/jython/NEWS trunk/jython/src/org/python/core/PyFile.java trunk/jython/src/org/python/core/PySystemState.java trunk/jython/src/org/python/core/__builtin__.java Modified: trunk/jython/Lib/test/output/test_extcall =================================================================== --- trunk/jython/Lib/test/output/test_extcall 2007-04-08 19:20:36 UTC (rev 3147) +++ trunk/jython/Lib/test/output/test_extcall 2007-04-13 06:04:05 UTC (rev 3148) @@ -26,12 +26,12 @@ f() keywords must be strings h() got an unexpected keyword argument 'e' h() argument after * must be a sequence -reflectedfunction argument after * must be a sequence +builtin_function_or_method argument after * must be a sequence NoneType argument after * must be a sequence h() argument after ** must be a dictionary -reflectedfunction argument after ** must be a dictionary +builtin_function_or_method argument after ** must be a dictionary NoneType argument after ** must be a dictionary -reflectedfunction got multiple values for keyword argument 'b' +builtin_function_or_method got multiple values for keyword argument 'b' 3 512 1 3 3 Modified: trunk/jython/NEWS =================================================================== --- trunk/jython/NEWS 2007-04-08 19:20:36 UTC (rev 3147) +++ trunk/jython/NEWS 2007-04-13 06:04:05 UTC (rev 3148) @@ -1,7 +1,11 @@ Jython NEWS +Jython 2.2 beta2 + New features + - All functions in __builtin__ are new style functions instead of reflected + functions + Jython 2.2 beta1 - New features - much improved support for __unicode__ especially in the parser (u"string" and friends now result in a PyUnicode object) Modified: trunk/jython/src/org/python/core/PyFile.java =================================================================== --- trunk/jython/src/org/python/core/PyFile.java 2007-04-08 19:20:36 UTC (rev 3147) +++ trunk/jython/src/org/python/core/PyFile.java 2007-04-13 06:04:05 UTC (rev 3148) @@ -1090,10 +1090,10 @@ final void file_init(PyObject[] args,String[] kwds) { - ArgParser ap = new ArgParser("file", args, kwds, new String[] { "name", "mode" }, 1); + ArgParser ap = new ArgParser("file", args, kwds, new String[] { "name", "mode", "bufsize" }, 1); String nameArg = ap.getString(0, null); String modeArg = ap.getString(1, "r"); - int buffArg = 0;//ap.getInt(2, 0); + int buffArg = ap.getInt(2, 0); FileWrapper fw = _setup(nameArg, modeArg, buffArg); //xxx: c&p'ed from one of the constructors. Modified: trunk/jython/src/org/python/core/PySystemState.java =================================================================== --- trunk/jython/src/org/python/core/PySystemState.java 2007-04-08 19:20:36 UTC (rev 3147) +++ trunk/jython/src/org/python/core/PySystemState.java 2007-04-13 06:04:05 UTC (rev 3148) @@ -129,8 +129,6 @@ public static PyList warnoptions; - private static PyJavaClass __builtin__class; - private ClassLoader classLoader = null; public ClassLoader getClassLoader() { return classLoader; @@ -276,7 +274,12 @@ __excepthook__ = new PySystemStateFunctions("excepthook", 30, 3, 3); // This isn't quite right... - builtins = __builtin__class.__getattr__("__dict__"); + if(builtins == null){ + builtins = new PyStringMap(); + __builtin__.fillWithBuiltins(builtins); + }else{ + builtins = Py.defaultSystemState.builtins; + } PyModule __builtin__ = new PyModule("__builtin__", builtins); modules.__setitem__("__builtin__", __builtin__); @@ -472,7 +475,7 @@ if (classLoader != null) Py.defaultSystemState.setClassLoader(classLoader); - Py.initClassExceptions(__builtin__class.__getattr__("__dict__")); + Py.initClassExceptions(Py.defaultSystemState.builtins); // Make sure that Exception classes have been loaded new PySyntaxError("", 1,1,"", ""); } @@ -493,8 +496,6 @@ Py.EmptyString = new PyString(""); Py.Newline = new PyString("\n"); Py.Space = new PyString(" "); - // xxx what to do about modules - __builtin__class = PyJavaClass.lookup(__builtin__.class); // Setup standard wrappers for stdout and stderr... Py.stderr = new StderrWrapper(); Modified: trunk/jython/src/org/python/core/__builtin__.java =================================================================== --- trunk/jython/src/org/python/core/__builtin__.java 2007-04-08 19:20:36 UTC (rev 3147) +++ trunk/jython/src/org/python/core/__builtin__.java 2007-04-13 06:04:05 UTC (rev 3148) @@ -4,987 +4,1164 @@ import java.util.Hashtable; class BuiltinFunctions extends PyBuiltinFunctionSet { - public BuiltinFunctions(String name, int index, int argcount) { - this(name, index, argcount, argcount); - } - public BuiltinFunctions(String name, int index, int minargs, int maxargs) { - super(name, index, minargs, maxargs); - } + public BuiltinFunctions(String name, int index, int argcount) { + this(name, index, argcount, argcount); + } - public PyObject __call__() { - switch (this.index) { - case 4: - return __builtin__.globals(); - default: - throw info.unexpectedCall(0, false); - } - } + public BuiltinFunctions(String name, int index, int minargs, int maxargs) { + super(name, index, minargs, maxargs); + } - public PyObject __call__(PyObject arg1) { - switch (this.index) { - case 0: - return Py.newString(__builtin__.chr(Py.py2int(arg1, - "chr(): 1st arg can't be coerced to int"))); - case 1: - return Py.newInteger(__builtin__.len(arg1)); - case 2: - return __builtin__.range(Py.py2int(arg1, - "range(): 1st arg can't be coerced to int")); - case 3: - return Py.newInteger(__builtin__.ord(Py.py2char(arg1, - "ord(): 1st arg can't be coerced to char"))); - case 5: - return __builtin__.hash(arg1); - case 8: - return __builtin__.tuple(arg1); - case 11: - return Py.newInteger(__builtin__.id(arg1)); - case 12: - return __builtin__.sum(arg1); - default: - throw info.unexpectedCall(1, false); - } - } + public PyObject __call__() { + switch (this.index) { + case 4: + return __builtin__.globals(); + case 16: + return __builtin__.dir(); + case 24: + return __builtin__.input(); + case 28: + return __builtin__.locals(); + case 34: + return Py.newString(__builtin__.raw_input()); + case 41: + return __builtin__.vars(); + default: + throw info.unexpectedCall(0, false); + } + } - public PyObject __call__(PyObject arg1, PyObject arg2) { - switch (this.index) { - case 2: - return __builtin__.range(Py.py2int(arg1, - "range(): 1st arg can't be coerced to int"), Py.py2int( - arg2, "range(): 2nd arg can't be coerced to int")); - case 6: - return Py.newInteger(__builtin__.cmp(arg1, arg2)); - case 9: - return __builtin__.apply(arg1, arg2); - case 10: - return Py.newBoolean(__builtin__.isinstance(arg1, arg2)); - case 12: - return __builtin__.sum(arg1, arg2); - default: - throw info.unexpectedCall(2, false); - } - } + public PyObject __call__(PyObject arg1) { + switch (this.index) { + case 0: + return Py.newString(__builtin__.chr(Py.py2int(arg1, "chr(): 1st arg can't be coerced to int"))); + case 1: + return Py.newInteger(__builtin__.len(arg1)); + case 2: + return __builtin__.range(Py.py2int(arg1, "range(): 1st arg can't be coerced to int")); + case 3: + return Py.newInteger(__builtin__.ord(Py.py2char(arg1, "ord(): 1st arg can't be coerced to char"))); + case 5: + return __builtin__.hash(arg1); + case 6: + return Py.newUnicode(__builtin__.chr(Py.py2int(arg1, "unichr(): 1st arg can't be coerced to int"))); + case 7: + return __builtin__.abs(arg1); + case 8: + return __builtin__.bool(arg1); + case 11: + return Py.newInteger(__builtin__.id(arg1)); + case 12: + return __builtin__.sum(arg1); + case 14: + return Py.newBoolean(__builtin__.callable(arg1)); + case 16: + return __builtin__.dir(arg1); + case 18: + return __builtin__.eval(arg1); + case 19: + try { + __builtin__.execfile(arg1.asString(0)); + } catch (ConversionException e) { + throw Py.TypeError("execfile's first argument must be str"); + } + return null; + case 23: + return __builtin__.hex(arg1); + case 24: + return __builtin__.input(arg1); + case 25: + return __builtin__.intern(arg1.__str__()); + case 27: + return __builtin__.iter(arg1); + case 32: + return __builtin__.oct(arg1); + case 34: + return Py.newString(__builtin__.raw_input(arg1)); + case 36: + Object o = arg1.__tojava__(PyModule.class); + if (o == Py.NoConversion) { + o = arg1.__tojava__(PyJavaClass.class); + if (o == Py.NoConversion) { + Py.TypeError("reload() argument must be a module"); + } + return __builtin__.reload((PyJavaClass) o); + } + return __builtin__.reload((PyModule) o); + case 37: + return __builtin__.repr(arg1); + case 38: + return __builtin__.round(Py.py2double(arg1)); + case 40: + return __builtin__.slice(arg1); + case 41: + return __builtin__.vars(arg1); + case 42: + return __builtin__.xrange(Py.py2int(arg1)); + case 30: + return fancyCall(new PyObject[] { arg1 }); + case 31: + return fancyCall(new PyObject[] { arg1 }); + case 43: + return fancyCall(new PyObject[] { arg1 }); + default: + throw info.unexpectedCall(1, false); + } + } - public PyObject __call__(PyObject arg1, PyObject arg2, PyObject arg3) { - switch (this.index) { - case 2: - return __builtin__.range(Py.py2int(arg1, - "range(): 1st arg can't be coerced to int"), Py.py2int( - arg2, "range(): 2nd arg can't be coerced to int"), Py - .py2int(arg3, "range(): 3rd arg can't be coerced to int")); - case 9: - try { - if (arg3 instanceof PyStringMap) { - PyDictionary d = new PyDictionary(); - d.update(arg3); - arg3 = d; - } + public PyObject __call__(PyObject arg1, PyObject arg2) { + switch (this.index) { + case 2: + return __builtin__.range(Py.py2int(arg1, "range(): 1st arg can't be coerced to int"), Py.py2int(arg2, + "range(): 2nd arg can't be coerced to int")); + case 6: + return Py.newInteger(__builtin__.cmp(arg1, arg2)); + case 9: + return __builtin__.apply(arg1, arg2); + case 10: + return Py.newBoolean(__builtin__.isinstance(arg1, arg2)); + case 12: + return __builtin__.sum(arg1, arg2); + case 13: + return __builtin__.coerce(arg1, arg2); + case 15: + __builtin__.delattr(arg1, asString(arg2, "delattr(): attribute name must be string")); + return null; + case 17: + return __builtin__.divmod(arg1, arg2); + case 18: + return __builtin__.eval(arg1, arg2); + case 19: + try { + __builtin__.execfile(arg1.asString(0), arg2); + } catch (ConversionException e) { + throw Py.TypeError("execfile's first argument must be str"); + } + return null; + case 20: + return __builtin__.filter(arg1, arg2); + case 21: + return __builtin__.getattr(arg1, asString(arg2, "getattr(): attribute name must be string")); + case 22: + return Py.newBoolean(__builtin__.hasattr(arg1, asString(arg2, "hasattr(): attribute name must be string"))); + case 26: + return Py.newBoolean(__builtin__.issubclass(arg1, arg2)); + case 27: + return __builtin__.iter(arg1, arg2); + case 33: + return __builtin__.pow(arg1, arg2); + case 35: + return __builtin__.reduce(arg1, arg2); + case 38: + return __builtin__.round(Py.py2double(arg1), Py.py2int(arg2)); + case 40: + return __builtin__.slice(arg1, arg2); + case 42: + return __builtin__.xrange(Py.py2int(arg1), Py.py2int(arg2)); + case 29: + return fancyCall(new PyObject[] { arg1, arg2 }); + case 30: + return fancyCall(new PyObject[] { arg1, arg2 }); + case 31: + return fancyCall(new PyObject[] { arg1, arg2 }); + case 43: + return fancyCall(new PyObject[] { arg1, arg2 }); + default: + throw info.unexpectedCall(2, false); + } + } - // this catches both casts of arg3 to a PyDictionary, and - // all casts of keys in the dictionary to PyStrings inside - // apply(PyObject, PyObject, PyDictionary) - PyDictionary d = (PyDictionary) arg3; - return __builtin__.apply(arg1, arg2, d); - } catch (ClassCastException e) { - throw Py.TypeError("apply() 3rd argument must be a " - + "dictionary with string keys"); - } - default: - throw info.unexpectedCall(3, false); - } - } -} + public PyObject __call__(PyObject arg1, PyObject arg2, PyObject arg3) { + switch (this.index) { + case 2: + return __builtin__.range(Py.py2int(arg1, "range(): 1st arg can't be coerced to int"), Py.py2int(arg2, + "range(): 2nd arg can't be coerced to int"), Py.py2int(arg3, + "range(): 3rd arg can't be coerced to int")); + case 9: + try { + if (arg3 instanceof PyStringMap) { + PyDictionary d = new PyDictionary(); + d.update(arg3); + arg3 = d; + } + // this catches both casts of arg3 to a PyDictionary, and + // all casts of keys in the dictionary to PyStrings inside + // apply(PyObject, PyObject, PyDictionary) + PyDictionary d = (PyDictionary) arg3; + return __builtin__.apply(arg1, arg2, d); + } catch (ClassCastException e) { + throw Py.TypeError("apply() 3rd argument must be a " + "dictionary with string keys"); + } + case 18: + return __builtin__.eval(arg1, arg2, arg3); + case 19: + __builtin__.execfile(asString(arg1, "execfile's first argument must be str", false), arg2, arg3); + return null; + case 21: + return __builtin__.getattr(arg1, asString(arg2, "getattr(): attribute name must be string"), arg3); + case 33: + return __builtin__.pow(arg1, arg2, arg3); + case 35: + return __builtin__.reduce(arg1, arg2, arg3); + case 39: + __builtin__.setattr(arg1, asString(arg2, "setattr(): attribute name must be string"), arg3); + return null; + case 40: + return __builtin__.slice(arg1, arg2, arg3); + case 42: + return __builtin__.xrange(Py.py2int(arg1), Py.py2int(arg2), Py.py2int(arg3)); + case 44: + return fancyCall(new PyObject[] { arg1, arg2, arg3 }); + case 29: + return fancyCall(new PyObject[] { arg1, arg2, arg3 }); + case 30: + return fancyCall(new PyObject[] { arg1, arg2, arg3 }); + case 31: + return fancyCall(new PyObject[] { arg1, arg2, arg3 }); + case 43: + return fancyCall(new PyObject[] { arg1, arg2, arg3 }); + default: + throw info.unexpectedCall(3, false); + } + } -/** - * The builtin module. All builtin functions are defined here - */ -public class __builtin__ implements ClassDictInit { - /** <i>Internal use only. Do not call this method explicitly.</i> */ - public static void classDictInit(PyObject dict) { - /* newstyle */ + /** + * @return arg as an interned String, or throws TypeError with mesage if asString throws a ConversionException + */ + private String asString(PyObject arg, String message) { + return asString(arg, message, true); + } - dict.__setitem__("object", PyType.fromClass(PyObject.class)); - dict.__setitem__("type", PyType.fromClass(PyType.class)); - dict.__setitem__("int", PyType.fromClass(PyInteger.class)); - dict.__setitem__("enumerate", PyType.fromClass(PyEnumerate.class)); - dict.__setitem__("float", PyType.fromClass(PyFloat.class)); - dict.__setitem__("long", PyType.fromClass(PyLong.class)); - dict.__setitem__("complex", PyType.fromClass(PyComplex.class)); - dict.__setitem__("dict", PyType.fromClass(PyDictionary.class)); - dict.__setitem__("list", PyType.fromClass(PyList.class)); - dict.__setitem__("tuple", PyType.fromClass(PyTuple.class)); - dict.__setitem__("property", PyType.fromClass(PyProperty.class)); - dict - .__setitem__("staticmethod", PyType - .fromClass(PyStaticMethod.class)); - dict.__setitem__("classmethod", PyType.fromClass(PyClassMethod.class)); - dict.__setitem__("super", PyType.fromClass(PySuper.class)); - dict.__setitem__("str", PyType.fromClass(PyString.class)); - dict.__setitem__("unicode", PyType.fromClass(PyUnicode.class)); - dict.__setitem__("basestring", PyType.fromClass(PyBaseString.class)); - dict.__setitem__("file", PyType.fromClass(PyFile.class)); + /** + * + * @param intern - should the resulting string be interned + * @return arg as a String, or throws TypeError with message if asString throws a ConversionException. + */ + private String asString(PyObject arg, String message, boolean intern) { - /* - */ + try { + return intern ? arg.asString(0).intern() : arg.asString(0); + } catch (ConversionException e) { + throw Py.TypeError(message); + } + } - dict.__setitem__("None", Py.None); - dict.__setitem__("NotImplemented", Py.NotImplemented); - dict.__setitem__("Ellipsis", Py.Ellipsis); - dict.__setitem__("True", Py.One); - dict.__setitem__("False", Py.Zero); + public PyObject __call__(PyObject arg1, PyObject arg2, PyObject arg3, PyObject arg4) { + switch (this.index) { + case 44: + return fancyCall(new PyObject[] { arg1, arg2, arg3, arg4 }); + case 29: + return fancyCall(new PyObject[] { arg1, arg2, arg3, arg4 }); + case 30: + return fancyCall(new PyObject[] { arg1, arg2, arg3, arg4 }); + case 31: + return fancyCall(new PyObject[] { arg1, arg2, arg3, arg4 }); + case 43: + return fancyCall(new PyObject[] { arg1, arg2, arg3, arg4 }); + default: + throw info.unexpectedCall(4, false); + } + } - // Work in debug mode by default - // Hopefully add -O option in the future to change this - dict.__setitem__("__debug__", Py.One); + public PyObject fancyCall(PyObject[] args) { + switch (this.index) { + case 44: + if (args.length > 5) { + throw info.unexpectedCall(args.length, false); + } + int flags = 0; + if (args.length > 3) { + flags = Py.py2int(args[3]); + } + boolean dont_inherit = false; + if (args.length > 4) { + dont_inherit = Py.py2boolean(args[4]); + } - dict.__setitem__("chr", new BuiltinFunctions("chr", 0, 1)); - dict.__setitem__("len", new BuiltinFunctions("len", 1, 1)); - dict.__setitem__("range", new BuiltinFunctions("range", 2, 1, 3)); - dict.__setitem__("ord", new BuiltinFunctions("ord", 3, 1)); - dict.__setitem__("globals", new BuiltinFunctions("globals", 4, 0)); - dict.__setitem__("hash", new BuiltinFunctions("hash", 5, 1)); - dict.__setitem__("cmp", new BuiltinFunctions("cmp", 6, 2)); - dict.__setitem__("apply", new BuiltinFunctions("apply", 9, 2, 3)); - dict.__setitem__("isinstance", - new BuiltinFunctions("isinstance", 10, 2)); - dict.__setitem__("id", new BuiltinFunctions("id", 11, 1)); - dict.__setitem__("sum", new BuiltinFunctions("sum", 12, 1, 2)); - dict.__setitem__("__import__", new ImportFunction()); + return __builtin__.compile(args[0].toString(), args[1].toString(), args[2].toString(), flags, dont_inherit); + case 29: + return __builtin__.map(args); + case 30: + return __builtin__.max(args); + case 31: + return __builtin__.min(args); + case 43: + return __builtin__.zip(args); + default: + throw info.unexpectedCall(args.length, false); + } + } - dict.__delitem__("execfile_flags"); // -execfile_flags - } +} - public static PyObject abs(PyObject o) { - if (o.isNumberType()) { - return o.__abs__(); - } - throw Py.TypeError("bad operand type for abs()"); - } +/** + * The builtin module. All builtin functions are defined here + */ +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)); + dict.__setitem__("enumerate", PyType.fromClass(PyEnumerate.class)); + dict.__setitem__("float", PyType.fromClass(PyFloat.class)); + dict.__setitem__("long", PyType.fromClass(PyLong.class)); + dict.__setitem__("complex", PyType.fromClass(PyComplex.class)); + dict.__setitem__("dict", PyType.fromClass(PyDictionary.class)); + dict.__setitem__("list", PyType.fromClass(PyList.class)); + dict.__setitem__("tuple", PyType.fromClass(PyTuple.class)); + + dict.__setitem__("property", PyType.fromClass(PyProperty.class)); + dict.__setitem__("staticmethod", PyType.fromClass(PyStaticMethod.class)); + dict.__setitem__("classmethod", PyType.fromClass(PyClassMethod.class)); + dict.__setitem__("super", PyType.fromClass(PySuper.class)); + dict.__setitem__("str", PyType.fromClass(PyString.class)); + dict.__setitem__("unicode", PyType.fromClass(PyUnicode.class)); + dict.__setitem__("basestring", PyType.fromClass(PyBaseString.class)); + dict.__setitem__("file", PyType.fromClass(PyFile.class)); + dict.__setitem__("open", PyType.fromClass(PyFile.class)); + + /* - */ + + dict.__setitem__("None", Py.None); + dict.__setitem__("NotImplemented", Py.NotImplemented); + dict.__setitem__("Ellipsis", Py.Ellipsis); + dict.__setitem__("True", Py.One); + dict.__setitem__("False", Py.Zero); + + // Work in debug mode by default + // Hopefully add -O option in the future to change this + dict.__setitem__("__debug__", Py.One); + + dict.__setitem__("abs", new BuiltinFunctions("abs", 7, 1)); + dict.__setitem__("apply", new BuiltinFunctions("apply", 9, 2, 3)); + dict.__setitem__("bool", new BuiltinFunctions("bool", 8, 1)); + dict.__setitem__("callable", new BuiltinFunctions("callable", 14, 1)); + dict.__setitem__("coerce", new BuiltinFunctions("coerce", 13, 2)); + dict.__setitem__("chr", new BuiltinFunctions("chr", 0, 1)); + dict.__setitem__("cmp", new BuiltinFunctions("cmp", 6, 2)); + dict.__setitem__("globals", new BuiltinFunctions("globals", 4, 0)); + dict.__setitem__("hash", new BuiltinFunctions("hash", 5, 1)); + dict.__setitem__("id", new BuiltinFunctions("id", 11, 1)); + dict.__setitem__("isinstance", new BuiltinFunctions("isinstance", 10, 2)); + dict.__setitem__("len", new BuiltinFunctions("len", 1, 1)); + dict.__setitem__("ord", new BuiltinFunctions("ord", 3, 1)); + dict.__setitem__("range", new BuiltinFunctions("range", 2, 1, 3)); + dict.__setitem__("sum", new BuiltinFunctions("sum", 12, 1, 2)); + dict.__setitem__("unichr", new BuiltinFunctions("unichr", 6, 1)); + dict.__setitem__("compile", new BuiltinFunctions("compile", 44, 3, -1)); + dict.__setitem__("delattr", new BuiltinFunctions("delattr", 15, 2)); + dict.__setitem__("dir", new BuiltinFunctions("dir", 16, 0, 1)); + dict.__setitem__("divmod", new BuiltinFunctions("divmod", 17, 2)); + dict.__setitem__("eval", new BuiltinFunctions("eval", 18, 1, 3)); + dict.__setitem__("execfile", new BuiltinFunctions("execfile", 19, 1, 3)); + dict.__setitem__("filter", new BuiltinFunctions("filter", 20, 2)); + dict.__setitem__("getattr", new BuiltinFunctions("getattr", 21, 2, 3)); + dict.__setitem__("hasattr", new BuiltinFunctions("hasattr", 22, 2)); + dict.__setitem__("hex", new BuiltinFunctions("hex", 23, 1)); + dict.__setitem__("input", new BuiltinFunctions("input", 24, 0, 1)); + dict.__setitem__("intern", new BuiltinFunctions("intern", 25, 1)); + dict.__setitem__("issubclass", new BuiltinFunctions("issubclass", 26, 2)); + dict.__setitem__("iter", new BuiltinFunctions("iter", 27, 1, 2)); + dict.__setitem__("locals", new BuiltinFunctions("locals", 28, 0)); + dict.__setitem__("map", new BuiltinFunctions("map", 29, 2, -1)); + dict.__setitem__("max", new BuiltinFunctions("max", 30, 1, -1)); + dict.__setitem__("min", new BuiltinFunctions("min", 31, 1, -1)); + dict.__setitem__("oct", new BuiltinFunctions("oct", 32, 1)); + dict.__setitem__("pow", new BuiltinFunctions("pow", 33, 2, 3)); + dict.__setitem__("raw_input", new BuiltinFunctions("raw_input", 34, 0, 1)); + dict.__setitem__("reduce", new BuiltinFunctions("reduce", 35, 2, 3)); + dict.__setitem__("reload", new BuiltinFunctions("reload", 36, 1)); + dict.__setitem__("repr", new BuiltinFunctions("repr", 37, 1)); + dict.__setitem__("round", new BuiltinFunctions("round", 38, 1, 2)); + dict.__setitem__("setattr", new BuiltinFunctions("setattr", 39, 3)); + dict.__setitem__("slice", new BuiltinFunctions("slice", 40, 1, 3)); + dict.__setitem__("vars", new BuiltinFunctions("vars", 41, 0, 1)); + dict.__setitem__("xrange", new BuiltinFunctions("xrange", 42, 1, 3)); + dict.__setitem__("zip", new BuiltinFunctions("zip", 43, 1, -1)); + + dict.__setitem__("__import__", new ImportFunction()); + + } - public static PyObject apply(PyObject o, PyObject args) { - return o.__call__(Py.make_array(args)); - } + public static PyObject abs(PyObject o) { + if (o.isNumberType()) { + return o.__abs__(); + } + throw Py.TypeError("bad operand type for abs()"); + } - public static PyObject apply(PyObject o, PyObject args, PyDictionary kws) { - PyObject[] a; - String[] kw; - Hashtable table = kws.table; - if (table.size() > 0) { - java.util.Enumeration ek = table.keys(); - java.util.Enumeration ev = table.elements(); - int n = table.size(); - kw = new String[n]; - PyObject[] aargs = Py.make_array(args); - a = new PyObject[n + aargs.length]; - System.arraycopy(aargs, 0, a, 0, aargs.length); - int offset = aargs.length; + public static PyObject apply(PyObject o, PyObject args) { + return o.__call__(Py.make_array(args)); + } - for (int i = 0; i < n; i++) { - kw[i] = ((PyString) ek.nextElement()).internedString(); - a[i + offset] = (PyObject) ev.nextElement(); - } - return o.__call__(a, kw); - } else { - return apply(o, args); - } - } + public static PyObject apply(PyObject o, PyObject args, PyDictionary kws) { + PyObject[] a; + String[] kw; + Hashtable table = kws.table; + if (table.size() > 0) { + java.util.Enumeration ek = table.keys(); + java.util.Enumeration ev = table.elements(); + int n = table.size(); + kw = new String[n]; + PyObject[] aargs = Py.make_array(args); + a = new PyObject[n + aargs.length]; + System.arraycopy(aargs, 0, a, 0, aargs.length); + int offset = aargs.length; - public static PyObject bool(PyObject o) { - return (o == null ? Py.Zero : o.__nonzero__() ? Py.One : Py.Zero); - } + for (int i = 0; i < n; i++) { + kw[i] = ((PyString) ek.nextElement()).internedString(); + a[i + offset] = (PyObject) ev.nextElement(); + } + return o.__call__(a, kw); + } else { + return apply(o, args); + } + } - public static boolean callable(PyObject o) { - return o.__findattr__("__call__") != null; - } + public static PyObject bool(PyObject o) { + return (o == null ? Py.Zero : o.__nonzero__() ? Py.One : Py.Zero); + } - public static char unichr(int i) { - return chr(i); - } + public static boolean callable(PyObject o) { + return o.__findattr__("__call__") != null; + } - public static char chr(int i) { - if (i < 0 || i > 65535) { - throw Py.ValueError("chr() arg not in range(65535)"); - } - return (char) i; - } + public static char unichr(int i) { + return chr(i); + } - public static int cmp(PyObject x, PyObject y) { - return x._cmp(y); - } + public static char chr(int i) { + if (i < 0 || i > 65535) { + throw Py.ValueError("chr() arg not in range(65535)"); + } + return (char) i; + } - public static PyTuple coerce(PyObject o1, PyObject o2) { - PyObject[] result = o1._coerce(o2); - if (result != null) { - return new PyTuple(result); - } - throw Py.TypeError("number coercion failed"); - } + public static int cmp(PyObject x, PyObject y) { + return x._cmp(y); + } - public static PyCode compile(String data, String filename, String type) { - return Py.compile_flags(data, filename, type, Py.getCompilerFlags()); - } + public static PyTuple coerce(PyObject o1, PyObject o2) { + PyObject[] result = o1._coerce(o2); + if (result != null) { + return new PyTuple(result); + } + throw Py.TypeError("number coercion failed"); + } - public static PyCode compile(String data, String filename, String type, - int flags, boolean dont_inherit) { - if ((flags & ~PyTableCode.CO_ALL_FEATURES) != 0) { - throw Py.ValueError("compile(): unrecognised flags"); - } - return Py.compile_flags(data, filename, type, Py.getCompilerFlags( - flags, dont_inherit)); - } + public static PyCode compile(String data, String filename, String type) { + return Py.compile_flags(data, filename, type, Py.getCompilerFlags()); + } - public static void delattr(PyObject o, PyString n) { - o.__delattr__(n); - } + public static PyCode compile(String data, String filename, String type, int flags, boolean dont_inherit) { + if ((flags & ~PyTableCode.CO_ALL_FEATURES) != 0) { + throw Py.ValueError("compile(): unrecognised flags"); + } + return Py.compile_flags(data, filename, type, Py.getCompilerFlags(flags, dont_inherit)); + } - public static PyObject dir(PyObject o) { - PyList ret = (PyList) o.__dir__(); - ret.sort(); - return ret; - } + public static void delattr(PyObject o, String n) { + o.__delattr__(n); + } - public static PyObject dir() { - PyObject l = locals(); - PyList ret; + public static PyObject dir(PyObject o) { + PyList ret = (PyList) o.__dir__(); + ret.sort(); + return ret; + } - if (l instanceof PyStringMap) { - ret = ((PyStringMap) l).keys(); - } else if (l instanceof PyDictionary) { - ret = ((PyDictionary) l).keys(); - } + public static PyObject dir() { + PyObject l = locals(); + PyList ret; - ret = (PyList) l.invoke("keys"); - ret.sort(); - return ret; - } + if (l instanceof PyStringMap) { + ret = ((PyStringMap) l).keys(); + } else if (l instanceof PyDictionary) { + ret = ((PyDictionary) l).keys(); + } - public static PyObject divmod(PyObject x, PyObject y) { - return x._divmod(y); - } + ret = (PyList) l.invoke("keys"); + ret.sort(); + return ret; + } - public static PyEnumerate enumerate(PyObject seq) { - return new PyEnumerate(seq); - } + public static PyObject divmod(PyObject x, PyObject y) { + return x._divmod(y); + } - public static PyObject eval(PyObject o, PyObject globals, PyObject locals) { - PyCode code; - if (o instanceof PyCode) { - code = (PyCode) o; - } else { - if (o instanceof PyString) { - code = compile(o.toString(), "<string>", "eval"); - } else { - throw Py - .TypeError("eval: argument 1 must be string or code object"); - } - } - return Py.runCode(code, locals, globals); - } + public static PyEnumerate enumerate(PyObject seq) { + return new PyEnumerate(seq); + } - public static PyObject eval(PyObject o, PyObject globals) { - return eval(o, globals, globals); - } + public static PyObject eval(PyObject o, PyObject globals, PyObject locals) { + PyCode code; + if (o instanceof PyCode) { + code = (PyCode) o; + } else { + if (o instanceof PyString) { + code = compile(o.toString(), "<string>", "eval"); + } else { + throw Py.TypeError("eval: argument 1 must be string or code object"); + } + } + return Py.runCode(code, locals, globals); + } - public static PyObject eval(PyObject o) { - 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); - } + public static PyObject eval(PyObject o, PyObject globals) { + return eval(o, globals, globals); + } - public static void execfile(String name, PyObject globals, PyObject locals) { - execfile_flags(name, globals, locals, Py.getCompilerFlags()); - } + public static PyObject eval(PyObject o) { + 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); + } - public static void execfile_flags(String name, PyObject globals, - PyObject locals, CompilerFlags cflags) { - java.io.FileInputStream file; - try { - file = new java.io.FileInputStream(name); - } catch (java.io.FileNotFoundException e) { - throw Py.IOError(e); - } - PyCode code; + public static void execfile(String name, PyObject globals, PyObject locals) { + execfile_flags(name, globals, locals, Py.getCompilerFlags()); + } - try { - code = Py.compile_flags(file, name, "exec", cflags); - } finally { - try { - file.close(); - } catch (java.io.IOException e) { - throw Py.IOError(e); - } - } - Py.runCode(code, locals, globals); - } + public static void execfile_flags(String name, PyObject globals, PyObject locals, CompilerFlags cflags) { + java.io.FileInputStream file; + try { + file = new java.io.FileInputStream(name); + } catch (java.io.FileNotFoundException e) { + throw Py.IOError(e); + } + PyCode code; - public static void execfile(String name, PyObject globals) { - execfile(name, globals, globals); - } + try { + code = Py.compile_flags(file, name, "exec", cflags); + } finally { + try { + file.close(); + } catch (java.io.IOException e) { + throw Py.IOError(e); + } + } + Py.runCode(code, locals, globals); + } - public static void execfile(String name) { - execfile(name, null, null); - } + public static void execfile(String name, PyObject globals) { + execfile(name, globals, globals); + } - public static PyObject filter(PyObject f, PyString s) { - if (f == Py.None) { - return s; - } - PyObject[] args = new PyObject[1]; - char[] chars = s.toString().toCharArray(); - int i; - int j; - int n = chars.length; - for (i = 0, j = 0; i < n; i++) { - args[0] = Py.makeCharacter(chars[i]); - if (!f.__call__(args).__nonzero__()) { - continue; - } - chars[j++] = chars[i]; - } - return new PyString(new String(chars, 0, j)); - } + public static void execfile(String name) { + execfile(name, null, null); + } - public static PyObject filter(PyObject f, PyObject l) { - PyList list = new PyList(); - PyObject iter = l.__iter__(); - for (PyObject item = null; (item = iter.__iternext__()) != null;) { - if (f == Py.None) { - if (!item.__nonzero__()) { - continue; - } - } else if (!f.__call__(item).__nonzero__()) { - continue; - } - list.append(item); - } - if (l instanceof PyTuple) { - return tuple(list); - } - return list; - } + public static PyObject filter(PyObject f, PyString s) { + if (f == Py.None) { + return s; + } + PyObject[] args = new PyObject[1]; + char[] chars = s.toString().toCharArray(); + int i; + int j; + int n = chars.length; + for (i = 0, j = 0; i < n; i++) { + args[0] = Py.makeCharacter(chars[i]); + if (!f.__call__(args).__nonzero__()) { + continue; + } + chars[j++] = chars[i]; + } + return new PyString(new String(chars, 0, j)); + } - public static PyObject getattr(PyObject o, PyString n) { - return o.__getattr__(n); - } + public static PyObject filter(PyObject f, PyObject l) { + if (l instanceof PyString) { + return filter(f, (PyString) l); + } + PyList list = new PyList(); + PyObject iter = l.__iter__(); + for (PyObject item = null; (item = iter.__iternext__()) != null;) { + if (f == Py.None) { + if (!item.__nonzero__()) { + continue; + } + } else if (!f.__call__(item).__nonzero__()) { + continue; + } + list.append(item); + } + if (l instanceof PyTuple) { + return tuple(list); + } + return list; + } - public static PyObject getattr(PyObject o, PyString n, PyObject def) { - PyObject val = o.__findattr__(n); - if (val != null) { - return val; - } - return def; - } + public static PyObject getattr(PyObject o, String n) { + return o.__getattr__(n); + } - public static PyObject globals() { - return Py.getFrame().f_globals; - } + public static PyObject getattr(PyObject o, String n, PyObject def) { + PyObject val = o.__findattr__(n); + if (val != null) { + return val; + } + return def; + } - public static boolean hasattr(PyObject o, PyString n) { - try { - return o.__findattr__(n) != null; - } catch (PyException exc) { - if (Py.matchException(exc, Py.AttributeError)) { - return false; - } - throw exc; - } - } + public static PyObject globals() { + return Py.getFrame().f_globals; + } - public static PyInteger hash(PyObject o) { - return o.__hash__(); - } + public static boolean hasattr(PyObject o, String n) { + try { + return o.__findattr__(n) != null; + } catch (PyException exc) { + if (Py.matchException(exc, Py.AttributeError)) { + return false; + } + throw exc; + } + } - public static PyString hex(PyObject o) { - return o.__hex__(); - } + public static PyInteger hash(PyObject o) { + return o.__hash__(); + } - public static long id(PyObject o) { - return Py.id(o); - } + public static PyString hex(PyObject o) { + return o.__hex__(); + } - public static PyObject input(PyObject prompt) { - String line = raw_input(prompt); - return eval(new PyString(line)); - } + public static long id(PyObject o) { + return Py.id(o); + } - public static PyObject input() { - return input(new PyString("")); - } + public static PyObject input(PyObject prompt) { + String line = raw_input(prompt); + return eval(new PyString(line)); + } - private static PyStringMap internedStrings; + public static PyObject input() { + return input(new PyString("")); + } - public static PyString intern(PyString s) { - if (internedStrings == null) { - internedStrings = new PyStringMap(); - } + private static PyStringMap internedStrings; - String istring = s.internedString(); - PyObject ret = internedStrings.__finditem__(istring); - if (ret != null) { - return (PyString) ret; - } - if (s instanceof PyStringDerived) { - s = s.__str__(); - } - internedStrings.__setitem__(istring, s); - return s; - } + public static PyString intern(PyString s) { + if (internedStrings == null) { + internedStrings = new PyStringMap(); + } - // xxx find where used, modify with more appropriate if necessary - public static boolean isinstance(PyObject obj, PyObject cls) { - return Py.isInstance(obj, cls); - } + String istring = s.internedString(); + PyObject ret = internedStrings.__finditem__(istring); + if (ret != null) { + return (PyString) ret; + } + if (s instanceof PyStringDerived) { + s = s.__str__(); + } + internedStrings.__setitem__(istring, s); + return s; + } - // xxx find where used, modify with more appropriate if necessary - public static boolean issubclass(PyObject derived, PyObject cls) { - return Py.isSubClass(derived, cls); - } + // xxx find where used, modify with more appropriate if necessary + public static boolean isinstance(PyObject obj, PyObject cls) { + return Py.isInstance(obj, cls); + } - public static int len(PyObject o) { - try { - return o.__len__(); - } catch (PyException e) { - // Make this work like CPython where - // - // a = 7; len(a) raises a TypeError, - // a.__len__() raises an AttributeError - // and - // class F: pass - // f = F(); len(f) also raises an AttributeError - // - // Testing the type of o feels unclean though - if (e.type == Py.AttributeError && !(o instanceof PyInstance)) { - throw Py.TypeError("len() of unsized object"); - } - throw e; - } - } + // xxx find where used, modify with more appropriate if necessary + public static boolean issubclass(PyObject derived, PyObject cls) { + return Py.isSubClass(derived, cls); + } - public static PyObject locals() { - return Py.getFrame().getf_locals(); - } + public static PyObject iter(PyObject obj) { + return obj.__iter__(); + } - public static PyObject map(PyObject[] argstar) { - int n = argstar.length - 1; - if (n < 1) { - throw Py.TypeError("map requires at least two arguments"); - } - PyObject element; - PyObject f = argstar[0]; - PyList list = new PyList(); - PyObject[] args = new PyObject[n]; - PyObject[] iters = new PyObject[n]; + public static PyObject iter(PyObject callable, PyObject sentinel) { + return new PyCallIter(callable, sentinel); + } - for (int j = 0; j < n; j++) { - iters[j] = Py.iter(argstar[j + 1], "argument " + (j + 1) - + " to map() must support iteration"); - } + public static int len(PyObject o) { + try { + return o.__len__(); + } catch (PyException e) { + // Make this work like CPython where + // + // a = 7; len(a) raises a TypeError, + // a.__len__() raises an AttributeError + // and + // class F: pass + // f = F(); len(f) also raises an AttributeError + // + // Testing the type of o feels unclean though + if (e.type == Py.AttributeError && !(o instanceof PyInstance)) { + throw Py.TypeError("len() of unsized object"); + } + throw e; + } + } - while (true) { - boolean any_items = false; - for (int j = 0; j < n; j++) { - if ((element = iters[j].__iternext__()) != null) { - args[j] = element; - any_items = true; - } else { - args[j] = Py.None; - } - } - if (!any_items) { - break; - } - if (f == Py.None) { - if (n == 1) { - list.append(args[0]); - } else { - list.append(new PyTuple((PyObject[]) args.clone())); - } - } else { - list.append(f.__call__(args)); - } - } - return list; - } + public static PyObject locals() { + return Py.getFrame().getf_locals(); + } - // I've never been happy with max and min builtin's... + public static PyObject map(PyObject[] argstar) { + int n = argstar.length - 1; + if (n < 1) { + throw Py.TypeError("map requires at least two arguments"); + } + PyObject element; + PyObject f = argstar[0]; + PyList list = new PyList(); + PyObject[] args = new PyObject[n]; + PyObject[] iters = new PyObject[n]; - public static PyObject max(PyObject[] l) { - if (l.length == 1) { - return max(l[0]); - } - return max(new PyTuple(l)); - } + for (int j = 0; j < n; j++) { + iters[j] = Py.iter(argstar[j + 1], "argument " + (j + 1) + " to map() must support iteration"); + } - private static PyObject max(PyObject o) { - PyObject max = null; - PyObject iter = o.__iter__(); - for (PyObject item; (item = iter.__iternext__()) != null;) { - if (max == null || item._gt(max).__nonzero__()) { - max = item; - } - } - if (max == null) { - throw Py.ValueError("max of empty sequence"); - } - return max; - } + while (true) { + boolean any_items = false; + for (int j = 0; j < n; j++) { + if ((element = iters[j].__iternext__()) != null) { + args[j] = element; + any_items = true; + } else { + args[j] = Py.None; + } + } + if (!any_items) { + break; + } + if (f == Py.None) { + if (n == 1) { + list.append(args[0]); + } else { + list.append(new PyTuple((PyObject[]) args.clone())); + } + } else { + list.append(f.__call__(args)); + } + } + return list; + } - public static PyObject min(PyObject[] l) { - if (l.length == 1) { - return min(l[0]); - } - return min(new PyTuple(l)); - } + // I've never been happy with max and min builtin's... - private static PyObject min(PyObject o) { - PyObject min = null; - PyObject iter = o.__iter__(); - for (PyObject item; (item = iter.__iternext__()) != null;) { - if (min == null || item._lt(min).__nonzero__()) { - min = item; - } - } - if (min == null) { - throw Py.ValueError("min of empty sequence"); - } - return min; - } + public static PyObject max(PyObject[] l) { + if (l.length == 1) { + return max(l[0]); + } + return max(new PyTuple(l)); + } - public static PyString oct(PyObject o) { - return o.__oct__(); - } + private static PyObject max(PyObject o) { + PyObject max = null; + PyObject iter = o.__iter__(); + for (PyObject item; (item = iter.__iternext__()) != null;) { + if (max == null || item._gt(max).__nonzero__()) { + max = item; + } + } + if (max == null) { + throw Py.ValueError("max of empty sequence"); + } + return max; + } - /** - * Open a file read-only. - * - * @param name the file to open. - * @exception java.io.IOException - */ - public static PyFile open(String name) { - return new PyFile(name, "r", -1); - } + public static PyObject min(PyObject[] l) { + if (l.length == 1) { + return min(l[0]); + } + return min(new PyTuple(l)); + } - /** - * Open a file with the specified mode. - * - * @param name name of the file to open. - * @param mode open mode of the file. Use "r", "w", "r+", "w+" and "a". - * @exception java.io.IOException - */ - public static PyFile open(String name, String mode) { - return new PyFile(name, mode, -1); - } + private static PyObject min(PyObject o) { + PyObject min = null; + PyObject iter = o.__iter__(); + for (PyObject item; (item = iter.__iternext__()) != null;) { + if (min == null || item._lt(min).__nonzero__()) { + min = item; + } + } + if (min == null) { + throw Py.ValueError("min of empty sequence"); + } + return min; + } - /** - * Open a file with the specified mode and buffer size. - * - * @param name name of the file to open. - * @param mode open mode of the file. Use "r", "w", "r+", "w+" and "a". - * @param bufsize size of the internal buffer. Not currently used. - * @exception java.io.IOException - */ - public static PyFile open(String name, String mode, int bufsize) { - return new PyFile(name, mode, bufsize); - } + public static PyString oct(PyObject o) { + return o.__oct__(); + } - public static final int ord(char c) { - return c; - } + public static final int ord(char c) { + return c; + } - public static PyObject pow(PyObject x, PyObject y) { - return x._pow(y); - } + public static PyObject pow(PyObject x, PyObject y) { + return x._pow(y); + } - private static boolean coerce(PyObject[] objs) { - PyObject x = objs[0]; - PyObject y = objs[1]; - PyObject[] result; - result = x._coerce(y); - if (result != null) { - objs[0] = result[0]; - objs[1] = result[1]; - return true; - } - result = y._coerce(x); - if (result != null) { - objs[0] = result[1]; - objs[1] = result[0]; - return true; - } - return false; - } + private static boolean coerce(PyObject[] objs) { + PyObject x = objs[0]; + PyObject y = objs[1]; + PyObject[] result; + result = x._coerce(y); + if (result != null) { + objs[0] = result[0]; + objs[1] = result[1]; + return true; + } + result = y._coerce(x); + if (result != null) { + objs[0] = result[1]; + objs[1] = result[0]; + return true; + } + return false; + } - public static PyObject pow(PyObject xi, PyObject yi, PyObject zi) { - PyObject x = xi; - PyObject y = yi; - PyObject z = zi; + public static PyObject pow(PyObject xi, PyObject yi, PyObject zi) { + PyObject x = xi; + PyObject y = yi; + PyObject z = zi; - PyObject[] tmp = new PyObject[2]; + PyObject[] tmp = new PyObject[2]; - tmp[0] = x; - tmp[1] = y; - if (coerce(tmp)) { - x = tmp[0]; - y = tmp[1]; - tmp[1] = z; - if (coerce(tmp)) { - x = tmp[0]; - z = tmp[1]; - tmp[0] = y; - if (coerce(tmp)) { - z = tmp[1]; - y = tmp[0]; - } - } - } else { - tmp[1] = z; - if (coerce(tmp)) { - x = tmp[0]; - z = tmp[1]; - tmp[0] = y; - if (coerce(tmp)) { - y = tmp[0]; - z = tmp[1]; - tmp[1] = x; - if (coerce(tmp)) { - x = tmp[1]; - y = tmp[0]; - } - } - } - } + tmp[0] = x; + tmp[1] = y; + if (coerce(tmp)) { + x = tmp[0]; + y = tmp[1]; + tmp[1] = z; + if (coerce(tmp)) { + x = tmp[0]; + z = tmp[1]; + tmp[0] = y; + if (coerce(tmp)) { + z = tmp[1]; + y = tmp[0]; + } + } + } else { + tmp[1] = z; + if (coerce(tmp)) { + x = tmp[0]; + z = tmp[1]; + tmp[0] = y; + if (coerce(tmp)) { + y = tmp[0]; + z = tmp[1]; + tmp[1] = x; + if (coerce(tmp)) { + x = tmp[1]; + y = tmp[0]; + } + } + } + } - if (x.getType() == y.getType() && x.getType() == z.getType()) { - x = x.__pow__(y, z); - if (x != null) { - return x; - } - } - throw Py.TypeError("__pow__ not defined for these operands"); - } + if (x.getType() == y.getType() && x.getType() == z.getType()) { + x = x.__pow__(y, z); + if (x != null) { + return x; + } + } + throw Py.TypeError("__pow__ not defined for these operands"); + } - public static PyObject range(int start, int stop, int step) { - if (step == 0) { - throw Py.ValueError("zero step for range()"); - } - int n; - if (step > 0) { - n = (stop - start + step - 1) / step; - } else { - n = (stop - start + step + 1) / step; - } - if (n <= 0) { - return new PyList(); - } - PyObject[] l = new PyObject[n]; - int j = start; - for (int i = 0; i < n; i++) { - l[i] = Py.newInteger(j); - j += step; - } - return new PyList(l); - } + public static PyObject range(int start, int stop, int step) { + if (step == 0) { + throw Py.ValueError("zero step for range()"); + } + int n; + if (step > 0) { + n = (stop - start + step - 1) / step; + } else { + n = (stop - start + step + 1) / step; + } + if (n <= 0) { + return new PyList(); + } + PyObject[] l = new PyObject[n]; + int j = start; + for (int i = 0; i < n; i++) { + l[i] = Py.newInteger(j); + j += step; + } + return new PyList(l); + } - public static PyObject range(int n) { - return range(0, n, 1); - } + public static PyObject range(int n) { + return range(0, n, 1); + } - public static PyObject range(int start, int stop) { - return range(start, stop, 1); - } + public static PyObject range(int start, int stop) { + return range(start, stop, 1); + } - private static PyString readline(PyObject file) { - if (file instanceof PyFile) { - return new PyString(((PyFile) file).readline()); - } else { - PyObject ret = file.invoke("readline"); - if (!(ret instanceof PyString)) { - throw Py.TypeError("object.readline() returned non-string"); - } - return (PyString) ret; - } - } + private static PyString readline(PyObject file) { + if (file instanceof PyFile) { + return new PyString(((PyFile) file).readline()); + } else { + PyObject ret = file.invoke("readline"); + if (!(ret instanceof PyString)) { + throw Py.TypeError("object.readline() returned non-string"); + } + return (PyString) ret; + } + } - public static String raw_input(PyObject prompt) { - Py.print(prompt); - PyObject stdin = Py.getSystemState().stdin; - String data = readline(stdin).toString(); - if (data.endsWith("\n")) { - return data.substring(0, data.length() - 1); - } else { - if (data.length() == 0) { - throw Py.EOFError("raw_input()"); - } - } - return data; - } + public static String raw_input(PyObject prompt) { + Py.print(prompt); + PyObject stdin = Py.getSystemState().stdin; + String data = readline(stdin).toString(); + if (data.endsWith("\n")) { + return data.substring(0, data.length() - 1); + } else { + if (data.length() == 0) { + throw Py.EOFError("raw_input()"); + } + } + return data; + } - public static String raw_input() { - return raw_input(new PyString("")); - } + public static String raw_input() { + return raw_input(new PyString("")); + } - public static PyObject reduce(PyObject f, PyObject l, PyObject z) { - PyObject result = z; - PyObject iter = Py.iter(l, "reduce() arg 2 must support iteration"); + public static PyObject reduce(PyObject f, PyObject l, PyObject z) { + PyObject result = z; + PyObject iter = Py.iter(l, "reduce() arg 2 must support iteration"); - for (PyObject item; (item = iter.__iternext__()) != null;) { - if (result == null) { - result = item; - } else { - result = f.__call__(result, item); - } - } - if (result == null) { - throw Py - .TypeError("reduce of empty sequence with no initial value"); - } - return result; - } + for (PyObject item; (item = iter.__iternext__()) != null;) { + if (result == null) { + result = item; + } else { + result = f.__call__(result, item); + } + } + if (result == null) { + throw Py.TypeError("reduce of empty sequence with no initial value"); + } + return result; + } - public static PyObject reduce(PyObject f, PyObject l) { - return reduce(f, l, null); - } + public static PyObject reduce(PyObject f, PyObject l) { + return reduce(f, l, null); + } - public static PyObject reload(PyModule o) { - return imp.reload(o); - } + public static PyObject reload(PyModule o) { + return imp.reload(o); + } - public static PyObject reload(PyJavaClass o) { - return imp.reload(o); - } + public static PyObject reload(PyJavaClass o) { + return imp.reload(o); + } - public static PyString repr(PyObject o) { - return o.__repr__(); - } + public static PyString repr(PyObject o) { + return o.__repr__(); + } - // This seems awfully special purpose... - public static PyFloat round(double f, int digits) { - boolean neg = f < 0; - double multiple = Math.pow(10., digits); - if (neg) { - f = -f; - } - double tmp = Math.floor(f * multiple + 0.5); - if (neg) { - tmp = -tmp; - } - return new PyFloat(tmp / multiple); - } + // This seems awfully special purpose... + public static PyFloat round(double f, int digits) { + boolean neg = f < 0; + double multiple = Math.pow(10., digits); + if (neg) { + f = -f; + } + double tmp = Math.floor(f * multiple + 0.5); + if (neg) { + tmp = -tmp; + } + return new PyFloat(tmp / multiple); + } - public static PyFloat round(double f) { - return round(f, 0); - } + public static PyFloat round(double f) { + return round(f, 0); + } - public static void setattr(PyObject o, PyString n, PyObject v) { - o.__setattr__(n, v); - } + public static void setattr(PyObject o, String n, PyObject v) { + o.__setattr__(n, v); + } - public static PySlice slice(PyObject start, PyObject stop, PyObject step) { - return new PySlice(start, stop, step); - } + public static PySlice slice(PyObject start, PyObject stop, PyObject step) { + return new PySlice(start, stop, step); + } - public static PySlice slice(PyObject start, PyObject stop) { - return slice(start, stop, Py.None); - } + public static PySlice slice(PyObject start, PyObject stop) { + return slice(start, stop, Py.None); + } - public static PySlice slice(PyObject stop) { - return slice(Py.None, stop, Py.None); - } + public static PySlice slice(PyObject stop) { + return slice(Py.None, stop, Py.None); + } - public static PyObject iter(PyObject obj) { - return obj.__iter__(); - } + public static PyObject sum(PyObject seq, PyObject result) { - public static PyObject iter(PyObject callable, PyObject sentinel) { - return new PyCallIter(callable, sentinel); - } + if (result instanceof PyString) { + throw Py.TypeError("sum() can't sum strings [use ''.join(seq) instead]"); + } - public static PyObject sum(PyObject seq, PyObject result) { + PyObject item; + PyObject iter = seq.__iter__(); + while ((item = iter.__iternext__()) != null) { + result = result._add(item); + } + return result; + } - if (result instanceof PyString) { - throw Py - .TypeError("sum() can't sum strings [use ''.join(seq) instead]"); - } + public static PyObject sum(PyObject seq) { + return sum(seq, Py.Zero); + } - PyObject item; - PyObject iter = seq.__iter__(); - while ((item = iter.__iternext__()) != null) { - result = result._add(item); - } - return result; - } + public static PyTuple tuple(PyObject o) { + if (o instanceof PyTuple) { + return (PyTuple) o; + } + if (o instanceof PyList) { + // always make a copy, otherwise the tuple will share the + // underlying data structure with the list object, which + // renders the tuple mutable! + PyList l = (PyList) o; + PyObject[] a = new PyObject[l.size()]; + System.arraycopy(l.getArray(), 0, a, 0, a.length); + return new PyTuple(a); + } + return new PyTuple(Py.make_array(o)); + } - public static PyObject sum(PyObject seq) { - return sum(seq,... [truncated message content] |
From: <cg...@us...> - 2007-04-17 05:41:56
|
Revision: 3155 http://svn.sourceforge.net/jython/?rev=3155&view=rev Author: cgroves Date: 2007-04-16 22:41:53 -0700 (Mon, 16 Apr 2007) Log Message: ----------- exposed operator and comparison methods missing from CPython Modified Paths: -------------- trunk/jython/Lib/test/regrtest.py trunk/jython/NEWS trunk/jython/src/org/python/core/PyComplex.java trunk/jython/src/org/python/core/PyFloat.java trunk/jython/src/org/python/core/PyInteger.java trunk/jython/src/org/python/core/PyLong.java trunk/jython/src/templates/complex.expose trunk/jython/src/templates/float.expose trunk/jython/src/templates/int.expose trunk/jython/src/templates/long.expose Modified: trunk/jython/Lib/test/regrtest.py =================================================================== --- trunk/jython/Lib/test/regrtest.py 2007-04-17 01:38:17 UTC (rev 3154) +++ trunk/jython/Lib/test/regrtest.py 2007-04-17 05:41:53 UTC (rev 3155) @@ -1050,7 +1050,6 @@ 'java': ''' test_atexit - test_class test_cpickle test_descr test_descrtut @@ -1066,7 +1065,6 @@ test_sre test_threaded_import test_trace - test_uu test_weakref test_zlib ''', Modified: trunk/jython/NEWS =================================================================== --- trunk/jython/NEWS 2007-04-17 01:38:17 UTC (rev 3154) +++ trunk/jython/NEWS 2007-04-17 05:41:53 UTC (rev 3155) @@ -23,6 +23,7 @@ - [ 1603747 ] Multiple InteractiveInterpreter share same setErr/Out - [ 1619040 ] dict.fromkeys() should take iterable - [ 1658647 ] type(x) calls x.__class__.__init__ + - [ 1699556 ] SAXException descends from Java's Exception instead of Python's Jython 2.2 beta1 New features Modified: trunk/jython/src/org/python/core/PyComplex.java =================================================================== --- trunk/jython/src/org/python/core/PyComplex.java 2007-04-17 01:38:17 UTC (rev 3154) +++ trunk/jython/src/org/python/core/PyComplex.java 2007-04-17 05:41:53 UTC (rev 3155) @@ -437,6 +437,120 @@ } dict.__setitem__("__truediv__",new PyMethodDescr("__truediv__",PyComplex.class,1,1,new exposed___truediv__(null,null))); + class exposed___eq__ extends PyBuiltinMethodNarrow { + + exposed___eq__(PyObject self,PyBuiltinFunction.Info info) { + super(self,info); + } + + public PyBuiltinFunction bind(PyObject self) { + return new exposed___eq__(self,info); + } + + public PyObject __call__(PyObject arg0) { + PyObject ret=((PyComplex)self).complex___eq__(arg0); + if (ret==null) + return Py.NotImplemented; + return ret; + } + + } + dict.__setitem__("__eq__",new PyMethodDescr("__eq__",PyComplex.class,1,1,new exposed___eq__(null,null))); + class exposed___ne__ extends PyBuiltinMethodNarrow { + + exposed___ne__(PyObject self,PyBuiltinFunction.Info info) { + super(self,info); + } + + public PyBuiltinFunction bind(PyObject self) { + return new exposed___ne__(self,info); + } + + public PyObject __call__(PyObject arg0) { + PyObject ret=((PyComplex)self).complex___ne__(arg0); + if (ret==null) + return Py.NotImplemented; + return ret; + } + + } + dict.__setitem__("__ne__",new PyMethodDescr("__ne__",PyComplex.class,1,1,new exposed___ne__(null,null))); + class exposed___ge__ extends PyBuiltinMethodNarrow { + + exposed___ge__(PyObject self,PyBuiltinFunction.Info info) { + super(self,info); + } + + public PyBuiltinFunction bind(PyObject self) { + return new exposed___ge__(self,info); + } + + public PyObject __call__(PyObject arg0) { + PyObject ret=((PyComplex)self).complex___ge__(arg0); + if (ret==null) + return Py.NotImplemented; + return ret; + } + + } + dict.__setitem__("__ge__",new PyMethodDescr("__ge__",PyComplex.class,1,1,new exposed___ge__(null,null))); + class exposed___le__ extends PyBuiltinMethodNarrow { + + exposed___le__(PyObject self,PyBuiltinFunction.Info info) { + super(self,info); + } + + public PyBuiltinFunction bind(PyObject self) { + return new exposed___le__(self,info); + } + + public PyObject __call__(PyObject arg0) { + PyObject ret=((PyComplex)self).complex___le__(arg0); + if (ret==null) + return Py.NotImplemented; + return ret; + } + + } + dict.__setitem__("__le__",new PyMethodDescr("__le__",PyComplex.class,1,1,new exposed___le__(null,null))); + class exposed___gt__ extends PyBuiltinMethodNarrow { + + exposed___gt__(PyObject self,PyBuiltinFunction.Info info) { + super(self,info); + } + + public PyBuiltinFunction bind(PyObject self) { + return new exposed___gt__(self,info); + } + + public PyObject __call__(PyObject arg0) { + PyObject ret=((PyComplex)self).complex___gt__(arg0); + if (ret==null) + return Py.NotImplemented; + return ret; + } + + } + dict.__setitem__("__gt__",new PyMethodDescr("__gt__",PyComplex.class,1,1,new exposed___gt__(null,null))); + class exposed___lt__ extends PyBuiltinMethodNarrow { + + exposed___lt__(PyObject self,PyBuiltinFunction.Info info) { + super(self,info); + } + + public PyBuiltinFunction bind(PyObject self) { + return new exposed___lt__(self,info); + } + + public PyObject __call__(PyObject arg0) { + PyObject ret=((PyComplex)self).complex___lt__(arg0); + if (ret==null) + return Py.NotImplemented; + return ret; + } + + } + dict.__setitem__("__lt__",new PyMethodDescr("__lt__",PyComplex.class,1,1,new exposed___lt__(null,null))); class exposed___pow__ extends PyBuiltinMethodNarrow { exposed___pow__(PyObject self,PyBuiltinFunction.Info info) { Modified: trunk/jython/src/org/python/core/PyFloat.java =================================================================== --- trunk/jython/src/org/python/core/PyFloat.java 2007-04-17 01:38:17 UTC (rev 3154) +++ trunk/jython/src/org/python/core/PyFloat.java 2007-04-17 05:41:53 UTC (rev 3155) @@ -396,6 +396,44 @@ } dict.__setitem__("__truediv__",new PyMethodDescr("__truediv__",PyFloat.class,1,1,new exposed___truediv__(null,null))); + class exposed___rdivmod__ extends PyBuiltinMethodNarrow { + + exposed___rdivmod__(PyObject self,PyBuiltinFunction.Info info) { + super(self,info); + } + + public PyBuiltinFunction bind(PyObject self) { + return new exposed___rdivmod__(self,info); + } + + public PyObject __call__(PyObject arg0) { + PyObject ret=((PyFloat)self).float___rdivmod__(arg0); + if (ret==null) + return Py.NotImplemented; + return ret; + } + + } + dict.__setitem__("__rdivmod__",new PyMethodDescr("__rdivmod__",PyFloat.class,1,1,new exposed___rdivmod__(null,null))); + class exposed___rpow__ extends PyBuiltinMethodNarrow { + + exposed___rpow__(PyObject self,PyBuiltinFunction.Info info) { + super(self,info); + } + + public PyBuiltinFunction bind(PyObject self) { + return new exposed___rpow__(self,info); + } + + public PyObject __call__(PyObject arg0) { + PyObject ret=((PyFloat)self).float___rpow__(arg0); + if (ret==null) + return Py.NotImplemented; + return ret; + } + + } + dict.__setitem__("__rpow__",new PyMethodDescr("__rpow__",PyFloat.class,1,1,new exposed___rpow__(null,null))); class exposed___cmp__ extends PyBuiltinMethodNarrow { exposed___cmp__(PyObject self,PyBuiltinFunction.Info info) { @@ -866,7 +904,11 @@ ); } + final PyObject float___rdivmod__(PyObject left) { + return __rdivmod__(left); + } + public PyObject __pow__(PyObject right, PyObject modulo) { return float___pow__(right, modulo); } @@ -882,7 +924,11 @@ return _pow(value, coerce(right), modulo); } - + + final PyObject float___rpow__(PyObject left) { + return __rpow__(left); + } + public PyObject __rpow__(PyObject left) { if (!canCoerce(left)) return null; Modified: trunk/jython/src/org/python/core/PyInteger.java =================================================================== --- trunk/jython/src/org/python/core/PyInteger.java 2007-04-17 01:38:17 UTC (rev 3154) +++ trunk/jython/src/org/python/core/PyInteger.java 2007-04-17 05:41:53 UTC (rev 3155) @@ -537,6 +537,139 @@ } dict.__setitem__("__xor__",new PyMethodDescr("__xor__",PyInteger.class,1,1,new exposed___xor__(null,null))); + class exposed___rxor__ extends PyBuiltinMethodNarrow { + + exposed___rxor__(PyObject self,PyBuiltinFunction.Info info) { + super(self,info); + } + + public PyBuiltinFunction bind(PyObject self) { + return new exposed___rxor__(self,info); + } + + public PyObject __call__(PyObject arg0) { + PyObject ret=((PyInteger)self).int___rxor__(arg0); + if (ret==null) + return Py.NotImplemented; + return ret; + } + + } + dict.__setitem__("__rxor__",new PyMethodDescr("__rxor__",PyInteger.class,1,1,new exposed___rxor__(null,null))); + class exposed___rrshift__ extends PyBuiltinMethodNarrow { + + exposed___rrshift__(PyObject self,PyBuiltinFunction.Info info) { + super(self,info); + } + + public PyBuiltinFunction bind(PyObject self) { + return new exposed___rrshift__(self,info); + } + + public PyObject __call__(PyObject arg0) { + PyObject ret=((PyInteger)self).int___rrshift__(arg0); + if (ret==null) + return Py.NotImplemented; + return ret; + } + + } + dict.__setitem__("__rrshift__",new PyMethodDescr("__rrshift__",PyInteger.class,1,1,new exposed___rrshift__(null,null))); + class exposed___ror__ extends PyBuiltinMethodNarrow { + + exposed___ror__(PyObject self,PyBuiltinFunction.Info info) { + super(self,info); + } + + public PyBuiltinFunction bind(PyObject self) { + return new exposed___ror__(self,info); + } + + public PyObject __call__(PyObject arg0) { + PyObject ret=((PyInteger)self).int___ror__(arg0); + if (ret==null) + return Py.NotImplemented; + return ret; + } + + } + dict.__setitem__("__ror__",new PyMethodDescr("__ror__",PyInteger.class,1,1,new exposed___ror__(null,null))); + class exposed___rand__ extends PyBuiltinMethodNarrow { + + exposed___rand__(PyObject self,PyBuiltinFunction.Info info) { + super(self,info); + } + + public PyBuiltinFunction bind(PyObject self) { + return new exposed___rand__(self,info); + } + + public PyObject __call__(PyObject arg0) { + PyObject ret=((PyInteger)self).int___rand__(arg0); + if (ret==null) + return Py.NotImplemented; + return ret; + } + + } + dict.__setitem__("__rand__",new PyMethodDescr("__rand__",PyInteger.class,1,1,new exposed___rand__(null,null))); + class exposed___rpow__ extends PyBuiltinMethodNarrow { + + exposed___rpow__(PyObject self,PyBuiltinFunction.Info info) { + super(self,info); + } + + public PyBuiltinFunction bind(PyObject self) { + return new exposed___rpow__(self,info); + } + + public PyObject __call__(PyObject arg0) { + PyObject ret=((PyInteger)self).int___rpow__(arg0); + if (ret==null) + return Py.NotImplemented; + return ret; + } + + } + dict.__setitem__("__rpow__",new PyMethodDescr("__rpow__",PyInteger.class,1,1,new exposed___rpow__(null,null))); + class exposed___rlshift__ extends PyBuiltinMethodNarrow { + + exposed___rlshift__(PyObject self,PyBuiltinFunction.Info info) { + super(self,info); + } + + public PyBuiltinFunction bind(PyObject self) { + return new exposed___rlshift__(self,info); + } + + public PyObject __call__(PyObject arg0) { + PyObject ret=((PyInteger)self).int___rlshift__(arg0); + if (ret==null) + return Py.NotImplemented; + return ret; + } + + } + dict.__setitem__("__rlshift__",new PyMethodDescr("__rlshift__",PyInteger.class,1,1,new exposed___rlshift__(null,null))); + class exposed___rdivmod__ extends PyBuiltinMethodNarrow { + + exposed___rdivmod__(PyObject self,PyBuiltinFunction.Info info) { + super(self,info); + } + + public PyBuiltinFunction bind(PyObject self) { + return new exposed___rdivmod__(self,info); + } + + public PyObject __call__(PyObject arg0) { + PyObject ret=((PyInteger)self).int___rdivmod__(arg0); + if (ret==null) + return Py.NotImplemented; + return ret; + } + + } + dict.__setitem__("__rdivmod__",new PyMethodDescr("__rdivmod__",PyInteger.class,1,1,new exposed___rdivmod__(null,null))); class exposed___cmp__ extends PyBuiltinMethodNarrow { exposed___cmp__(PyObject self,PyBuiltinFunction.Info info) { @@ -1037,7 +1170,20 @@ Py.newInteger(modulo(v, rightv, xdivy)) }); } + + final PyObject int___rdivmod__(PyObject left){ + if (!canCoerce(left)) + return null; + int leftv = coerce(left); + int v = getValue(); + int xdivy = divide(leftv, v); + return new PyTuple(new PyObject[] { + Py.newInteger(xdivy), + Py.newInteger(modulo(leftv, v, xdivy)) + }); + } + public PyObject __pow__(PyObject right, PyObject modulo) { return int___pow__(right,modulo); } @@ -1061,6 +1207,10 @@ return _pow(coerce(left), getValue(), modulo, left, this); } + + final PyObject int___rpow__(PyObject left){ + return __rpow__(left, null); + } private static PyObject _pow(int value, int pow, PyObject modulo, PyObject left, PyObject right) { @@ -1144,7 +1294,21 @@ throw Py.ValueError("negative shift count"); return Py.newInteger(getValue() << rightv); } + + final PyObject int___rlshift__(PyObject left){ + int leftv; + if (left instanceof PyInteger) + leftv = ((PyInteger)left).getValue(); + else + return null; + if (getValue() > 31) + return Py.newInteger(0); + else if(getValue() < 0) + throw Py.ValueError("negative shift count"); + return Py.newInteger(leftv << getValue()); + } + public PyObject __rshift__(PyObject right) { return int___rshift__(right); } @@ -1162,6 +1326,19 @@ return Py.newInteger(getValue() >> rightv); } + final PyObject int___rrshift__(PyObject left) { + int leftv; + if (left instanceof PyInteger) + leftv = ((PyInteger)left).getValue(); + else + return null; + + if(getValue() < 0) + throw Py.ValueError("negative shift count"); + + return Py.newInteger(leftv >> getValue()); + } + public PyObject __and__(PyObject right) { return int___and__(right); } @@ -1175,6 +1352,10 @@ return Py.newInteger(getValue() & rightv); } + + final PyObject int___rand__(PyObject left){ + return int___and__(left); + } public PyObject __xor__(PyObject right) { return int___xor__(right); @@ -1189,7 +1370,17 @@ return Py.newInteger(getValue() ^ rightv); } + + final PyObject int___rxor__(PyObject left){ + int leftv; + if (left instanceof PyInteger) + leftv = ((PyInteger)left).getValue(); + else + return null; + return Py.newInteger(leftv ^ getValue()); + } + public PyObject __or__(PyObject right) { return int___or__(right); } @@ -1203,6 +1394,10 @@ return Py.newInteger(getValue() | rightv); } + + final PyObject int___ror__(PyObject left){ + return int___or__(left); + } public PyObject __neg__() { return int___neg__(); @@ -1325,4 +1520,12 @@ }) }); } + + //PLACEHOLDER R METHODS + // These r methods just exist to fill out our exposed methods. They return + // null to signify that they can't operate on this object, because if they + // could, it would be a PyInteger and would've been handled by the left operand + // version of this method + + //END PLACEHOLDER R METHODS } Modified: trunk/jython/src/org/python/core/PyLong.java =================================================================== --- trunk/jython/src/org/python/core/PyLong.java 2007-04-17 01:38:17 UTC (rev 3154) +++ trunk/jython/src/org/python/core/PyLong.java 2007-04-17 05:41:53 UTC (rev 3155) @@ -548,6 +548,139 @@ } dict.__setitem__("__xor__",new PyMethodDescr("__xor__",PyLong.class,1,1,new exposed___xor__(null,null))); + class exposed___rxor__ extends PyBuiltinMethodNarrow { + + exposed___rxor__(PyObject self,PyBuiltinFunction.Info info) { + super(self,info); + } + + public PyBuiltinFunction bind(PyObject self) { + return new exposed___rxor__(self,info); + } + + public PyObject __call__(PyObject arg0) { + PyObject ret=((PyLong)self).long___rxor__(arg0); + if (ret==null) + return Py.NotImplemented; + return ret; + } + + } + dict.__setitem__("__rxor__",new PyMethodDescr("__rxor__",PyLong.class,1,1,new exposed___rxor__(null,null))); + class exposed___rrshift__ extends PyBuiltinMethodNarrow { + + exposed___rrshift__(PyObject self,PyBuiltinFunction.Info info) { + super(self,info); + } + + public PyBuiltinFunction bind(PyObject self) { + return new exposed___rrshift__(self,info); + } + + public PyObject __call__(PyObject arg0) { + PyObject ret=((PyLong)self).long___rrshift__(arg0); + if (ret==null) + return Py.NotImplemented; + return ret; + } + + } + dict.__setitem__("__rrshift__",new PyMethodDescr("__rrshift__",PyLong.class,1,1,new exposed___rrshift__(null,null))); + class exposed___ror__ extends PyBuiltinMethodNarrow { + + exposed___ror__(PyObject self,PyBuiltinFunction.Info info) { + super(self,info); + } + + public PyBuiltinFunction bind(PyObject self) { + return new exposed___ror__(self,info); + } + + public PyObject __call__(PyObject arg0) { + PyObject ret=((PyLong)self).long___ror__(arg0); + if (ret==null) + return Py.NotImplemented; + return ret; + } + + } + dict.__setitem__("__ror__",new PyMethodDescr("__ror__",PyLong.class,1,1,new exposed___ror__(null,null))); + class exposed___rand__ extends PyBuiltinMethodNarrow { + + exposed___rand__(PyObject self,PyBuiltinFunction.Info info) { + super(self,info); + } + + public PyBuiltinFunction bind(PyObject self) { + return new exposed___rand__(self,info); + } + + public PyObject __call__(PyObject arg0) { + PyObject ret=((PyLong)self).long___rand__(arg0); + if (ret==null) + return Py.NotImplemented; + return ret; + } + + } + dict.__setitem__("__rand__",new PyMethodDescr("__rand__",PyLong.class,1,1,new exposed___rand__(null,null))); + class exposed___rpow__ extends PyBuiltinMethodNarrow { + + exposed___rpow__(PyObject self,PyBuiltinFunction.Info info) { + super(self,info); + } + + public PyBuiltinFunction bind(PyObject self) { + return new exposed___rpow__(self,info); + } + + public PyObject __call__(PyObject arg0) { + PyObject ret=((PyLong)self).long___rpow__(arg0); + if (ret==null) + return Py.NotImplemented; + return ret; + } + + } + dict.__setitem__("__rpow__",new PyMethodDescr("__rpow__",PyLong.class,1,1,new exposed___rpow__(null,null))); + class exposed___rlshift__ extends PyBuiltinMethodNarrow { + + exposed___rlshift__(PyObject self,PyBuiltinFunction.Info info) { + super(self,info); + } + + public PyBuiltinFunction bind(PyObject self) { + return new exposed___rlshift__(self,info); + } + + public PyObject __call__(PyObject arg0) { + PyObject ret=((PyLong)self).long___rlshift__(arg0); + if (ret==null) + return Py.NotImplemented; + return ret; + } + + } + dict.__setitem__("__rlshift__",new PyMethodDescr("__rlshift__",PyLong.class,1,1,new exposed___rlshift__(null,null))); + class exposed___rdivmod__ extends PyBuiltinMethodNarrow { + + exposed___rdivmod__(PyObject self,PyBuiltinFunction.Info info) { + super(self,info); + } + + public PyBuiltinFunction bind(PyObject self) { + return new exposed___rdivmod__(self,info); + } + + public PyObject __call__(PyObject arg0) { + PyObject ret=((PyLong)self).long___rdivmod__(arg0); + if (ret==null) + return Py.NotImplemented; + return ret; + } + + } + dict.__setitem__("__rdivmod__",new PyMethodDescr("__rdivmod__",PyLong.class,1,1,new exposed___rdivmod__(null,null))); class exposed___cmp__ extends PyBuiltinMethodNarrow { exposed___cmp__(PyObject self,PyBuiltinFunction.Info info) { @@ -594,6 +727,22 @@ } dict.__setitem__("__pow__",new PyMethodDescr("__pow__",PyLong.class,1,2,new exposed___pow__(null,null))); + class exposed___nonzero__ extends PyBuiltinMethodNarrow { + + exposed___nonzero__(PyObject self,PyBuiltinFunction.Info info) { + super(self,info); + } + + public PyBuiltinFunction bind(PyObject self) { + return new exposed___nonzero__(self,info); + } + + public PyObject __call__() { + return Py.newBoolean(((PyLong)self).long___nonzero__()); + } + + } + dict.__setitem__("__nonzero__",new PyMethodDescr("__nonzero__",PyLong.class,0,0,new exposed___nonzero__(null,null))); class exposed___repr__ extends PyBuiltinMethodNarrow { exposed___repr__(PyObject self,PyBuiltinFunction.Info info) { @@ -747,6 +896,10 @@ return !value.equals(BigInteger.valueOf(0)); } + public boolean long___nonzero__() { + return __nonzero__(); + } + public double doubleValue() { double v = value.doubleValue(); if (v == Double.NEGATIVE_INFINITY || v == Double.POSITIVE_INFINITY) { @@ -1189,6 +1342,14 @@ return Py.newLong(value.shiftLeft(rightv)); } + final PyObject long___rlshift__(PyObject left) { + if (!canCoerce(left)) + return null; + if(value.intValue() < 0) + throw Py.ValueError("negative shift count"); + return Py.newLong(coerce(left).shiftLeft(coerceInt(this))); + } + public PyObject __rshift__(PyObject right) { return long___rshift__(right); } @@ -1202,6 +1363,14 @@ return Py.newLong(value.shiftRight(rightv)); } + final PyObject long___rrshift__(PyObject left) { + if (!canCoerce(left)) + return null; + if(value.intValue() < 0) + throw Py.ValueError("negative shift count"); + return Py.newLong(coerce(left).shiftRight(coerceInt(this))); + } + public PyObject __and__(PyObject right) { return long___and__(right); } Modified: trunk/jython/src/templates/complex.expose =================================================================== --- trunk/jython/src/templates/complex.expose 2007-04-17 01:38:17 UTC (rev 3154) +++ trunk/jython/src/templates/complex.expose 2007-04-17 05:41:53 UTC (rev 3155) @@ -6,11 +6,12 @@ expose_getset: real getReal # exposed methods expose_unary: __abs__ __float__ __int__ __long__ \ - __neg__ __pos__ + __neg__ __pos__ expose_binary: __add__ __div__ __divmod__ __floordiv__ \ __mod__ __mul__ __radd__ __rdiv__ __rdivmod__ \ __rfloordiv__ __rmod__ __rmul__ __rpow__ __rsub__ \ - __rtruediv__ __sub__ __truediv__ + __rtruediv__ __sub__ __truediv__ __eq__ __ne__ __ge__ \ + __le__ __gt__ __lt__ #expose_vanilla_cmp expose_vanilla_pow expose_new_immutable: @@ -25,5 +26,4 @@ return Py.newInteger(((`typ)self).complex_hashCode()); # TODO # (__coerce__, __doc__) -# (__eq__, __ge__, __gt__, __le__, __lt__, __ne__) # (__reduce__ ?) Modified: trunk/jython/src/templates/float.expose =================================================================== --- trunk/jython/src/templates/float.expose 2007-04-17 01:38:17 UTC (rev 3154) +++ trunk/jython/src/templates/float.expose 2007-04-17 05:41:53 UTC (rev 3155) @@ -8,7 +8,7 @@ __floordiv__ __mod__ __mul__ \ __radd__ __rdiv__ __rfloordiv__ __rmod__ \ __rmul__ __rsub__ __rtruediv__ \ - __sub__ __truediv__ + __sub__ __truediv__ __rdivmod__ __rpow__ expose_vanilla_cmp expose_vanilla_pow expose_new_immutable: @@ -21,5 +21,3 @@ return Py.newInteger(((PyFloat)self).float_hashCode()); # TODO # (__coerce__, __doc__) -# -# (( __rdivmod__, __rpow__ )) Modified: trunk/jython/src/templates/int.expose =================================================================== --- trunk/jython/src/templates/int.expose 2007-04-17 01:38:17 UTC (rev 3154) +++ trunk/jython/src/templates/int.expose 2007-04-17 05:41:53 UTC (rev 3155) @@ -8,7 +8,8 @@ __floordiv__ __lshift__ __mod__ __mul__ __or__ \ __radd__ __rdiv__ __rfloordiv__ __rmod__ \ __rmul__ __rshift__ __rsub__ __rtruediv__ \ - __sub__ __truediv__ __xor__ + __sub__ __truediv__ __xor__ __rxor__ __rrshift__ \ + __ror__ __rand__ __rpow__ __rlshift__ __rdivmod__ expose_vanilla_cmp expose_vanilla_pow expose_new_immutable: @@ -22,5 +23,3 @@ return Py.newInteger(((`typ)self).int_hashCode()); # TODO # (__coerce__, __doc__) -# -# (( __rand__, __rdivmod__, __rlshift__, __ror__, __rrshift__, __rxor__, __rpow__ )) Modified: trunk/jython/src/templates/long.expose =================================================================== --- trunk/jython/src/templates/long.expose 2007-04-17 01:38:17 UTC (rev 3154) +++ trunk/jython/src/templates/long.expose 2007-04-17 05:41:53 UTC (rev 3155) @@ -8,7 +8,9 @@ __floordiv__ __lshift__ __mod__ __mul__ __or__ \ __radd__ __rdiv__ __rfloordiv__ __rmod__ \ __rmul__ __rshift__ __rsub__ __rtruediv__ \ - __sub__ __truediv__ __xor__ + __sub__ __truediv__ __xor__ __rxor__ __rrshift__ \ + __ror__ __rand__ __rpow__ __rlshift__ __rdivmod__ +expose_meth: :b __nonzero__ expose_vanilla_cmp expose_vanilla_pow expose_new_immutable: @@ -20,5 +22,3 @@ return Py.newInteger(((`typ)self).long_hashCode()); # TODO # (__coerce__, __doc__) -# -# (( __rand__, __rdivmod__, __rlshift__, __ror__, __rrshift__, __rxor__, __rpow__ )) \ No newline at end of file This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <cg...@us...> - 2007-04-17 06:35:15
|
Revision: 3156 http://svn.sourceforge.net/jython/?rev=3156&view=rev Author: cgroves Date: 2007-04-16 23:35:13 -0700 (Mon, 16 Apr 2007) Log Message: ----------- applied patch #1681774 from pjenvey to fix str.decode and unicode.encode Modified Paths: -------------- trunk/jython/Lib/test/test_unicode.py trunk/jython/NEWS trunk/jython/src/org/python/core/PyString.java trunk/jython/src/org/python/core/PyUnicode.java trunk/jython/src/templates/str.expose trunk/jython/src/templates/unicode.expose Modified: trunk/jython/Lib/test/test_unicode.py =================================================================== --- trunk/jython/Lib/test/test_unicode.py 2007-04-17 05:41:53 UTC (rev 3155) +++ trunk/jython/Lib/test/test_unicode.py 2007-04-17 06:35:13 UTC (rev 3156) @@ -485,6 +485,10 @@ verify('%i%s %*.*s' % (10, 3, 5,3,u'abc',) == u'103 abc') print 'done.' +print 'Testing builtin str()...', +verify(str(u"") == "") +verify(isinstance(str(u""), str)) + print 'Testing builtin unicode()...', # unicode(obj) tests (this maps to PyObject_Unicode() at C level) @@ -584,9 +588,8 @@ # UTF-8 specific encoding tests: verify(u''.encode('utf-8') == '') verify(u'\u20ac'.encode('utf-8') == '\xe2\x82\xac') -#XXX: ? -if not sys.platform.startswith('java'): - verify(u'\ud800\udc02'.encode('utf-8') == '\xf0\x90\x80\x82') +verify(u'\ud800\udc02'.encode('utf-8') == '\xf0\x90\x80\x82') +verify(isinstance(u'\ud800\udc02'.encode('utf-8'), str)) verify(u'\ud84d\udc56'.encode('utf-8') == '\xf0\xa3\x91\x96') #XXX: ? if not sys.platform.startswith('java'): @@ -655,15 +658,14 @@ verify(unicode('Andr\202 x','ascii','ignore') == u"Andr x") verify(unicode('Andr\202 x','ascii','replace') == u'Andr\uFFFD x') -# XXX: ? -if not sys.platform.startswith('java'): - verify("\\N{foo}xx".decode("unicode-escape", "ignore") == u"xx") - try: - "\\".decode("unicode-escape") - except ValueError: - pass - else: - raise TestFailed, '"\\".decode("unicode-escape") should fail' +verify("\\N{foo}xx".decode("unicode-escape", "ignore") == u"xx") +verify(isinstance("\\N{foo}xx".decode("unicode-escape", "ignore"), unicode)) +try: + "\\".decode("unicode-escape") +except ValueError: + pass +else: + raise TestFailed, '"\\".decode("unicode-escape") should fail' verify(u'hello'.encode('ascii') == 'hello') # XXX: Jython does not support utf-7 yet. Modified: trunk/jython/NEWS =================================================================== --- trunk/jython/NEWS 2007-04-17 05:41:53 UTC (rev 3155) +++ trunk/jython/NEWS 2007-04-17 06:35:13 UTC (rev 3156) @@ -24,6 +24,8 @@ - [ 1619040 ] dict.fromkeys() should take iterable - [ 1658647 ] type(x) calls x.__class__.__init__ - [ 1699556 ] SAXException descends from Java's Exception instead of Python's + Patches applied + - [ 1681774 ] str.decode, unicode.encode and str(u'') fixes Jython 2.2 beta1 New features Modified: trunk/jython/src/org/python/core/PyString.java =================================================================== --- trunk/jython/src/org/python/core/PyString.java 2007-04-17 05:41:53 UTC (rev 3155) +++ trunk/jython/src/org/python/core/PyString.java 2007-04-17 06:35:13 UTC (rev 3156) @@ -465,7 +465,7 @@ public PyObject __call__(PyObject arg0,PyObject arg1) { try { - return new PyString(((PyString)self).str_decode(arg0.asString(0),arg1.asString(1))); + return new PyUnicode(((PyString)self).str_decode(arg0.asString(0),arg1.asString(1))); } catch (PyObject.ConversionException e) { String msg; switch (e.index) { @@ -482,7 +482,7 @@ public PyObject __call__(PyObject arg0) { try { - return new PyString(((PyString)self).str_decode(arg0.asString(0))); + return new PyUnicode(((PyString)self).str_decode(arg0.asString(0))); } catch (PyObject.ConversionException e) { String msg; switch (e.index) { @@ -497,7 +497,7 @@ } public PyObject __call__() { - return new PyString(((PyString)self).str_decode()); + return new PyUnicode(((PyString)self).str_decode()); } } Modified: trunk/jython/src/org/python/core/PyUnicode.java =================================================================== --- trunk/jython/src/org/python/core/PyUnicode.java 2007-04-17 05:41:53 UTC (rev 3155) +++ trunk/jython/src/org/python/core/PyUnicode.java 2007-04-17 06:35:13 UTC (rev 3156) @@ -409,7 +409,7 @@ public PyObject __call__(PyObject arg0,PyObject arg1) { try { - return new PyUnicode(((PyUnicode)self).unicode_encode(arg0.asString(0),arg1.asString(1))); + return new PyString(((PyUnicode)self).unicode_encode(arg0.asString(0),arg1.asString(1))); } catch (PyObject.ConversionException e) { String msg; switch (e.index) { @@ -426,7 +426,7 @@ public PyObject __call__(PyObject arg0) { try { - return new PyUnicode(((PyUnicode)self).unicode_encode(arg0.asString(0))); + return new PyString(((PyUnicode)self).unicode_encode(arg0.asString(0))); } catch (PyObject.ConversionException e) { String msg; switch (e.index) { @@ -441,7 +441,7 @@ } public PyObject __call__() { - return new PyUnicode(((PyUnicode)self).unicode_encode()); + return new PyString(((PyUnicode)self).unicode_encode()); } } @@ -1491,6 +1491,10 @@ return str___unicode__(); } + public PyString __str__() { + return unicode___str__(); + } + public PyString unicode___str__() { return new PyString(toString()); } Modified: trunk/jython/src/templates/str.expose =================================================================== --- trunk/jython/src/templates/str.expose 2007-04-17 05:41:53 UTC (rev 3155) +++ trunk/jython/src/templates/str.expose 2007-04-17 06:35:13 UTC (rev 3156) @@ -22,7 +22,7 @@ expose_meth: :s capitalize expose_meth: :s center i expose_meth: :i count s i? i? -expose_meth: :s decode s? s? +expose_meth: :u decode s? s? expose_meth: :s encode s? s? expose_meth: :b endswith s i? i? expose_meth: :s expandtabs i? Modified: trunk/jython/src/templates/unicode.expose =================================================================== --- trunk/jython/src/templates/unicode.expose 2007-04-17 05:41:53 UTC (rev 3155) +++ trunk/jython/src/templates/unicode.expose 2007-04-17 06:35:13 UTC (rev 3156) @@ -21,7 +21,7 @@ expose_meth: :u center i expose_meth: :i count s i? i? expose_meth: :u decode s? s? -expose_meth: :u encode s? s? +expose_meth: :s encode s? s? expose_meth: :b endswith s i? i? expose_meth: :u expandtabs i? expose_meth: :i find s i? i? This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <cg...@us...> - 2007-04-17 06:53:16
|
Revision: 3158 http://svn.sourceforge.net/jython/?rev=3158&view=rev Author: cgroves Date: 2007-04-16 23:53:15 -0700 (Mon, 16 Apr 2007) Log Message: ----------- applied patch #1682498 from pjenvey. int(None) now raises a TypeError instead of an AttributeError Modified Paths: -------------- trunk/jython/Lib/test/test_descr.py trunk/jython/src/org/python/core/PyInteger.java Modified: trunk/jython/Lib/test/test_descr.py =================================================================== --- trunk/jython/Lib/test/test_descr.py 2007-04-17 06:37:37 UTC (rev 3157) +++ trunk/jython/Lib/test/test_descr.py 2007-04-17 06:53:15 UTC (rev 3158) @@ -479,6 +479,18 @@ pass else: raise TestFailed, "should have raised OverflowError" + try: + foo = int(None) + except TypeError: + pass + else: + raise TestFailed, "should have raised TypeError" + try: + foo = C(None) + except TypeError: + pass + else: + raise TestFailed, "should have raised TypeError" def longs(): if verbose: print "Testing long operations..." Modified: trunk/jython/src/org/python/core/PyInteger.java =================================================================== --- trunk/jython/src/org/python/core/PyInteger.java 2007-04-17 06:37:37 UTC (rev 3157) +++ trunk/jython/src/org/python/core/PyInteger.java 2007-04-17 06:53:15 UTC (rev 3158) @@ -816,27 +816,24 @@ if (x == null) { return Py.Zero; } - if (base == -909) { - return x.__int__(); - } - if (!(x instanceof PyString)) { - throw Py - .TypeError("int: can't convert non-string with explicit base"); - } + if (base == -909) { + return asPyInteger(x); + } + if (!(x instanceof PyString)) { + throw Py.TypeError("int: can't convert non-string with explicit base"); + } return Py.newInteger(((PyString) x).atoi(base)); } else { if (x == null) { return new PyIntegerDerived(subtype, 0); } if (base == -909) { - PyObject intOrLong = x.__int__(); - if (intOrLong instanceof PyInteger) { - return new PyIntegerDerived(subtype, ((PyInteger)intOrLong).getValue()); - } - else { - throw Py - .OverflowError("long int too large to convert to int"); - } + PyObject intOrLong = asPyInteger(x); + if (intOrLong instanceof PyInteger) { + return new PyIntegerDerived(subtype, ((PyInteger) intOrLong).getValue()); + } else { + throw Py.OverflowError("long int too large to convert to int"); + } } if (!(x instanceof PyString)) { throw Py @@ -845,6 +842,20 @@ return new PyIntegerDerived(subtype, ((PyString) x).atoi(base)); } } // xxx + + /** + * @return the result of x.__int__ + * @throws Py.Type error if x.__int__ throws an Py.AttributeError + */ + private static PyObject asPyInteger(PyObject x) { + try { + return x.__int__(); + } catch (PyException pye) { + if (!Py.matchException(pye, Py.AttributeError)) + throw pye; + throw Py.TypeError("int() argument must be a string or a number"); + } + } private static final PyType INTTYPE = PyType.fromClass(PyInteger.class); This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <cg...@us...> - 2007-04-17 06:37:41
|
Revision: 3157 http://svn.sourceforge.net/jython/?rev=3157&view=rev Author: cgroves Date: 2007-04-16 23:37:37 -0700 (Mon, 16 Apr 2007) Log Message: ----------- applied patch #1682423 from pjenvey to fix bug #1603314. PyModule is now a new-style class. Modified Paths: -------------- trunk/jython/Lib/test/test_descr.py trunk/jython/NEWS trunk/jython/src/org/python/core/PyModule.java trunk/jython/src/templates/mappings Added Paths: ----------- trunk/jython/Lib/test/test_module.py trunk/jython/src/org/python/core/PyModuleDerived.java trunk/jython/src/templates/module.derived trunk/jython/src/templates/module.expose Modified: trunk/jython/Lib/test/test_descr.py =================================================================== --- trunk/jython/Lib/test/test_descr.py 2007-04-17 06:35:13 UTC (rev 3156) +++ trunk/jython/Lib/test/test_descr.py 2007-04-17 06:37:37 UTC (rev 3157) @@ -345,8 +345,8 @@ verify('im_self' in dir(a.Amethod)) # Try a module subclass. - import sys - class M(type(sys)): + from types import ModuleType + class M(ModuleType): pass minstance = M("m") minstance.b = 2 @@ -749,8 +749,7 @@ def pymods(): if verbose: print "Testing Python subclass of module..." log = [] - import sys - MT = type(sys) + from types import ModuleType as MT class MM(MT): def __init__(self, name): MT.__init__(self, name) Added: trunk/jython/Lib/test/test_module.py =================================================================== --- trunk/jython/Lib/test/test_module.py (rev 0) +++ trunk/jython/Lib/test/test_module.py 2007-04-17 06:37:37 UTC (rev 3157) @@ -0,0 +1,77 @@ +# Test the module type + +from test_support import verify, vereq, verbose, TestFailed +from types import ModuleType as module + +# An uninitialized module has no __dict__ or __name__, and __doc__ is None +foo = module.__new__(module) +verify(foo.__dict__ is None) +try: + s = foo.__name__ +except AttributeError: + pass +else: + raise TestFailed, "__name__ = %s" % repr(s) +# __doc__ is None by default in CPython but not in Jython. +# We're not worrying about that now. +#vereq(foo.__doc__, module.__doc__) + +try: + foo_dir = dir(foo) +except TypeError: + pass +else: + raise TestFailed, "__dict__ = %s" % repr(foo_dir) + +try: + del foo.somename +except AttributeError: + pass +else: + raise TestFailed, "del foo.somename" + +try: + del foo.__dict__ +except TypeError: + pass +else: + raise TestFailed, "del foo.__dict__" + +try: + foo.__dict__ = {} +except TypeError: + pass +else: + raise TestFailed, "foo.__dict__ = {}" +verify(foo.__dict__ is None) + +# Regularly initialized module, no docstring +foo = module("foo") +vereq(foo.__name__, "foo") +vereq(foo.__doc__, None) +vereq(foo.__dict__, {"__name__": "foo", "__doc__": None}) + +# ASCII docstring +foo = module("foo", "foodoc") +vereq(foo.__name__, "foo") +vereq(foo.__doc__, "foodoc") +vereq(foo.__dict__, {"__name__": "foo", "__doc__": "foodoc"}) + +# Unicode docstring +foo = module("foo", u"foodoc\u1234") +vereq(foo.__name__, "foo") +vereq(foo.__doc__, u"foodoc\u1234") +vereq(foo.__dict__, {"__name__": "foo", "__doc__": u"foodoc\u1234"}) + +# Reinitialization should not replace the __dict__ +foo.bar = 42 +d = foo.__dict__ +foo.__init__("foo", "foodoc") +vereq(foo.__name__, "foo") +vereq(foo.__doc__, "foodoc") +vereq(foo.bar, 42) +vereq(foo.__dict__, {"__name__": "foo", "__doc__": "foodoc", "bar": 42}) +verify(foo.__dict__ is d) + +if verbose: + print "All OK" Modified: trunk/jython/NEWS =================================================================== --- trunk/jython/NEWS 2007-04-17 06:35:13 UTC (rev 3156) +++ trunk/jython/NEWS 2007-04-17 06:37:37 UTC (rev 3157) @@ -26,6 +26,7 @@ - [ 1699556 ] SAXException descends from Java's Exception instead of Python's Patches applied - [ 1681774 ] str.decode, unicode.encode and str(u'') fixes + - [ 1682423 ] Convert PyModule to a new-style class Jython 2.2 beta1 New features Modified: trunk/jython/src/org/python/core/PyModule.java =================================================================== --- trunk/jython/src/org/python/core/PyModule.java 2007-04-17 06:35:13 UTC (rev 3156) +++ trunk/jython/src/org/python/core/PyModule.java 2007-04-17 06:37:37 UTC (rev 3157) @@ -3,17 +3,201 @@ public class PyModule extends PyObject { + //~ BEGIN GENERATED REGION -- DO NOT EDIT SEE gexpose.py + /* type info */ + + public static final String exposed_name="module"; + + public static void typeSetup(PyObject dict,PyType.Newstyle marker) { + dict.__setitem__("__dict__",new PyGetSetDescr("__dict__",PyModule.class,"getDict","setDict","delDict")); + dict.__setitem__("__doc__",new PyGetSetDescr("__doc__",PyModule.class,"getDoc",null,null)); + class exposed___repr__ extends PyBuiltinMethodNarrow { + + exposed___repr__(PyObject self,PyBuiltinFunction.Info info) { + super(self,info); + } + + public PyBuiltinFunction bind(PyObject self) { + return new exposed___repr__(self,info); + } + + public PyObject __call__() { + return new PyString(((PyModule)self).module_toString()); + } + + } + dict.__setitem__("__repr__",new PyMethodDescr("__repr__",PyModule.class,0,0,new exposed___repr__(null,null))); + class exposed___setattr__ extends PyBuiltinMethodNarrow { + + exposed___setattr__(PyObject self,PyBuiltinFunction.Info info) { + super(self,info); + } + + public PyBuiltinFunction bind(PyObject self) { + return new exposed___setattr__(self,info); + } + + public PyObject __call__(PyObject arg0,PyObject arg1) { + try { + ((PyModule)self).module___setattr__(arg0.asName(0),arg1); + return Py.None; + } catch (PyObject.ConversionException e) { + String msg; + switch (e.index) { + case 0: + msg="attribute name must be a string"; + break; + default: + msg="xxx"; + } + throw Py.TypeError(msg); + } + } + + } + dict.__setitem__("__setattr__",new PyMethodDescr("__setattr__",PyModule.class,2,2,new exposed___setattr__(null,null))); + class exposed___delattr__ extends PyBuiltinMethodNarrow { + + exposed___delattr__(PyObject self,PyBuiltinFunction.Info info) { + super(self,info); + } + + public PyBuiltinFunction bind(PyObject self) { + return new exposed___delattr__(self,info); + } + + public PyObject __call__(PyObject arg0) { + try { + ((PyModule)self).module___delattr__(arg0.asName(0)); + return Py.None; + } catch (PyObject.ConversionException e) { + String msg; + switch (e.index) { + case 0: + msg="attribute name must be a string"; + break; + default: + msg="xxx"; + } + throw Py.TypeError(msg); + } + } + + } + dict.__setitem__("__delattr__",new PyMethodDescr("__delattr__",PyModule.class,1,1,new exposed___delattr__(null,null))); + class exposed___init__ extends PyBuiltinMethod { + + exposed___init__(PyObject self,PyBuiltinFunction.Info info) { + super(self,info); + } + + public PyBuiltinFunction bind(PyObject self) { + return new exposed___init__(self,info); + } + + public PyObject __call__(PyObject[]args) { + return __call__(args,Py.NoKeywords); + } + + public PyObject __call__(PyObject[]args,String[]keywords) { + ((PyModule)self).module_init(args,keywords); + return Py.None; + } + + } + dict.__setitem__("__init__",new PyMethodDescr("__init__",PyModule.class,-1,-1,new exposed___init__(null,null))); + dict.__setitem__("__new__",new PyNewWrapper(PyModule.class,"__new__",-1,-1) { + + public PyObject new_impl(boolean init,PyType subtype,PyObject[]args,String[]keywords) { + PyModule newobj; + if (for_type==subtype) { + newobj=new PyModule(); + if (init) + newobj.module_init(args,keywords); + } else { + newobj=new PyModuleDerived(subtype); + } + return newobj; + } + + }); + } + //~ END GENERATED REGION -- DO NOT EDIT SEE gexpose.py + + private final PyObject module_doc = new PyString( + "module(name[, doc])\n" + + "\n" + + "Create a module object.\n" + + "The name must be a string; the optional doc argument can have any type."); + public PyObject __dict__; + public PyModule() { + super(); + } + + public PyModule(PyType subType) { + super(subType); + } + + public PyModule(PyType subType, String name) { + super(subType); + module_init(new PyString(name), Py.None); + } + + public PyModule(String name) { + this(name, null); + } + public PyModule(String name, PyObject dict) { - if (dict == null) - __dict__ = new PyStringMap(); - else - __dict__ = dict; - __dict__.__setitem__("__name__", new PyString(name)); - __dict__.__setitem__("__doc__", Py.None); + super(); + __dict__ = dict; + module_init(new PyString(name), Py.None); } + final void module_init(PyObject name, PyObject doc) { + ensureDict(); + __dict__.__setitem__("__name__", name); + __dict__.__setitem__("__doc__", doc); + } + + final void module_init(PyObject[] args, String[] keywords) { + ArgParser ap = new ArgParser("__init__", args, keywords, new String[] {"name", + "doc"}); + PyObject name = ap.getPyObject(0); + PyObject docs = ap.getPyObject(1, Py.None); + module_init(name, docs); + } + + public PyObject fastGetDict() { + return __dict__; + } + + public PyObject getDict() { + if (__dict__ == null) + return Py.None; + return __dict__; + } + + public void setDict(PyObject newDict) { + throw Py.TypeError("readonly attribute"); + } + + public void delDict() { + throw Py.TypeError("readonly attribute"); + } + + public PyObject getDoc() { + PyObject d = fastGetDict(); + if (d != null) { + PyObject doc = d.__finditem__("__doc__"); + if (doc != null) { + return doc; + } + } + return module_doc; + } + protected PyObject impAttr(String attr) { PyObject path = __dict__.__finditem__("__path__"); PyObject pyname = __dict__.__finditem__("__name__"); @@ -53,18 +237,27 @@ } return null; + } + public PyObject __findattr__(String attr) { + return module___findattr__(attr); } - public PyObject __findattr__(String attr) { + final PyObject module___findattr__(String attr) { PyObject ret; - ret = __dict__.__finditem__(attr); - if (ret != null) return ret; + if (__dict__ != null) { + ret = __dict__.__finditem__(attr); + if (ret != null) return ret; + } ret = super.__findattr__(attr); if (ret != null) return ret; + if (__dict__ == null) { + return null; + } + PyObject pyname = __dict__.__finditem__("__name__"); if (pyname == null) return null; @@ -72,21 +265,52 @@ } public void __setattr__(String attr, PyObject value) { - __dict__.__setitem__(attr, value); + module___setattr__(attr, value); } + final void module___setattr__(String attr, PyObject value) { + if (attr != "__dict__") + ensureDict(); + super.__setattr__(attr, value); + } + public void __delattr__(String attr) { - __dict__.__delitem__(attr); + module___delattr__(attr); } + final void module___delattr__(String attr) { + super.__delattr__(attr); + } + + public String toString() { + return module_toString(); + } + + final String module_toString() { + PyObject name = null; + PyObject filename = null; + if (__dict__ != null) { + name = __dict__.__finditem__("__name__"); + filename = __dict__.__finditem__("__file__"); + } + if (name == null) + name = new PyString("?"); + if (filename == null) + filename = new PyString("(built-in)"); + else + filename = new PyString("from '" + filename + "'"); + return "<module '" + name + "' " + filename + ">"; + } + public PyObject __dir__() { + if (__dict__ == null) + throw Py.TypeError("module.__dict__ is not a dictionary"); return __dict__.invoke("keys"); } - public String toString() { - PyObject name = __dict__.__finditem__("__name__"); - PyObject file = __dict__.__finditem__("__file__"); - return "<module '"+ name + "' from '" + file + "'>"; + private void ensureDict() { + if (__dict__ == null) + __dict__ = new PyStringMap(); } static private PyObject silly_list = null; @@ -106,13 +330,4 @@ } } - /** - * @see org.python.core.PyObject#safeRepr() - */ - public String safeRepr() throws PyIgnoreMethodTag { - PyObject name = __dict__.__finditem__("__name__"); - if (name == null) return "unnamed module"; - return "module '"+name+"'"; - } - } Added: trunk/jython/src/org/python/core/PyModuleDerived.java =================================================================== --- trunk/jython/src/org/python/core/PyModuleDerived.java (rev 0) +++ trunk/jython/src/org/python/core/PyModuleDerived.java 2007-04-17 06:37:37 UTC (rev 3157) @@ -0,0 +1,930 @@ +package org.python.core; + +public class PyModuleDerived extends PyModule implements Slotted { + + public PyObject getSlot(int index) { + return slots[index]; + } + + public void setSlot(int index,PyObject value) { + slots[index]=value; + } + + private PyObject[]slots; + + public PyModuleDerived(PyType subtype) { + super(subtype); + slots=new PyObject[subtype.getNumSlots()]; + } + + 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 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 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 __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__"); + 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 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 PyInteger||res instanceof PyLong) + return(PyObject)res; + throw Py.TypeError("__int__"+" should return an integer"); + } + return super.__int__(); + } + + 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 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__"); + 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 PyObject __getslice__(PyObject start,PyObject stop,PyObject step) { // ??? + PyType self_type=getType(); + PyObject impl=self_type.lookup("__getslice__"); + if (impl!=null) + try { + return impl.__get__(this,self_type).__call__(start,stop); + } catch (PyException exc) { + if (Py.matchException(exc,Py.LookupError)) + return null; + throw exc; + } + return super.__getslice__(start,stop,step); + } + + 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); + } + } + +} Modified: trunk/jython/src/templates/mappings =================================================================== --- trunk/jython/src/templates/mappings 2007-04-17 06:35:13 UTC (rev 3156) +++ trunk/jython/src/templates/mappings 2007-04-17 06:37:37 UTC (rev 3157) @@ -33,6 +33,8 @@ list.expose:org.python.core.PyList long.derived:org.python.core.PyLongDerived long.expose:org.python.core.PyLong +module.derived:org.python.core.PyModuleDerived +module.expose:org.python.core.PyModule None.expose:org.python.core.PyNone object.derived:org.python.core.PyObjectDerived object.expose:org.python.core.PyObject Added: trunk/jython/src/templates/module.derived =================================================================== --- trunk/jython/src/templates/module.derived (rev 0) +++ trunk/jython/src/templates/module.derived 2007-04-17 06:37:37 UTC (rev 3157) @@ -0,0 +1,4 @@ +base_class: PyModule +want_dict: false +ctr: +incl: object Added: trunk/jython/src/templates/module.expose =================================================================== --- trunk/jython/src/templates/module.expose (rev 0) +++ trunk/jython/src/templates/module.expose 2007-04-17 06:37:37 UTC (rev 3157) @@ -0,0 +1,15 @@ +# setup +type_name: module +type_class: PyModule +# getsets +expose_getset: __dict__ getDict setDict delDict +expose_getset: __doc__ getDoc +# exposed methods +expose_meth: __repr__ + `sdeleg`(toString); +expose_new_mutable: +expose_meth: :- __setattr__ n{attribute name}o +expose_meth: :- __delattr__ n{attribute name} +expose_wide_meth: __init__ -1 -1 + `vdeleg`(init); + `void; This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |