From: <m_...@us...> - 2006-07-18 17:23:19
|
Revision: 2839 Author: m_small Date: 2006-07-18 10:23:11 -0700 (Tue, 18 Jul 2006) ViewCVS: http://svn.sourceforge.net/jython/?rev=2839&view=rev Log Message: ----------- - add template generation ant task, 'ant template' build target - copy sandbox/jt to src/templates Modified Paths: -------------- branches/2.3/build.xml Added Paths: ----------- branches/2.3/src/org/python/util/TemplateAntTask.java branches/2.3/src/templates/ branches/2.3/src/templates/mappings Modified: branches/2.3/build.xml =================================================================== --- branches/2.3/build.xml 2006-07-17 16:41:58 UTC (rev 2838) +++ branches/2.3/build.xml 2006-07-18 17:23:11 UTC (rev 2839) @@ -196,6 +196,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}/src/templates" /> <property name="python.lib" value="${python.home}/Lib" /> </target> @@ -368,6 +369,37 @@ </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" /> + </gentempl> + </target> + + <!-- compile java sources --> <target name="compile" depends="checkout, parser"> <javac srcdir="${source.dir}/" Added: branches/2.3/src/org/python/util/TemplateAntTask.java =================================================================== --- branches/2.3/src/org/python/util/TemplateAntTask.java (rev 0) +++ branches/2.3/src/org/python/util/TemplateAntTask.java 2006-07-18 17:23:11 UTC (rev 2839) @@ -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.separator)+".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; + } +} Copied: branches/2.3/src/templates (from rev 2838, trunk/sandbox/jt) Added: branches/2.3/src/templates/mappings =================================================================== --- branches/2.3/src/templates/mappings (rev 0) +++ branches/2.3/src/templates/mappings 2006-07-18 17:23:11 UTC (rev 2839) @@ -0,0 +1,50 @@ +# mapping file; specifies how expose & derive filenames should map to classes +# for instance, a line like: +# +# str.expose:org.python.core.PyString +# +# will map str.expose to org.python.core.PyString. Many classes will have 2 +# lines; one for their expose, and one for their derived class. + +#baseset.expose +bool.derived:org.python.core.PyBooleanDerived +bool.expose:org.python.core.PyBoolean +classmethod.derived:org.python.core.PyClassMethodDerived +classmethod.expose:org.python.core.PyClassMethod +complex.derived:org.python.core.PyComplexDerived +complex.expose:org.python.core.PyComplex +dict.derived:org.python.core.PyDictionaryDerived +dict.expose:org.python.core.PyDictionary +enumerate.expose:org.python.core.PyEnumerate +#file.derived +#file.expose +float.derived:org.python.core.PyFloatDerived +float.expose:org.python.core.PyFloat +function.expose:org.python.core.PyFunction +#immutableset.expose +int.derived:org.python.core.PyIntegerDerived +int.expose:org.python.core.PyInteger +list.derived:org.python.core.PyListDerived +list.expose:org.python.core.PyList +long.derived:org.python.core.PyLongDerived +long.expose:org.python.core.PyLong +None.expose:org.python.core.PyNone +object.derived:org.python.core.PyObjectDerived +object.expose:org.python.core.PyObject +property.derived:org.python.core.PyPropertyDerived +property.expose:org.python.core.PyProperty +sequence.expose:org.python.core.PySequence +#set.expose +str.expose:org.python.core.PyString +str.derived:org.python.core.PyStringDerived +super.derived:org.python.core.PySuperDerived +super.expose:org.python.core.PySuper +#test.derived +#test.expose +timetuple.expose:org.python.modules.time.PyTimeTuple +tuple.derived:org.python.core.PyTupleDerived +tuple.expose:org.python.core.PyTuple +type.derived:org.python.core.PyTypeDerived +type.expose:org.python.core.PyType +unicode.derived:org.python.core.PyUnicodeDerived +unicode.expose:org.python.core.PyUnicode This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <m_...@us...> - 2006-07-19 22:38:21
|
Revision: 2844 Author: m_small Date: 2006-07-19 15:38:16 -0700 (Wed, 19 Jul 2006) ViewCVS: http://svn.sourceforge.net/jython/?rev=2844&view=rev Log Message: ----------- ignore some derived & expose scripts with custom modifications Modified Paths: -------------- branches/2.3/build.xml branches/2.3/src/templates/mappings Modified: branches/2.3/build.xml =================================================================== --- branches/2.3/build.xml 2006-07-19 22:36:09 UTC (rev 2843) +++ branches/2.3/build.xml 2006-07-19 22:38:16 UTC (rev 2844) @@ -396,6 +396,19 @@ 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> Modified: branches/2.3/src/templates/mappings =================================================================== --- branches/2.3/src/templates/mappings 2006-07-19 22:36:09 UTC (rev 2843) +++ branches/2.3/src/templates/mappings 2006-07-19 22:38:16 UTC (rev 2844) @@ -34,8 +34,7 @@ property.derived:org.python.core.PyPropertyDerived property.expose:org.python.core.PyProperty sequence.expose:org.python.core.PySequence -# XXX commented out; need a fix for different modules -#random.derived:org.python.modules.random.PyRandomDerived +random.derived:org.python.modules.random.PyRandomDerived random.expose:org.python.modules.random.PyRandom #set.expose str.expose:org.python.core.PyString This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <m_...@us...> - 2006-07-20 00:24:14
|
Revision: 2846 Author: m_small Date: 2006-07-19 17:23:58 -0700 (Wed, 19 Jul 2006) ViewCVS: http://svn.sourceforge.net/jython/?rev=2846&view=rev Log Message: ----------- more complete pickle support (from patch 1521369) Modified Paths: -------------- branches/2.3/build.Lib.include.properties branches/2.3/src/org/python/core/PyComplex.java branches/2.3/src/org/python/core/PyInteger.java branches/2.3/src/org/python/core/PyList.java branches/2.3/src/org/python/core/PyObject.java branches/2.3/src/org/python/core/PyString.java branches/2.3/src/org/python/core/PyTuple.java branches/2.3/src/org/python/modules/cPickle.java branches/2.3/src/org/python/modules/types.java branches/2.3/src/templates/complex.expose branches/2.3/src/templates/int.expose branches/2.3/src/templates/list.expose branches/2.3/src/templates/object.expose branches/2.3/src/templates/str.expose branches/2.3/src/templates/tuple.expose Added Paths: ----------- branches/2.3/Lib/dis.py branches/2.3/Lib/opcode.py Removed Paths: ------------- branches/2.3/Lib/copy.py branches/2.3/Lib/inspect.py Deleted: branches/2.3/Lib/copy.py =================================================================== --- branches/2.3/Lib/copy.py 2006-07-19 22:49:26 UTC (rev 2845) +++ branches/2.3/Lib/copy.py 2006-07-20 00:23:58 UTC (rev 2846) @@ -1,330 +0,0 @@ -"""Generic (shallow and deep) copying operations. - -Interface summary: - - import copy - - x = copy.copy(y) # make a shallow copy of y - x = copy.deepcopy(y) # make a deep copy of y - -For module specific errors, copy.error is raised. - -The difference between shallow and deep copying is only relevant for -compound objects (objects that contain other objects, like lists or -class instances). - -- A shallow copy constructs a new compound object and then (to the - extent possible) inserts *the same objects* into in that the - original contains. - -- A deep copy constructs a new compound object and then, recursively, - inserts *copies* into it of the objects found in the original. - -Two problems often exist with deep copy operations that don't exist -with shallow copy operations: - - a) recursive objects (compound objects that, directly or indirectly, - contain a reference to themselves) may cause a recursive loop - - b) because deep copy copies *everything* it may copy too much, e.g. - administrative data structures that should be shared even between - copies - -Python's deep copy operation avoids these problems by: - - a) keeping a table of objects already copied during the current - copying pass - - b) letting user-defined classes override the copying operation or the - set of components copied - -This version does not copy types like module, class, function, method, -nor stack trace, stack frame, nor file, socket, window, nor array, nor -any similar types. - -Classes can use the same interfaces to control copying that they use -to control pickling: they can define methods called __getinitargs__(), -__getstate__() and __setstate__(). See the documentation for module -"pickle" for information on these methods. -""" - -# XXX need to support copy_reg here too... - -import types - -class Error(Exception): - pass -error = Error # backward compatibility - -try: - from org.python.core import PyStringMap -except ImportError: - PyStringMap = None - -__all__ = ["Error","error","copy","deepcopy"] - -def copy(x): - """Shallow copy operation on arbitrary Python objects. - - See the module's __doc__ string for more info. - """ - - try: - copierfunction = _copy_dispatch[type(x)] - except KeyError: - try: - copier = x.__copy__ - except AttributeError: - raise error, \ - "un(shallow)copyable object of type %s" % type(x) - y = copier() - else: - y = copierfunction(x) - return y - -_copy_dispatch = d = {} - -def _copy_atomic(x): - return x -d[types.NoneType] = _copy_atomic -d[types.IntType] = _copy_atomic -d[types.LongType] = _copy_atomic -d[types.FloatType] = _copy_atomic -d[types.StringType] = _copy_atomic -d[types.UnicodeType] = _copy_atomic -try: - d[types.CodeType] = _copy_atomic -except AttributeError: - pass -d[types.TypeType] = _copy_atomic -d[types.XRangeType] = _copy_atomic -d[types.ClassType] = _copy_atomic - -def _copy_list(x): - return x[:] -d[types.ListType] = _copy_list - -def _copy_tuple(x): - return x[:] -d[types.TupleType] = _copy_tuple - -def _copy_dict(x): - return x.copy() -d[types.DictionaryType] = _copy_dict -if PyStringMap is not None: - d[PyStringMap] = _copy_dict - -def _copy_inst(x): - if hasattr(x, '__copy__'): - return x.__copy__() - if hasattr(x, '__getinitargs__'): - args = x.__getinitargs__() - y = apply(x.__class__, args) - else: - if hasattr(x.__class__, '__del__'): - y = _EmptyClassDel() - else: - y = _EmptyClass() - y.__class__ = x.__class__ - if hasattr(x, '__getstate__'): - state = x.__getstate__() - else: - state = x.__dict__ - if hasattr(y, '__setstate__'): - y.__setstate__(state) - else: - y.__dict__.update(state) - return y -d[types.InstanceType] = _copy_inst - -del d - -def deepcopy(x, memo = None): - """Deep copy operation on arbitrary Python objects. - - See the module's __doc__ string for more info. - """ - - if memo is None: - memo = {} - d = id(x) - if memo.has_key(d): - return memo[d] - try: - copierfunction = _deepcopy_dispatch[type(x)] - except KeyError: - try: - copier = x.__deepcopy__ - except AttributeError: - raise error, \ - "un-deep-copyable object of type %s" % type(x) - y = copier(memo) - else: - y = copierfunction(x, memo) - memo[d] = y - return y - -_deepcopy_dispatch = d = {} - -def _deepcopy_atomic(x, memo): - return x -d[types.NoneType] = _deepcopy_atomic -d[types.IntType] = _deepcopy_atomic -d[types.LongType] = _deepcopy_atomic -d[types.FloatType] = _deepcopy_atomic -d[types.StringType] = _deepcopy_atomic -d[types.UnicodeType] = _deepcopy_atomic -d[types.CodeType] = _deepcopy_atomic -d[types.TypeType] = _deepcopy_atomic -d[types.XRangeType] = _deepcopy_atomic - -def _deepcopy_list(x, memo): - y = [] - memo[id(x)] = y - for a in x: - y.append(deepcopy(a, memo)) - return y -d[types.ListType] = _deepcopy_list - -def _deepcopy_tuple(x, memo): - y = [] - for a in x: - y.append(deepcopy(a, memo)) - d = id(x) - try: - return memo[d] - except KeyError: - pass - for i in range(len(x)): - if x[i] is not y[i]: - y = tuple(y) - break - else: - y = x - memo[d] = y - return y -d[types.TupleType] = _deepcopy_tuple - -def _deepcopy_dict(x, memo): - y = {} - memo[id(x)] = y - for key in x.keys(): - y[deepcopy(key, memo)] = deepcopy(x[key], memo) - return y -d[types.DictionaryType] = _deepcopy_dict -if PyStringMap is not None: - d[PyStringMap] = _deepcopy_dict - -def _keep_alive(x, memo): - """Keeps a reference to the object x in the memo. - - Because we remember objects by their id, we have - to assure that possibly temporary objects are kept - alive by referencing them. - We store a reference at the id of the memo, which should - normally not be used unless someone tries to deepcopy - the memo itself... - """ - try: - memo[id(memo)].append(x) - except KeyError: - # aha, this is the first one :-) - memo[id(memo)]=[x] - -def _deepcopy_inst(x, memo): - if hasattr(x, '__deepcopy__'): - return x.__deepcopy__(memo) - if hasattr(x, '__getinitargs__'): - args = x.__getinitargs__() - _keep_alive(args, memo) - args = deepcopy(args, memo) - y = apply(x.__class__, args) - else: - if hasattr(x.__class__, '__del__'): - y = _EmptyClassDel() - else: - y = _EmptyClass() - y.__class__ = x.__class__ - memo[id(x)] = y - if hasattr(x, '__getstate__'): - state = x.__getstate__() - _keep_alive(state, memo) - else: - state = x.__dict__ - state = deepcopy(state, memo) - if hasattr(y, '__setstate__'): - y.__setstate__(state) - else: - y.__dict__.update(state) - return y -d[types.InstanceType] = _deepcopy_inst - -del d - -del types - -# Helper for instance creation without calling __init__ -class _EmptyClass: - pass - -# Helper for instance creation without calling __init__. Used when -# the source class contains a __del__ attribute. -class _EmptyClassDel: - def __del__(self): - pass - -def _test(): - l = [None, 1, 2L, 3.14, 'xyzzy', (1, 2L), [3.14, 'abc'], - {'abc': 'ABC'}, (), [], {}] - l1 = copy(l) - print l1==l - l1 = map(copy, l) - print l1==l - l1 = deepcopy(l) - print l1==l - class C: - def __init__(self, arg=None): - self.a = 1 - self.arg = arg - if __name__ == '__main__': - import sys - file = sys.argv[0] - else: - file = __file__ - self.fp = open(file) - self.fp.close() - def __getstate__(self): - return {'a': self.a, 'arg': self.arg} - def __setstate__(self, state): - for key in state.keys(): - setattr(self, key, state[key]) - def __deepcopy__(self, memo = None): - new = self.__class__(deepcopy(self.arg, memo)) - new.a = self.a - return new - c = C('argument sketch') - l.append(c) - l2 = copy(l) - print l == l2 - print l - print l2 - l2 = deepcopy(l) - print l == l2 - print l - print l2 - l.append({l[1]: l, 'xyz': l[2]}) - l3 = copy(l) - import repr - print map(repr.repr, l) - print map(repr.repr, l1) - print map(repr.repr, l2) - print map(repr.repr, l3) - l3 = deepcopy(l) - import repr - print map(repr.repr, l) - print map(repr.repr, l1) - print map(repr.repr, l2) - print map(repr.repr, l3) - -if __name__ == '__main__': - _test() Added: branches/2.3/Lib/dis.py =================================================================== --- branches/2.3/Lib/dis.py (rev 0) +++ branches/2.3/Lib/dis.py 2006-07-20 00:23:58 UTC (rev 2846) @@ -0,0 +1 @@ +# stub dis module added to allow imports Deleted: branches/2.3/Lib/inspect.py =================================================================== --- branches/2.3/Lib/inspect.py 2006-07-19 22:49:26 UTC (rev 2845) +++ branches/2.3/Lib/inspect.py 2006-07-20 00:23:58 UTC (rev 2846) @@ -1,23 +0,0 @@ -# -# Very simple version of inspect, just enough is supported for -# doctest to work. -# - -import org.python.core as _core - -def isclass(cls): - return isinstance(cls, _core.PyClass) - -def isfunction(func): - return isinstance(func, _core.PyFunction) - -def ismodule(mod): - return isinstance(mod, _core.PyModule) - -def ismethod(meth): - return isinstance(meth, _core.PyMethod) - -def classify_class_attrs(obj): - return [] - - Added: branches/2.3/Lib/opcode.py =================================================================== --- branches/2.3/Lib/opcode.py (rev 0) +++ branches/2.3/Lib/opcode.py 2006-07-20 00:23:58 UTC (rev 2846) @@ -0,0 +1 @@ +# stub opcode module added to allow imports Modified: branches/2.3/build.Lib.include.properties =================================================================== --- branches/2.3/build.Lib.include.properties 2006-07-19 22:49:26 UTC (rev 2845) +++ branches/2.3/build.Lib.include.properties 2006-07-20 00:23:58 UTC (rev 2846) @@ -57,6 +57,7 @@ httplib.py imaplib.py imghdr.py +inspect.py keyword.py linecache.py macpath.py @@ -77,6 +78,7 @@ nturl2path.py pdb.py pickle.py +pickletools.py pipes.py poplib.py posixfile.py Modified: branches/2.3/src/org/python/core/PyComplex.java =================================================================== --- branches/2.3/src/org/python/core/PyComplex.java 2006-07-19 22:49:26 UTC (rev 2845) +++ branches/2.3/src/org/python/core/PyComplex.java 2006-07-20 00:23:58 UTC (rev 2846) @@ -869,34 +869,6 @@ } dict.__setitem__("__nonzero__",new PyMethodDescr("__nonzero__",PyComplex.class,0,0,new exposed___nonzero__(null,null))); - class exposed___reduce__ extends PyBuiltinFunctionNarrow { - - private PyComplex self; - - public PyObject getSelf() { - return self; - } - - exposed___reduce__(PyComplex self,PyBuiltinFunction.Info info) { - super(info); - this.self=self; - } - - public PyBuiltinFunction makeBound(PyObject self) { - return new exposed___reduce__((PyComplex)self,info); - } - - public PyObject __call__() { - return self.complex___reduce__(); - } - - public PyObject inst_call(PyObject gself) { - PyComplex self=(PyComplex)gself; - return self.complex___reduce__(); - } - - } - dict.__setitem__("__reduce__",new PyMethodDescr("__reduce__",PyComplex.class,0,0,new exposed___reduce__(null,null))); class exposed___repr__ extends PyBuiltinFunctionNarrow { private PyComplex self; @@ -1623,24 +1595,6 @@ return new PyComplex(real, -imag); } - /** - * Used for pickling. - * - * @return a tuple of (class, (Integer)) - */ - public PyObject __reduce__() { - return complex___reduce__(); - } - - final PyObject complex___reduce__() { - return new PyTuple(new PyObject[]{ - getType(), - new PyTuple(new PyObject[]{ - getReal(), getImag() - }) - }); - } - public boolean isMappingType() { return false; } public boolean isSequenceType() { return false; } } Modified: branches/2.3/src/org/python/core/PyInteger.java =================================================================== --- branches/2.3/src/org/python/core/PyInteger.java 2006-07-19 22:49:26 UTC (rev 2845) +++ branches/2.3/src/org/python/core/PyInteger.java 2006-07-20 00:23:58 UTC (rev 2846) @@ -1058,34 +1058,6 @@ } dict.__setitem__("__nonzero__",new PyMethodDescr("__nonzero__",PyInteger.class,0,0,new exposed___nonzero__(null,null))); - class exposed___reduce__ extends PyBuiltinFunctionNarrow { - - private PyInteger self; - - public PyObject getSelf() { - return self; - } - - exposed___reduce__(PyInteger self,PyBuiltinFunction.Info info) { - super(info); - this.self=self; - } - - public PyBuiltinFunction makeBound(PyObject self) { - return new exposed___reduce__((PyInteger)self,info); - } - - public PyObject __call__() { - return self.int___reduce__(); - } - - public PyObject inst_call(PyObject gself) { - PyInteger self=(PyInteger)gself; - return self.int___reduce__(); - } - - } - dict.__setitem__("__reduce__",new PyMethodDescr("__reduce__",PyInteger.class,0,0,new exposed___reduce__(null,null))); class exposed___repr__ extends PyBuiltinFunctionNarrow { private PyInteger self; @@ -1812,22 +1784,4 @@ public int asInt(int index) { return getValue(); } - - /** - * Used for pickling. - * - * @return a tuple of (class, (Integer)) - */ - public PyObject __reduce__() { - return int___reduce__(); - } - - final PyObject int___reduce__() { - return new PyTuple(new PyObject[]{ - getType(), - new PyTuple(new PyObject[]{ - Py.newInteger(getValue()) - }) - }); - } } Modified: branches/2.3/src/org/python/core/PyList.java =================================================================== --- branches/2.3/src/org/python/core/PyList.java 2006-07-19 22:49:26 UTC (rev 2845) +++ branches/2.3/src/org/python/core/PyList.java 2006-07-20 00:23:58 UTC (rev 2846) @@ -892,34 +892,6 @@ } dict.__setitem__("__imul__",new PyMethodDescr("__imul__",PyList.class,1,1,new exposed___imul__(null,null))); - class exposed___reduce__ extends PyBuiltinFunctionNarrow { - - private PyList self; - - public PyObject getSelf() { - return self; - } - - exposed___reduce__(PyList self,PyBuiltinFunction.Info info) { - super(info); - this.self=self; - } - - public PyBuiltinFunction makeBound(PyObject self) { - return new exposed___reduce__((PyList)self,info); - } - - public PyObject __call__() { - return self.list___reduce__(); - } - - public PyObject inst_call(PyObject gself) { - PyList self=(PyList)gself; - return self.list___reduce__(); - } - - } - dict.__setitem__("__reduce__",new PyMethodDescr("__reduce__",PyList.class,0,0,new exposed___reduce__(null,null))); class exposed___mul__ extends PyBuiltinFunctionNarrow { private PyList self; @@ -1711,22 +1683,6 @@ throw Py.TypeError("unhashable type"); } - /** - * Used for pickling. - * - * @return a tuple of (class, tuple) - */ - public PyObject __reduce__() { - return list___reduce__(); - } - - final PyObject list___reduce__() { - PyTuple newargs = __getnewargs__(); - return new PyTuple(new PyObject[]{ - getType(), newargs - }); - } - public PyTuple __getnewargs__() { return new PyTuple(new PyObject[] {new PyTuple(list.getArray())} Modified: branches/2.3/src/org/python/core/PyObject.java =================================================================== --- branches/2.3/src/org/python/core/PyObject.java 2006-07-19 22:49:26 UTC (rev 2845) +++ branches/2.3/src/org/python/core/PyObject.java 2006-07-20 00:23:58 UTC (rev 2846) @@ -48,6 +48,67 @@ } dict.__setitem__("__reduce__",new PyMethodDescr("__reduce__",PyObject.class,0,0,new exposed___reduce__(null,null))); + class exposed___reduce_ex__ extends PyBuiltinFunctionNarrow { + + private PyObject self; + + public PyObject getSelf() { + return self; + } + + exposed___reduce_ex__(PyObject self,PyBuiltinFunction.Info info) { + super(info); + this.self=self; + } + + public PyBuiltinFunction makeBound(PyObject self) { + return new exposed___reduce_ex__((PyObject)self,info); + } + + public PyObject __call__(PyObject arg0) { + try { + return self.object___reduce_ex__(arg0.asInt(0)); + } catch (PyObject.ConversionException e) { + String msg; + switch (e.index) { + case 0: + msg="expected an integer"; + break; + default: + msg="xxx"; + } + throw Py.TypeError(msg); + } + } + + public PyObject inst_call(PyObject gself,PyObject arg0) { + PyObject self=(PyObject)gself; + try { + return self.object___reduce_ex__(arg0.asInt(0)); + } catch (PyObject.ConversionException e) { + String msg; + switch (e.index) { + case 0: + msg="expected an integer"; + break; + default: + msg="xxx"; + } + throw Py.TypeError(msg); + } + } + + public PyObject __call__() { + return self.object___reduce_ex__(); + } + + public PyObject inst_call(PyObject gself) { + PyObject self=(PyObject)gself; + return self.object___reduce_ex__(); + } + + } + dict.__setitem__("__reduce_ex__",new PyMethodDescr("__reduce_ex__",PyObject.class,0,1,new exposed___reduce_ex__(null,null))); class exposed___str__ extends PyBuiltinFunctionNarrow { private PyObject self; @@ -2917,7 +2978,7 @@ } /** - * Used for pickling. + * Used for pickling. Default implementation calls __reduce_ex__(0). * * @return a tuple of (class, tuple) */ @@ -2926,12 +2987,151 @@ } final PyObject object___reduce__() { - PyTuple newargs = __getnewargs__(); - return new PyTuple(new PyObject[]{ - getType(), newargs - }); + return object___reduce_ex__(0); } + /** Used for pickling. If the subclass specifies __reduce__, it will + * override __reduce_ex__ in the base-class, even if __reduce_ex__ was + * called with an argument. + * + * @param arg PyInteger specifying reduce algorithm (method without this + * argument defaults to 0). + * @return a tuple of (class, tuple) + */ + public PyObject __reduce_ex__(int arg) { + return object___reduce_ex__(arg); + } + public PyObject __reduce_ex__() { + return object___reduce_ex__(0); + } + final PyObject object___reduce_ex__() { + return object___reduce_ex__(0); + } + final PyObject object___reduce_ex__(int arg) { + PyObject res; + + PyObject clsreduce=this.getType().__findattr__("__reduce__"); + PyObject objreduce=(new PyObject()).getType().__findattr__("__reduce__"); + + if (clsreduce!=objreduce) { + res=this.__reduce__(); + } else if (arg>=2) { + res=reduce_2(); + } else { + PyObject copyreg=__builtin__.__import__("copy_reg", null, null, + Py.EmptyTuple); + PyObject copyreg_reduce=copyreg.__findattr__("_reduce_ex"); + res=copyreg_reduce.__call__(this, new PyInteger(arg)); + } + return res; + } + + private static PyObject slotnames(PyObject cls) { + PyObject slotnames; + + slotnames=cls.__findattr__("__slotnames__"); + if(null!=slotnames) { + return slotnames; + } + + PyObject copyreg=__builtin__.__import__("copy_reg", null, null, + Py.EmptyTuple); + PyObject copyreg_slotnames=copyreg.__findattr__("_slotnames"); + slotnames=copyreg_slotnames.__call__(cls); + if (null!=slotnames && Py.None!=slotnames && + (!(slotnames instanceof PyList))) { + throw Py.TypeError("copy_reg._slotnames didn't return a list or None"); + } + + return slotnames; + } + + private PyObject reduce_2() { + PyObject args, state; + PyObject res=null; + int n,i; + + PyObject cls=this.__findattr__("__class__"); + + PyObject getnewargs=this.__findattr__("__getnewargs__"); + if (null!=getnewargs) { + args=getnewargs.__call__(); + if (null!=args && !(args instanceof PyTuple)) { + throw Py.TypeError("__getnewargs__ should return a tuple"); + } + } else { + args=Py.EmptyTuple; + } + + PyObject getstate=this.__findattr__("__getstate__"); + if (null!=getstate) { + state=getstate.__call__(); + if (null==state) { + return res; + } + } else { + state=this.__findattr__("__dict__"); + if (null==state) { + state=Py.None; + } + + PyObject names=slotnames(cls); + if (null==names) { + return res; + } + + if (names != Py.None) { + if (!(names instanceof PyList)) { + throw Py.AssertionError("slots not a list"); + } + PyObject slots=new PyDictionary(); + + n=0; + for (i=0;i<((PyList)names).size();i++) { + PyObject name=((PyList)names).pyget(i); + PyObject value=this.__findattr__(name.toString()); + if (null==value) { + // do nothing + } else { + slots.__setitem__(name, value); + n++; + } + } + if (n>0) { + state=new PyTuple(new PyObject[] {state, slots}); + } + } + } + PyObject listitems; + PyObject dictitems; + if (!(this instanceof PyList)) { + listitems=Py.None; + } else { + listitems=((PyList)this).__iter__(); + } + if (!(this instanceof PyDictionary)) { + dictitems=Py.None; + } else { + dictitems=((PyDictionary)this).iteritems(); + } + + PyObject copyreg=__builtin__.__import__("copy_reg", null, null, + Py.EmptyTuple); + PyObject newobj=copyreg.__findattr__("__newobj__"); + + n=((PyTuple)args).size(); + PyObject args2[]=new PyObject[n+1]; + args2[0]=cls; + for(i=0;i<n;i++) { + args2[i+1]=((PyTuple)args).pyget(i); + } + + res=new PyTuple(new PyObject[] {newobj, + new PyTuple(args2), state, listitems, dictitems}); + + return res; + } + public PyTuple __getnewargs__() { //default is empty tuple return new PyTuple(); Modified: branches/2.3/src/org/python/core/PyString.java =================================================================== --- branches/2.3/src/org/python/core/PyString.java 2006-07-19 22:49:26 UTC (rev 2845) +++ branches/2.3/src/org/python/core/PyString.java 2006-07-20 00:23:58 UTC (rev 2846) @@ -285,34 +285,6 @@ } dict.__setitem__("__mul__",new PyMethodDescr("__mul__",PyString.class,1,1,new exposed___mul__(null,null))); - class exposed___reduce__ extends PyBuiltinFunctionNarrow { - - private PyString self; - - public PyObject getSelf() { - return self; - } - - exposed___reduce__(PyString self,PyBuiltinFunction.Info info) { - super(info); - this.self=self; - } - - public PyBuiltinFunction makeBound(PyObject self) { - return new exposed___reduce__((PyString)self,info); - } - - public PyObject __call__() { - return self.str___reduce__(); - } - - public PyObject inst_call(PyObject gself) { - PyString self=(PyString)gself; - return self.str___reduce__(); - } - - } - dict.__setitem__("__reduce__",new PyMethodDescr("__reduce__",PyString.class,0,0,new exposed___reduce__(null,null))); class exposed___rmul__ extends PyBuiltinFunctionNarrow { private PyString self; @@ -3480,19 +3452,6 @@ return seq___getitem__(index); } - /** - * Used for pickling. - * - * @return a tuple of (class, tuple) - */ - public PyObject __reduce__() { - return str___reduce__(); - } - - final PyObject str___reduce__() { - return object___reduce__(); - } - public PyTuple __getnewargs__() { return new PyTuple(new PyObject[]{ new PyString(str_toString()) Modified: branches/2.3/src/org/python/core/PyTuple.java =================================================================== --- branches/2.3/src/org/python/core/PyTuple.java 2006-07-19 22:49:26 UTC (rev 2845) +++ branches/2.3/src/org/python/core/PyTuple.java 2006-07-20 00:23:58 UTC (rev 2846) @@ -175,7 +175,7 @@ } dict.__setitem__("__add__",new PyMethodDescr("__add__",PyTuple.class,1,1,new exposed___add__(null,null))); - class exposed___reduce__ extends PyBuiltinFunctionNarrow { + class exposed___mul__ extends PyBuiltinFunctionNarrow { private PyTuple self; @@ -183,27 +183,27 @@ return self; } - exposed___reduce__(PyTuple self,PyBuiltinFunction.Info info) { + exposed___mul__(PyTuple self,PyBuiltinFunction.Info info) { super(info); this.self=self; } public PyBuiltinFunction makeBound(PyObject self) { - return new exposed___reduce__((PyTuple)self,info); + return new exposed___mul__((PyTuple)self,info); } - public PyObject __call__() { - return self.tuple___reduce__(); + public PyObject __call__(PyObject arg0) { + return self.tuple___mul__(arg0); } - public PyObject inst_call(PyObject gself) { + public PyObject inst_call(PyObject gself,PyObject arg0) { PyTuple self=(PyTuple)gself; - return self.tuple___reduce__(); + return self.tuple___mul__(arg0); } } - dict.__setitem__("__reduce__",new PyMethodDescr("__reduce__",PyTuple.class,0,0,new exposed___reduce__(null,null))); - class exposed___mul__ extends PyBuiltinFunctionNarrow { + dict.__setitem__("__mul__",new PyMethodDescr("__mul__",PyTuple.class,1,1,new exposed___mul__(null,null))); + class exposed___rmul__ extends PyBuiltinFunctionNarrow { private PyTuple self; @@ -211,27 +211,27 @@ return self; } - exposed___mul__(PyTuple self,PyBuiltinFunction.Info info) { + exposed___rmul__(PyTuple self,PyBuiltinFunction.Info info) { super(info); this.self=self; } public PyBuiltinFunction makeBound(PyObject self) { - return new exposed___mul__((PyTuple)self,info); + return new exposed___rmul__((PyTuple)self,info); } public PyObject __call__(PyObject arg0) { - return self.tuple___mul__(arg0); + return self.tuple___rmul__(arg0); } public PyObject inst_call(PyObject gself,PyObject arg0) { PyTuple self=(PyTuple)gself; - return self.tuple___mul__(arg0); + return self.tuple___rmul__(arg0); } } - dict.__setitem__("__mul__",new PyMethodDescr("__mul__",PyTuple.class,1,1,new exposed___mul__(null,null))); - class exposed___rmul__ extends PyBuiltinFunctionNarrow { + dict.__setitem__("__rmul__",new PyMethodDescr("__rmul__",PyTuple.class,1,1,new exposed___rmul__(null,null))); + class exposed___getitem__ extends PyBuiltinFunctionNarrow { private PyTuple self; @@ -239,26 +239,26 @@ return self; } - exposed___rmul__(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___rmul__((PyTuple)self,info); + return new exposed___getitem__((PyTuple)self,info); } public PyObject __call__(PyObject arg0) { - return self.tuple___rmul__(arg0); + return self.tuple___getitem__(arg0); } public PyObject inst_call(PyObject gself,PyObject arg0) { PyTuple self=(PyTuple)gself; - return self.tuple___rmul__(arg0); + return self.tuple___getitem__(arg0); } } - dict.__setitem__("__rmul__",new PyMethodDescr("__rmul__",PyTuple.class,1,1,new exposed___rmul__(null,null))); + dict.__setitem__("__getitem__",new PyMethodDescr("__getitem__",PyTuple.class,1,1,new exposed___getitem__(null,null))); class exposed___getslice__ extends PyBuiltinFunctionNarrow { private PyTuple self; @@ -296,34 +296,6 @@ } dict.__setitem__("__getslice__",new PyMethodDescr("__getslice__",PyTuple.class,2,3,new exposed___getslice__(null,null))); - class exposed___getitem__ extends PyBuiltinFunctionNarrow { - - private PyTuple self; - - public PyObject getSelf() { - return self; - } - - exposed___getitem__(PyTuple self,PyBuiltinFunction.Info info) { - super(info); - this.self=self; - } - - public PyBuiltinFunction makeBound(PyObject self) { - return new exposed___getitem__((PyTuple)self,info); - } - - public PyObject __call__(PyObject arg0) { - return self.tuple___getitem__(arg0); - } - - public PyObject inst_call(PyObject gself,PyObject arg0) { - PyTuple self=(PyTuple)gself; - return self.tuple___getitem__(arg0); - } - - } - dict.__setitem__("__getitem__",new PyMethodDescr("__getitem__",PyTuple.class,1,1,new exposed___getitem__(null,null))); class exposed___hash__ extends PyBuiltinFunctionNarrow { private PyTuple self; @@ -539,23 +511,6 @@ return seq___getitem__(index); } - - /** - * Used for pickling. - * - * @return a tuple of (class, tuple) - */ - public PyObject __reduce__() { - return tuple___reduce__(); - } - - final PyObject tuple___reduce__() { - PyTuple newargs = __getnewargs__(); - return new PyTuple(new PyObject[]{ - getType(), newargs - }); - } - public PyTuple __getnewargs__() { return new PyTuple(new PyObject[] {new PyList(list.getArray())} Modified: branches/2.3/src/org/python/modules/cPickle.java =================================================================== --- branches/2.3/src/org/python/modules/cPickle.java 2006-07-19 22:49:26 UTC (rev 2845) +++ branches/2.3/src/org/python/modules/cPickle.java 2006-07-20 00:23:58 UTC (rev 2846) @@ -343,6 +343,10 @@ public static final String[] compatible_formats = new String[] { "1.0", "1.1", "1.2" }; + /** + * Highest protocol version supported. + */ + public static final int HIGHEST_PROTOCOL = 2; public static String[] __depends__ = new String[] { "copy_reg", @@ -450,8 +454,8 @@ PyModule copyreg = (PyModule)importModule("copy_reg"); dispatch_table = (PyDictionary)copyreg.__getattr__("dispatch_table"); - safe_constructors = (PyDictionary) - copyreg.__getattr__("safe_constructors"); + // safe_constructors = (PyDictionary) + // copyreg.__getattr__("safe_constructors"); PickleError = buildClass("PickleError", Py.Exception, "_PickleError", ""); Modified: branches/2.3/src/org/python/modules/types.java =================================================================== --- branches/2.3/src/org/python/modules/types.java 2006-07-19 22:49:26 UTC (rev 2845) +++ branches/2.3/src/org/python/modules/types.java 2006-07-20 00:23:58 UTC (rev 2846) @@ -48,7 +48,7 @@ dict.__setitem__("TracebackType", PyType.fromClass(PyTraceback.class)); dict.__setitem__("TupleType", PyType.fromClass(PyTuple.class)); - dict.__setitem__("TypeType", PyType.fromClass(PyJavaClass.class)); + dict.__setitem__("TypeType", PyType.fromClass(PyType.class)); dict.__setitem__("UnboundMethodType", PyType.fromClass(PyMethod.class)); dict.__setitem__("UnicodeType", PyType.fromClass(PyString.class)); Modified: branches/2.3/src/templates/complex.expose =================================================================== --- branches/2.3/src/templates/complex.expose 2006-07-19 22:49:26 UTC (rev 2845) +++ branches/2.3/src/templates/complex.expose 2006-07-20 00:23:58 UTC (rev 2846) @@ -16,7 +16,6 @@ expose_new_immutable: expose_meth: conjugate expose_meth: :b __nonzero__ -expose_meth: :o __reduce__ expose_meth: __repr__ return new PyString(self.complex_toString()); expose_meth: __str__ Modified: branches/2.3/src/templates/int.expose =================================================================== --- branches/2.3/src/templates/int.expose 2006-07-19 22:49:26 UTC (rev 2845) +++ branches/2.3/src/templates/int.expose 2006-07-20 00:23:58 UTC (rev 2846) @@ -13,7 +13,6 @@ expose_vanilla_pow expose_new_immutable: expose_meth: :b __nonzero__ -expose_meth: :o __reduce__ expose_meth: __repr__ return new PyString(self.int_toString()); expose_meth: __str__ Modified: branches/2.3/src/templates/list.expose =================================================================== --- branches/2.3/src/templates/list.expose 2006-07-19 22:49:26 UTC (rev 2845) +++ branches/2.3/src/templates/list.expose 2006-07-20 00:23:58 UTC (rev 2846) @@ -18,7 +18,6 @@ expose_meth: __radd__ o expose_meth: __iadd__ o expose_meth: __imul__ o -expose_meth: __reduce__ expose_meth: __mul__ o expose_meth: __rmul__ o expose_meth: __hash__ Modified: branches/2.3/src/templates/object.expose =================================================================== --- branches/2.3/src/templates/object.expose 2006-07-19 22:49:26 UTC (rev 2845) +++ branches/2.3/src/templates/object.expose 2006-07-20 00:23:58 UTC (rev 2846) @@ -6,7 +6,8 @@ expose_getset: __doc__ getDoc # exposed methods -expose_meth: :o __reduce__ +expose_meth: __reduce__ +expose_meth: __reduce_ex__ i? expose_meth: __str__ return self.__repr__(); expose_meth: __getattribute__ n{attribute name} Modified: branches/2.3/src/templates/str.expose =================================================================== --- branches/2.3/src/templates/str.expose 2006-07-19 22:49:26 UTC (rev 2845) +++ branches/2.3/src/templates/str.expose 2006-07-20 00:23:58 UTC (rev 2846) @@ -10,7 +10,6 @@ expose_meth: __getslice__ ooo? expose_meth: __iter__ expose_meth: __mul__ o -expose_meth: __reduce__ expose_meth: __rmul__ o expose_meth: __str__ expose_meth: __unicode__ Modified: branches/2.3/src/templates/tuple.expose =================================================================== --- branches/2.3/src/templates/tuple.expose 2006-07-19 22:49:26 UTC (rev 2845) +++ branches/2.3/src/templates/tuple.expose 2006-07-20 00:23:58 UTC (rev 2846) @@ -6,7 +6,6 @@ expose_meth: :b __contains__ o expose_meth: :i __len__ expose_meth: __add__ o -expose_meth: __reduce__ expose_meth: __mul__ o expose_meth: __rmul__ o expose_meth: __getitem__ o This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <m_...@us...> - 2006-07-24 20:26:52
|
Revision: 2857 Author: m_small Date: 2006-07-24 11:36:21 -0700 (Mon, 24 Jul 2006) ViewCVS: http://svn.sourceforge.net/jython/?rev=2857&view=rev Log Message: ----------- - copy logging module - add note about ant builds for templates Modified Paths: -------------- branches/2.3/build.Lib.include.properties branches/2.3/src/templates/README.txt Modified: branches/2.3/build.Lib.include.properties =================================================================== --- branches/2.3/build.Lib.include.properties 2006-07-22 02:40:40 UTC (rev 2856) +++ branches/2.3/build.Lib.include.properties 2006-07-24 18:36:21 UTC (rev 2857) @@ -6,6 +6,7 @@ email/test/*.py email/test/data/* encodings/*.py +logging/* test/** # Lib files, in alphabetical order: Modified: branches/2.3/src/templates/README.txt =================================================================== --- branches/2.3/src/templates/README.txt 2006-07-22 02:40:40 UTC (rev 2856) +++ branches/2.3/src/templates/README.txt 2006-07-24 18:36:21 UTC (rev 2857) @@ -11,5 +11,7 @@ python gderived.py int.derived >../../jython/src/org/python/core/PyIntegerDerived.java -Note: The above examples assume that the whole jython trunk is checked out so -that the trunk/sandbox directory is a sibling of the trunk/jython directory. +There is an ant target to generate these automatically. See the template +target in the top-level build file, or the org.python.util.TemplateAntTask +ant task. In the future, the template generation will be linked into the +main build targets. This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <cg...@us...> - 2006-08-15 04:22:44
|
Revision: 2893 Author: cgroves Date: 2006-08-14 21:22:36 -0700 (Mon, 14 Aug 2006) ViewCVS: http://svn.sourceforge.net/jython/?rev=2893&view=rev Log Message: ----------- from patch #1522926 Modified Paths: -------------- branches/2.3/build.Lib.include.properties Added Paths: ----------- branches/2.3/Lib/readline.py Added: branches/2.3/Lib/readline.py =================================================================== --- branches/2.3/Lib/readline.py (rev 0) +++ branches/2.3/Lib/readline.py 2006-08-15 04:22:36 UTC (rev 2893) @@ -0,0 +1,84 @@ +""" Emulate module 'readline' from CPython. +We are using the JavaReadline JNI wrapper for GNU readline. + +2004-10-27, mar...@rw... + +""" + +try: + from org.gnu.readline import Readline, ReadlineCompleter +except ImportError, msg: + raise ImportError, '%s. The readline module requires that java-readline from http://java-readline.sourceforge.net/ be on the classpath' % msg + +__all__ = ["readline"] + +def parse_and_bind (bindings): + """Parse and execute single line of a readline init file.\ + + """ + Readline.parseAndBind(bindings) + +def get_line_buffer(): + """Return the current contents of the line buffer. + + """ + return Readline.getLineBuffer() + +def read_init_file(filename): + """Parse a readline initialization file. + The default filename is the last filename used. + + """ + Readline.readInitFile(filename) + +def read_history_file(filename): + """Load a readline history file. + The default filename is '~/.history'. + + """ + Readline.readHistoryFile(filename) + +def write_history_file(filename): + """Save a readline history file. + The default filename is '~/.history'. + + """ + Readline.writeHistoryFile(filename) + +def set_completer(completionfunction = None): + """Set or remove the completer instance. If an instance of ReadlineCompleter is specified, + it will be used as the new completer; if omitted or None, any completer already installed is removed. + + The completer method is called as completerclass.completer(text, state), for state in 0, 1, 2, ..., + until it returns a non-string value. It should return the next possible completion starting with text. + + """ + class DerivedCompleter (ReadlineCompleter): + def __init__ (self, method): + self.method = method + + def completer (self, text, state): + return self.method(text, state) + + Readline.setCompleter(DerivedCompleter(completionfunction)) + +def get_completer(): + """Get the current completer instance.""" + return Readline.getCompleter() + +def set_completer_delims(delimiters): + """Set the readline word delimiters for tab-completion.""" + Readline.setWordBreakCharacters(delimiters) + +def get_completer_delims(): + """Get the readline word delimiters for tab-completion.""" + return Readline.getWordBreakCharacters() + +def add_history(line): + """Append a line to the history buffer, as if it was the last line typed.""" + Readline.addToHistory(line) + +def get_current_history_length(): + """Get the number of lines currently available in history.""" + return Readline.getHistorySize() + Modified: branches/2.3/build.Lib.include.properties =================================================================== --- branches/2.3/build.Lib.include.properties 2006-08-15 04:17:27 UTC (rev 2892) +++ branches/2.3/build.Lib.include.properties 2006-08-15 04:22:36 UTC (rev 2893) @@ -94,6 +94,7 @@ reconvert.py repr.py rfc822.py +rlcompleter.py sched.py sgmllib.py shelve.py 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:07:46
|
Revision: 2981 http://svn.sourceforge.net/jython/?rev=2981&view=rev Author: cgroves Date: 2006-11-20 19:07:44 -0800 (Mon, 20 Nov 2006) Log Message: ----------- added CPython's release23-maint/Lib to svn:externals as CPythonLib Modified Paths: -------------- branches/2.3/build.xml Property Changed: ---------------- branches/2.3/ Property changes on: branches/2.3 ___________________________________________________________________ Name: svn:externals + CPythonLib http://svn.python.org/projects/python/branches/release23-maint/Lib/ Modified: branches/2.3/build.xml =================================================================== --- branches/2.3/build.xml 2006-11-21 03:06:48 UTC (rev 2980) +++ branches/2.3/build.xml 2006-11-21 03:07:44 UTC (rev 2981) @@ -202,7 +202,7 @@ <property name="jython.base.dir" value="${basedir}" /> <property name="source.dir" value="${basedir}/src" /> <property name="templates.dir" value="${basedir}/src/templates" /> - <property name="python.lib" value="${python.home}/Lib" /> + <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-18 19:47:28
|
Revision: 2973 http://svn.sourceforge.net/jython/?rev=2973&view=rev Author: cgroves Date: 2006-11-18 11:47:26 -0800 (Sat, 18 Nov 2006) Log Message: ----------- Merged 2830 to HEAD from trunk Modified Paths: -------------- branches/2.3/Lib/javaos.py branches/2.3/Lib/test/regrtest.py branches/2.3/Lib/test/test_descr.py branches/2.3/Tools/jythonc/ImportName.py branches/2.3/build.xml branches/2.3/registry branches/2.3/src/org/python/compiler/CodeCompiler.java branches/2.3/src/org/python/compiler/Module.java branches/2.3/src/org/python/compiler/ProxyMaker.java branches/2.3/src/org/python/compiler/ScopeInfo.java branches/2.3/src/org/python/compiler/ScopesCompiler.java branches/2.3/src/org/python/core/CachedJarsPackageManager.java branches/2.3/src/org/python/core/Py.java branches/2.3/src/org/python/core/PyBaseString.java branches/2.3/src/org/python/core/PyBooleanDerived.java branches/2.3/src/org/python/core/PyClassMethodDerived.java branches/2.3/src/org/python/core/PyComplexDerived.java branches/2.3/src/org/python/core/PyDictionary.java branches/2.3/src/org/python/core/PyDictionaryDerived.java branches/2.3/src/org/python/core/PyFileDerived.java branches/2.3/src/org/python/core/PyFloatDerived.java branches/2.3/src/org/python/core/PyFrame.java branches/2.3/src/org/python/core/PyIntegerDerived.java branches/2.3/src/org/python/core/PyJavaClass.java branches/2.3/src/org/python/core/PyListDerived.java branches/2.3/src/org/python/core/PyLongDerived.java branches/2.3/src/org/python/core/PyMethod.java branches/2.3/src/org/python/core/PyObject.java branches/2.3/src/org/python/core/PyObjectDerived.java branches/2.3/src/org/python/core/PyPropertyDerived.java branches/2.3/src/org/python/core/PyString.java branches/2.3/src/org/python/core/PyStringDerived.java branches/2.3/src/org/python/core/PySuperDerived.java branches/2.3/src/org/python/core/PySystemState.java branches/2.3/src/org/python/core/PyTableCode.java branches/2.3/src/org/python/core/PyTuple.java branches/2.3/src/org/python/core/PyTupleDerived.java branches/2.3/src/org/python/core/PyTypeDerived.java branches/2.3/src/org/python/core/PyUnicode.java branches/2.3/src/org/python/core/PyUnicodeDerived.java branches/2.3/src/org/python/core/ZipFileImporter.java branches/2.3/src/org/python/core/__builtin__.java branches/2.3/src/org/python/core/imp.java branches/2.3/src/org/python/modules/cPickle.java branches/2.3/src/org/python/modules/imp.java branches/2.3/src/org/python/modules/time/PyTimeTuple.java branches/2.3/src/org/python/modules/time/PyTimeTupleSetup.java branches/2.3/src/org/python/util/PyServlet.java branches/2.3/src/org/python/util/jython.java branches/2.3/src/templates/float.derived branches/2.3/src/templates/list.expose branches/2.3/src/templates/long.derived branches/2.3/src/templates/object.derived branches/2.3/src/templates/str.expose branches/2.3/src/templates/timetuple.expose branches/2.3/src/templates/tuple.expose branches/2.3/src/templates/unicode.expose Added Paths: ----------- branches/2.3/Lib/test/test_cpickle.py branches/2.3/Lib/test/test_minidom.py branches/2.3/Lib/test/test_sax.py branches/2.3/Lib/test/test_scope.py branches/2.3/Lib/xml/ branches/2.3/Lib/xml/FtCore.py branches/2.3/Lib/xml/Uri.py branches/2.3/Lib/xml/__init__.py branches/2.3/Lib/xml/dom/ branches/2.3/Lib/xml/dom/MessageSource.py branches/2.3/Lib/xml/dom/NodeFilter.py branches/2.3/Lib/xml/dom/__init__.py branches/2.3/Lib/xml/dom/domreg.py branches/2.3/Lib/xml/dom/minicompat.py branches/2.3/Lib/xml/dom/minidom.py branches/2.3/Lib/xml/dom/pulldom.py branches/2.3/Lib/xml/dom/xmlbuilder.py branches/2.3/Lib/xml/sax/ branches/2.3/Lib/xml/sax/__init__.py branches/2.3/Lib/xml/sax/_exceptions.py branches/2.3/Lib/xml/sax/drivers2/ branches/2.3/Lib/xml/sax/drivers2/__init__.py branches/2.3/Lib/xml/sax/drivers2/drv_javasax.py branches/2.3/Lib/xml/sax/handler.py branches/2.3/Lib/xml/sax/saxlib.py branches/2.3/Lib/xml/sax/saxutils.py branches/2.3/Lib/xml/sax/xmlreader.py branches/2.3/src/org/python/core/FilelikeInputStream.java branches/2.3/src/org/python/core/JavaImportHelper.java branches/2.3/src/templates/basestring.expose Removed Paths: ------------- branches/2.3/Lib/xml/FtCore.py branches/2.3/Lib/xml/Uri.py branches/2.3/Lib/xml/__init__.py branches/2.3/Lib/xml/dom/ branches/2.3/Lib/xml/dom/MessageSource.py branches/2.3/Lib/xml/dom/NodeFilter.py branches/2.3/Lib/xml/dom/__init__.py branches/2.3/Lib/xml/dom/domreg.py branches/2.3/Lib/xml/dom/minicompat.py branches/2.3/Lib/xml/dom/minidom.py branches/2.3/Lib/xml/dom/pulldom.py branches/2.3/Lib/xml/dom/xmlbuilder.py branches/2.3/Lib/xml/sax/ branches/2.3/Lib/xml/sax/__init__.py branches/2.3/Lib/xml/sax/_exceptions.py branches/2.3/Lib/xml/sax/drivers2/ branches/2.3/Lib/xml/sax/drivers2/__init__.py branches/2.3/Lib/xml/sax/drivers2/drv_javasax.py branches/2.3/Lib/xml/sax/handler.py branches/2.3/Lib/xml/sax/saxlib.py branches/2.3/Lib/xml/sax/saxutils.py branches/2.3/Lib/xml/sax/xmlreader.py Modified: branches/2.3/Lib/javaos.py =================================================================== --- branches/2.3/Lib/javaos.py 2006-11-16 07:49:15 UTC (rev 2972) +++ branches/2.3/Lib/javaos.py 2006-11-18 19:47:26 UTC (rev 2973) @@ -49,22 +49,31 @@ def __init__(self, results): if len(results) != 10: - raise TypeError("stat_result() takes an at least 10-sequence") + raise TypeError("stat_result() takes an a 10-sequence") for (name, index) in stat_result._stat_members: self.__dict__[name] = results[index] + def __getitem__(self, i): if i < 0 or i > 9: raise IndexError(i) return getattr(self, stat_result._stat_members[i][0]) + def __setitem__(self, x, value): raise TypeError("object doesn't support item assignment") + def __setattr__(self, name, value): if name in [x[0] for x in stat_result._stat_members]: raise TypeError(name) raise AttributeError("readonly attribute") + def __len__(self): return 10 + def __cmp__(self, other): + if not isinstance(other, stat_result): + return 1 + return cmp(self.__dict__, other.__dict__) + error = OSError name = 'java' # discriminate based on JDK version? Modified: branches/2.3/Lib/test/regrtest.py =================================================================== --- branches/2.3/Lib/test/regrtest.py 2006-11-16 07:49:15 UTC (rev 2972) +++ branches/2.3/Lib/test/regrtest.py 2006-11-18 19:47:26 UTC (rev 2973) @@ -372,7 +372,7 @@ sys.path = saved_sys_path - test = test_spec +# test = test_spec if ok > 0: good.append(test) @@ -407,27 +407,14 @@ if verbose: print "CAUTION: stdout isn't compared in verbose mode: a test" print "that passes in verbose mode may fail without it." + if skipped and not quiet: + print count(len(skipped), "test"), "skipped:" + printlist(skipped) + printsurprises(_Expected(_skips), skipped, 'skip') if bad: print count(len(bad), "test"), "failed:" printlist(bad) - if skipped and not quiet: - print count(len(skipped), "test"), "skipped:" - printlist(skipped) - - e = _ExpectedSkips() - plat = sys.platform - if e.isvalid(): - surprise = _Set(skipped) - e.getexpected() - if surprise: - print count(len(surprise), "skip"), \ - "unexpected on", plat + ":" - printlist(surprise) - else: - print "Those skips are all expected on", plat + "." - else: - print "Ask someone to teach regrtest.py about which tests are" - print "expected to get skipped on", plat + "." - + printsurprises(_Expected(_failures), bad, 'fail') ## if single: ## alltests = findtests(testdir, stdtests, nottests) ## for i in range(len(alltests)): @@ -644,6 +631,18 @@ if len(line) > indent: print line +def printsurprises(e, actual, name): + plat = sys.platform + if e.isvalid(): + surprise = _Set(actual) - e.getexpected() + if surprise: + print count(len(surprise), name), \ + "unexpected on", plat + ":" + printlist(surprise) + else: + print "Ask someone to teach regrtest.py about which tests are" + print "expected to %s on %s." % (name, plat) + class _Set: def __init__(self, seq=[]): data = self.data = {} @@ -672,7 +671,7 @@ data.sort() return data -_expectations = { +_skips = { 'win32': """ test_al @@ -983,18 +982,104 @@ test_winreg test_winsound """, + 'java': + """ + test_al + test_asynchat + test_audioop + test_bsddb + test_capi + test_cd + test_cl + test_cmath + test_commands + test_crypt + test_curses + test_dbm + test_dl + test_email + test_email_codecs + test_fcntl + test_fork1 + test_gc + test_gdbm + test_gettext + test_gl + test_grp + test_hotshot + test_imageop + test_imgfile + test_linuxaudiodev + test_locale + test_longexp + test_mmap + test_nis + test_openpty + test_parser + test_poll + test_pty + test_pwd + test_pyexpat + test_regex + test_rgbimg + test_rotor + test_select + test_signal + test_socket_ssl + test_socketserver + test_strop + test_sunaudiodev + test_sundry + test_symtable + test_timing + test_ucn + test_unicode_file + test_unicodedata + test_wave + test_winreg + test_winsound + """ } -class _ExpectedSkips: - def __init__(self): +_failures = { + 'java': + ''' + test_atexit + test_class + test_cpickle + test_descr + test_descrtut + test_doctest2 + test_frozen + test_long_future + test_marshal + test_new + test_pickle + test_pkgimport + test_profilehooks + test_pyclbr + test_sre + test_threaded_import + test_trace + test_uu + test_weakref + test_zlib + ''', +} + +class _Expected: + def __init__(self, expect_dict): self.valid = 0 - if _expectations.has_key(sys.platform): - s = _expectations[sys.platform] + platform = sys.platform + if platform[:4] == 'java': + platform = 'java' + if expect_dict.has_key(platform): + s = expect_dict[platform] self.expected = _Set(s.split()) self.valid = 1 def isvalid(self): - "Return true iff _ExpectedSkips knows about the current platform." + "Return true iff _Expected knows about the current platform." return self.valid def getexpected(self): Copied: branches/2.3/Lib/test/test_cpickle.py (from rev 2972, trunk/jython/Lib/test/test_cpickle.py) =================================================================== --- branches/2.3/Lib/test/test_cpickle.py (rev 0) +++ branches/2.3/Lib/test/test_cpickle.py 2006-11-18 19:47:26 UTC (rev 2973) @@ -0,0 +1,81 @@ +import cPickle +import test_support +import unittest +from cStringIO import StringIO +from pickletester import AbstractPickleTests, AbstractPickleModuleTests + +class cPickleTests(AbstractPickleTests, AbstractPickleModuleTests): + + def setUp(self): + self.dumps = cPickle.dumps + self.loads = cPickle.loads + + error = cPickle.BadPickleGet + module = cPickle + +class cPicklePicklerTests(AbstractPickleTests): + + def dumps(self, arg, bin=0): + f = StringIO() + p = cPickle.Pickler(f, bin) + p.dump(arg) + f.seek(0) + return f.read() + + def loads(self, buf): + f = StringIO(buf) + p = cPickle.Unpickler(f) + return p.load() + + error = cPickle.BadPickleGet + +class cPickleListPicklerTests(AbstractPickleTests): + + def dumps(self, arg, bin=0): + p = cPickle.Pickler(bin) + p.dump(arg) + return p.getvalue() + + def loads(self, *args): + f = StringIO(args[0]) + p = cPickle.Unpickler(f) + return p.load() + + error = cPickle.BadPickleGet + +class cPickleFastPicklerTests(AbstractPickleTests): + + def dumps(self, arg, bin=0): + f = StringIO() + p = cPickle.Pickler(f, bin) + p.fast = 1 + p.dump(arg) + f.seek(0) + return f.read() + + def loads(self, *args): + f = StringIO(args[0]) + p = cPickle.Unpickler(f) + return p.load() + + error = cPickle.BadPickleGet + + def test_nonrecursive_deep(self): + a = [] + for i in range(100): + a = [a] + b = self.loads(self.dumps(a)) + self.assertEqual(a, b) + +def test_main(): + loader = unittest.TestLoader() + suite = unittest.TestSuite() + suite.addTest(loader.loadTestsFromTestCase(cPickleTests)) + suite.addTest(loader.loadTestsFromTestCase(cPicklePicklerTests)) + #Jython doesn't support list based picklers + #suite.addTest(loader.loadTestsFromTestCase(cPickleListPicklerTests)) + suite.addTest(loader.loadTestsFromTestCase(cPickleFastPicklerTests)) + test_support.run_suite(suite) + +if __name__ == "__main__": + test_main() Modified: branches/2.3/Lib/test/test_descr.py =================================================================== --- branches/2.3/Lib/test/test_descr.py 2006-11-16 07:49:15 UTC (rev 2972) +++ branches/2.3/Lib/test/test_descr.py 2006-11-18 19:47:26 UTC (rev 2973) @@ -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, Copied: branches/2.3/Lib/test/test_minidom.py (from rev 2972, trunk/jython/Lib/test/test_minidom.py) =================================================================== --- branches/2.3/Lib/test/test_minidom.py (rev 0) +++ branches/2.3/Lib/test/test_minidom.py 2006-11-18 19:47:26 UTC (rev 2973) @@ -0,0 +1,648 @@ +# test for xml.dom.minidom + +from xml.dom.minidom import parse, Node, Document, parseString +from xml.dom import HierarchyRequestErr + +import os +import sys +import traceback +from test_support import verbose + +if __name__ == "__main__": + base = sys.argv[0] +else: + base = __file__ +tstfile = os.path.join(os.path.dirname(base), "test"+os.extsep+"xml") +del base + +def confirm(test, testname = "Test"): + if not test: + print "Failed " + testname + raise Exception + +Node._debug = 1 + +def testParseFromFile(): + from StringIO import StringIO + dom = parse(StringIO(open(tstfile).read())) + dom.unlink() + confirm(isinstance(dom,Document)) + +def testGetElementsByTagName(): + dom = parse(tstfile) + confirm(dom.getElementsByTagName("LI") == \ + dom.documentElement.getElementsByTagName("LI")) + dom.unlink() + +def testInsertBefore(): + dom = parseString("<doc><foo/></doc>") + root = dom.documentElement + elem = root.childNodes[0] + nelem = dom.createElement("element") + root.insertBefore(nelem, elem) + confirm(len(root.childNodes) == 2 + and root.childNodes.length == 2 + and root.childNodes[0] is nelem + and root.childNodes.item(0) is nelem + and root.childNodes[1] is elem + and root.childNodes.item(1) is elem + and root.firstChild is nelem + and root.lastChild is elem + and root.toxml() == "<doc><element/><foo/></doc>" + , "testInsertBefore -- node properly placed in tree") + nelem = dom.createElement("element") + root.insertBefore(nelem, None) + confirm(len(root.childNodes) == 3 + and root.childNodes.length == 3 + and root.childNodes[1] is elem + and root.childNodes.item(1) is elem + and root.childNodes[2] is nelem + and root.childNodes.item(2) is nelem + and root.lastChild is nelem + and nelem.previousSibling is elem + and root.toxml() == "<doc><element/><foo/><element/></doc>" + , "testInsertBefore -- node properly placed in tree") + nelem2 = dom.createElement("bar") + root.insertBefore(nelem2, nelem) + confirm(len(root.childNodes) == 4 + and root.childNodes.length == 4 + and root.childNodes[2] is nelem2 + and root.childNodes.item(2) is nelem2 + and root.childNodes[3] is nelem + and root.childNodes.item(3) is nelem + and nelem2.nextSibling is nelem + and nelem.previousSibling is nelem2 + and root.toxml() == "<doc><element/><foo/><bar/><element/></doc>" + , "testInsertBefore -- node properly placed in tree") + dom.unlink() + +def _create_fragment_test_nodes(): + dom = parseString("<doc/>") + orig = dom.createTextNode("original") + c1 = dom.createTextNode("foo") + c2 = dom.createTextNode("bar") + c3 = dom.createTextNode("bat") + dom.documentElement.appendChild(orig) + frag = dom.createDocumentFragment() + frag.appendChild(c1) + frag.appendChild(c2) + frag.appendChild(c3) + return dom, orig, c1, c2, c3, frag + +def testInsertBeforeFragment(): + dom, orig, c1, c2, c3, frag = _create_fragment_test_nodes() + dom.documentElement.insertBefore(frag, None) + confirm(tuple(dom.documentElement.childNodes) == (orig, c1, c2, c3), + "insertBefore(<fragment>, None)") + frag.unlink() + dom.unlink() + # + dom, orig, c1, c2, c3, frag = _create_fragment_test_nodes() + dom.documentElement.insertBefore(frag, orig) + confirm(tuple(dom.documentElement.childNodes) == (c1, c2, c3, orig), + "insertBefore(<fragment>, orig)") + frag.unlink() + dom.unlink() + +def testAppendChild(): + dom = parse(tstfile) + dom.documentElement.appendChild(dom.createComment(u"Hello")) + confirm(dom.documentElement.childNodes[-1].nodeName == "#comment") + confirm(dom.documentElement.childNodes[-1].data == "Hello") + dom.unlink() + +def testAppendChildFragment(): + dom, orig, c1, c2, c3, frag = _create_fragment_test_nodes() + dom.documentElement.appendChild(frag) + confirm(tuple(dom.documentElement.childNodes) == (orig, c1, c2, c3), + "appendChild(<fragment>)") + frag.unlink() + dom.unlink() + +def testReplaceChildFragment(): + dom, orig, c1, c2, c3, frag = _create_fragment_test_nodes() + dom.documentElement.replaceChild(frag, orig) + orig.unlink() + confirm(tuple(dom.documentElement.childNodes) == (c1, c2, c3), + "replaceChild(<fragment>)") + frag.unlink() + dom.unlink() + +def testLegalChildren(): + dom = Document() + elem = dom.createElement('element') + text = dom.createTextNode('text') + + try: dom.appendChild(text) + except HierarchyRequestErr: pass + else: + print "dom.appendChild didn't raise HierarchyRequestErr" + + dom.appendChild(elem) + try: dom.insertBefore(text, elem) + except HierarchyRequestErr: pass + else: + print "dom.appendChild didn't raise HierarchyRequestErr" + + try: dom.replaceChild(text, elem) + except HierarchyRequestErr: pass + else: + print "dom.appendChild didn't raise HierarchyRequestErr" + + nodemap = elem.attributes + try: nodemap.setNamedItem(text) + except HierarchyRequestErr: pass + else: + print "NamedNodeMap.setNamedItem didn't raise HierarchyRequestErr" + + try: nodemap.setNamedItemNS(text) + except HierarchyRequestErr: pass + else: + print "NamedNodeMap.setNamedItemNS didn't raise HierarchyRequestErr" + + elem.appendChild(text) + dom.unlink() + +def testNamedNodeMapSetItem(): + dom = Document() + elem = dom.createElement('element') + attrs = elem.attributes + attrs["foo"] = "bar" + a = attrs.item(0) + confirm(a.ownerDocument is dom, + "NamedNodeMap.__setitem__() sets ownerDocument") + confirm(a.ownerElement is elem, + "NamedNodeMap.__setitem__() sets ownerElement") + confirm(a.value == "bar", + "NamedNodeMap.__setitem__() sets value") + confirm(a.nodeValue == "bar", + "NamedNodeMap.__setitem__() sets nodeValue") + elem.unlink() + dom.unlink() + +def testNonZero(): + dom = parse(tstfile) + confirm(dom)# should not be zero + dom.appendChild(dom.createComment("foo")) + confirm(not dom.childNodes[-1].childNodes) + dom.unlink() + +def testUnlink(): + dom = parse(tstfile) + dom.unlink() + +def testElement(): + dom = Document() + dom.appendChild(dom.createElement("abc")) + confirm(dom.documentElement) + dom.unlink() + +def testAAA(): + dom = parseString("<abc/>") + el = dom.documentElement + el.setAttribute("spam", "jam2") + confirm(el.toxml() == '<abc spam="jam2"/>', "testAAA") + a = el.getAttributeNode("spam") + confirm(a.ownerDocument is dom, + "setAttribute() sets ownerDocument") + confirm(a.ownerElement is dom.documentElement, + "setAttribute() sets ownerElement") + dom.unlink() + +def testAAB(): + dom = parseString("<abc/>") + el = dom.documentElement + el.setAttribute("spam", "jam") + el.setAttribute("spam", "jam2") + confirm(el.toxml() == '<abc spam="jam2"/>', "testAAB") + dom.unlink() + +def testAddAttr(): + dom = Document() + child = dom.appendChild(dom.createElement("abc")) + + child.setAttribute("def", "ghi") + confirm(child.getAttribute("def") == "ghi") + confirm(child.attributes["def"].value == "ghi") + + child.setAttribute("jkl", "mno") + confirm(child.getAttribute("jkl") == "mno") + confirm(child.attributes["jkl"].value == "mno") + + confirm(len(child.attributes) == 2) + + child.setAttribute("def", "newval") + confirm(child.getAttribute("def") == "newval") + confirm(child.attributes["def"].value == "newval") + + confirm(len(child.attributes) == 2) + dom.unlink() + +def testDeleteAttr(): + dom = Document() + child = dom.appendChild(dom.createElement("abc")) + + confirm(len(child.attributes) == 0) + child.setAttribute("def", "ghi") + confirm(len(child.attributes) == 1) + del child.attributes["def"] + confirm(len(child.attributes) == 0) + dom.unlink() + +def testRemoveAttr(): + dom = Document() + child = dom.appendChild(dom.createElement("abc")) + + child.setAttribute("def", "ghi") + confirm(len(child.attributes) == 1) + child.removeAttribute("def") + confirm(len(child.attributes) == 0) + + dom.unlink() + +def testRemoveAttrNS(): + dom = Document() + child = dom.appendChild( + dom.createElementNS("http://www.python.org", "python:abc")) + child.setAttributeNS("http://www.w3.org", "xmlns:python", + "http://www.python.org") + child.setAttributeNS("http://www.python.org", "python:abcattr", "foo") + confirm(len(child.attributes) == 2) + child.removeAttributeNS("http://www.python.org", "abcattr") + confirm(len(child.attributes) == 1) + + dom.unlink() + +def testRemoveAttributeNode(): + dom = Document() + child = dom.appendChild(dom.createElement("foo")) + child.setAttribute("spam", "jam") + confirm(len(child.attributes) == 1) + node = child.getAttributeNode("spam") + child.removeAttributeNode(node) + confirm(len(child.attributes) == 0) + + dom.unlink() + +def testChangeAttr(): + dom = parseString("<abc/>") + el = dom.documentElement + el.setAttribute("spam", "jam") + confirm(len(el.attributes) == 1) + el.setAttribute("spam", "bam") + confirm(len(el.attributes) == 1) + el.attributes["spam"] = "ham" + confirm(len(el.attributes) == 1) + el.setAttribute("spam2", "bam") + confirm(len(el.attributes) == 2) + el.attributes[ "spam2"] = "bam2" + confirm(len(el.attributes) == 2) + dom.unlink() + +def testGetAttrList(): + pass + +def testGetAttrValues(): pass + +def testGetAttrLength(): pass + +def testGetAttribute(): pass + +def testGetAttributeNS(): pass + +def testGetAttributeNode(): pass + +def testGetElementsByTagNameNS(): + d="""<foo xmlns:minidom="http://pyxml.sf.net/minidom"> + <minidom:myelem/> + </foo>""" + dom = parseString(d) + elem = dom.getElementsByTagNameNS("http://pyxml.sf.net/minidom","myelem") + confirm(len(elem) == 1) + dom.unlink() + +def testGetEmptyNodeListFromElementsByTagNameNS(): pass + +def testElementReprAndStr(): + dom = Document() + el = dom.appendChild(dom.createElement("abc")) + string1 = repr(el) + string2 = str(el) + confirm(string1 == string2) + dom.unlink() + +# commented out until Fredrick's fix is checked in +def _testElementReprAndStrUnicode(): + dom = Document() + el = dom.appendChild(dom.createElement(u"abc")) + string1 = repr(el) + string2 = str(el) + confirm(string1 == string2) + dom.unlink() + +# commented out until Fredrick's fix is checked in +def _testElementReprAndStrUnicodeNS(): + dom = Document() + el = dom.appendChild( + dom.createElementNS(u"http://www.slashdot.org", u"slash:abc")) + string1 = repr(el) + string2 = str(el) + confirm(string1 == string2) + confirm(string1.find("slash:abc") != -1) + dom.unlink() + +def testAttributeRepr(): + dom = Document() + el = dom.appendChild(dom.createElement(u"abc")) + node = el.setAttribute("abc", "def") + confirm(str(node) == repr(node)) + dom.unlink() + +def testTextNodeRepr(): pass + +def testWriteXML(): + str = '<?xml version="1.0" ?>\n<a b="c"/>' + dom = parseString(str) + domstr = dom.toxml() + dom.unlink() + confirm(str == domstr) + +def testProcessingInstruction(): pass + +def testProcessingInstructionRepr(): pass + +def testTextRepr(): pass + +def testWriteText(): pass + +def testDocumentElement(): pass + +def testTooManyDocumentElements(): + doc = parseString("<doc/>") + elem = doc.createElement("extra") + try: + doc.appendChild(elem) + except HierarchyRequestErr: + pass + else: + print "Failed to catch expected exception when" \ + " adding extra document element." + elem.unlink() + doc.unlink() + +def testCreateElementNS(): pass + +def testCreateAttributeNS(): pass + +def testParse(): pass + +def testParseString(): pass + +def testComment(): pass + +def testAttrListItem(): pass + +def testAttrListItems(): pass + +def testAttrListItemNS(): pass + +def testAttrListKeys(): pass + +def testAttrListKeysNS(): pass + +def testAttrListValues(): pass + +def testAttrListLength(): pass + +def testAttrList__getitem__(): pass + +def testAttrList__setitem__(): pass + +def testSetAttrValueandNodeValue(): pass + +def testParseElement(): pass + +def testParseAttributes(): pass + +def testParseElementNamespaces(): pass + +def testParseAttributeNamespaces(): pass + +def testParseProcessingInstructions(): pass + +def testChildNodes(): pass + +def testFirstChild(): pass + +def testHasChildNodes(): pass + +def testCloneElementShallow(): + dom, clone = _setupCloneElement(0) + confirm(len(clone.childNodes) == 0 + and clone.childNodes.length == 0 + and clone.parentNode is None + and clone.toxml() == '<doc attr="value"/>' + , "testCloneElementShallow") + dom.unlink() + +def testCloneElementDeep(): + dom, clone = _setupCloneElement(1) + confirm(len(clone.childNodes) == 1 + and clone.childNodes.length == 1 + and clone.parentNode is None + and clone.toxml() == '<doc attr="value"><foo/></doc>' + , "testCloneElementDeep") + dom.unlink() + +def _setupCloneElement(deep): + dom = parseString("<doc attr='value'><foo/></doc>") + root = dom.documentElement + clone = root.cloneNode(deep) + _testCloneElementCopiesAttributes( + root, clone, "testCloneElement" + (deep and "Deep" or "Shallow")) + # mutilate the original so shared data is detected + root.tagName = root.nodeName = "MODIFIED" + root.setAttribute("attr", "NEW VALUE") + root.setAttribute("added", "VALUE") + return dom, clone + +def _testCloneElementCopiesAttributes(e1, e2, test): + attrs1 = e1.attributes + attrs2 = e2.attributes + keys1 = attrs1.keys() + keys2 = attrs2.keys() + keys1.sort() + keys2.sort() + confirm(keys1 == keys2, "clone of element has same attribute keys") + for i in range(len(keys1)): + a1 = attrs1.item(i) + a2 = attrs2.item(i) + confirm(a1 is not a2 + and a1.value == a2.value + and a1.nodeValue == a2.nodeValue + and a1.namespaceURI == a2.namespaceURI + and a1.localName == a2.localName + , "clone of attribute node has proper attribute values") + confirm(a2.ownerElement is e2, + "clone of attribute node correctly owned") + + +def testCloneDocumentShallow(): pass + +def testCloneDocumentDeep(): pass + +def testCloneAttributeShallow(): pass + +def testCloneAttributeDeep(): pass + +def testClonePIShallow(): pass + +def testClonePIDeep(): pass + +def testNormalize(): + doc = parseString("<doc/>") + root = doc.documentElement + root.appendChild(doc.createTextNode("first")) + root.appendChild(doc.createTextNode("second")) + confirm(len(root.childNodes) == 2 + and root.childNodes.length == 2, "testNormalize -- preparation") + doc.normalize() + confirm(len(root.childNodes) == 1 + and root.childNodes.length == 1 + and root.firstChild is root.lastChild + and root.firstChild.data == "firstsecond" + , "testNormalize -- result") + doc.unlink() + + doc = parseString("<doc/>") + root = doc.documentElement + root.appendChild(doc.createTextNode("")) + doc.normalize() + confirm(len(root.childNodes) == 0 + and root.childNodes.length == 0, + "testNormalize -- single empty node removed") + doc.unlink() + +def testSiblings(): + doc = parseString("<doc><?pi?>text?<elm/></doc>") + root = doc.documentElement + (pi, text, elm) = root.childNodes + + confirm(pi.nextSibling is text and + pi.previousSibling is None and + text.nextSibling is elm and + text.previousSibling is pi and + elm.nextSibling is None and + elm.previousSibling is text, "testSiblings") + + doc.unlink() + +def testParents(): + doc = parseString("<doc><elm1><elm2/><elm2><elm3/></elm2></elm1></doc>") + root = doc.documentElement + elm1 = root.childNodes[0] + (elm2a, elm2b) = elm1.childNodes + elm3 = elm2b.childNodes[0] + + confirm(root.parentNode is doc and + elm1.parentNode is root and + elm2a.parentNode is elm1 and + elm2b.parentNode is elm1 and + elm3.parentNode is elm2b, "testParents") + + doc.unlink() + +def testNodeListItem(): + doc = parseString("<doc><e/><e/></doc>") + children = doc.childNodes + docelem = children[0] + confirm(children[0] is children.item(0) + and children.item(1) is None + and docelem.childNodes.item(0) is docelem.childNodes[0] + and docelem.childNodes.item(1) is docelem.childNodes[1] + and docelem.childNodes.item(0).childNodes.item(0) is None, + "test NodeList.item()") + doc.unlink() + +def testSAX2DOM(): + from xml.dom import pulldom + + sax2dom = pulldom.SAX2DOM() + sax2dom.startDocument() + sax2dom.startElement("doc", {}) + sax2dom.characters("text") + sax2dom.startElement("subelm", {}) + sax2dom.characters("text") + sax2dom.endElement("subelm") + sax2dom.characters("text") + sax2dom.endElement("doc") + sax2dom.endDocument() + + doc = sax2dom.document + root = doc.documentElement + (text1, elm1, text2) = root.childNodes + text3 = elm1.childNodes[0] + + confirm(text1.previousSibling is None and + text1.nextSibling is elm1 and + elm1.previousSibling is text1 and + elm1.nextSibling is text2 and + text2.previousSibling is elm1 and + text2.nextSibling is None and + text3.previousSibling is None and + text3.nextSibling is None, "testSAX2DOM - siblings") + + confirm(root.parentNode is doc and + text1.parentNode is root and + elm1.parentNode is root and + text2.parentNode is root and + text3.parentNode is elm1, "testSAX2DOM - parents") + + doc.unlink() + +# --- MAIN PROGRAM + +names = globals().keys() +names.sort() + +failed = [] + +try: + Node.allnodes +except AttributeError: + # We don't actually have the minidom from the standard library, + # but are picking up the PyXML version from site-packages. + def check_allnodes(): + pass +else: + def check_allnodes(): + confirm(len(Node.allnodes) == 0, + "assertion: len(Node.allnodes) == 0") + if len(Node.allnodes): + print "Garbage left over:" + if verbose: + print Node.allnodes.items()[0:10] + else: + # Don't print specific nodes if repeatable results + # are needed + print len(Node.allnodes) + Node.allnodes = {} + +for name in names: + if name.startswith("test"): + func = globals()[name] + try: + func() + check_allnodes() + except: + failed.append(name) + print "Test Failed: ", name + sys.stdout.flush() + traceback.print_exception(*sys.exc_info()) + print `sys.exc_info()[1]` + Node.allnodes = {} + +if failed: + print "\n\n\n**** Check for failures in these tests:" + for name in failed: + print " " + name Copied: branches/2.3/Lib/test/test_sax.py (from rev 2972, trunk/jython/Lib/test/test_sax.py) =================================================================== --- branches/2.3/Lib/test/test_sax.py (rev 0) +++ branches/2.3/Lib/test/test_sax.py 2006-11-18 19:47:26 UTC (rev 2973) @@ -0,0 +1,713 @@ +# -*- coding: iso-8859-1 -*- +# regression test for SAX 2.0 +# $Id: test_sax.py,v 1.13 2004/03/20 07:46:04 fdrake Exp $ + +from xml.sax import handler, make_parser, ContentHandler, \ + SAXException, SAXReaderNotAvailable, SAXParseException +try: + make_parser() +except SAXReaderNotAvailable: + # don't try to test this module if we cannot create a parser + raise ImportError("no XML parsers available") +from xml.sax.saxutils import XMLGenerator, escape, unescape, quoteattr, \ + XMLFilterBase, Location +from xml.sax.xmlreader import InputSource, AttributesImpl, AttributesNSImpl +from cStringIO import StringIO +from test.test_support import verbose, TestFailed, findfile + +# ===== Utilities + +tests = 0 +failures = [] + +def confirm(outcome, name): + global tests + + tests = tests + 1 + if outcome: + if verbose: + print "Passed", name + else: + print "Failed", name + failures.append(name) + +def test_make_parser2(): + try: + # Creating parsers several times in a row should succeed. + # Testing this because there have been failures of this kind + # before. + from xml.sax import make_parser + p = make_parser() + from xml.sax import make_parser + p = make_parser() + from xml.sax import make_parser + p = make_parser() + from xml.sax import make_parser + p = make_parser() + from xml.sax import make_parser + p = make_parser() + from xml.sax import make_parser + p = make_parser() + except: + return 0 + else: + return p + + +# =========================================================================== +# +# saxutils tests +# +# =========================================================================== + +# ===== escape + +def test_escape_basic(): + return escape("Donald Duck & Co") == "Donald Duck & Co" + +def test_escape_all(): + return escape("<Donald Duck & Co>") == "<Donald Duck & Co>" + +def test_escape_extra(): + return escape("Hei p\xE5 deg", {"\xE5" : "å"}) == "Hei på deg" + +# ===== unescape + +def test_unescape_basic(): + return unescape("Donald Duck & Co") == "Donald Duck & Co" + +def test_unescape_all(): + return unescape("<Donald Duck & Co>") == "<Donald Duck & Co>" + +def test_unescape_extra(): + return unescape("Hei p\xE5 deg", {"\xE5" : "å"}) == "Hei på deg" + +def test_unescape_amp_extra(): + return unescape("&foo;", {"&foo;": "splat"}) == "&foo;" + +# ===== quoteattr + +def test_quoteattr_basic(): + return quoteattr("Donald Duck & Co") == '"Donald Duck & Co"' + +def test_single_quoteattr(): + return (quoteattr('Includes "double" quotes') + == '\'Includes "double" quotes\'') + +def test_double_quoteattr(): + return (quoteattr("Includes 'single' quotes") + == "\"Includes 'single' quotes\"") + +def test_single_double_quoteattr(): + return (quoteattr("Includes 'single' and \"double\" quotes") + == "\"Includes 'single' and "double" quotes\"") + +# ===== make_parser + +def test_make_parser(): + try: + # Creating a parser should succeed - it should fall back + # to the expatreader + p = make_parser(['xml.parsers.no_such_parser']) + except: + return 0 + else: + return p + + +# ===== XMLGenerator + +start = '<?xml version="1.0" encoding="iso-8859-1"?>\n' + +def test_xmlgen_basic(): + result = StringIO() + gen = XMLGenerator(result) + gen.startDocument() + gen.startElement("doc", {}) + gen.endElement("doc") + gen.endDocument() + + return result.getvalue() == start + "<doc></doc>" + +def test_xmlgen_content(): + result = StringIO() + gen = XMLGenerator(result) + + gen.startDocument() + gen.startElement("doc", {}) + gen.characters("huhei") + gen.endElement("doc") + gen.endDocument() + + return result.getvalue() == start + "<doc>huhei</doc>" + +def test_xmlgen_escaped_content(): + result = StringIO() + gen = XMLGenerator(result) + + gen.startDocument() + gen.startElement("doc", {}) + gen.characters(unicode("\xa0\\u3042", "unicode-escape")) + gen.endElement("doc") + gen.endDocument() + + return result.getvalue() == start + "<doc>\xa0あ</doc>" + +def test_xmlgen_escaped_attr(): + result = StringIO() + gen = XMLGenerator(result) + + gen.startDocument() + gen.startElement("doc", {"x": unicode("\\u3042", "unicode-escape")}) + gen.endElement("doc") + gen.endDocument() + + return result.getvalue() == start + '<doc x="あ"></doc>' + +def test_xmlgen_pi(): + result = StringIO() + gen = XMLGenerator(result) + + gen.startDocument() + gen.processingInstruction("test", "data") + gen.startElement("doc", {}) + gen.endElement("doc") + gen.endDocument() + + return result.getvalue() == start + "<?test data?><doc></doc>" + +def test_xmlgen_content_escape(): + result = StringIO() + gen = XMLGenerator(result) + + gen.startDocument() + gen.startElement("doc", {}) + gen.characters("<huhei&") + gen.endElement("doc") + gen.endDocument() + + return result.getvalue() == start + "<doc><huhei&</doc>" + +def test_xmlgen_attr_escape(): + result = StringIO() + gen = XMLGenerator(result) + + gen.startDocument() + gen.startElement("doc", {"a": '"'}) + gen.startElement("e", {"a": "'"}) + gen.endElement("e") + gen.startElement("e", {"a": "'\""}) + gen.endElement("e") + gen.endElement("doc") + gen.endDocument() + + return result.getvalue() == start \ + + "<doc a='\"'><e a=\"'\"></e><e a=\"'"\"></e></doc>" + +def test_xmlgen_attr_escape_manydouble(): + result = StringIO() + gen = XMLGenerator(result) + + gen.startDocument() + gen.startElement("doc", {"a": '"\'"'}) + gen.endElement("doc") + gen.endDocument() + + return result.getvalue() == start + "<doc a='\"'\"'></doc>" + +def test_xmlgen_attr_escape_manysingle(): + result = StringIO() + gen = XMLGenerator(result) + + gen.startDocument() + gen.startElement("doc", {"a": "'\"'"}) + gen.endElement("doc") + gen.endDocument() + + return result.getvalue() == start + '<doc a="\'"\'"></doc>' + +def test_xmlgen_ignorable(): + result = StringIO() + gen = XMLGenerator(result) + + gen.startDocument() + gen.startElement("doc", {}) + gen.ignorableWhitespace(" ") + gen.endElement("doc") + gen.endDocument() + + return result.getvalue() == start + "<doc> </doc>" + +ns_uri = "http://www.python.org/xml-ns/saxtest/" + +def test_xmlgen_ns(): + result = StringIO() + gen = XMLGenerator(result) + + gen.startDocument() + gen.startPrefixMapping("ns1", ns_uri) + gen.startElementNS((ns_uri, "doc"), "ns1:doc", {}) + # add an unqualified name + gen.startElementNS((None, "udoc"), None, {}) + gen.endElementNS((None, "udoc"), None) + gen.endElementNS((ns_uri, "doc"), "ns1:doc") + gen.endPrefixMapping("ns1") + gen.endDocument() + + return result.getvalue() == start + \ + ('<ns1:doc xmlns:ns1="%s"><udoc></udoc></ns1:doc>' % + ns_uri) + +# ===== XMLFilterBase + +def test_filter_basic(): + result = StringIO() + gen = XMLGenerator(result) + filter = XMLFilterBase() + filter.setContentHandler(gen) + + filter.startDocument() + filter.startElement("doc", {}) + filter.characters("content") + filter.ignorableWhitespace(" ") + filter.endElement("doc") + filter.endDocument() + + return result.getvalue() == start + "<doc>content </doc>" + +# =========================================================================== +# +# expatreader tests +# +# =========================================================================== + +# ===== XMLReader support + +def test_expat_file(): + parser = make_parser() + result = StringIO() + xmlgen = XMLGenerator(result) + + parser.setContentHandler(xmlgen) + parser.parse(open(findfile("test.xml"))) + + return result.getvalue() == xml_test_out + +# ===== DTDHandler support + +class TestDTDHandler: + + def __init__(self): + self._notations = [] + self._entities = [] + + def notationDecl(self, name, publicId, systemId): + self._notations.append((name, publicId, systemId)) + + def unparsedEntityDecl(self, name, publicId, systemId, ndata): + self._entities.append((name, publicId, systemId, ndata)) + +def test_expat_dtdhandler(): + parser = make_parser() + handler = TestDTDHandler() + parser.setDTDHandler(handler) + + parser.parse(StringIO('''<!DOCTYPE doc [ + <!ENTITY img SYSTEM "expat.gif" NDATA GIF> + <!NOTATION GIF PUBLIC "-//CompuServe//NOTATION Graphics Interchange Format 89a//EN"> +]> +<doc></doc>''')) + if len(handler._entities) != 1 or len(handler._entities[0]) != 4: + return 0 + name, pubId, sysId, ndata = handler._entities[0] + if name != 'img' or not pubId is None or not sysId.endswith('expat.gif') or ndata != 'GIF': + return 0 + return handler._notations == [("GIF", "-//CompuServe//NOTATION Graphics Interchange Format 89a//EN", None)] + +# ===== EntityResolver support + +class TestEntityResolver: + + def resolveEntity(self, publicId, systemId): + inpsrc = InputSource() + inpsrc.setByteStream(StringIO("<entity/>")) + return inpsrc + +def test_expat_entityresolver(): + parser = make_parser() + parser.setEntityResolver(TestEntityResolver()) + result = StringIO() + parser.setContentHandler(XMLGenerator(result)) + + parser.parse(StringIO('''<!DOCTYPE doc [ + <!ENTITY test SYSTEM "whatever"> +]> +<doc>&test;</doc>''')) + return result.getvalue() == start + "<doc><entity></entity></doc>" + +# ===== Attributes support + +class AttrGatherer(ContentHandler): + + def startElement(self, name, attrs): + self._attrs = attrs + + def startElementNS(self, name, qname, attrs): + self._attrs = attrs + +def test_expat_attrs_empty(): + parser = make_parser() + gather = AttrGatherer() + parser.setContentHandler(gather) + + parser.parse(StringIO("<doc/>")) + + return verify_empty_attrs(gather._attrs) + +def test_expat_attrs_wattr(): + parser = make_parser() + gather = AttrGatherer() + parser.setContentHandler(gather) + + parser.parse(StringIO("<doc attr='val'/>")) + + return verify_attrs_wattr(gather._attrs) + +def test_expat_nsattrs_empty(): + parser = make_parser() + parser.setFeature(handler.feature_namespaces, 1) + gather = AttrGatherer() + parser.setContentHandler(gather) + + parser.parse(StringIO("<doc/>")) + + return verify_empty_nsattrs(gather._attrs) + +def test_expat_nsattrs_wattr(): + parser = make_parser() + parser.setFeature(handler.feature_namespaces, 1) + gather = AttrGatherer() + parser.setContentHandler(gather) + + parser.parse(StringIO("<doc xmlns:ns='%s' ns:attr='val'/>" % ns_uri)) + + attrs = gather._attrs + + return attrs.getLength() == 1 and \ + attrs.getNames() == [(ns_uri, "attr")] and \ + attrs.getQNames() == ["ns:attr"] and \ + len(attrs) == 1 and \ + attrs.has_key((ns_uri, "attr")) and \ + attrs.keys() == [(ns_uri, "attr")] and \ + attrs.get((ns_uri, "attr")) == "val" and \ + attrs.get((ns_uri, "attr"), 25) == "val" and \ + attrs.items() == [((ns_uri, "attr"), "val")] and \ + attrs.values() == ["val"] and \ + attrs.getValue((ns_uri, "attr")) == "val" and \ + attrs[(ns_uri, "attr")] == "val" + +# ===== InputSource support + +xml_test_out = open(findfile("test.xml.out")).read() + +def test_expat_inpsource_filename(): + parser = make_parser() + result = StringIO() + xmlgen = XMLGenerator(result) + + parser.setContentHandler(xmlgen) + parser.parse(findfile("test.xml")) + + return result.getvalue() == xml_test_out + +def test_expat_inpsource_sysid(): + parser = make_parser() + result = StringIO() + xmlgen = XMLGenerator(result) + + parser.setContentHandler(xmlgen) + parser.parse(InputSource(findfile("test.xml"))) + + return result.getvalue() == xml_test_out + +def test_expat_inpsource_stream(): + parser = make_parser() + result = StringIO() + xmlgen = XMLGenerator(result) + + parser.setContentHandler(xmlgen) + inpsrc = InputSource() + inpsrc.setByteStream(open(findfile("test.xml"))) + parser.parse(inpsrc) + + return result.getvalue() == xml_test_out + +# ===== Locator support + +class LocatorTest(XMLGenerator): + def __init__(self, out=None, encoding="iso-8859-1"): + XMLGenerator.__init__(self, out, encoding) + self.location = None + + def endDocument(self): + XMLGenerator.endDocument(self) + self.location = Location(self._locator) + +def test_expat_locator_noinfo(): + result = StringIO() + xmlgen = LocatorTest(result) + parser = make_parser() + parser.setContentHandler(xmlgen) + + parser.parse(StringIO("<doc></doc>")) + + return xmlgen.location.getSystemId() is None and \ + xmlgen.location.getPublicId() is None and \ + xmlgen.location.getLineNumber() == 1 + +def test_expat_locator_withinfo(): + result = StringIO() + xmlgen = LocatorTest(result) + parser = make_parser() + parser.setContentHandler(xmlgen) + parser.parse(findfile("test.xml")) + + return xmlgen.location.getSystemId().endswith(findfile("test.xml")) and \ + xmlgen.location.getPublicId() is None + + +# =========================================================================== +# +# error reporting +# +# =========================================================================== + +def test_expat_incomplete(): + parser = make_parser() + parser.setContentHandler(ContentHandler()) # do nothing + try: + parser.parse(StringIO("<foo>")) + except SAXParseException: + return 1 # ok, error found + else: + return 0 + +def test_sax_location_str(): + # pass various values from a locator to the SAXParseException to + # make sure that the __str__() doesn't fall apart when None is + # passed instead of an integer line and column number + # + # use "normal" values for the locator: + str(Location(DummyLocator(1, 1))) + # use None for the line number: + str(Location(DummyLocator(None, 1))) + # use None for the column number: + str(Location(DummyLocator(1, None))) + # use None for both: + str(Location(DummyLocator(None, None))) + return 1 + +def test_sax_parse_exception_str(): + # pass various values from a locator to the SAXParseException to + # make sure that the __str__() doesn't fall apart when None is + # passed instead of an integer line and column number + # + # use "normal" values for the locator: + str(SAXParseException("message", None, + DummyLocator(1, 1))) + # use None for the line number: + str(SAXParseException("message", None, + DummyLocator(None, 1))) + # use None for the column number: + str(SAXParseException("message", None, + DummyLocator(1, None))) + # use None for both: + str(SAXParseException("message", None, + DummyLocator(None, None))) + return 1 + +class DummyLocator: + def __init__(self, lineno, colno): + self._lineno = lineno + self._colno = colno + + def getPublicId(self): + return "pubid" + + def getSystemId(self): + return "sysid" + + def getLineNumber(self): + return self._lineno + + def getColumnNumber(self): + return self._colno + +# =========================================================================== +# +# xmlreader tests +# +# =========================================================================== + +# ===== AttributesImpl + +def verify_empty_attrs(attrs): + try: + attrs.getValue("attr") + gvk = 0 + except KeyError: + gvk = 1 + + try: + attrs.getValueByQName("attr") + gvqk = 0 + except KeyError: + gvqk = 1 + + try: + attrs.getNameByQName("attr") + gnqk = 0 + except KeyError: + gnqk = 1 + + try: + attrs.getQNameByName("attr") + gqnk = 0 + except KeyError: + gqnk = 1 + + try: + attrs["attr"] + gik = 0 + except KeyError: + gik = 1 + + return attrs.getLength() == 0 and \ + attrs.getNames() == [] and \ + attrs.getQNames() == [] and \ + len(attrs) == 0 and \ + not attrs.has_key("attr") and \ + attrs.keys() == [] and \ + attrs.get("attrs") is None and \ + attrs.get("attrs", 25) == 25 and \ + attrs.items() == [] and \ + attrs.values() == [] and \ + gvk and gvqk and gnqk and gik and gqnk + +def verify_attrs_wattr(attrs): + return attrs.getLength() == 1 and \ + attrs.getNames() == ["attr"] and \ + attrs.getQNames() == ["attr"] and \ + len(attrs) == 1 and \ + attrs.has_key("attr") and \ + attrs.keys() == ["attr"] and \ + attrs.get("attr") == "val" and \ + attrs.get("attr", 25) == "val" and \ + attrs.items() == [("attr", "val")] and \ + attrs.values() == ["val"] and \ + attrs.getValue("attr") == "val" and \ + attrs.getValueByQName("attr") == "val" and \ + attrs.getNameByQName("attr") == "attr" and \ + attrs["attr"] == "val" and \ + attrs.getQNameByName("attr") == "attr" + +def test_attrs_empty(): + return verify_empty_attrs(AttributesImpl({})) + +def test_attrs_wattr(): + return verify_attrs_wattr(AttributesImpl({"attr" : "val"})) + +# ===== AttributesImpl + +def verify_empty_nsattrs(attrs): + try: + attrs.getValue((ns_uri, "attr")) + gvk = 0 + except KeyError: + gvk = 1 + + try: + attrs.getValueByQName("ns:attr") + gvqk = 0 + except KeyError: + gvqk = 1 + + try: + attrs.getNameByQName("ns:attr") + gnqk = 0 + except KeyError: + gnqk = 1 + + try: + attrs.getQNameByName((ns_uri, "attr")) + gqnk = 0 + except KeyError: + gqnk = 1 + + try: + attrs[(ns_uri, "attr")] + gik = 0 + except KeyError: + gik = 1 + + return attrs.getLength() == 0 and \ + attrs.getNames() == [] and \ + attrs.getQNames() == [] and \ + len(attrs) == 0 and \ + not attrs.has_key((ns_uri, "attr")) and \ + attrs.keys() == [] and \ + attrs.get((ns_uri, "attr")) is None and \ + attrs.get((ns_uri, "attr"), 25) == 25 and \ + attrs.items() == [] and \ + attrs.values() == [] and \ + gvk and gvqk and gnqk and gik and gqnk + +def test_nsattrs_empty(): + return verify_empty_nsattrs(AttributesNSImpl({}, {})) + +def test_nsattrs_wattr(): + attrs = AttributesNSImpl({(ns_uri, "attr") : "val"}, + {(ns_uri, "attr") : "ns:attr"}) + + return attrs.getLength() == 1 and \ + attrs.getNames() == [(ns_uri, "attr")] and \ + attrs.getQNames() == ["ns:attr"] and \ + len(attrs) == 1 and \ + attrs.has_key((ns_uri, "attr")) and \ + attrs.keys() == [(ns_uri, "attr")] and \ + attrs.get((ns_uri, "attr")) == "val" and \ + attrs.get((ns_uri, "attr"), 25) == "val" and \ + attrs.items() == [((ns_uri, "attr"), "val")] and \ + attrs.values() == ["val"] and \ + attrs.getValue((ns_uri, "attr")) == "val" and \ + attrs.getValueByQName("ns:attr") == "val" and \ + attrs.getNameByQName("ns:attr") == (ns_uri, "attr") and \ + attrs[(ns_uri, "attr")] == "val" and \ + attrs.getQNameByName((ns_uri, "attr")) == "ns:attr" + + +# ===== Main program + +def make_test_output(): + parser = make_parser() + result = StringIO() + xmlgen = XMLGenerator(result) + + parser.setContentHandler(xmlgen) + parser.parse(findfile("test.xml")) + + outf = open(findfile("test.xml.out"), "w") + outf.write(result.getvalue()) + outf.close() + +items = locals().items() +items.sort() +for (name, value) in items: + if name[:5] == "test_": + confirm(value(), name) + +if verbose: + print "%d tests, %d failures" % (tests, len(failures)) +if failures: + raise TestFailed("%d of %d tests failed: %s" + % (len(failures), tests, ", ".join(failures))) Copied: branches/2.3/Lib/test/test_scope.py (from rev 2972, trunk/jython/Lib/test/test_scope.py) =================================================================== --- branches/2.3/Lib/test/test_scope.py (rev 0) +++ branches/2.3/Lib/test/test_scope.py 2006-11-18 19:47:26 UTC (rev 2973) @@ -0,0 +1,530 @@ +from test_support import verify, TestFailed, check_syntax + +import warnings +warnings.filterwarnings("ignore", r"import \*", SyntaxWarning, "<string>") + +print "1. simple nesting" + +def make_adder(x): + def adder(y): + return x + y + return adder + +inc = make_adder(1) +plus10 = make_adder(10) + +verify(inc(1) == 2) +verify(plus10(-2) == 8) + +print "2. extra nesting" + +def make_adder2(x): + def extra(): # check freevars passing through non-use scopes + def adder(y): + return x + y + return adder + return extra() + +inc = make_adder2(1) +plus10 = make_adder2(10) + +verify(inc(1) == 2) +verify(plus10(-2) == 8) + +print "3. simple nesting + rebinding" + +def make_adder3(x): + def adder(y): + return x + y + x = x + 1 # check tracking of assignment to x in defining scope + return adder + +inc = make_adder3(0) +plus10 = make_adder3(9) + +verify(inc(1) == 2) +verify(plus10(-2) == 8) + +print "4. nesting with global but no free" + +def make_adder4(): # XXX add exta level of indirection + def nest(): + def nest(): + def adder(y): + return global_x + y # check that plain old globals work + return adder + return nest() + return nest() + +global_x = 1 +adder = make_adder4() +verify(adder(1) == 2) + +global_x = 10 +verify(adder(-2) == 8) + +print "5. nesting through class" + +def make_adder5(x): + class Adder: + def __call__(self, y): + return x + y + return Adder() + +inc = make_adder5(1) +plus10 = make_adder5(10) + +verify(inc(1) == 2) +verify(plus10(-2) == 8) + +print "6. nesting plus free ref to global" + +def make_adder6(x): + global global_nest_x + def adder(y): + return global_nest_x + y + global_nest_x = x + return adder + +inc = make_adder6(1) +plus10 = make_adder6(10) + +verify(inc(1) == 11) # there's only one global +verify(plus10(-2) == 8) + +print "7. nearest enclosing scope" + +def f(x): + def g(y): + x = 42 # check that this masks binding in f() + def h(z): + return x + z + return h + return g(2) + +test_func = f(10) +verify(test_func(5) == 47) + +print "8. mixed freevars and cellvars" + +def identity(x): + return x + +def f(x, y, z): + def g(a, b, c): + a = a + x # 3 + def h(): + # z * (4 + 9) + # 3 * 13 + return identity(z * (b + y)) + y = c + z # 9 + return h + return g + +g = f(1, 2, 3) +h = g(2, 4, 6) +verify(h() == 39) + +print "9. free variable in method" + +def test(): + method_and_var = "var" + class Test: + def method_and_var(self): + return "method" + def test(self): + return method_and_var + def actual_global(self): + return str("global") + def str(self): + return str(self) + return Test() + +t = test() +verify(t.test() == "var") +verify(t.method_and_var() == "method") +verify(t.actual_global() == "global") + +method_and_var = "var" +class Test: + # this class is not nested, so the rules are different + def method_and_var(self): + return "method" + def test(self): + return method_and_var + def actual_global(self): + return str("global") + def str(self): + return str(self) + +t = Test() +verify(t.test() == "var") +verify(t.method_and_var() == "method") +verify(t.actual_global() == "global") + +print "10. recursion" + +def f(x): + def fact(n): + if n == 0: + return 1 + else: + return n * fact(n - 1) + if x >= 0: + return fact(x) + else: + raise ValueError, "x must be >= 0" + +verify(f(6) == 720) + + +print "11. unoptimized namespaces" + +check_syntax("""\ +def unoptimized_clash1(strip): + def f(s): + from string import * + return strip(s) # ambiguity: free or local + return f +""") + +check_syntax("""\ +def unoptimized_clash2(): + from string import * + def f(s): + return strip(s) # ambiguity: global or local + return f +""") + +check_syntax("""\ +def unoptimized_clash2(): + from string import * + def g(): + def f(s): + return strip(s) # ambiguity: global or local + return f +""") + +# XXX could allow this for exec with const argument, but what's the point +check_syntax("""\ +def error(y): + exec "a = 1" + def f(x): + return x + y + return f +""") + +check_syntax("""\ +def f(x): + def g(): + return x + del x # can't del name +""") + +check_syntax("""\ +def f(): + def g(): + from string import * + return strip # global or local? +""") + +# and verify a few cases that should work + +exec """ +def noproblem1(): + from string import * + f = lambda x:x + +def noproblem2(): + from string import * + def f(x): + return x + 1 + +def noproblem3(): + from string import * + def f(x): + global y + y = x +""" + +print "12. lambdas" + +f1 = lambda x: lambda y: x + y +inc = f1(1) +plus10 = f1(10) +verify(inc(1) == 2) +verify(plus10(5) == ... [truncated message content] |
From: <cg...@us...> - 2006-11-28 01:48:04
|
Revision: 2997 http://svn.sourceforge.net/jython/?rev=2997&view=rev Author: cgroves Date: 2006-11-27 17:47:58 -0800 (Mon, 27 Nov 2006) Log Message: ----------- merge -r 2974:2994 from trunk/jython Modified Paths: -------------- branches/2.3/build.xml branches/2.3/src/org/python/core/PyClassMethod.java branches/2.3/src/org/python/core/PyClassMethodDerived.java branches/2.3/src/org/python/core/PyComplexDerived.java branches/2.3/src/org/python/core/PyDictionaryDerived.java branches/2.3/src/org/python/core/PyFileDerived.java branches/2.3/src/org/python/core/PyFloatDerived.java branches/2.3/src/org/python/core/PyGetSetDescr.java branches/2.3/src/org/python/core/PyIntegerDerived.java branches/2.3/src/org/python/core/PyListDerived.java branches/2.3/src/org/python/core/PyObjectDerived.java branches/2.3/src/org/python/core/PyPropertyDerived.java branches/2.3/src/org/python/core/PyStringDerived.java branches/2.3/src/org/python/core/PySuperDerived.java branches/2.3/src/org/python/core/PySystemState.java branches/2.3/src/org/python/core/PyTupleDerived.java branches/2.3/src/org/python/core/PyType.java branches/2.3/src/org/python/core/PyTypeDerived.java branches/2.3/src/org/python/core/PyUnicodeDerived.java Added Paths: ----------- branches/2.3/Lib/test/test_zlib.py branches/2.3/src/org/python/core/PySlot.java branches/2.3/src/org/python/core/Slotted.java Copied: branches/2.3/Lib/test/test_zlib.py (from rev 2994, trunk/jython/Lib/test/test_zlib.py) =================================================================== --- branches/2.3/Lib/test/test_zlib.py (rev 0) +++ branches/2.3/Lib/test/test_zlib.py 2006-11-28 01:47:58 UTC (rev 2997) @@ -0,0 +1,482 @@ +import unittest +from test import test_support +import zlib +import random + +# print test_support.TESTFN + +def getbuf(): + # This was in the original. Avoid non-repeatable sources. + # Left here (unused) in case something wants to be done with it. + import imp + try: + t = imp.find_module('test_zlib') + file = t[0] + except ImportError: + file = open(__file__) + buf = file.read() * 8 + file.close() + return buf + + + +class ChecksumTestCase(unittest.TestCase): + # checksum test cases + def test_crc32start(self): + self.assertEqual(zlib.crc32(""), zlib.crc32("", 0)) + self.assert_(zlib.crc32("abc", 0xffffffff)) + + def test_crc32empty(self): + self.assertEqual(zlib.crc32("", 0), 0) + self.assertEqual(zlib.crc32("", 1), 1) + self.assertEqual(zlib.crc32("", 432), 432) + + def test_adler32start(self): + self.assertEqual(zlib.adler32(""), zlib.adler32("", 1)) + ##self.assert_(zlib.adler32("abc", 0xffffffff)) + + def test_adler32empty(self): + ##self.assertEqual(zlib.adler32("", 0), 0) + self.assertEqual(zlib.adler32("", 1), 1) + ##self.assertEqual(zlib.adler32("", 432), 432) + + def assertEqual32(self, seen, expected): + # 32-bit values masked -- checksums on 32- vs 64- bit machines + # This is important if bit 31 (0x08000000L) is set. + self.assertEqual(seen & 0x0FFFFFFFFL, expected & 0x0FFFFFFFFL) + + def test_penguins(self): + ##self.assertEqual32(zlib.crc32("penguin", 0), 0x0e5c1a120L) + self.assertEqual32(zlib.crc32("penguin", 1), 0x43b6aa94) + ##self.assertEqual32(zlib.adler32("penguin", 0), 0x0bcf02f6) + self.assertEqual32(zlib.adler32("penguin", 1), 0x0bd602f7) + + ##self.assertEqual(zlib.crc32("penguin"), zlib.crc32("penguin", 0)) + self.assertEqual(zlib.adler32("penguin"),zlib.adler32("penguin",1)) + + + +class ExceptionTestCase(unittest.TestCase): + # make sure we generate some expected errors + def test_bigbits(self): + # specifying total bits too large causes an error + self.assertRaises(zlib.error, + zlib.compress, 'ERROR', zlib.MAX_WBITS + 1) + + def test_badcompressobj(self): + # verify failure on building compress object with bad params + self.assertRaises(ValueError, zlib.compressobj, 1, zlib.DEFLATED, 0) + + def test_baddecompressobj(self): + # verify failure on building decompress object with bad params + self.assertRaises(ValueError, zlib.decompressobj, 0) + + + +class CompressTestCase(unittest.TestCase): + # Test compression in one go (whole message compression) + def test_speech(self): + x = zlib.compress(HAMLET_SCENE) + self.assertEqual(zlib.decompress(x), HAMLET_SCENE) + + def test_speech128(self): + # compress more data + data = HAMLET_SCENE * 128 + x = zlib.compress(data) + self.assertEqual(zlib.decompress(x), data) + + + + +class CompressObjectTestCase(unittest.TestCase): + # Test compression object + def test_pair(self): + # straightforward compress/decompress objects + data = HAMLET_SCENE * 128 + co = zlib.compressobj() + x1 = co.compress(data) + x2 = co.flush() + self.assertRaises(zlib.error, co.flush) # second flush should not work + dco = zlib.decompressobj() + y1 = dco.decompress(x1 + x2) + y2 = dco.flush() + self.assertEqual(data, y1 + y2) + + def test_compressoptions(self): + # specify lots of options to compressobj() + level = 2 + method = zlib.DEFLATED + wbits = -12 + memlevel = 9 + strategy = zlib.Z_FILTERED + co = zlib.compressobj(level, method, wbits, memlevel, strategy) + x1 = co.compress(HAMLET_SCENE) + x2 = co.flush() + dco = zlib.decompressobj(wbits) + y1 = dco.decompress(x1 + x2) + y2 = dco.flush() + self.assertEqual(HAMLET_SCENE, y1 + y2) + + def test_compressincremental(self): + # compress object in steps, decompress object as one-shot + data = HAMLET_SCENE * 128 + co = zlib.compressobj() + bufs = [] + for i in range(0, len(data), 256): + bufs.append(co.compress(data[i:i+256])) + bufs.append(co.flush()) + combuf = ''.join(bufs) + + dco = zlib.decompressobj() + y1 = dco.decompress(''.join(bufs)) + y2 = dco.flush() + self.assertEqual(data, y1 + y2) + + def test_decompinc(self, flush=False, source=None, cx=256, dcx=64): + # compress object in steps, decompress object in steps + source = source or HAMLET_SCENE + data = source * 128 + co = zlib.compressobj() + bufs = [] + for i in range(0, len(data), cx): + bufs.append(co.compress(data[i:i+cx])) + bufs.append(co.flush()) + combuf = ''.join(bufs) + + self.assertEqual(data, zlib.decompress(combuf)) + + dco = zlib.decompressobj() + bufs = [] + for i in range(0, len(combuf), dcx): + bufs.append(dco.decompress(combuf[i:i+dcx])) + self.assertEqual('', dco.unconsumed_tail, ######## + "(A) uct should be '': not %d long" % + len(dco.unconsumed_tail)) + if flush: + bufs.append(dco.flush()) + else: + while True: + chunk = dco.decompress('') + if chunk: + bufs.append(chunk) + else: + break + self.assertEqual('', dco.unconsumed_tail, ######## + "(B) uct should be '': not %d long" % + len(dco.unconsumed_tail)) + self.assertEqual(data, ''.join(bufs)) + # Failure means: "decompressobj with init options failed" + + def test_decompincflush(self): + self.test_decompinc(flush=True) + + def test_decompimax(self, source=None, cx=256, dcx=64): + # compress in steps, decompress in length-restricted steps + source = source or HAMLET_SCENE + # Check a decompression object with max_length specified + data = source * 128 + co = zlib.compressobj() + bufs = [] + for i in range(0, len(data), cx): + bufs.append(co.compress(data[i:i+cx])) + bufs.append(co.flush()) + combuf = ''.join(bufs) + self.assertEqual(data, zlib.decompress(combuf), + 'compressed data failure') + + dco = zlib.decompressobj() + bufs = [] + cb = combuf + while cb: + #max_length = 1 + len(cb)//10 + chunk = dco.decompress(cb, dcx) + self.failIf(len(chunk) > dcx, + 'chunk too big (%d>%d)' % (len(chunk), dcx)) + bufs.append(chunk) + cb = dco.unconsumed_tail + bufs.append(dco.flush()) + self.assertEqual(data, ''.join(bufs), 'Wrong data retrieved') + + def test_decompressmaxlen(self, flush=False): + # Check a decompression object with max_length specified + data = HAMLET_SCENE * 128 + co = zlib.compressobj() + bufs = [] + for i in range(0, len(data), 256): + bufs.append(co.compress(data[i:i+256])) + bufs.append(co.flush()) + combuf = ''.join(bufs) + self.assertEqual(data, zlib.decompress(combuf), + 'compressed data failure') + + dco = zlib.decompressobj() + bufs = [] + cb = combuf + while cb: + max_length = 1 + len(cb)//10 + chunk = dco.decompress(cb, max_length) + self.failIf(len(chunk) > max_length, + 'chunk too big (%d>%d)' % (len(chunk),max_length)) + bufs.append(chunk) + cb = dco.unconsumed_tail + if flush: + bufs.append(dco.flush()) + else: + while chunk: + chunk = dco.decompress('', max_length) + self.failIf(len(chunk) > max_length, + 'chunk too big (%d>%d)' % (len(chunk),max_length)) + bufs.append(chunk) + self.assertEqual(data, ''.join(bufs), 'Wrong data retrieved') + + def test_decompressmaxlenflush(self): + self.test_decompressmaxlen(flush=True) + + def test_maxlenmisc(self): + # Misc tests of max_length + dco = zlib.decompressobj() + self.assertRaises(ValueError, dco.decompress, "", -1) + self.assertEqual('', dco.unconsumed_tail) + + def test_flushes(self): + # Test flush() with the various options, using all the + # different levels in order to provide more variations. + sync_opt = ['Z_NO_FLUSH', 'Z_SYNC_FLUSH', 'Z_FULL_FLUSH'] + sync_opt = [getattr(zlib, opt) for opt in sync_opt + if hasattr(zlib, opt)] + data = HAMLET_SCENE * 8 + + for sync in sync_opt: + for level in range(10): + obj = zlib.compressobj( level ) + a = obj.compress( data[:3000] ) + b = obj.flush( sync ) + c = obj.compress( data[3000:] ) + d = obj.flush() + self.assertEqual(zlib.decompress(''.join([a,b,c,d])), + data, ("Decompress failed: flush " + "mode=%i, level=%i") % (sync, level)) + del obj + + def test_odd_flush(self): + # Test for odd flushing bugs noted in 2.0, and hopefully fixed in 2.1 + import random + + if hasattr(zlib, 'Z_SYNC_FLUSH'): + # Testing on 17K of "random" data + + # Create compressor and decompressor objects + co = zlib.compressobj(zlib.Z_BEST_COMPRESSION) + dco = zlib.decompressobj() + + # Try 17K of data + # generate random data stream + try: + # In 2.3 and later, WichmannHill is the RNG of the bug report + gen = random.WichmannHill() + except AttributeError: + try: + # 2.2 called it Random + gen = random.Random() + except AttributeError: + # others might simply have a single RNG + gen = random + gen.seed(1) + data = genblock(1, 17 * 1024, generator=gen) + + # compress, sync-flush, and decompress + first = co.compress(data) + second = co.flush(zlib.Z_SYNC_FLUSH) + expanded = dco.decompress(first + second) + + # if decompressed data is different from the input data, choke. + self.assertEqual(expanded, data, "17K random source doesn't match") + + def test_empty_flush(self): + # Test that calling .flush() on unused objects works. + # (Bug #1083110 -- calling .flush() on decompress objects + # caused a core dump.) + + co = zlib.compressobj(zlib.Z_BEST_COMPRESSION) + self.failUnless(co.flush()) # Returns a zlib header + dco = zlib.decompressobj() + self.assertEqual(dco.flush(), "") # Returns nothing + + if hasattr(zlib.compressobj(), "copy"): + def test_compresscopy(self): + # Test copying a compression object + data0 = HAMLET_SCENE + data1 = HAMLET_SCENE.swapcase() + c0 = zlib.compressobj(zlib.Z_BEST_COMPRESSION) + bufs0 = [] + bufs0.append(c0.compress(data0)) + + c1 = c0.copy() + bufs1 = bufs0[:] + + bufs0.append(c0.compress(data0)) + bufs0.append(c0.flush()) + s0 = ''.join(bufs0) + + bufs1.append(c1.compress(data1)) + bufs1.append(c1.flush()) + s1 = ''.join(bufs1) + + self.assertEqual(zlib.decompress(s0),data0+data0) + self.assertEqual(zlib.decompress(s1),data0+data1) + + def test_badcompresscopy(self): + # Test copying a compression object in an inconsistent state + c = zlib.compressobj() + c.compress(HAMLET_SCENE) + c.flush() + self.assertRaises(ValueError, c.copy) + + if hasattr(zlib.decompressobj(), "copy"): + def test_decompresscopy(self): + # Test copying a decompression object + data = HAMLET_SCENE + comp = zlib.compress(data) + + d0 = zlib.decompressobj() + bufs0 = [] + bufs0.append(d0.decompress(comp[:32])) + + d1 = d0.copy() + bufs1 = bufs0[:] + + bufs0.append(d0.decompress(comp[32:])) + s0 = ''.join(bufs0) + + bufs1.append(d1.decompress(comp[32:])) + s1 = ''.join(bufs1) + + self.assertEqual(s0,s1) + self.assertEqual(s0,data) + + def test_baddecompresscopy(self): + # Test copying a compression object in an inconsistent state + data = zlib.compress(HAMLET_SCENE) + d = zlib.decompressobj() + d.decompress(data) + d.flush() + self.assertRaises(ValueError, d.copy) + +def genblock(seed, length, step=1024, generator=random): + """length-byte stream of random data from a seed (in step-byte blocks).""" + if seed is not None: + generator.seed(seed) + randint = generator.randint + if length < step or step < 2: + step = length + blocks = [] + for i in range(0, length, step): + blocks.append(''.join([chr(randint(0,255)) + for x in range(step)])) + return ''.join(blocks)[:length] + + + +def choose_lines(source, number, seed=None, generator=random): + """Return a list of number lines randomly chosen from the source""" + if seed is not None: + generator.seed(seed) + sources = source.split('\n') + return [generator.choice(sources) for n in range(number)] + + + +HAMLET_SCENE = """ +LAERTES + + O, fear me not. + I stay too long: but here my father comes. + + Enter POLONIUS + + A double blessing is a double grace, + Occasion smiles upon a second leave. + +LORD POLONIUS + + Yet here, Laertes! aboard, aboard, for shame! + The wind sits in the shoulder of your sail, + And you are stay'd for. There; my blessing with thee! + And these few precepts in thy memory + See thou character. Give thy thoughts no tongue, + Nor any unproportioned thought his act. + Be thou familiar, but by no means vulgar. + Those friends thou hast, and their adoption tried, + Grapple them to thy soul with hoops of steel; + But do not dull thy palm with entertainment + Of each new-hatch'd, unfledged comrade. Beware + Of entrance to a quarrel, but being in, + Bear't that the opposed may beware of thee. + Give every man thy ear, but few thy voice; + Take each man's censure, but reserve thy judgment. + Costly thy habit as thy purse can buy, + But not express'd in fancy; rich, not gaudy; + For the apparel oft proclaims the man, + And they in France of the best rank and station + Are of a most select and generous chief in that. + Neither a borrower nor a lender be; + For loan oft loses both itself and friend, + And borrowing dulls the edge of husbandry. + This above all: to thine ownself be true, + And it must follow, as the night the day, + Thou canst not then be false to any man. + Farewell: my blessing season this in thee! + +LAERTES + + Most humbly do I take my leave, my lord. + +LORD POLONIUS + + The time invites you; go; your servants tend. + +LAERTES + + Farewell, Ophelia; and remember well + What I have said to you. + +OPHELIA + + 'Tis in my memory lock'd, + And you yourself shall keep the key of it. + +LAERTES + + Farewell. +""" + + +def test_main(): + for cls in (ChecksumTestCase, + ExceptionTestCase, + CompressTestCase, + CompressObjectTestCase): + test_support.run_unittest(cls) + +if __name__ == "__main__": + test_main() + +def test(tests=''): + if not tests: tests = 'o' + testcases = [] + if 'k' in tests: testcases.append(ChecksumTestCase) + if 'x' in tests: testcases.append(ExceptionTestCase) + if 'c' in tests: testcases.append(CompressTestCase) + if 'o' in tests: testcases.append(CompressObjectTestCase) + test_support.run_unittest(*testcases) + +if False: + import sys + sys.path.insert(1, '/Py23Src/python/dist/src/Lib/test') + import test_zlib as tz + ts, ut = tz.test_support, tz.unittest + su = ut.TestSuite() + su.addTest(ut.makeSuite(tz.CompressTestCase)) + ts.run_suite(su) + + Modified: branches/2.3/build.xml =================================================================== --- branches/2.3/build.xml 2006-11-27 18:23:24 UTC (rev 2996) +++ branches/2.3/build.xml 2006-11-28 01:47:58 UTC (rev 2997) @@ -16,7 +16,6 @@ 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 and to cpython anonymous cvs (pserver:ano...@cv...:/cvsroot/python) - 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 @@ -60,14 +59,14 @@ Actions for a release --------------------- 1. determine the new svn tag to be applied to jython - 2. determine the existing cvs tag of the CPython Lib files which should be included + 2. check the svn:externals property of project jython for an appropriate cpython maintenance branch 3. change the following properties in this build.xml, if necessary: - svn.tag (target: full-init) - - python.cvs.tag (target: full-init) - 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. adjust the version strings in target 'version' of this build.xml + (this is for upcoming snapshot builds only) 7. check in all the changes 8. apply the new tag to the jython svn (all projects) 9. call target 'full-build' @@ -213,7 +212,6 @@ <!-- predefined tags for jython and cpython --> <property name="svn.tag" value="HEAD" /> - <property name="python.cvs.tag" value="r223" /> <!-- revision handling --> <property name="svn.revision" value="${svn.tag}" /> @@ -223,8 +221,7 @@ <property name="jython.base.dir" value="${svn.checkout.dir}/jython" /> <property name="source.dir" value="${jython.base.dir}/src" /> <property name="has.repositories.connection" value="true" /> - <property name="python.module" value="python/dist/src/Lib" /> - <property name="python.lib" value="${svn.checkout.dir}/${python.module}" /> + <property name="python.lib" value="${jython.base.dir}/CPythonLib" /> <property name="python.exe" value="${python.home}/python" /> <condition property="do.checkout" value="true"> <istrue value="${has.repositories.connection}" /> @@ -288,7 +285,6 @@ <echo>--- properties (used for full-build only ) ---</echo> <echo>python.exe = '${python.exe}'</echo> <echo>svn.tag = '${svn.tag}'</echo> - <echo>python.cvs.tag = '${python.cvs.tag}'</echo> <echo>svn.checkout.dir = '${svn.checkout.dir}'</echo> <echo>javahl.dir = '${javahl.dir}'</echo> <echo>svnant.jar.dir = '${svnant.jar.dir}'</echo> @@ -353,7 +349,7 @@ <!-- checkout if so defined --> <target name="checkout" depends="prepare" if="do.checkout"> - <!-- jython and installer: determine if to checkout from /tags/${svn.tag} (any tag), or /trunk (HEAD) --> + <!-- determine if to checkout from /tags/${svn.tag} (any tag), or /trunk (HEAD) --> <condition property="svn.main.dir" value="trunk"> <equals arg1="${svn.tag}" arg2="HEAD" /> </condition> @@ -363,16 +359,6 @@ <checkout url="https://svn.sourceforge.net/svnroot/jython/${svn.main.dir}/installer" revision="${svn.revision}" destPath="${svn.checkout.dir}/installer" /> <checkout url="https://svn.sourceforge.net/svnroot/jython/${svn.main.dir}/bugtests" revision="${svn.revision}" destPath="${svn.checkout.dir}/bugtests" /> </svn> - - <!-- cpython --> - <property name="python.cvs.root" value=":pserver:ano...@cv...:/cvsroot/python" /> - <echo>setting python password for anonymous</echo> - <cvspass cvsroot="${python.cvs.root}" password="" /> - <!-- -r: use the cvs tag, -P: prune empty directories --> - <property name="python.checkout.options" value="checkout -r ${python.cvs.tag} -P" /> - <property name="python.checkout.command" value="-z3 -d${python.cvs.root} ${python.checkout.options}" /> - <echo>checking out ${python.module} with the following command: ${python.checkout.command} ${python.module}</echo> - <cvs command="${python.checkout.command} ${python.module}" dest="${svn.checkout.dir}" /> </target> @@ -422,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" /> @@ -633,7 +613,7 @@ <fileset dir="${python.lib}" excludes="**/*.pyc, **/*.pyo"> <patternset> <includesfile name="${jython.base.dir}/build.Lib.include.properties" /> - <exclude name="test/output/test_sax"/> + <exclude name="test/output/test_sax"/> </patternset> </fileset> </copy> @@ -686,7 +666,6 @@ <!-- info section. ATTN: no blanks, no '.' in the names --> <section name="Build-Info"> <attribute name="svn-build" value="${do.checkout}" /> - <attribute name="cpython-version" value="${python.cvs.tag}" /> <attribute name="threadlocal" value="${threadlocal.present}" /> <attribute name="secureclassloader" value="${secureclassloader.present}" /> <attribute name="servlet" value="${servlet.present}" /> Modified: branches/2.3/src/org/python/core/PyClassMethod.java =================================================================== --- branches/2.3/src/org/python/core/PyClassMethod.java 2006-11-27 18:23:24 UTC (rev 2996) +++ branches/2.3/src/org/python/core/PyClassMethod.java 2006-11-28 01:47:58 UTC (rev 2997) @@ -66,7 +66,7 @@ } public PyObject __get__(PyObject obj) { - return classmethod___get__(obj, null); + return classmethod___get__(obj, null); } public PyObject __get__(PyObject obj, PyObject type) { @@ -74,13 +74,14 @@ } final PyObject classmethod___get__(PyObject obj) { - return classmethod___get__(obj, null); + return classmethod___get__(obj, null); } final PyObject classmethod___get__(PyObject obj, PyObject type) { - if (type == null) - type = obj.getType(); - return new PyMethod(type, callable, type.getType()); + if(obj == null) { + return new PyMethod(type, callable, type); + } + return new PyMethod(obj, callable, type); } final static PyObject classmethod_new(PyNewWrapper new_, boolean init, PyType subtype, Modified: branches/2.3/src/org/python/core/PyClassMethodDerived.java =================================================================== --- branches/2.3/src/org/python/core/PyClassMethodDerived.java 2006-11-27 18:23:24 UTC (rev 2996) +++ branches/2.3/src/org/python/core/PyClassMethodDerived.java 2006-11-28 01:47:58 UTC (rev 2997) @@ -1,7 +1,17 @@ package org.python.core; -public class PyClassMethodDerived extends PyClassMethod { +public class PyClassMethodDerived extends PyClassMethod implements Slotted { + public PyObject getSlot(int index) { + return slots[index]; + } + + public void setSlot(int index,PyObject value) { + slots[index]=value; + } + + private PyObject[]slots; + private PyObject dict; public PyObject fastGetDict() { @@ -14,6 +24,7 @@ public PyClassMethodDerived(PyType subtype) { super(subtype); + slots=new PyObject[subtype.getNumSlots()]; dict=subtype.instDict(); } Modified: branches/2.3/src/org/python/core/PyComplexDerived.java =================================================================== --- branches/2.3/src/org/python/core/PyComplexDerived.java 2006-11-27 18:23:24 UTC (rev 2996) +++ branches/2.3/src/org/python/core/PyComplexDerived.java 2006-11-28 01:47:58 UTC (rev 2997) @@ -1,7 +1,17 @@ package org.python.core; -public class PyComplexDerived extends PyComplex { +public class PyComplexDerived extends PyComplex implements Slotted { + public PyObject getSlot(int index) { + return slots[index]; + } + + public void setSlot(int index,PyObject value) { + slots[index]=value; + } + + private PyObject[]slots; + private PyObject dict; public PyObject fastGetDict() { @@ -14,6 +24,7 @@ public PyComplexDerived(PyType subtype,double real,double imaginary) { super(subtype,real,imaginary); + slots=new PyObject[subtype.getNumSlots()]; dict=subtype.instDict(); } Modified: branches/2.3/src/org/python/core/PyDictionaryDerived.java =================================================================== --- branches/2.3/src/org/python/core/PyDictionaryDerived.java 2006-11-27 18:23:24 UTC (rev 2996) +++ branches/2.3/src/org/python/core/PyDictionaryDerived.java 2006-11-28 01:47:58 UTC (rev 2997) @@ -1,7 +1,17 @@ package org.python.core; -public class PyDictionaryDerived extends PyDictionary { +public class PyDictionaryDerived extends PyDictionary implements Slotted { + public PyObject getSlot(int index) { + return slots[index]; + } + + public void setSlot(int index,PyObject value) { + slots[index]=value; + } + + private PyObject[]slots; + private PyObject dict; public PyObject fastGetDict() { @@ -14,6 +24,7 @@ public PyDictionaryDerived(PyType subtype) { super(subtype); + slots=new PyObject[subtype.getNumSlots()]; dict=subtype.instDict(); } Modified: branches/2.3/src/org/python/core/PyFileDerived.java =================================================================== --- branches/2.3/src/org/python/core/PyFileDerived.java 2006-11-27 18:23:24 UTC (rev 2996) +++ branches/2.3/src/org/python/core/PyFileDerived.java 2006-11-28 01:47:58 UTC (rev 2997) @@ -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: branches/2.3/src/org/python/core/PyFloatDerived.java =================================================================== --- branches/2.3/src/org/python/core/PyFloatDerived.java 2006-11-27 18:23:24 UTC (rev 2996) +++ branches/2.3/src/org/python/core/PyFloatDerived.java 2006-11-28 01:47:58 UTC (rev 2997) @@ -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(); } Modified: branches/2.3/src/org/python/core/PyGetSetDescr.java =================================================================== --- branches/2.3/src/org/python/core/PyGetSetDescr.java 2006-11-27 18:23:24 UTC (rev 2996) +++ branches/2.3/src/org/python/core/PyGetSetDescr.java 2006-11-28 01:47:58 UTC (rev 2997) @@ -7,87 +7,92 @@ public class PyGetSetDescr extends PyDescriptor { private Method get_meth; + private Method set_meth; + private Class getset_type; - public PyGetSetDescr(PyType dtype, String name, Class c, String get, String set) { + public PyGetSetDescr(PyType dtype, + String name, + Class c, + String get, + String set) { this.name = name; this.dtype = dtype; try { - get_meth = c.getMethod(get, new Class[] { - }); - } catch (NoSuchMethodException e) { + get_meth = c.getMethod(get, new Class[] {}); + } catch(NoSuchMethodException e) { throw Py.SystemError("bogus getset spec"); } - if (Modifier.isStatic(get_meth.getModifiers())) + if(Modifier.isStatic(get_meth.getModifiers())) throw Py.SystemError("static getset not supported"); getset_type = get_meth.getReturnType(); - if (set != null) { + if(set != null) { try { - set_meth = c.getMethod(set, new Class[] { getset_type }); - } catch (NoSuchMethodException e) { + set_meth = c.getMethod(set, new Class[] {getset_type}); + } catch(NoSuchMethodException e) { throw Py.SystemError("bogus getset spec"); } - if (Modifier.isStatic(set_meth.getModifiers())) + if(Modifier.isStatic(set_meth.getModifiers())) throw Py.SystemError("static getset not supported"); - } } public PyGetSetDescr(String name, Class c, String get, String set) { - this(PyType.fromClass(c),name,c,get,set); + this(PyType.fromClass(c), name, c, get, set); } - + public String toString() { - return "<attribute '"+name+"' of '"+dtype.fastGetName()+"' objects>"; + return "<attribute '" + name + "' of '" + dtype.fastGetName() + + "' objects>"; } - /** - * @see org.python.core.PyObject#__get__(org.python.core.PyObject, org.python.core.PyObject) + * @see org.python.core.PyObject#__get__(org.python.core.PyObject, + * org.python.core.PyObject) */ public PyObject __get__(PyObject obj, PyObject type) { try { - if (obj != null) { + if(obj != null) { PyType objtype = obj.getType(); - if (objtype != dtype && !objtype.isSubType(dtype)) + if(objtype != dtype && !objtype.isSubType(dtype)) throw get_wrongtype(objtype); Object v = get_meth.invoke(obj, new Object[0]); - if (v == null) { + if(v == null) { obj.noAttributeError(name); } return Py.java2py(v); } return this; - } catch (IllegalArgumentException e) { + } catch(IllegalArgumentException e) { throw Py.JavaError(e); - } catch (IllegalAccessException e) { + } catch(IllegalAccessException e) { throw Py.JavaError(e); // unexpected - } catch (InvocationTargetException e) { + } catch(InvocationTargetException e) { throw Py.JavaError(e); } } /** - * @see org.python.core.PyObject#__set__(org.python.core.PyObject, org.python.core.PyObject) + * @see org.python.core.PyObject#__set__(org.python.core.PyObject, + * org.python.core.PyObject) */ public void __set__(PyObject obj, PyObject value) { try { // obj != null PyType objtype = obj.getType(); - if (objtype != dtype && !objtype.isSubType(dtype)) + if(objtype != dtype && !objtype.isSubType(dtype)) throw get_wrongtype(objtype); Object converted = value.__tojava__(getset_type); - if (converted == Py.NoConversion) { + if(converted == Py.NoConversion) { throw Py.TypeError(""); // xxx } - set_meth.invoke(obj, new Object[] { converted }); - - } catch (IllegalArgumentException e) { + set_meth.invoke(obj, new Object[] {converted}); + } catch(IllegalArgumentException e) { throw Py.JavaError(e); - } catch (IllegalAccessException e) { + } catch(IllegalAccessException e) { throw Py.JavaError(e); // unexpected - } catch (InvocationTargetException e) { + } catch(InvocationTargetException e) { throw Py.JavaError(e); } } @@ -105,5 +110,4 @@ public boolean isDataDescr() { return true; } - } Modified: branches/2.3/src/org/python/core/PyIntegerDerived.java =================================================================== --- branches/2.3/src/org/python/core/PyIntegerDerived.java 2006-11-27 18:23:24 UTC (rev 2996) +++ branches/2.3/src/org/python/core/PyIntegerDerived.java 2006-11-28 01:47:58 UTC (rev 2997) @@ -1,7 +1,17 @@ package org.python.core; -public class PyIntegerDerived extends PyInteger { +public class PyIntegerDerived extends PyInteger implements Slotted { + public PyObject getSlot(int index) { + return slots[index]; + } + + public void setSlot(int index,PyObject value) { + slots[index]=value; + } + + private PyObject[]slots; + private PyObject dict; public PyObject fastGetDict() { @@ -14,6 +24,7 @@ public PyIntegerDerived(PyType subtype,int v) { super(subtype,v); + slots=new PyObject[subtype.getNumSlots()]; dict=subtype.instDict(); } Modified: branches/2.3/src/org/python/core/PyListDerived.java =================================================================== --- branches/2.3/src/org/python/core/PyListDerived.java 2006-11-27 18:23:24 UTC (rev 2996) +++ branches/2.3/src/org/python/core/PyListDerived.java 2006-11-28 01:47:58 UTC (rev 2997) @@ -1,7 +1,17 @@ package org.python.core; -public class PyListDerived extends PyList { +public class PyListDerived extends PyList implements Slotted { + public PyObject getSlot(int index) { + return slots[index]; + } + + public void setSlot(int index,PyObject value) { + slots[index]=value; + } + + private PyObject[]slots; + private PyObject dict; public PyObject fastGetDict() { @@ -14,6 +24,7 @@ public PyListDerived(PyType subtype) { super(subtype); + slots=new PyObject[subtype.getNumSlots()]; dict=subtype.instDict(); } Modified: branches/2.3/src/org/python/core/PyObjectDerived.java =================================================================== --- branches/2.3/src/org/python/core/PyObjectDerived.java 2006-11-27 18:23:24 UTC (rev 2996) +++ branches/2.3/src/org/python/core/PyObjectDerived.java 2006-11-28 01:47:58 UTC (rev 2997) @@ -1,7 +1,17 @@ package org.python.core; -public class PyObjectDerived extends PyObject { +public class PyObjectDerived extends PyObject implements Slotted { + public PyObject getSlot(int index) { + return slots[index]; + } + + public void setSlot(int index,PyObject value) { + slots[index]=value; + } + + private PyObject[]slots; + private PyObject dict; public PyObject fastGetDict() { @@ -14,6 +24,7 @@ public PyObjectDerived(PyType subtype) { super(subtype); + slots=new PyObject[subtype.getNumSlots()]; dict=subtype.instDict(); } Modified: branches/2.3/src/org/python/core/PyPropertyDerived.java =================================================================== --- branches/2.3/src/org/python/core/PyPropertyDerived.java 2006-11-27 18:23:24 UTC (rev 2996) +++ branches/2.3/src/org/python/core/PyPropertyDerived.java 2006-11-28 01:47:58 UTC (rev 2997) @@ -1,7 +1,17 @@ package org.python.core; -public class PyPropertyDerived extends PyProperty { +public class PyPropertyDerived extends PyProperty implements Slotted { + public PyObject getSlot(int index) { + return slots[index]; + } + + public void setSlot(int index,PyObject value) { + slots[index]=value; + } + + private PyObject[]slots; + private PyObject dict; public PyObject fastGetDict() { @@ -14,6 +24,7 @@ public PyPropertyDerived(PyType subtype) { super(subtype); + slots=new PyObject[subtype.getNumSlots()]; dict=subtype.instDict(); } Copied: branches/2.3/src/org/python/core/PySlot.java (from rev 2994, trunk/jython/src/org/python/core/PySlot.java) =================================================================== --- branches/2.3/src/org/python/core/PySlot.java (rev 0) +++ branches/2.3/src/org/python/core/PySlot.java 2006-11-28 01:47:58 UTC (rev 2997) @@ -0,0 +1,48 @@ +package org.python.core; + +public class PySlot extends PyDescriptor { + + public PySlot(PyType dtype, String name, int index) { + this.name = name; + this.dtype = dtype; + this.index = index; + } + + public boolean implementsDescrSet() { + return true; + } + + public boolean isDataDescr() { + return true; + } + + public PyObject __get__(PyObject obj, PyObject type) { + if(obj != null) { + checkType((PyType)type); + return ((Slotted)obj).getSlot(index); + } + return this; + } + + public void __set__(PyObject obj, PyObject value) { + checkType(obj.getType()); + ((Slotted)obj).setSlot(index, value); + } + + public void __delete__(PyObject obj) { + checkType(obj.getType()); + ((Slotted)obj).setSlot(index, null); + } + + public String toString() { + return "<member '" + name + "' of '" + dtype.fastGetName() + + "' objects>"; + } + + private void checkType(PyType type) { + if(type != dtype && !type.isSubType(dtype)) + throw get_wrongtype(type); + } + + private int index; +} Modified: branches/2.3/src/org/python/core/PyStringDerived.java =================================================================== --- branches/2.3/src/org/python/core/PyStringDerived.java 2006-11-27 18:23:24 UTC (rev 2996) +++ branches/2.3/src/org/python/core/PyStringDerived.java 2006-11-28 01:47:58 UTC (rev 2997) @@ -1,7 +1,17 @@ package org.python.core; -public class PyStringDerived extends PyString { +public class PyStringDerived extends PyString implements Slotted { + public PyObject getSlot(int index) { + return slots[index]; + } + + public void setSlot(int index,PyObject value) { + slots[index]=value; + } + + private PyObject[]slots; + private PyObject dict; public PyObject fastGetDict() { @@ -14,6 +24,7 @@ public PyStringDerived(PyType subtype,String v) { super(subtype,v); + slots=new PyObject[subtype.getNumSlots()]; dict=subtype.instDict(); } Modified: branches/2.3/src/org/python/core/PySuperDerived.java =================================================================== --- branches/2.3/src/org/python/core/PySuperDerived.java 2006-11-27 18:23:24 UTC (rev 2996) +++ branches/2.3/src/org/python/core/PySuperDerived.java 2006-11-28 01:47:58 UTC (rev 2997) @@ -1,7 +1,17 @@ package org.python.core; -public class PySuperDerived extends PySuper { +public class PySuperDerived extends PySuper implements Slotted { + public PyObject getSlot(int index) { + return slots[index]; + } + + public void setSlot(int index,PyObject value) { + slots[index]=value; + } + + private PyObject[]slots; + private PyObject dict; public PyObject fastGetDict() { @@ -14,6 +24,7 @@ public PySuperDerived(PyType subtype) { super(subtype); + slots=new PyObject[subtype.getNumSlots()]; dict=subtype.instDict(); } Modified: branches/2.3/src/org/python/core/PySystemState.java =================================================================== --- branches/2.3/src/org/python/core/PySystemState.java 2006-11-27 18:23:24 UTC (rev 2996) +++ branches/2.3/src/org/python/core/PySystemState.java 2006-11-28 01:47:58 UTC (rev 2997) @@ -295,7 +295,8 @@ public static String exec_prefix=""; private static String findRoot(Properties preProperties, - Properties postProperties) + Properties postProperties, + String jarFileName) { String root = null; try { @@ -323,25 +324,25 @@ } catch (Exception exc) { return null; } - //System.err.println("root: "+root); - if (root != null) - return root; - // If install.root is undefined find JYTHON_JAR in class.path - String classpath = preProperties.getProperty("java.class.path"); - if (classpath == null) - return null; - - int jpy = classpath.toLowerCase().indexOf(JYTHON_JAR); - if (jpy == -1) { - return null; + if (root == null) { + String classpath = preProperties.getProperty("java.class.path"); + if (classpath != null) { + int jpy = classpath.toLowerCase().indexOf(JYTHON_JAR); + if (jpy >= 0) { + int start = classpath.lastIndexOf(java.io.File.pathSeparator, jpy) + 1; + root = classpath.substring(start, jpy); + } else { + // in case JYTHON_JAR is referenced from a MANIFEST inside another jar on the classpath + root = jarFileName; + } + } } - int start = classpath.lastIndexOf(java.io.File.pathSeparator, jpy)+1; - return classpath.substring(start, jpy); + return root; } private static void initRegistry(Properties preProperties, Properties postProperties, - boolean standalone) + boolean standalone, String jarFileName) { if (registry != null) { Py.writeError("systemState", "trying to reinitialize registry"); @@ -349,7 +350,7 @@ } registry = preProperties; - prefix = exec_prefix = findRoot(preProperties, postProperties); + prefix = exec_prefix = findRoot(preProperties, postProperties, jarFileName); // Load the default registry if (prefix != null) { @@ -451,7 +452,7 @@ } // initialize the JPython registry - initRegistry(preProperties, postProperties, standalone); + initRegistry(preProperties, postProperties, standalone, jarFileName); // other initializations initBuiltins(registry); Modified: branches/2.3/src/org/python/core/PyTupleDerived.java =================================================================== --- branches/2.3/src/org/python/core/PyTupleDerived.java 2006-11-27 18:23:24 UTC (rev 2996) +++ branches/2.3/src/org/python/core/PyTupleDerived.java 2006-11-28 01:47:58 UTC (rev 2997) @@ -1,7 +1,17 @@ package org.python.core; -public class PyTupleDerived extends PyTuple { +public class PyTupleDerived extends PyTuple implements Slotted { + public PyObject getSlot(int index) { + return slots[index]; + } + + public void setSlot(int index,PyObject value) { + slots[index]=value; + } + + private PyObject[]slots; + private PyObject dict; public PyObject fastGetDict() { @@ -14,6 +24,7 @@ public PyTupleDerived(PyType subtype,PyObject[]elements) { super(subtype,elements); + slots=new PyObject[subtype.getNumSlots()]; dict=subtype.instDict(); } Modified: branches/2.3/src/org/python/core/PyType.java =================================================================== --- branches/2.3/src/org/python/core/PyType.java 2006-11-27 18:23:24 UTC (rev 2996) +++ branches/2.3/src/org/python/core/PyType.java 2006-11-28 01:47:58 UTC (rev 2997) @@ -383,11 +383,6 @@ return null; } - public List getSlotnames() { - return slotnames; - } - - private String name; private PyType base; private PyObject[] bases; @@ -395,17 +390,15 @@ private PyObject[] mro; private long tp_flags; private Class underlying_class; - private List slotnames; private boolean non_instantiable = false; - boolean has_set, has_delete, hide_dict; + boolean has_set, has_delete; private boolean needs_finalizer; + private int numSlots; + private boolean needs_userdict = true; - private int nuserslots; - private boolean needs_userdict; - private java.lang.ref.ReferenceQueue subclasses_refq = new java.lang.ref.ReferenceQueue(); private java.util.HashSet subclasses = new java.util.HashSet(); @@ -519,22 +512,13 @@ } - final PyTuple type_mro() { - return getMro(); + final PyList type_mro() { + return new PyList(compute_mro()); + } - final PyTuple type_mro(PyObject o) { - //FIXME: PyMethDescr should be gaurding against args that are not the - // correct type in the generated code, but that is not working. - // fix and delete this instanceof check. - if (!(o instanceof PyType)) { - throw Py.TypeError( - "descriptor 'mro' requires a 'type' object but received a '" - + o.getType().fastGetName() - + "'"); - } - PyType type = (PyType)o; - return type.type_mro(); + final PyList type_mro(PyObject o) { + return ((PyType)o).type_mro(); } final PyObject[] compute_mro() { @@ -608,7 +592,7 @@ PyObject parent = mro[i]; if (parent instanceof PyType) { PyType parent_type =(PyType)parent; - if (parent_type.underlying_class != null || parent_type.nuserslots != 0) + if (parent_type.underlying_class != null || parent_type.numSlots != 0) return parent_type; } } @@ -685,23 +669,7 @@ // xxx can be subclassed ? - boolean needs_userdict = base.needs_userdict; - if (!needs_userdict) { - for (int i=0; i<bases_list.length;i++) { - PyObject cur = bases_list[i]; - if (cur != base) { - if ((cur instanceof PyType && ((PyType)cur).needs_userdict) || cur instanceof PyClass) { - needs_userdict = true; - break; - } - } - } - } - int nuserslots = base.nuserslots; - - needs_userdict = true; - if (dict.__finditem__("__module__") == null) { PyFrame frame = Py.getFrame(); if (frame != null) { @@ -714,76 +682,63 @@ } // xxx also __doc__ __module__ - List slotnames = null; - boolean hide_dict = false; - PyObject slots = dict.__finditem__("__slots__"); - if (slots != null) { - hide_dict = true; - if (base.nuserslots > 0) { - nuserslots = base.nuserslots; - slotnames = new ArrayList(base.getSlotnames()); - } - else { - slotnames = new ArrayList(); - } - PyObject iter = slots.__iter__(); - PyObject slotname; - for (; (slotname = iter.__iternext__())!= null; ) { - confirmIdentifier(slotname); - String slotstring = slotname.toString(); - if (slotstring.equals("__dict__")) { - hide_dict = false; - } - slotnames.add(mangleName(name, slotstring)); - nuserslots += 1; - } - } - PyType newtype; if (new_.for_type == metatype) { newtype = new PyType(); // xxx set metatype } else { newtype = new PyTypeDerived(metatype); } - + newtype.dict = dict; + newtype.numSlots = base.numSlots; newtype.name = name; newtype.base = base; newtype.bases = bases_list; + + PyObject slots = dict.__finditem__("__slots__"); + if(slots != null) { + newtype.needs_userdict = false; + if(slots instanceof PyString) { + addSlot(newtype, slots); + } else { + PyObject iter = slots.__iter__(); + PyObject slotname; + 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; + } + } + } + - /* initialize tp flags */ newtype.tp_flags=Py.TPFLAGS_HEAPTYPE; - newtype.needs_userdict = needs_userdict; - newtype.nuserslots = nuserslots; - newtype.hide_dict = hide_dict; - newtype.dict = dict; - - newtype.slotnames = slotnames; - // special case __new__, if function => static method PyObject tmp = dict.__finditem__("__new__"); if (tmp != null && tmp instanceof PyFunction) { // xxx java functions? dict.__setitem__("__new__",new PyStaticMethod(tmp)); } - - PyObject mro_meth = null; - PyObject[] newmro; - - if (metatype.underlying_class != PyType.class) - mro_meth = metatype.lookup("mro"); - - if (mro_meth == null) { - newmro = newtype.compute_mro(); - } else { - newmro = Py.make_array(mro_meth.__get__(newtype,metatype).__call__()); + newtype.mro = newtype.compute_mro(); + if(metatype.underlying_class != PyType.class + && metatype.lookup("mro") != null) { + newtype.mro = Py.make_array(metatype.lookup("mro") + .__get__(newtype, metatype) + .__call__()); } - - newtype.mro = newmro; - + // __dict__ descriptor - if (needs_userdict && newtype.lookup("__dict__")==null) { + if (newtype.needs_userdict && newtype.lookup("__dict__")==null) { dict.__setitem__("__dict__",new PyGetSetDescr(newtype,"__dict__",PyObject.class,"getDict",null)); } @@ -797,11 +752,22 @@ if (cur instanceof PyType) ((PyType)cur).attachSubclass(newtype); } - return newtype; } + private static void addSlot(PyType newtype, PyObject slotname) { + confirmIdentifier(slotname); + String slotstring = mangleName(newtype.name, slotname.toString()); + if(slotstring.equals("__dict__")) { + newtype.needs_userdict = true; + } else { + newtype.dict.__setitem__(slotstring, new PySlot(newtype, + slotstring, + newtype.numSlots++)); + } + } + public String fastGetName() { return name; } @@ -816,19 +782,18 @@ } /** - * INTERNAL - * lookup for name through mro objects' dicts - * - * @param name attribute name (must be interned) + * INTERNAL lookup for name through mro objects' dicts + * + * @param name + * attribute name (must be interned) * @return found object or null */ public PyObject lookup(String name) { - PyObject[] mro = this.mro; - for (int i = 0; i < mro.length; i++) { + for(int i = 0; i < mro.length; i++) { PyObject dict = mro[i].fastGetDict(); - if (dict != null) { + if(dict != null) { PyObject obj = dict.__finditem__(name); - if (obj != null) + if(obj != null) return obj; } } @@ -862,7 +827,7 @@ } PyType(PyType subtype) { - super(true); + super(subtype); } private static String decapitalize(String s) { @@ -1175,15 +1140,14 @@ } catch (Exception e) { throw error(e); } - if (newstyle) { // newstyle - base = (Class) exposed_decl_get_object(c, "base"); - name = (String) exposed_decl_get_object(c, "name"); - if (base == null) { + if(newstyle) { // newstyle + base = (Class)exposed_decl_get_object(c, "base"); + name = (String)exposed_decl_get_object(c, "name"); + if(base == null) { Class cur = c; - while (cur != PyObject.class) { - Class exposed_as = - (Class) exposed_decl_get_object(cur, "as"); - if (exposed_as != null) { + while(cur != PyObject.class) { + Class exposed_as = (Class)exposed_decl_get_object(cur, "as"); + if(exposed_as != null) { PyType exposed_as_type = fromClass(exposed_as); class_to_type.put(c, exposed_as_type); return exposed_as_type; @@ -1353,6 +1317,10 @@ return new PyString("__builtin__"); return dict.__finditem__("__module__"); } + + public int getNumSlots(){ + return numSlots; + } public String getFullName () { if (underlying_class != null) @@ -1461,7 +1429,7 @@ int i = 0; while (classname.charAt(i) == '_') i++; - return "_"+classname.substring(i)+methodname; + return ("_"+classname.substring(i)+methodname).intern(); } return methodname; } Modified: branches/2.3/src/org/python/core/PyTypeDerived.java =================================================================== --- branches/2.3/src/org/python/core/PyTypeDerived.java 2006-11-27 18:23:24 UTC (rev 2996) +++ branches/2.3/src/org/python/core/PyTypeDerived.java 2006-11-28 01:47:58 UTC (rev 2997) @@ -1,7 +1,17 @@ package org.python.core; -public class PyTypeDerived extends PyType { +public class PyTypeDerived extends PyType implements Slotted { + public PyObject getSlot(int index) { + return slots[index]; + } + + public void setSlot(int index,PyObject value) { + slots[index]=value; + } + + private PyObject[]slots; + private PyObject dict; public PyObject fastGetDict() { @@ -14,6 +24,7 @@ public PyTypeDerived(PyType subtype) { super(subtype); + slots=new PyObject[subtype.getNumSlots()]; dict=subtype.instDict(); } Modified: branches/2.3/src/org/python/core/PyUnicodeDerived.java =================================================================== --- branches/2.3/src/org/python/core/PyUnicodeDerived.java 2006-11-27 18:23:24 UTC (rev 2996) +++ branches/2.3/src/org/python/core/PyUnicodeDerived.java 2006-11-28 01:47:58 UTC (rev 2997) @@ -1,7 +1,17 @@ package org.python.core; -public class PyUnicodeDerived extends PyUnicode { +public class PyUnicodeDerived extends PyUnicode implements Slotted { + public PyObject getSlot(int index) { + return slots[index]; + } + + public void setSlot(int index,PyObject value) { + slots[index]=value; + } + + private PyObject[]slots; + private PyObject dict; public PyObject fastGetDict() { @@ -14,6 +24,7 @@ public PyUnicodeDerived(PyType subtype,String string) { super(subtype,string); + slots=new PyObject[subtype.getNumSlots()]; dict=subtype.instDict(); } Copied: branches/2.3/src/org/python/core/Slotted.java (from rev 2994, trunk/jython/src/org/python/core/Slotted.java) =================================================================== --- branches/2.3/src/org/python/core/Slotted.java (rev 0) +++ branches/2.3/src/org/python/core/Slotted.java 2006-11-28 01:47:58 UTC (rev 2997) @@ -0,0 +1,8 @@ +package org.python.core; + +public interface Slotted { + + public PyObject getSlot(int index); + + public void setSlot(int index, PyObject value); +} This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <cg...@us...> - 2006-12-05 02:58:38
|
Revision: 3006 http://svn.sourceforge.net/jython/?rev=3006&view=rev Author: cgroves Date: 2006-12-04 18:58:36 -0800 (Mon, 04 Dec 2006) Log Message: ----------- adding Tim Freund's cmath implementation from patch #1600162 Modified Paths: -------------- branches/2.3/src/org/python/modules/Setup.java Added Paths: ----------- branches/2.3/Lib/test/test_cmath.py branches/2.3/src/org/python/modules/cmath.java Added: branches/2.3/Lib/test/test_cmath.py =================================================================== --- branches/2.3/Lib/test/test_cmath.py (rev 0) +++ branches/2.3/Lib/test/test_cmath.py 2006-12-05 02:58:36 UTC (rev 3006) @@ -0,0 +1,109 @@ +#! /usr/bin/env python +""" Simple test script for cmathmodule.c + Roger E. Masse +""" +import cmath +import unittest +from test import test_support +from test.test_support import verbose + +p = cmath.pi +e = cmath.e +if verbose: + print 'PI = ', abs(p) + print 'E = ', abs(e) + + +class CmathTestCase(unittest.TestCase): + def assertAlmostEqual(self, x, y, places=5, msg=None): + unittest.TestCase.assertAlmostEqual(self, x.real, y.real, places, msg) + unittest.TestCase.assertAlmostEqual(self, x.imag, y.imag, places, msg) + + def test_acos(self): + self.assertAlmostEqual(complex(0.936812, -2.30551), + cmath.acos(complex(3, 4))) + + def test_acosh(self): + self.assertAlmostEqual(complex(2.30551, 0.93681), + cmath.acosh(complex(3, 4))) + + def test_asin(self): + self.assertAlmostEqual(complex(0.633984, 2.30551), + cmath.asin(complex(3, 4))) + + def test_asinh(self): + self.assertAlmostEqual(complex(2.29991, 0.917617), + cmath.asinh(complex(3, 4))) + + def test_atan(self): + self.assertAlmostEqual(complex(1.44831, 0.158997), + cmath.atan(complex(3, 4))) + + def test_atanh(self): + self.assertAlmostEqual(complex(0.11750, 1.40992), + cmath.atanh(complex(3, 4))) + + def test_cos(self): + self.assertAlmostEqual(complex(-27.03495, -3.851153), + cmath.cos(complex(3, 4))) + + def test_cosh(self): + self.assertAlmostEqual(complex(-6.58066, -7.58155), + cmath.cosh(complex(3, 4))) + + def test_exp(self): + self.assertAlmostEqual(complex(-13.12878, -15.20078), + cmath.exp(complex(3, 4))) + + def test_log(self): + self.assertAlmostEqual(complex(1.60944, 0.927295), + cmath.log(complex(3, 4))) + + def test_log10(self): + self.assertAlmostEqual(complex(0.69897, 0.40272), + cmath.log10(complex(3, 4))) + + def test_sin(self): + self.assertAlmostEqual(complex(3.853738, -27.01681), + cmath.sin(complex(3, 4))) + + def test_sinh(self): + self.assertAlmostEqual(complex(-6.54812, -7.61923), + cmath.sinh(complex(3, 4))) + + def test_sqrt_real_positive(self): + self.assertAlmostEqual(complex(2, 1), + cmath.sqrt(complex(3, 4))) + + def test_sqrt_real_zero(self): + self.assertAlmostEqual(complex(1.41421, 1.41421), + cmath.sqrt(complex(0, 4))) + + def test_sqrt_real_negative(self): + self.assertAlmostEqual(complex(1, 2), + cmath.sqrt(complex(-3, 4))) + + def test_sqrt_imaginary_zero(self): + self.assertAlmostEqual(complex(0.0, 1.73205), + cmath.sqrt(complex(-3, 0))) + + def test_sqrt_imaginary_negative(self): + self.assertAlmostEqual(complex(1.0, -2.0), + cmath.sqrt(complex(-3, -4))) + + def test_tan(self): + self.assertAlmostEqual(complex(-0.000187346, 0.999356), + cmath.tan(complex(3, 4))) + + def test_tanh(self): + self.assertAlmostEqual(complex(1.00071, 0.00490826), + cmath.tanh(complex(3, 4))) + +def test_main(): + test_support.run_unittest(CmathTestCase) + +if __name__ == "__main__": + test_main() + + + Modified: branches/2.3/src/org/python/modules/Setup.java =================================================================== --- branches/2.3/src/org/python/modules/Setup.java 2006-12-03 22:23:58 UTC (rev 3005) +++ branches/2.3/src/org/python/modules/Setup.java 2006-12-05 02:58:36 UTC (rev 3006) @@ -53,6 +53,7 @@ "errno", "array:org.python.modules.ArrayModule", "sets:org.python.modules.sets.Sets", - "_random:org.python.modules.random.RandomModule" + "_random:org.python.modules.random.RandomModule", + "cmath" }; } Added: branches/2.3/src/org/python/modules/cmath.java =================================================================== --- branches/2.3/src/org/python/modules/cmath.java (rev 0) +++ branches/2.3/src/org/python/modules/cmath.java 2006-12-05 02:58:36 UTC (rev 3006) @@ -0,0 +1,213 @@ +package org.python.modules; + +import org.python.core.Py; +import org.python.core.PyComplex; +import org.python.core.PyException; +import org.python.core.PyFloat; +import org.python.core.PyObject; +import org.python.modules.math; + +public class cmath { + public static PyFloat pi = new PyFloat(Math.PI); + public static PyFloat e = new PyFloat(Math.E); + + private static PyComplex one = new PyComplex(1.0, 0.0); + private static PyComplex half = new PyComplex(0.5, 0.0); + private static PyComplex i = new PyComplex(0.0, 1.0); + private static PyComplex half_i = new PyComplex(0.0, 0.5); + + private static PyComplex c_prodi(PyComplex x) { + return (new PyComplex(-x.imag, x.real)); + } + + private static double hypot(double x, double y) { + return (Math.sqrt(x * x + y * y)); + } + + private static PyComplex complexFromPyObject(PyObject in) { + try{ + return(in.__complex__()); + } catch(PyException e){ + if(e.type == Py.AttributeError) { + throw Py.TypeError("a float is required"); + } + throw e; + } + } + + public static PyObject acos(PyObject in) { + PyComplex x = complexFromPyObject(in); + return (c_prodi(log(x.__add__(i + .__mul__(sqrt(one.__sub__(x.__mul__(x))))))).__neg__()); + } + + public static PyComplex acosh(PyObject in) { + PyComplex x = complexFromPyObject(in); + PyComplex r = null; + + PyComplex a = sqrt(x.__sub__(one)); + PyComplex b = sqrt(x.__add__(one)); + PyComplex c = sqrt(half); + r = log(c.__mul__(b.__add__(a))); + + return ((PyComplex) r.__add__(r)); + } + + public static PyComplex asin(PyObject in) { + PyComplex x = complexFromPyObject(in); + PyComplex r = null; + + PyComplex squared = (PyComplex) x.__mul__(x); + PyComplex sq1_minus_xsq = sqrt(one.__sub__(squared)); + + r = (PyComplex) c_prodi(log(sq1_minus_xsq.__add__(c_prodi(x)))) + .__neg__(); + return (r); + } + + public static PyComplex asinh(PyObject in) { + PyComplex x = complexFromPyObject(in); + PyComplex r = null; + + PyComplex a = sqrt(x.__add__(i)); + PyComplex b = sqrt(x.__sub__(i)); + PyComplex z = sqrt(half); + r = log(z.__mul__(a.__add__(b))); + + return ((PyComplex) r.__add__(r)); + } + + public static PyComplex atan(PyObject in) { + PyComplex x = complexFromPyObject(in); + PyComplex r = (PyComplex) half_i.__mul__(log(i.__add__(x).__div__( + i.__sub__(x)))); + + return (r); + } + + public static PyComplex atanh(PyObject in) { + PyComplex x = complexFromPyObject(in); + PyComplex r = (PyComplex) half.__mul__(log(one.__add__(x).__div__( + one.__sub__(x)))); + return (r); + } + + public static PyComplex cos(PyObject in) { + PyComplex x = complexFromPyObject(in); + PyComplex r = new PyComplex(Math.cos(x.real) * math.cosh(x.imag), -Math + .sin(x.real) + * math.sinh(x.imag)); + return (r); + } + + public static PyComplex cosh(PyObject in) { + PyComplex x = complexFromPyObject(in); + PyComplex r = new PyComplex(Math.cos(x.imag) * math.cosh(x.real), Math + .sin(x.imag) + * math.sinh(x.real)); + return (r); + } + + public static PyComplex exp(PyObject in) { + PyComplex x = complexFromPyObject(in); + PyComplex r = new PyComplex(0.0, 0.0); + double l = Math.exp(x.real); + r.real = l * Math.cos(x.imag); + r.imag = l * Math.sin(x.imag); + return (r); + } + + public static PyComplex log(PyObject in) { + PyComplex r = new PyComplex(0.0, 0.0); + PyComplex x = complexFromPyObject(in); + r.imag = Math.atan2(x.imag, x.real); + r.real = Math.log(hypot(x.real, x.imag)); + return (r); + } + + public static PyComplex log10(PyObject in) { + PyComplex r = new PyComplex(0.0, 0.0); + PyComplex x = complexFromPyObject(in); + double l = hypot(x.real, x.imag); + r.imag = Math.atan2(x.imag, x.real) / Math.log(10.0); + r.real = math.log10(new PyFloat(l)); + return (r); + } + + public static PyComplex sin(PyObject in) { + PyComplex r = new PyComplex(0.0, 0.0); + PyComplex x = complexFromPyObject(in); + r.real = Math.sin(x.real) * math.cosh(x.imag); + r.imag = Math.cos(x.real) * math.sinh(x.imag); + return (r); + } + + public static PyComplex sinh(PyObject in) { + PyComplex r = new PyComplex(0.0, 0.0); + PyComplex x = complexFromPyObject(in); + r.real = Math.cos(x.imag) * math.sinh(x.real); + r.imag = Math.sin(x.imag) * math.cosh(x.real); + return (r); + } + + public static PyComplex sqrt(PyObject in) { + PyComplex x = complexFromPyObject(in); + PyComplex r = new PyComplex(0.0, 0.0); + + if ((x.real != 0.0) || (x.imag != 0.0)) { + double s = Math + .sqrt(0.5 * (Math.abs(x.real) + hypot(x.real, x.imag))); + double d = 0.5 * x.imag / s; + + if (x.real > 0) { + r.real = s; + r.imag = d; + } else if (x.imag >= 0) { + r.real = d; + r.imag = s; + } else { + r.real = -d; + r.imag = -s; + } + } + return (r); + } + + public static PyComplex tan(PyObject in) { + PyComplex x = complexFromPyObject(in); + PyComplex r = new PyComplex(0.0, 0.0); + + double sr = Math.sin(x.real); + double cr = Math.cos(x.real); + double shi = math.sinh(x.imag); + double chi = math.cosh(x.imag); + double rs = sr * chi; + double is = cr * shi; + double rc = cr * chi; + double ic = -sr * shi; + double d = rc * rc + ic * ic; + r.real = ((rs * rc) + (is * ic)) / d; + r.imag = ((is * rc) - (rs * ic)) / d; + + return (r); + } + + public static PyComplex tanh(PyObject in) { + PyComplex x = complexFromPyObject(in); + PyComplex r = new PyComplex(0.0, 0.0); + + double si = Math.sin(x.imag); + double ci = Math.cos(x.imag); + double shr = math.sinh(x.real); + double chr = math.cosh(x.real); + double rs = ci * shr; + double is = si * chr; + double rc = ci * chr; + double ic = si * shr; + double d = rc * rc + ic * ic; + r.real = ((rs * rc) + (is * ic)) / d; + r.imag = ((is * rc) - (rs * ic)) / d; + + return (r); + } +} This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <cg...@us...> - 2007-02-22 05:44:04
|
Revision: 3118 http://svn.sourceforge.net/jython/?rev=3118&view=rev Author: cgroves Date: 2007-02-21 21:44:02 -0800 (Wed, 21 Feb 2007) Log Message: ----------- merge -r 3084:3089 https://jython.svn.sourceforge.net/svnroot/jython/trunk/jython Modified Paths: -------------- branches/2.3/LICENSE.txt branches/2.3/build.xml Added Paths: ----------- branches/2.3/bugtests/test392LibDir/ branches/2.3/bugtests/test392LibDir/__init__.py branches/2.3/bugtests/test392importer.py Removed Paths: ------------- branches/2.3/bugtests/test392LibDir/__init__.py Modified: branches/2.3/LICENSE.txt =================================================================== --- branches/2.3/LICENSE.txt 2007-02-22 05:40:25 UTC (rev 3117) +++ branches/2.3/LICENSE.txt 2007-02-22 05:44:02 UTC (rev 3118) @@ -1,32 +1,28 @@ -HISTORY OF THE SOFTWARE +A. HISTORY OF THE SOFTWARE ======================= JPython was created in late 1997 by Jim Hugunin. Jim was also the primary developer while he was at CNRI. In February 1999 Barry Warsaw took over as primary developer and released JPython version 1.1. + In October 2000 Barry helped move the software to SourceForge -where it was renamed to Jython. Jython is developed by a group -of volunteers. +where it was renamed to Jython. Jython 2.0 and on are licensed under +the Jython specific license below. +The standard library is covered by the Python Software Foundation +license. See the LICENSE_CPython.txt file for details. -The standard library is covered by the BeOpen / CNRI license. See the -Lib/LICENSE file for details. - -The oro regular expresion matcher is covered by the apache license. -See the org/apache/LICENSE file for details. - The zxJDBC package was written by Brian Zimmer and originally licensed under the GNU Public License. The package is now covered by the Jython Software License. -The command line interpreter is covered by the Apache Software License. -See the org/apache/LICENSE file for details. - +The command line interpreter is covered by the Apache Software +License. See the LICENSE_Apache.txt file for details. -Jython changes Software License. +B. TERMS AND CONDITIONS FOR ACCESSING OR OTHERWISE USING JYTHON ================================ -Copyright (c) 2000, Jython Developers +Copyright (c) 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007 Jython Developers All rights reserved. Redistribution and use in source and binary forms, with or without @@ -59,7 +55,7 @@ -JPython Software License. +JPython 1.1.x Software License. ========================= ______________________________________________________________________ Copied: branches/2.3/bugtests/test392LibDir (from rev 3089, trunk/jython/bugtests/test392LibDir) Property changes on: branches/2.3/bugtests/test392LibDir ___________________________________________________________________ Name: svn:ignore + *.class Deleted: branches/2.3/bugtests/test392LibDir/__init__.py =================================================================== Copied: branches/2.3/bugtests/test392LibDir/__init__.py (from rev 3089, trunk/jython/bugtests/test392LibDir/__init__.py) =================================================================== Copied: branches/2.3/bugtests/test392importer.py (from rev 3089, trunk/jython/bugtests/test392importer.py) =================================================================== --- branches/2.3/bugtests/test392importer.py (rev 0) +++ branches/2.3/bugtests/test392importer.py 2007-02-22 05:44:02 UTC (rev 3118) @@ -0,0 +1,5 @@ +import sys +sys.path.append('test392LibDir') +import test392m + +assert 'test392LibDir' in test392m.__file__, "test392m.__file__ doesn't contain test392LibDir, the directory it's in" Modified: branches/2.3/build.xml =================================================================== --- branches/2.3/build.xml 2007-02-22 05:40:25 UTC (rev 3117) +++ branches/2.3/build.xml 2007-02-22 05:44:02 UTC (rev 3118) @@ -243,6 +243,13 @@ </path> <!-- taskdef for svn ant task --> <taskdef name="svn" classname="org.tigris.subversion.svnant.SvnTask" classpathref="svn.classpath" /> + <!-- Require all of the optional jars for a full build --> + <fail unless="readline.present" message="readline jar not present" /> + <fail unless="servlet.present" message="servlet jar not present" /> + <fail unless="informix.present" message="informix jar not present" /> + <fail unless="mysql.present" message="mysql jar not present" /> + <fail unless="postgresql.present" message="postgres jar not present" /> + <fail unless="oracle.present" message="oracle jar not present" /> </target> @@ -653,6 +660,7 @@ <include name="org/apache/commons/cli/*.class" /> </fileset> </copy> + <copy file="${install.src.dir}/org/apache/LICENSE.txt" tofile="${dist.dir}/LICENSE_Apache.txt" preservelastmodified="true" /> <echo>copy installer icon to ${dist.dir}</echo> <copy todir="${dist.dir}" preservelastmodified="true"> <!-- check no /bin directory --> This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <cg...@us...> - 2007-02-22 05:21:14
|
Revision: 3114 http://svn.sourceforge.net/jython/?rev=3114&view=rev Author: cgroves Date: 2007-02-21 21:21:12 -0800 (Wed, 21 Feb 2007) Log Message: ----------- merged from r3003 to r3019 from trunk Modified Paths: -------------- branches/2.3/Lib/test/test_descr.py branches/2.3/Misc/make_binops.py branches/2.3/src/org/python/core/PyClassMethod.java branches/2.3/src/org/python/core/PyClassMethodDerived.java branches/2.3/src/org/python/core/PyComplex.java branches/2.3/src/org/python/core/PyComplexDerived.java branches/2.3/src/org/python/core/PyDictionaryDerived.java branches/2.3/src/org/python/core/PyFileDerived.java branches/2.3/src/org/python/core/PyFloatDerived.java branches/2.3/src/org/python/core/PyGetSetDescr.java branches/2.3/src/org/python/core/PyIntegerDerived.java branches/2.3/src/org/python/core/PyListDerived.java branches/2.3/src/org/python/core/PyLongDerived.java branches/2.3/src/org/python/core/PyObject.java branches/2.3/src/org/python/core/PyObjectDerived.java branches/2.3/src/org/python/core/PyProperty.java branches/2.3/src/org/python/core/PyPropertyDerived.java branches/2.3/src/org/python/core/PyStringDerived.java branches/2.3/src/org/python/core/PySuper.java branches/2.3/src/org/python/core/PySuperDerived.java branches/2.3/src/org/python/core/PyTupleDerived.java branches/2.3/src/org/python/core/PyType.java branches/2.3/src/org/python/core/PyTypeDerived.java branches/2.3/src/org/python/core/PyUnicodeDerived.java branches/2.3/src/org/python/modules/time/PyTimeTuple.java branches/2.3/src/templates/gderived-defs branches/2.3/src/templates/gexpose-defs branches/2.3/src/templates/gexpose.py branches/2.3/src/templates/java_pretty.py branches/2.3/src/templates/java_templating.py branches/2.3/src/templates/mappings branches/2.3/src/templates/object.expose branches/2.3/src/templates/type.expose Added Paths: ----------- branches/2.3/src/templates/make_binops.py Modified: branches/2.3/Lib/test/test_descr.py =================================================================== --- branches/2.3/Lib/test/test_descr.py 2007-02-22 05:08:42 UTC (rev 3113) +++ branches/2.3/Lib/test/test_descr.py 2007-02-22 05:21:12 UTC (rev 3114) @@ -5,6 +5,7 @@ # depend on the c extension module xxsubtype # - merged code from the pypy version of this script to run all tests instead of stopping # at the first failure +# - allow specific tests to be run by specifying them on the command line from test.test_support import verify, vereq, verbose, TestFailed, TESTFN, get_original_stdout from copy import deepcopy @@ -3680,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..." @@ -3927,10 +3977,11 @@ 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, + subclass_cmp_right_op, dict_type_with_metaclass, meth_class_get, isinst_isclass, @@ -3938,6 +3989,10 @@ carloverre, filefault, ] + if __name__ == '__main__': + import sys + if len(sys.argv) > 1: + testfuncs = [globals()[arg] for arg in sys.argv[1:]] n = len(testfuncs) success = 0 @@ -3947,7 +4002,7 @@ print "*"*40 testfunc() except Exception, e: - if isinstance(e, KeyboardInterrupt): + if isinstance(e, KeyboardInterrupt) or n == 1: raise print "-->", testfunc.__name__, "FAILURE(%d/%d)" % (success, n), str(e) else: Modified: branches/2.3/Misc/make_binops.py =================================================================== --- branches/2.3/Misc/make_binops.py 2007-02-22 05:08:42 UTC (rev 3113) +++ branches/2.3/Misc/make_binops.py 2007-02-22 05:21:12 UTC (rev 3114) @@ -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: branches/2.3/src/org/python/core/PyClassMethod.java =================================================================== --- branches/2.3/src/org/python/core/PyClassMethod.java 2007-02-22 05:08:42 UTC (rev 3113) +++ branches/2.3/src/org/python/core/PyClassMethod.java 2007-02-22 05:21:12 UTC (rev 3114) @@ -78,10 +78,10 @@ } final PyObject classmethod___get__(PyObject obj, PyObject type) { - if(obj == null) { - return new PyMethod(type, callable, type); + if(type == null) { + type = obj.getType(); } - return new PyMethod(obj, callable, type); + return new PyMethod(type, callable, type.getType()); } final static PyObject classmethod_new(PyNewWrapper new_, boolean init, PyType subtype, Modified: branches/2.3/src/org/python/core/PyClassMethodDerived.java =================================================================== --- branches/2.3/src/org/python/core/PyClassMethodDerived.java 2007-02-22 05:08:42 UTC (rev 3113) +++ branches/2.3/src/org/python/core/PyClassMethodDerived.java 2007-02-22 05:21:12 UTC (rev 3114) @@ -22,6 +22,19 @@ return dict; } + public void setDict(PyObject newDict) { + if (newDict instanceof PyStringMap||newDict instanceof PyDictionary) { + dict=newDict; + } else { + throw Py.TypeError("__dict__ must be set to a Dictionary "+newDict.getClass().getName()); + } + } + + public void delDict() { + // deleting an object's instance dict makes it grow a new one + dict=new PyStringMap(); + } + public PyClassMethodDerived(PyType subtype) { super(subtype); slots=new PyObject[subtype.getNumSlots()]; Modified: branches/2.3/src/org/python/core/PyComplex.java =================================================================== --- branches/2.3/src/org/python/core/PyComplex.java 2007-02-22 05:08:42 UTC (rev 3113) +++ branches/2.3/src/org/python/core/PyComplex.java 2007-02-22 05:21:12 UTC (rev 3114) @@ -16,8 +16,8 @@ public static final String exposed_name="complex"; public static void typeSetup(PyObject dict,PyType.Newstyle marker) { - dict.__setitem__("imag",new PyGetSetDescr("imag",PyComplex.class,"getImag",null)); - dict.__setitem__("real",new PyGetSetDescr("real",PyComplex.class,"getReal",null)); + dict.__setitem__("imag",new PyGetSetDescr("imag",PyComplex.class,"getImag",null,null)); + dict.__setitem__("real",new PyGetSetDescr("real",PyComplex.class,"getReal",null,null)); class exposed___abs__ extends PyBuiltinFunctionNarrow { private PyComplex self; Modified: branches/2.3/src/org/python/core/PyComplexDerived.java =================================================================== --- branches/2.3/src/org/python/core/PyComplexDerived.java 2007-02-22 05:08:42 UTC (rev 3113) +++ branches/2.3/src/org/python/core/PyComplexDerived.java 2007-02-22 05:21:12 UTC (rev 3114) @@ -22,6 +22,19 @@ return dict; } + public void setDict(PyObject newDict) { + if (newDict instanceof PyStringMap||newDict instanceof PyDictionary) { + dict=newDict; + } else { + throw Py.TypeError("__dict__ must be set to a Dictionary "+newDict.getClass().getName()); + } + } + + public void delDict() { + // deleting an object's instance dict makes it grow a new one + dict=new PyStringMap(); + } + public PyComplexDerived(PyType subtype,double real,double imaginary) { super(subtype,real,imaginary); slots=new PyObject[subtype.getNumSlots()]; Modified: branches/2.3/src/org/python/core/PyDictionaryDerived.java =================================================================== --- branches/2.3/src/org/python/core/PyDictionaryDerived.java 2007-02-22 05:08:42 UTC (rev 3113) +++ branches/2.3/src/org/python/core/PyDictionaryDerived.java 2007-02-22 05:21:12 UTC (rev 3114) @@ -22,6 +22,19 @@ return dict; } + public void setDict(PyObject newDict) { + if (newDict instanceof PyStringMap||newDict instanceof PyDictionary) { + dict=newDict; + } else { + throw Py.TypeError("__dict__ must be set to a Dictionary "+newDict.getClass().getName()); + } + } + + public void delDict() { + // deleting an object's instance dict makes it grow a new one + dict=new PyStringMap(); + } + public PyDictionaryDerived(PyType subtype) { super(subtype); slots=new PyObject[subtype.getNumSlots()]; Modified: branches/2.3/src/org/python/core/PyFileDerived.java =================================================================== --- branches/2.3/src/org/python/core/PyFileDerived.java 2007-02-22 05:08:42 UTC (rev 3113) +++ branches/2.3/src/org/python/core/PyFileDerived.java 2007-02-22 05:21:12 UTC (rev 3114) @@ -22,6 +22,19 @@ return dict; } + public void setDict(PyObject newDict) { + if (newDict instanceof PyStringMap||newDict instanceof PyDictionary) { + dict=newDict; + } else { + throw Py.TypeError("__dict__ must be set to a Dictionary "+newDict.getClass().getName()); + } + } + + public void delDict() { + // deleting an object's instance dict makes it grow a new one + dict=new PyStringMap(); + } + public PyFileDerived(PyType subtype) { super(subtype); slots=new PyObject[subtype.getNumSlots()]; Modified: branches/2.3/src/org/python/core/PyFloatDerived.java =================================================================== --- branches/2.3/src/org/python/core/PyFloatDerived.java 2007-02-22 05:08:42 UTC (rev 3113) +++ branches/2.3/src/org/python/core/PyFloatDerived.java 2007-02-22 05:21:12 UTC (rev 3114) @@ -22,6 +22,19 @@ return dict; } + public void setDict(PyObject newDict) { + if (newDict instanceof PyStringMap||newDict instanceof PyDictionary) { + dict=newDict; + } else { + throw Py.TypeError("__dict__ must be set to a Dictionary "+newDict.getClass().getName()); + } + } + + public void delDict() { + // deleting an object's instance dict makes it grow a new one + dict=new PyStringMap(); + } + public PyFloatDerived(PyType subtype,double v) { super(subtype,v); slots=new PyObject[subtype.getNumSlots()]; Modified: branches/2.3/src/org/python/core/PyGetSetDescr.java =================================================================== --- branches/2.3/src/org/python/core/PyGetSetDescr.java 2007-02-22 05:08:42 UTC (rev 3113) +++ branches/2.3/src/org/python/core/PyGetSetDescr.java 2007-02-22 05:21:12 UTC (rev 3114) @@ -10,6 +10,8 @@ private Method set_meth; + private Method del_meth; + private Class getset_type; public PyGetSetDescr(PyType dtype, @@ -17,6 +19,18 @@ Class c, String get, String set) { + this(dtype, name, c, get, set, null); + } + public PyGetSetDescr(String name, Class c, String get, String set) { + this(PyType.fromClass(c), name, c, get, set, null); + } + + public PyGetSetDescr(PyType dtype, + String name, + Class c, + String get, + String set, + String del) { this.name = name; this.dtype = dtype; try { @@ -36,10 +50,19 @@ if(Modifier.isStatic(set_meth.getModifiers())) throw Py.SystemError("static getset not supported"); } - } + if(del != null) { + try { + del_meth = c.getMethod(del, new Class[] {}); + } catch(NoSuchMethodException e) { + throw Py.SystemError("bogus getset spec"); + } + if(Modifier.isStatic(del_meth.getModifiers())) + throw Py.SystemError("static getset not supported"); + } + } - public PyGetSetDescr(String name, Class c, String get, String set) { - this(PyType.fromClass(c), name, c, get, set); + public PyGetSetDescr(String name, Class c, String get, String set, String del) { + this(PyType.fromClass(c), name, c, get, set, del); } public String toString() { @@ -97,6 +120,23 @@ } } + public void __delete__(PyObject obj) { + try { + if(obj != null) { + PyType objtype = obj.getType(); + if(objtype != dtype && !objtype.isSubType(dtype)) + throw get_wrongtype(objtype); + del_meth.invoke(obj, new Object[0]); + } + } catch(IllegalArgumentException e) { + throw Py.JavaError(e); + } catch(IllegalAccessException e) { + throw Py.JavaError(e); // unexpected + } catch(InvocationTargetException e) { + throw Py.JavaError(e); + } + } + /** * @see org.python.core.PyObject#implementsDescrSet() */ @@ -104,10 +144,15 @@ return set_meth != null; } + public boolean implementsDescrDelete() { + return del_meth != null; + } + /** * @see org.python.core.PyObject#isDataDescr() */ public boolean isDataDescr() { return true; } + } Modified: branches/2.3/src/org/python/core/PyIntegerDerived.java =================================================================== --- branches/2.3/src/org/python/core/PyIntegerDerived.java 2007-02-22 05:08:42 UTC (rev 3113) +++ branches/2.3/src/org/python/core/PyIntegerDerived.java 2007-02-22 05:21:12 UTC (rev 3114) @@ -22,6 +22,19 @@ return dict; } + public void setDict(PyObject newDict) { + if (newDict instanceof PyStringMap||newDict instanceof PyDictionary) { + dict=newDict; + } else { + throw Py.TypeError("__dict__ must be set to a Dictionary "+newDict.getClass().getName()); + } + } + + public void delDict() { + // deleting an object's instance dict makes it grow a new one + dict=new PyStringMap(); + } + public PyIntegerDerived(PyType subtype,int v) { super(subtype,v); slots=new PyObject[subtype.getNumSlots()]; Modified: branches/2.3/src/org/python/core/PyListDerived.java =================================================================== --- branches/2.3/src/org/python/core/PyListDerived.java 2007-02-22 05:08:42 UTC (rev 3113) +++ branches/2.3/src/org/python/core/PyListDerived.java 2007-02-22 05:21:12 UTC (rev 3114) @@ -22,6 +22,19 @@ return dict; } + public void setDict(PyObject newDict) { + if (newDict instanceof PyStringMap||newDict instanceof PyDictionary) { + dict=newDict; + } else { + throw Py.TypeError("__dict__ must be set to a Dictionary "+newDict.getClass().getName()); + } + } + + public void delDict() { + // deleting an object's instance dict makes it grow a new one + dict=new PyStringMap(); + } + public PyListDerived(PyType subtype) { super(subtype); slots=new PyObject[subtype.getNumSlots()]; Modified: branches/2.3/src/org/python/core/PyLongDerived.java =================================================================== --- branches/2.3/src/org/python/core/PyLongDerived.java 2007-02-22 05:08:42 UTC (rev 3113) +++ branches/2.3/src/org/python/core/PyLongDerived.java 2007-02-22 05:21:12 UTC (rev 3114) @@ -1,7 +1,17 @@ package org.python.core; -public class PyLongDerived extends PyLong { +public class PyLongDerived extends PyLong 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() { @@ -12,8 +22,22 @@ return dict; } + public void setDict(PyObject newDict) { + if (newDict instanceof PyStringMap||newDict instanceof PyDictionary) { + dict=newDict; + } else { + throw Py.TypeError("__dict__ must be set to a Dictionary "+newDict.getClass().getName()); + } + } + + public void delDict() { + // deleting an object's instance dict makes it grow a new one + dict=new PyStringMap(); + } + public PyLongDerived(PyType subtype,java.math.BigInteger v) { super(subtype,v); + slots=new PyObject[subtype.getNumSlots()]; dict=subtype.instDict(); } Modified: branches/2.3/src/org/python/core/PyObject.java =================================================================== --- branches/2.3/src/org/python/core/PyObject.java 2007-02-22 05:08:42 UTC (rev 3113) +++ branches/2.3/src/org/python/core/PyObject.java 2007-02-22 05:21:12 UTC (rev 3114) @@ -18,8 +18,8 @@ public static final String exposed_name="object"; public static void typeSetup(PyObject dict,PyType.Newstyle marker) { - dict.__setitem__("__class__",new PyGetSetDescr("__class__",PyObject.class,"getType",null)); - dict.__setitem__("__doc__",new PyGetSetDescr("__doc__",PyObject.class,"getDoc",null)); + dict.__setitem__("__class__",new PyGetSetDescr("__class__",PyObject.class,"getType","setType","delType")); + dict.__setitem__("__doc__",new PyGetSetDescr("__doc__",PyObject.class,"getDoc",null,null)); class exposed___reduce__ extends PyBuiltinFunctionNarrow { private PyObject self; @@ -456,6 +456,19 @@ return objtype; } + public void setType(PyType type) { + 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"); + } + } + + public void delType() { + throw Py.TypeError("Can't delete __class__ attribute"); + } + // xxx public PyObject fastGetClass() { return objtype; @@ -1626,6 +1639,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 { @@ -1659,6 +1678,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 { @@ -1687,6 +1712,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 { @@ -1715,6 +1746,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 { @@ -1743,6 +1780,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 { @@ -1771,6 +1814,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 { @@ -1963,8 +2012,46 @@ public PyObject __invert__() { throw Py.AttributeError("__invert__"); } + + /** + * @param op the String form of the op (e.g. "+") + * @param o2 the right operand + */ + protected final String _unsupportedop(String op, PyObject o2) { + Object[] args = {op, getType().fastGetName(), o2.getType().fastGetName()}; + String msg = unsupportedopMessage(op, o2); + if (msg == null) { + msg = o2.runsupportedopMessage(op, o2); + } + if (msg == null) { + msg = "unsupported operand type(s) for {0}: ''{1}'' and ''{2}''"; + } + return MessageFormat.format(msg, args); + } /** + * Should return an error message suitable for substitution where. + * + * {0} is the op name. + * {1} is the left operand type. + * {2} is the right operand type. + */ + protected String unsupportedopMessage(String op, PyObject o2) { + return null; + } + + /** + * Should return an error message suitable for substitution where. + * + * {0} is the op name. + * {1} is the left operand type. + * {2} is the right operand type. + */ + protected String runsupportedopMessage(String op, PyObject o2) { + return null; + } + + /** * Implements the three argument power function. * * @param o2 the power to raise this number to. @@ -1976,6 +2063,53 @@ 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) /** @@ -2012,64 +2146,40 @@ } /** - * 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) { - PyObject x = __add__(o2); - if (x != null) { + final PyObject _basic_add(PyObject o2) { + PyObject x=__add__(o2); + if (x!=null) return x; - } - x = o2.__radd__(this); - if (x != null) { + x=o2.__radd__(this); + if (x!=null) return x; - } - throw Py.TypeError(_unsupportedop("+", o2)); + throw Py.TypeError(_unsupportedop("+",o2)); } /** - * @param op the String form of the op (e.g. "+") - * @param o2 the right operand - */ - protected final String _unsupportedop(String op, PyObject o2) { - Object[] args = {op, getType().fastGetName(), o2.getType().fastGetName()}; - String msg = unsupportedopMessage(op, o2); - if (msg == null) { - msg = o2.runsupportedopMessage(op, o2); - } - if (msg == null) { - msg = "unsupported operand type(s) for {0}: ''{1}'' and ''{2}''"; - } - return MessageFormat.format(msg, args); - } - - /** - * Should return an error message suitable for substitution where. - * - * {0} is the op name. - * {1} is the left operand type. - * {2} is the right operand type. - */ - protected String unsupportedopMessage(String op, PyObject o2) { - return null; - } - - /** - * Should return an error message suitable for substitution where. - * - * {0} is the op name. - * {1} is the left operand type. - * {2} is the right operand type. - */ - protected String runsupportedopMessage(String op, PyObject o2) { - return null; - } - - - /** * Equivalent to the standard Python __sub__ method * @param other the object to perform this binary operation with * (the right-hand operand). @@ -2103,20 +2213,37 @@ } /** - * 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) { - PyObject x = __sub__(o2); - if (x != null) + final PyObject _basic_sub(PyObject o2) { + PyObject x=__sub__(o2); + if (x!=null) return x; - x = o2.__rsub__(this); - if (x != null) + x=o2.__rsub__(this); + if (x!=null) return x; - throw Py.TypeError(_unsupportedop("-", o2)); + throw Py.TypeError(_unsupportedop("-",o2)); } /** @@ -2153,20 +2280,37 @@ } /** - * 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) { - PyObject x = __mul__(o2); - if (x != null) + final PyObject _basic_mul(PyObject o2) { + PyObject x=__mul__(o2); + if (x!=null) return x; - x = o2.__rmul__(this); - if (x != null) + x=o2.__rmul__(this); + if (x!=null) return x; - throw Py.TypeError(_unsupportedop("*", o2)); + throw Py.TypeError(_unsupportedop("*",o2)); } /** @@ -2203,22 +2347,39 @@ } /** - * 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); - if (x != null) + PyObject x=__div__(o2); + if (x!=null) return x; - x = o2.__rdiv__(this); - if (x != null) + x=o2.__rdiv__(this); + if (x!=null) return x; - throw Py.TypeError(_unsupportedop("/", o2)); + throw Py.TypeError(_unsupportedop("/",o2)); } /** @@ -2255,20 +2416,37 @@ } /** - * 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) { - PyObject x = __floordiv__(o2); - if (x != null) + final PyObject _basic_floordiv(PyObject o2) { + PyObject x=__floordiv__(o2); + if (x!=null) return x; - x = o2.__rfloordiv__(this); - if (x != null) + x=o2.__rfloordiv__(this); + if (x!=null) return x; - throw Py.TypeError(_unsupportedop("//", o2)); + throw Py.TypeError(_unsupportedop("//",o2)); } /** @@ -2305,20 +2483,37 @@ } /** - * 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) { - PyObject x = __truediv__(o2); - if (x != null) + final PyObject _basic_truediv(PyObject o2) { + PyObject x=__truediv__(o2); + if (x!=null) return x; - x = o2.__rtruediv__(this); - if (x != null) + x=o2.__rtruediv__(this); + if (x!=null) return x; - throw Py.TypeError(_unsupportedop("/", o2)); + throw Py.TypeError(_unsupportedop("/",o2)); } /** @@ -2355,20 +2550,37 @@ } /** - * 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) { - PyObject x = __mod__(o2); - if (x != null) + final PyObject _basic_mod(PyObject o2) { + PyObject x=__mod__(o2); + if (x!=null) return x; - x = o2.__rmod__(this); - if (x != null) + x=o2.__rmod__(this); + if (x!=null) return x; - throw Py.TypeError(_unsupportedop("%", o2)); + throw Py.TypeError(_unsupportedop("%",o2)); } /** @@ -2405,21 +2617,37 @@ } /** - * 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) { - PyObject x = __divmod__(o2); - if (x != null) + final PyObject _basic_divmod(PyObject o2) { + PyObject x=__divmod__(o2); + if (x!=null) return x; - x = o2.__rdivmod__(this); - if (x != null) + x=o2.__rdivmod__(this); + if (x!=null) return x; - //FIXME: - throw Py.TypeError(_unsupportedop("divmod", o2)); + throw Py.TypeError(_unsupportedop("divmod",o2)); } /** @@ -2430,7 +2658,7 @@ * is not defined **/ public PyObject __pow__(PyObject other) { - return __pow__(other, null); + return __pow__(other,null); } /** @@ -2456,20 +2684,37 @@ } /** - * 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) { - PyObject x = __pow__(o2); - if (x != null) + final PyObject _basic_pow(PyObject o2) { + PyObject x=__pow__(o2); + if (x!=null) return x; - x = o2.__rpow__(this); - if (x != null) + x=o2.__rpow__(this); + if (x!=null) return x; - throw Py.TypeError(_unsupportedop("**", o2)); + throw Py.TypeError(_unsupportedop("**",o2)); } /** @@ -2506,20 +2751,37 @@ } /** - * 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) { - PyObject x = __lshift__(o2); - if (x != null) + final PyObject _basic_lshift(PyObject o2) { + PyObject x=__lshift__(o2); + if (x!=null) return x; - x = o2.__rlshift__(this); - if (x != null) + x=o2.__rlshift__(this); + if (x!=null) return x; - throw Py.TypeError(_unsupportedop("<<", o2)); + throw Py.TypeError(_unsupportedop("<<",o2)); } /** @@ -2556,20 +2818,37 @@ } /** - * 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) { - PyObject x = __rshift__(o2); - if (x != null) + final PyObject _basic_rshift(PyObject o2) { + PyObject x=__rshift__(o2); + if (x!=null) return x; - x = o2.__rrshift__(this); - if (x != null) + x=o2.__rrshift__(this); + if (x!=null) return x; - throw Py.TypeError(_unsupportedop(">>", o2)); + throw Py.TypeError(_unsupportedop(">>",o2)); } /** @@ -2606,20 +2885,37 @@ } /** - * 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) { - PyObject x = __and__(o2); - if (x != null) + final PyObject _basic_and(PyObject o2) { + PyObject x=__and__(o2); + if (x!=null) return x; - x = o2.__rand__(this); - if (x != null) + x=o2.__rand__(this); + if (x!=null) return x; - throw Py.TypeError(_unsupportedop("&", o2)); + throw Py.TypeError(_unsupportedop("&",o2)); } /** @@ -2656,20 +2952,37 @@ } /** - * 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) { - PyObject x = __or__(o2); - if (x != null) + final PyObject _basic_or(PyObject o2) { + PyObject x=__or__(o2); + if (x!=null) return x; - x = o2.__ror__(this); - if (x != null) + x=o2.__ror__(this); + if (x!=null) return x; - throw Py.TypeError(_unsupportedop("|", o2)); + throw Py.TypeError(_unsupportedop("|",o2)); } /** @@ -2706,20 +3019,37 @@ } /** - * 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) { - PyObject x = __xor__(o2); - if (x != null) + final PyObject _basic_xor(PyObject o2) { + PyObject x=__xor__(o2); + if (x!=null) return x; - x = o2.__rxor__(this); - if (x != null) + x=o2.__rxor__(this); + if (x!=null) return x; - throw Py.TypeError(_unsupportedop("^", o2)); + throw Py.TypeError(_unsupportedop("^",o2)); } // Generated by make_binops.py (End) @@ -2853,7 +3183,16 @@ return null; } + public void setDict(PyObject newDict) { + // fallback if setDict not implemented in subclass + throw Py.TypeError("can't set attribute '__dict__' of instance of " + getType().safeRepr()); + } + public void delDict() { + // fallback to error + throw Py.TypeError("can't delete attribute '__dict__' of instance of '" + getType().safeRepr()+ "'"); + } + public boolean implementsDescrSet() { return objtype.has_set; } Modified: branches/2.3/src/org/python/core/PyObjectDerived.java =================================================================== --- branches/2.3/src/org/python/core/PyObjectDerived.java 2007-02-22 05:08:42 UTC (rev 3113) +++ branches/2.3/src/org/python/core/PyObjectDerived.java 2007-02-22 05:21:12 UTC (rev 3114) @@ -22,6 +22,19 @@ return dict; } + public void setDict(PyObject newDict) { + if (newDict instanceof PyStringMap||newDict instanceof PyDictionary) { + dict=newDict; + } else { + throw Py.TypeError("__dict__ must be set to a Dictionary "+newDict.getClass().getName()); + } + } + + public void delDict() { + // deleting an object's instance dict makes it grow a new one + dict=new PyStringMap(); + } + public PyObjectDerived(PyType subtype) { super(subtype); slots=new PyObject[subtype.getNumSlots()]; Modified: branches/2.3/src/org/python/core/PyProperty.java =================================================================== --- branches/2.3/src/org/python/core/PyProperty.java 2007-02-22 05:08:42 UTC (rev 3113) +++ branches/2.3/src/org/python/core/PyProperty.java 2007-02-22 05:21:12 UTC (rev 3114) @@ -7,10 +7,10 @@ public static final String exposed_name="property"; public static void typeSetup(PyObject dict,PyType.Newstyle marker) { - dict.__setitem__("fget",new PyGetSetDescr("fget",PyProperty.class,"getFget","setFget")); - dict.__setitem__("fset",new PyGetSetDescr("fset",PyProperty.class,"getFset","setFset")); - dict.__setitem__("fdel",new PyGetSetDescr("fdel",PyProperty.class,"getFdel","setFdel")); - dict.__setitem__("__doc__",new PyGetSetDescr("__doc__",PyProperty.class,"getDoc","setDoc")); + dict.__setitem__("fget",new PyGetSetDescr("fget",PyProperty.class,"getFget","setFget",null)); + dict.__setitem__("fset",new PyGetSetDescr("fset",PyProperty.class,"getFset","setFset",null)); + dict.__setitem__("fdel",new PyGetSetDescr("fdel",PyProperty.class,"getFdel","setFdel",null)); + dict.__setitem__("__doc__",new PyGetSetDescr("__doc__",PyProperty.class,"getDoc","setDoc",null)); class exposed___get__ extends PyBuiltinFunctionNarrow { private PyProperty self; Modified: branches/2.3/src/org/python/core/PyPropertyDerived.java =================================================================== --- branches/2.3/src/org/python/core/PyPropertyDerived.java 2007-02-22 05:08:42 UTC (rev 3113) +++ branches/2.3/src/org/python/core/PyPropertyDerived.java 2007-02-22 05:21:12 UTC (rev 3114) @@ -22,6 +22,19 @@ return dict; } + public void setDict(PyObject newDict) { + if (newDict instanceof PyStringMap||newDict instanceof PyDictionary) { + dict=newDict; + } else { + throw Py.TypeError("__dict__ must be set to a Dictionary "+newDict.getClass().getName()); + } + } + + public void delDict() { + // deleting an object's instance dict makes it grow a new one + dict=new PyStringMap(); + } + public PyPropertyDerived(PyType subtype) { super(subtype); slots=new PyObject[subtype.getNumSlots()]; Modified: branches/2.3/src/org/python/core/PyStringDerived.java =================================================================== --- branches/2.3/src/org/python/core/PyStringDerived.java 2007-02-22 05:08:42 UTC (rev 3113) +++ branches/2.3/src/org/python/core/PyStringDerived.java 2007-02-22 05:21:12 UTC (rev 3114) @@ -22,6 +22,19 @@ return dict; } + public void setDict(PyObject newDict) { + if (newDict instanceof PyStringMap||newDict instanceof PyDictionary) { + dict=newDict; + } else { + throw Py.TypeError("__dict__ must be set to a Dictionary "+newDict.getClass().getName()); + } + } + + public void delDict() { + // deleting an object's instance dict makes it grow a new one + dict=new PyStringMap(); + } + public PyStringDerived(PyType subtype,String v) { super(subtype,v); slots=new PyObject[subtype.getNumSlots()]; Modified: branches/2.3/src/org/python/core/PySuper.java =================================================================== --- branches/2.3/src/org/python/core/PySuper.java 2007-02-22 05:08:42 UTC (rev 3113) +++ branches/2.3/src/org/python/core/PySuper.java 2007-02-22 05:21:12 UTC (rev 3114) @@ -7,9 +7,9 @@ public static final String exposed_name="super"; public static void typeSetup(PyObject dict,PyType.Newstyle marker) { - dict.__setitem__("__thisclass__",new PyGetSetDescr("__thisclass__",PySuper.class,"getThisClass",null)); - dict.__setitem__("__self__",new PyGetSetDescr("__self__",PySuper.class,"getSelf",null)); - dict.__setitem__("__self_class__",new PyGetSetDescr("__self_class__",PySuper.class,"getSelfClass",null)); + dict.__setitem__("__thisclass__",new PyGetSetDescr("__thisclass__",PySuper.class,"getThisClass",null,null)); + dict.__setitem__("__self__",new PyGetSetDescr("__self__",PySuper.class,"getSelf",null,null)); + dict.__setitem__("__self_class__",new PyGetSetDescr("__self_class__",PySuper.class,"getSelfClass",null,null)); class exposed___getattribute__ extends PyBuiltinFunctionNarrow { private PySuper self; Modified: branches/2.3/src/org/python/core/PySuperDerived.java =================================================================== --- branches/2.3/src/org/python/core/PySuperDerived.java 2007-02-22 05:08:42 UTC (rev 3113) +++ branches/2.3/src/org/python/core/PySuperDerived.java 2007-02-22 05:21:12 UTC (rev 3114) @@ -22,6 +22,19 @@ return dict; } + public void setDict(PyObject newDict) { + if (newDict instanceof PyStringMap||newDict instanceof PyDictionary) { + dict=newDict; + } else { + throw Py.TypeError("__dict__ must be set to a Dictionary "+newDict.getClass().getName()); + } + } + + public void delDict() { + // deleting an object's instance dict makes it grow a new one + dict=new PySt... [truncated message content] |
From: <cg...@us...> - 2007-02-22 05:29:42
|
Revision: 3116 http://svn.sourceforge.net/jython/?rev=3116&view=rev Author: cgroves Date: 2007-02-21 21:29:40 -0800 (Wed, 21 Feb 2007) Log Message: ----------- merge -r 3023:3041 https://jython.svn.sourceforge.net/svnroot/jython/trunk/jython Modified Paths: -------------- branches/2.3/Lib/popen2.py branches/2.3/Lib/test/javatests/TestSupport.java branches/2.3/Lib/test/test_descr.py branches/2.3/Lib/test/test_sax.py branches/2.3/build.xml branches/2.3/src/org/python/core/Options.java branches/2.3/src/org/python/core/PyString.java branches/2.3/src/org/python/core/PySystemState.java branches/2.3/src/org/python/core/PyType.java branches/2.3/src/org/python/core/PyTypeDerived.java branches/2.3/src/org/python/modules/MD5Object.java branches/2.3/src/org/python/modules/SHA1.java branches/2.3/src/org/python/modules/sha.java branches/2.3/src/templates/type.derived Added Paths: ----------- branches/2.3/Lib/test/test_mailbox.py branches/2.3/Misc/checker22.py branches/2.3/Misc/checker23.py branches/2.3/Misc/make_checker.py Modified: branches/2.3/Lib/popen2.py =================================================================== --- branches/2.3/Lib/popen2.py 2007-02-22 05:23:37 UTC (rev 3115) +++ branches/2.3/Lib/popen2.py 2007-02-22 05:29:40 UTC (rev 3116) @@ -295,7 +295,7 @@ r = p.fromchild.read() x = p.poll() assert x == 0 - assert r == q + assert r.strip() == q.strip() if __name__ == '__main__': _test() Modified: branches/2.3/Lib/test/javatests/TestSupport.java =================================================================== --- branches/2.3/Lib/test/javatests/TestSupport.java 2007-02-22 05:23:37 UTC (rev 3115) +++ branches/2.3/Lib/test/javatests/TestSupport.java 2007-02-22 05:29:40 UTC (rev 3116) @@ -16,6 +16,7 @@ super(message); } + /* not until java 1.4 public AssertionError(String message, Throwable cause) { super(message, cause); } @@ -23,6 +24,7 @@ public AssertionError(Throwable cause) { super(cause); } + */ } public static void assertThat(boolean test, String message) { Modified: branches/2.3/Lib/test/test_descr.py =================================================================== --- branches/2.3/Lib/test/test_descr.py 2007-02-22 05:23:37 UTC (rev 3115) +++ branches/2.3/Lib/test/test_descr.py 2007-02-22 05:29:40 UTC (rev 3116) @@ -2610,7 +2610,6 @@ class Int(int): __slots__ = [] cant(2, Int) cant(Int(), int) - cant(True, int) cant(2, bool) o = object() cant(o, type(1)) Copied: branches/2.3/Lib/test/test_mailbox.py (from rev 3041, trunk/jython/Lib/test/test_mailbox.py) =================================================================== --- branches/2.3/Lib/test/test_mailbox.py (rev 0) +++ branches/2.3/Lib/test/test_mailbox.py 2007-02-22 05:29:40 UTC (rev 3116) @@ -0,0 +1,113 @@ +import mailbox +import os +import test_support +import time +import unittest + +# cleanup earlier tests +try: + os.unlink(test_support.TESTFN) +except os.error: + pass + + +DUMMY_MESSAGE = """\ +From: som...@du...main +To: me...@my...main + +This is a dummy message. +""" + + +class MaildirTestCase(unittest.TestCase): + + def setUp(self): + # create a new maildir mailbox to work with: + self._dir = test_support.TESTFN + os.mkdir(self._dir) + os.mkdir(os.path.join(self._dir, "cur")) + os.mkdir(os.path.join(self._dir, "tmp")) + os.mkdir(os.path.join(self._dir, "new")) + self._counter = 1 + self._msgfiles = [] + + def tearDown(self): + map(os.unlink, self._msgfiles) + os.rmdir(os.path.join(self._dir, "cur")) + os.rmdir(os.path.join(self._dir, "tmp")) + os.rmdir(os.path.join(self._dir, "new")) + os.rmdir(self._dir) + + def createMessage(self, dir): + t = int(time.time() % 1000000) + pid = self._counter + self._counter += 1 + filename = os.extsep.join((str(t), str(pid), "myhostname", "mydomain")) + tmpname = os.path.join(self._dir, "tmp", filename) + newname = os.path.join(self._dir, dir, filename) + fp = open(tmpname, "w") + self._msgfiles.append(tmpname) + fp.write(DUMMY_MESSAGE) + fp.close() + if hasattr(os, "link"): + os.link(tmpname, newname) + else: + fp = open(newname, "w") + fp.write(DUMMY_MESSAGE) + fp.close() + self._msgfiles.append(newname) + + def assert_msg_exists(self): + msg = self.mbox.next() + self.assert_(msg is not None) + #Force the file closed on Jython since Windows won't allow a file to + #be deleted if something has an open handle on it and garbage collection + #doesn't happen quickly enough to make this occur naturally + if os.name == 'java': + msg.fp.close() + + def test_empty_maildir(self): + """Test an empty maildir mailbox""" + # Test for regression on bug #117490: + # Make sure the boxes attribute actually gets set. + self.mbox = mailbox.Maildir(test_support.TESTFN) + self.assert_(hasattr(self.mbox, "boxes")) + self.assert_(len(self.mbox.boxes) == 0) + self.assert_(self.mbox.next() is None) + self.assert_(self.mbox.next() is None) + + def test_nonempty_maildir_cur(self): + self.createMessage("cur") + self.mbox = mailbox.Maildir(test_support.TESTFN) + self.assert_(len(self.mbox.boxes) == 1) + self.assert_msg_exists() + self.assert_(self.mbox.next() is None) + self.assert_(self.mbox.next() is None) + + def test_nonempty_maildir_new(self): + self.createMessage("new") + self.mbox = mailbox.Maildir(test_support.TESTFN) + self.assert_(len(self.mbox.boxes) == 1) + self.assert_msg_exists() + self.assert_(self.mbox.next() is None) + self.assert_(self.mbox.next() is None) + + def test_nonempty_maildir_both(self): + self.createMessage("cur") + self.createMessage("new") + self.mbox = mailbox.Maildir(test_support.TESTFN) + self.assert_(len(self.mbox.boxes) == 2) + self.assert_msg_exists() + self.assert_msg_exists() + self.assert_(self.mbox.next() is None) + self.assert_(self.mbox.next() is None) + + # XXX We still need more tests! + + +def test_main(): + test_support.run_unittest(MaildirTestCase) + + +if __name__ == "__main__": + test_main() Modified: branches/2.3/Lib/test/test_sax.py =================================================================== --- branches/2.3/Lib/test/test_sax.py 2007-02-22 05:23:37 UTC (rev 3115) +++ branches/2.3/Lib/test/test_sax.py 2007-02-22 05:29:40 UTC (rev 3116) @@ -470,9 +470,16 @@ xmlgen = LocatorTest(result) parser = make_parser() parser.setContentHandler(xmlgen) - parser.parse(findfile("test.xml")) + testfile = findfile("test.xml") + parser.parse(testfile) + #In Jython, the system id is a URL with forward slashes, and under Windows + #findfile returns a path with backslashes, so replace the backslashes with + #forward + import os + if os.name == 'java': + testfile = testfile.replace('\\', '/') - return xmlgen.location.getSystemId().endswith(findfile("test.xml")) and \ + return xmlgen.location.getSystemId().endswith(testfile) and \ xmlgen.location.getPublicId() is None Copied: branches/2.3/Misc/checker22.py (from rev 3041, trunk/jython/Misc/checker22.py) =================================================================== --- branches/2.3/Misc/checker22.py (rev 0) +++ branches/2.3/Misc/checker22.py 2007-02-22 05:29:40 UTC (rev 3116) @@ -0,0 +1,632 @@ +names = {0: 'object', + 1: 'type', + 2: 'unicode', + 3: 'dict', + 4: 'list', + 5: 'slice', + 6: 'super', + 7: 'staticmethod', + 8: 'float', + 10: 'file', + 12: 'long', + 13: 'tuple', + 14: 'str', + 15: 'property', + 16: 'int', + 17: 'xrange', + 18: 'file', + 19: 'complex', + 20: 'bool', + 21: 'classmethod', + 22: 'function', + 23: 'instance method', + 24: 'code', + 25: 'frame', + 26: 'traceback', + 27: 'builtin_function_or_method'} +checks = [[0, + 1, + (), + {'__class__': 'd', + '__delattr__': 'm', + '__doc__': 14, + '__getattribute__': 'm', + '__hash__': 'm', + '__init__': 'm', + '__new__': 27, + '__reduce__': 'm', + '__repr__': 'm', + '__setattr__': 'm', + '__str__': 'm'}], + [1, + 1, + (0,), + {'__base__': 'd', + '__bases__': 'd', + '__basicsize__': 'd', + '__call__': 'm', + '__cmp__': 'm', + '__delattr__': 'm', + '__dict__': 'd', + '__dictoffset__': 'd', + '__doc__': 'd', + '__flags__': 'd', + '__getattribute__': 'm', + '__hash__': 'm', + '__itemsize__': 'd', + '__module__': 'd', + '__mro__': 'd', + '__name__': 'd', + '__new__': 27, + '__repr__': 'm', + '__setattr__': 'm', + '__subclasses__': 'm', + '__weakrefoffset__': 'd', + 'mro': 'm'}], + [2, + 1, + (0,), + {'__add__': 'm', + '__cmp__': 'm', + '__contains__': 'm', + '__doc__': 14, + '__getattribute__': 'm', + '__getitem__': 'm', + '__getslice__': 'm', + '__hash__': 'm', + '__len__': 'm', + '__mul__': 'm', + '__new__': 27, + '__repr__': 'm', + '__rmul__': 'm', + '__str__': 'm', + 'capitalize': 'm', + 'center': 'm', + 'count': 'm', + 'encode': 'm', + 'endswith': 'm', + 'expandtabs': 'm', + 'find': 'm', + 'index': 'm', + 'isalnum': 'm', + 'isalpha': 'm', + 'isdecimal': 'm', + 'isdigit': 'm', + 'islower': 'm', + 'isnumeric': 'm', + 'isspace': 'm', + 'istitle': 'm', + 'isupper': 'm', + 'join': 'm', + 'ljust': 'm', + 'lower': 'm', + 'lstrip': 'm', + 'replace': 'm', + 'rfind': 'm', + 'rindex': 'm', + 'rjust': 'm', + 'rstrip': 'm', + 'split': 'm', + 'splitlines': 'm', + 'startswith': 'm', + 'strip': 'm', + 'swapcase': 'm', + 'title': 'm', + 'translate': 'm', + 'upper': 'm', + 'zfill': 'm'}], + [3, + 1, + (0,), + {'__cmp__': 'm', + '__contains__': 'm', + '__delitem__': 'm', + '__doc__': 14, + '__eq__': 'm', + '__ge__': 'm', + '__getattribute__': 'm', + '__getitem__': 'm', + '__gt__': 'm', + '__hash__': 'm', + '__init__': 'm', + '__iter__': 'm', + '__le__': 'm', + '__len__': 'm', + '__lt__': 'm', + '__ne__': 'm', + '__new__': 27, + '__repr__': 'm', + '__setitem__': 'm', + 'clear': 'm', + 'copy': 'm', + 'get': 'm', + 'has_key': 'm', + 'items': 'm', + 'iteritems': 'm', + 'iterkeys': 'm', + 'itervalues': 'm', + 'keys': 'm', + 'popitem': 'm', + 'setdefault': 'm', + 'update': 'm', + 'values': 'm'}], + [4, + 1, + (0,), + {'__add__': 'm', + '__contains__': 'm', + '__delitem__': 'm', + '__delslice__': 'm', + '__doc__': 14, + '__eq__': 'm', + '__ge__': 'm', + '__getattribute__': 'm', + '__getitem__': 'm', + '__getslice__': 'm', + '__gt__': 'm', + '__hash__': 'm', + '__iadd__': 'm', + '__imul__': 'm', + '__init__': 'm', + '__le__': 'm', + '__len__': 'm', + '__lt__': 'm', + '__mul__': 'm', + '__ne__': 'm', + '__new__': 27, + '__repr__': 'm', + '__rmul__': 'm', + '__setitem__': 'm', + '__setslice__': 'm', + 'append': 'm', + 'count': 'm', + 'extend': 'm', + 'index': 'm', + 'insert': 'm', + 'pop': 'm', + 'remove': 'm', + 'reverse': 'm', + 'sort': 'm'}], + [5, 27, None, None], + [6, + 1, + (0,), + {'__doc__': 14, + '__get__': 'm', + '__getattribute__': 'm', + '__init__': 'm', + '__new__': 27, + '__repr__': 'm', + '__self__': 'd', + '__thisclass__': 'd'}], + [7, + 1, + (0,), + {'__doc__': 14, + '__get__': 'm', + '__getattribute__': 'm', + '__init__': 'm', + '__new__': 27}], + [8, + 1, + (0,), + {'__abs__': 'm', + '__add__': 'm', + '__cmp__': 'm', + '__coerce__': 'm', + '__div__': 'm', + '__divmod__': 'm', + '__doc__': 14, + '__float__': 'm', + '__floordiv__': 'm', + '__getattribute__': 'm', + '__hash__': 'm', + '__int__': 'm', + '__long__': 'm', + '__mod__': 'm', + '__mul__': 'm', + '__neg__': 'm', + '__new__': 27, + '__nonzero__': 'm', + '__pos__': 'm', + '__pow__': 'm', + '__radd__': 'm', + '__rdiv__': 'm', + '__rdivmod__': 'm', + '__repr__': 'm', + '__rfloordiv__': 'm', + '__rmod__': 'm', + '__rmul__': 'm', + '__rpow__': 'm', + '__rsub__': 'm', + '__rtruediv__': 'm', + '__str__': 'm', + '__sub__': 'm', + '__truediv__': 'm'}], + [10, + 1, + (0,), + {'__doc__': 14, + '__getattribute__': 'm', + '__init__': 'm', + '__iter__': 'm', + '__new__': 27, + '__repr__': 'm', + 'close': 'm', + 'closed': 'd', + 'fileno': 'm', + 'flush': 'm', + 'isatty': 'm', + 'mode': 'd', + 'name': 'd', + 'read': 'm', + 'readinto': 'm', + 'readline': 'm', + 'readlines': 'm', + 'seek': 'm', + 'softspace': 'd', + 'tell': 'm', + 'truncate': 'm', + 'write': 'm', + 'writelines': 'm', + 'xreadlines': 'm'}], + [12, + 1, + (0,), + {'__abs__': 'm', + '__add__': 'm', + '__and__': 'm', + '__cmp__': 'm', + '__coerce__': 'm', + '__div__': 'm', + '__divmod__': 'm', + '__doc__': 14, + '__float__': 'm', + '__floordiv__': 'm', + '__getattribute__': 'm', + '__hash__': 'm', + '__hex__': 'm', + '__int__': 'm', + '__invert__': 'm', + '__long__': 'm', + '__lshift__': 'm', + '__mod__': 'm', + '__mul__': 'm', + '__neg__': 'm', + '__new__': 27, + '__nonzero__': 'm', + '__oct__': 'm', + '__or__': 'm', + '__pos__': 'm', + '__pow__': 'm', + '__radd__': 'm', + '__rand__': 'm', + '__rdiv__': 'm', + '__rdivmod__': 'm', + '__repr__': 'm', + '__rfloordiv__': 'm', + '__rlshift__': 'm', + '__rmod__': 'm', + '__rmul__': 'm', + '__ror__': 'm', + '__rpow__': 'm', + '__rrshift__': 'm', + '__rshift__': 'm', + '__rsub__': 'm', + '__rtruediv__': 'm', + '__rxor__': 'm', + '__str__': 'm', + '__sub__': 'm', + '__truediv__': 'm', + '__xor__': 'm'}], + [13, + 1, + (0,), + {'__add__': 'm', + '__contains__': 'm', + '__doc__': 14, + '__eq__': 'm', + '__ge__': 'm', + '__getattribute__': 'm', + '__getitem__': 'm', + '__getslice__': 'm', + '__gt__': 'm', + '__hash__': 'm', + '__le__': 'm', + '__len__': 'm', + '__lt__': 'm', + '__mul__': 'm', + '__ne__': 'm', + '__new__': 27, + '__repr__': 'm', + '__rmul__': 'm'}], + [14, + 1, + (0,), + {'__add__': 'm', + '__contains__': 'm', + '__doc__': 14, + '__eq__': 'm', + '__ge__': 'm', + '__getattribute__': 'm', + '__getitem__': 'm', + '__getslice__': 'm', + '__gt__': 'm', + '__hash__': 'm', + '__le__': 'm', + '__len__': 'm', + '__lt__': 'm', + '__mul__': 'm', + '__ne__': 'm', + '__new__': 27, + '__repr__': 'm', + '__rmul__': 'm', + '__str__': 'm', + 'capitalize': 'm', + 'center': 'm', + 'count': 'm', + 'decode': 'm', + 'encode': 'm', + 'endswith': 'm', + 'expandtabs': 'm', + 'find': 'm', + 'index': 'm', + 'isalnum': 'm', + 'isalpha': 'm', + 'isdigit': 'm', + 'islower': 'm', + 'isspace': 'm', + 'istitle': 'm', + 'isupper': 'm', + 'join': 'm', + 'ljust': 'm', + 'lower': 'm', + 'lstrip': 'm', + 'replace': 'm', + 'rfind': 'm', + 'rindex': 'm', + 'rjust': 'm', + 'rstrip': 'm', + 'split': 'm', + 'splitlines': 'm', + 'startswith': 'm', + 'strip': 'm', + 'swapcase': 'm', + 'title': 'm', + 'translate': 'm', + 'upper': 'm', + 'zfill': 'm'}], + [15, + 1, + (0,), + {'__delete__': 'm', + '__doc__': 'd', + '__get__': 'm', + '__getattribute__': 'm', + '__init__': 'm', + '__new__': 27, + '__set__': 'm', + 'fdel': 'd', + 'fget': 'd', + 'fset': 'd'}], + [16, + 1, + (0,), + {'__abs__': 'm', + '__add__': 'm', + '__and__': 'm', + '__cmp__': 'm', + '__coerce__': 'm', + '__div__': 'm', + '__divmod__': 'm', + '__doc__': 14, + '__float__': 'm', + '__floordiv__': 'm', + '__getattribute__': 'm', + '__hash__': 'm', + '__hex__': 'm', + '__int__': 'm', + '__invert__': 'm', + '__long__': 'm', + '__lshift__': 'm', + '__mod__': 'm', + '__mul__': 'm', + '__neg__': 'm', + '__new__': 27, + '__nonzero__': 'm', + '__oct__': 'm', + '__or__': 'm', + '__pos__': 'm', + '__pow__': 'm', + '__radd__': 'm', + '__rand__': 'm', + '__rdiv__': 'm', + '__rdivmod__': 'm', + '__repr__': 'm', + '__rfloordiv__': 'm', + '__rlshift__': 'm', + '__rmod__': 'm', + '__rmul__': 'm', + '__ror__': 'm', + '__rpow__': 'm', + '__rrshift__': 'm', + '__rshift__': 'm', + '__rsub__': 'm', + '__rtruediv__': 'm', + '__rxor__': 'm', + '__str__': 'm', + '__sub__': 'm', + '__truediv__': 'm', + '__xor__': 'm'}], + [17, 27, None, None], + [10, + 1, + (0,), + {'__doc__': 14, + '__getattribute__': 'm', + '__init__': 'm', + '__iter__': 'm', + '__new__': 27, + '__repr__': 'm', + 'close': 'm', + 'closed': 'd', + 'fileno': 'm', + 'flush': 'm', + 'isatty': 'm', + 'mode': 'd', + 'name': 'd', + 'read': 'm', + 'readinto': 'm', + 'readline': 'm', + 'readlines': 'm', + 'seek': 'm', + 'softspace': 'd', + 'tell': 'm', + 'truncate': 'm', + 'write': 'm', + 'writelines': 'm', + 'xreadlines': 'm'}], + [19, + 1, + (0,), + {'__abs__': 'm', + '__add__': 'm', + '__coerce__': 'm', + '__div__': 'm', + '__divmod__': 'm', + '__doc__': 14, + '__eq__': 'm', + '__float__': 'm', + '__floordiv__': 'm', + '__ge__': 'm', + '__getattribute__': 'm', + '__gt__': 'm', + '__hash__': 'm', + '__int__': 'm', + '__le__': 'm', + '__long__': 'm', + '__lt__': 'm', + '__mod__': 'm', + '__mul__': 'm', + '__ne__': 'm', + '__neg__': 'm', + '__new__': 27, + '__nonzero__': 'm', + '__pos__': 'm', + '__pow__': 'm', + '__radd__': 'm', + '__rdiv__': 'm', + '__rdivmod__': 'm', + '__repr__': 'm', + '__rfloordiv__': 'm', + '__rmod__': 'm', + '__rmul__': 'm', + '__rpow__': 'm', + '__rsub__': 'm', + '__rtruediv__': 'm', + '__str__': 'm', + '__sub__': 'm', + '__truediv__': 'm', + 'conjugate': 'm', + 'imag': 'd', + 'real': 'd'}], + [20, 27, None, None], + [21, + 1, + (0,), + {'__doc__': 14, + '__get__': 'm', + '__getattribute__': 'm', + '__init__': 'm', + '__new__': 27}], + [22, + 1, + (0,), + {'__call__': 'm', + '__delattr__': 'm', + '__dict__': 'd', + '__doc__': 'd', + '__get__': 'm', + '__getattribute__': 'm', + '__name__': 'd', + '__new__': 27, + '__repr__': 'm', + '__setattr__': 'm', + 'func_closure': 'd', + 'func_code': 'd', + 'func_defaults': 'd', + 'func_dict': 'd', + 'func_doc': 'd', + 'func_globals': 'd', + 'func_name': 'd'}], + [23, + 1, + (0,), + {'__call__': 'm', + '__cmp__': 'm', + '__delattr__': 'm', + '__doc__': '-', + '__get__': 'm', + '__getattribute__': 'm', + '__hash__': 'm', + '__repr__': 'm', + '__setattr__': 'm', + 'im_class': 'd', + 'im_func': 'd', + 'im_self': 'd'}], + [24, + 1, + (0,), + {'__cmp__': 'm', + '__doc__': '-', + '__getattribute__': 'm', + '__hash__': 'm', + '__repr__': 'm', + 'co_argcount': 'd', + 'co_cellvars': 'd', + 'co_code': 'd', + 'co_consts': 'd', + 'co_filename': 'd', + 'co_firstlineno': 'd', + 'co_flags': 'd', + 'co_freevars': 'd', + 'co_lnotab': 'd', + 'co_name': 'd', + 'co_names': 'd', + 'co_nlocals': 'd', + 'co_stacksize': 'd', + 'co_varnames': 'd'}], + [25, + 1, + (0,), + {'__delattr__': 'm', + '__doc__': '-', + '__getattribute__': 'm', + '__setattr__': 'm', + 'f_back': 'd', + 'f_builtins': 'd', + 'f_code': 'd', + 'f_exc_traceback': 'd', + 'f_exc_type': 'd', + 'f_exc_value': 'd', + 'f_globals': 'd', + 'f_lasti': 'd', + 'f_lineno': 'd', + 'f_locals': 'd', + 'f_restricted': 'd', + 'f_trace': 'd'}], + [26, 1, (0,), {'__doc__': '-'}], + [27, + 1, + (0,), + {'__call__': 'm', + '__cmp__': 'm', + '__doc__': 'd', + '__getattribute__': 'm', + '__hash__': 'm', + '__name__': 'd', + '__repr__': 'm', + '__self__': 'd'}]] +print 'comparing with information from 2.2.3+' +import make_checker +make_checker.do_check(names, checks) Copied: branches/2.3/Misc/checker23.py (from rev 3041, trunk/jython/Misc/checker23.py) =================================================================== --- branches/2.3/Misc/checker23.py (rev 0) +++ branches/2.3/Misc/checker23.py 2007-02-22 05:29:40 UTC (rev 3116) @@ -0,0 +1,720 @@ +names = {0: 'object', + 1: 'type', + 2: 'unicode', + 3: 'dict', + 4: 'list', + 5: 'slice', + 6: 'super', + 7: 'staticmethod', + 8: 'float', + 9: 'enumerate', + 10: 'file', + 11: 'basestring', + 12: 'long', + 13: 'tuple', + 14: 'str', + 15: 'property', + 16: 'int', + 17: 'xrange', + 18: 'file', + 19: 'complex', + 20: 'bool', + 21: 'classmethod', + 22: 'function', + 23: 'instancemethod', + 24: 'code', + 25: 'frame', + 26: 'traceback', + 27: 'type'} +checks = [[0, + 1, + (), + {'__class__': 'd', + '__delattr__': 'm', + '__doc__': 14, + '__getattribute__': 'm', + '__hash__': 'm', + '__init__': 'm', + '__new__': 'n', + '__reduce__': 'm', + '__reduce_ex__': 'm', + '__repr__': 'm', + '__setattr__': 'm', + '__str__': 'm'}], + [1, + 1, + (0,), + {'__base__': 'd', + '__bases__': 'd', + '__basicsize__': 'd', + '__call__': 'm', + '__cmp__': 'm', + '__delattr__': 'm', + '__dict__': 'd', + '__dictoffset__': 'd', + '__doc__': 'd', + '__flags__': 'd', + '__getattribute__': 'm', + '__hash__': 'm', + '__itemsize__': 'd', + '__module__': 'd', + '__mro__': 'd', + '__name__': 'd', + '__new__': 'n', + '__repr__': 'm', + '__setattr__': 'm', + '__subclasses__': 'm', + '__weakrefoffset__': 'd', + 'mro': 'm'}], + [2, + 1, + (11,), + {'__add__': 'm', + '__cmp__': 'm', + '__contains__': 'm', + '__doc__': 14, + '__getattribute__': 'm', + '__getitem__': 'm', + '__getnewargs__': 'm', + '__getslice__': 'm', + '__hash__': 'm', + '__len__': 'm', + '__mod__': 'm', + '__mul__': 'm', + '__new__': 'n', + '__repr__': 'm', + '__rmod__': 'm', + '__rmul__': 'm', + '__str__': 'm', + 'capitalize': 'm', + 'center': 'm', + 'count': 'm', + 'encode': 'm', + 'endswith': 'm', + 'expandtabs': 'm', + 'find': 'm', + 'index': 'm', + 'isalnum': 'm', + 'isalpha': 'm', + 'isdecimal': 'm', + 'isdigit': 'm', + 'islower': 'm', + 'isnumeric': 'm', + 'isspace': 'm', + 'istitle': 'm', + 'isupper': 'm', + 'join': 'm', + 'ljust': 'm', + 'lower': 'm', + 'lstrip': 'm', + 'replace': 'm', + 'rfind': 'm', + 'rindex': 'm', + 'rjust': 'm', + 'rstrip': 'm', + 'split': 'm', + 'splitlines': 'm', + 'startswith': 'm', + 'strip': 'm', + 'swapcase': 'm', + 'title': 'm', + 'translate': 'm', + 'upper': 'm', + 'zfill': 'm'}], + [3, + 1, + (0,), + {'__cmp__': 'm', + '__contains__': 'm', + '__delitem__': 'm', + '__doc__': 14, + '__eq__': 'm', + '__ge__': 'm', + '__getattribute__': 'm', + '__getitem__': 'm', + '__gt__': 'm', + '__hash__': 'm', + '__init__': 'm', + '__iter__': 'm', + '__le__': 'm', + '__len__': 'm', + '__lt__': 'm', + '__ne__': 'm', + '__new__': 'n', + '__repr__': 'm', + '__setitem__': 'm', + 'clear': 'm', + 'copy': 'm', + 'fromkeys': 21, + 'get': 'm', + 'has_key': 'm', + 'items': 'm', + 'iteritems': 'm', + 'iterkeys': 'm', + 'itervalues': 'm', + 'keys': 'm', + 'pop': 'm', + 'popitem': 'm', + 'setdefault': 'm', + 'update': 'm', + 'values': 'm'}], + [4, + 1, + (0,), + {'__add__': 'm', + '__contains__': 'm', + '__delitem__': 'm', + '__delslice__': 'm', + '__doc__': 14, + '__eq__': 'm', + '__ge__': 'm', + '__getattribute__': 'm', + '__getitem__': 'm', + '__getslice__': 'm', + '__gt__': 'm', + '__hash__': 'm', + '__iadd__': 'm', + '__imul__': 'm', + '__init__': 'm', + '__iter__': 'm', + '__le__': 'm', + '__len__': 'm', + '__lt__': 'm', + '__mul__': 'm', + '__ne__': 'm', + '__new__': 'n', + '__repr__': 'm', + '__rmul__': 'm', + '__setitem__': 'm', + '__setslice__': 'm', + 'append': 'm', + 'count': 'm', + 'extend': 'm', + 'index': 'm', + 'insert': 'm', + 'pop': 'm', + 'remove': 'm', + 'reverse': 'm', + 'sort': 'm'}], + [5, + 1, + (0,), + {'__cmp__': 'm', + '__doc__': 14, + '__getattribute__': 'm', + '__hash__': 'm', + '__new__': 'n', + '__repr__': 'm', + 'indices': 'm', + 'start': 'd', + 'step': 'd', + 'stop': 'd'}], + [6, + 1, + (0,), + {'__doc__': 14, + '__get__': 'm', + '__getattribute__': 'm', + '__init__': 'm', + '__new__': 'n', + '__repr__': 'm', + '__self__': 'd', + '__self_class__': 'd', + '__thisclass__': 'd'}], + [7, + 1, + (0,), + {'__doc__': 14, + '__get__': 'm', + '__getattribute__': 'm', + '__init__': 'm', + '__new__': 'n'}], + [8, + 1, + (0,), + {'__abs__': 'm', + '__add__': 'm', + '__cmp__': 'm', + '__coerce__': 'm', + '__div__': 'm', + '__divmod__': 'm', + '__doc__': 14, + '__float__': 'm', + '__floordiv__': 'm', + '__getattribute__': 'm', + '__getnewargs__': 'm', + '__hash__': 'm', + '__int__': 'm', + '__long__': 'm', + '__mod__': 'm', + '__mul__': 'm', + '__neg__': 'm', + '__new__': 'n', + '__nonzero__': 'm', + '__pos__': 'm', + '__pow__': 'm', + '__radd__': 'm', + '__rdiv__': 'm', + '__rdivmod__': 'm', + '__repr__': 'm', + '__rfloordiv__': 'm', + '__rmod__': 'm', + '__rmul__': 'm', + '__rpow__': 'm', + '__rsub__': 'm', + '__rtruediv__': 'm', + '__str__': 'm', + '__sub__': 'm', + '__truediv__': 'm'}], + [9, + 1, + (0,), + {'__doc__': 14, + '__getattribute__': 'm', + '__iter__': 'm', + '__new__': 'n', + 'next': 'm'}], + [10, + 1, + (0,), + {'__delattr__': 'm', + '__doc__': 14, + '__getattribute__': 'm', + '__init__': 'm', + '__iter__': 'm', + '__new__': 'n', + '__repr__': 'm', + '__setattr__': 'm', + 'close': 'm', + 'closed': 'd', + 'encoding': 'd', + 'fileno': 'm', + 'flush': 'm', + 'isatty': 'm', + 'mode': 'd', + 'name': 'd', + 'newlines': 'd', + 'next': 'm', + 'read': 'm', + 'readinto': 'm', + 'readline': 'm', + 'readlines': 'm', + 'seek': 'm', + 'softspace': 'd', + 'tell': 'm', + 'truncate': 'm', + 'write': 'm', + 'writelines': 'm', + 'xreadlines': 'm'}], + [11, 1, (0,), {'__new__': 'n', '__doc__': 14}], + [12, + 1, + (0,), + {'__abs__': 'm', + '__add__': 'm', + '__and__': 'm', + '__cmp__': 'm', + '__coerce__': 'm', + '__div__': 'm', + '__divmod__': 'm', + '__doc__': 14, + '__float__': 'm', + '__floordiv__': 'm', + '__getattribute__': 'm', + '__getnewargs__': 'm', + '__hash__': 'm', + '__hex__': 'm', + '__int__': 'm', + '__invert__': 'm', + '__long__': 'm', + '__lshift__': 'm', + '__mod__': 'm', + '__mul__': 'm', + '__neg__': 'm', + '__new__': 'n', + '__nonzero__': 'm', + '__oct__': 'm', + '__or__': 'm', + '__pos__': 'm', + '__pow__': 'm', + '__radd__': 'm', + '__rand__': 'm', + '__rdiv__': 'm', + '__rdivmod__': 'm', + '__repr__': 'm', + '__rfloordiv__': 'm', + '__rlshift__': 'm', + '__rmod__': 'm', + '__rmul__': 'm', + '__ror__': 'm', + '__rpow__': 'm', + '__rrshift__': 'm', + '__rshift__': 'm', + '__rsub__': 'm', + '__rtruediv__': 'm', + '__rxor__': 'm', + '__str__': 'm', + '__sub__': 'm', + '__truediv__': 'm', + '__xor__': 'm'}], + [13, + 1, + (0,), + {'__add__': 'm', + '__contains__': 'm', + '__doc__': 14, + '__eq__': 'm', + '__ge__': 'm', + '__getattribute__': 'm', + '__getitem__': 'm', + '__getnewargs__': 'm', + '__getslice__': 'm', + '__gt__': 'm', + '__hash__': 'm', + '__iter__': 'm', + '__le__': 'm', + '__len__': 'm', + '__lt__': 'm', + '__mul__': 'm', + '__ne__': 'm', + '__new__': 'n', + '__repr__': 'm', + '__rmul__': 'm'}], + [14, + 1, + (11,), + {'__add__': 'm', + '__contains__': 'm', + '__doc__': 14, + '__eq__': 'm', + '__ge__': 'm', + '__getattribute__': 'm', + '__getitem__': 'm', + '__getnewargs__': 'm', + '__getslice__': 'm', + '__gt__': 'm', + '__hash__': 'm', + '__le__': 'm', + '__len__': 'm', + '__lt__': 'm', + '__mod__': 'm', + '__mul__': 'm', + '__ne__': 'm', + '__new__': 'n', + '__repr__': 'm', + '__rmod__': 'm', + '__rmul__': 'm', + '__str__': 'm', + 'capitalize': 'm', + 'center': 'm', + 'count': 'm', + 'decode': 'm', + 'encode': 'm', + 'endswith': 'm', + 'expandtabs': 'm', + 'find': 'm', + 'index': 'm', + 'isalnum': 'm', + 'isalpha': 'm', + 'isdigit': 'm', + 'islower': 'm', + 'isspace': 'm', + 'istitle': 'm', + 'isupper': 'm', + 'join': 'm', + 'ljust': 'm', + 'lower': 'm', + 'lstrip': 'm', + 'replace': 'm', + 'rfind': 'm', + 'rindex': 'm', + 'rjust': 'm', + 'rstrip': 'm', + 'split': 'm', + 'splitlines': 'm', + 'startswith': 'm', + 'strip': 'm', + 'swapcase': 'm', + 'title': 'm', + 'translate': 'm', + 'upper': 'm', + 'zfill': 'm'}], + [15, + 1, + (0,), + {'__delete__': 'm', + '__doc__': 'd', + '__get__': 'm', + '__getattribute__': 'm', + '__init__': 'm', + '__new__': 'n', + '__set__': 'm', + 'fdel': 'd', + 'fget': 'd', + 'fset': 'd'}], + [16, + 1, + (0,), + {'__abs__': 'm', + '__add__': 'm', + '__and__': 'm', + '__cmp__': 'm', + '__coerce__': 'm', + '__div__': 'm', + '__divmod__': 'm', + '__doc__': 14, + '__float__': 'm', + '__floordiv__': 'm', + '__getattribute__': 'm', + '__getnewargs__': 'm', + '__hash__': 'm', + '__hex__': 'm', + '__int__': 'm', + '__invert__': 'm', + '__long__': 'm', + '__lshift__': 'm', + '__mod__': 'm', + '__mul__': 'm', + '__neg__': 'm', + '__new__': 'n', + '__nonzero__': 'm', + '__oct__': 'm', + '__or__': 'm', + '__pos__': 'm', + '__pow__': 'm', + '__radd__': 'm', + '__rand__': 'm', + '__rdiv__': 'm', + '__rdivmod__': 'm', + '__repr__': 'm', + '__rfloordiv__': 'm', + '__rlshift__': 'm', + '__rmod__': 'm', + '__rmul__': 'm', + '__ror__': 'm', + '__rpow__': 'm', + '__rrshift__': 'm', + '__rshift__': 'm', + '__rsub__': 'm', + '__rtruediv__': 'm', + '__rxor__': 'm', + '__str__': 'm', + '__sub__': 'm', + '__truediv__': 'm', + '__xor__': 'm'}], + [17, + 1, + (0,), + {'__doc__': 14, + '__getattribute__': 'm', + '__getitem__': 'm', + '__iter__': 'm', + '__len__': 'm', + '__new__': 'n', + '__repr__': 'm'}], + [10, + 1, + (0,), + {'__delattr__': 'm', + '__doc__': 14, + '__getattribute__': 'm', + '__init__': 'm', + '__iter__': 'm', + '__new__': 'n', + '__repr__': 'm', + '__setattr__': 'm', + 'close': 'm', + 'closed': 'd', + 'encoding': 'd', + 'fileno': 'm', + 'flush': 'm', + 'isatty': 'm', + 'mode': 'd', + 'name': 'd', + 'newlines': 'd', + 'next': 'm', + 'read': 'm', + 'readinto': 'm', + 'readline': 'm', + 'readlines': 'm', + 'seek': 'm', + 'softspace': 'd', + 'tell': 'm', + 'truncate': 'm', + 'write': 'm', + 'writelines': 'm', + 'xreadlines': 'm'}], + [19, + 1, + (0,), + {'__abs__': 'm', + '__add__': 'm', + '__coerce__': 'm', + '__div__': 'm', + '__divmod__': 'm', + '__doc__': 14, + '__eq__': 'm', + '__float__': 'm', + '__floordiv__': 'm', + '__ge__': 'm', + '__getattribute__': 'm', + '__getnewargs__': 'm', + '__gt__': 'm', + '__hash__': 'm', + '__int__': 'm', + '__le__': 'm', + '__long__': 'm', + '__lt__': 'm', + '__mod__': 'm', + '__mul__': 'm', + '__ne__': 'm', + '__neg__': 'm', + '__new__': 'n', + '__nonzero__': 'm', + '__pos__': 'm', + '__pow__': 'm', + '__radd__': 'm', + '__rdiv__': 'm', + '__rdivmod__': 'm', + '__repr__': 'm', + '__rfloordiv__': 'm', + '__rmod__': 'm', + '__rmul__': 'm', + '__rpow__': 'm', + '__rsub__': 'm', + '__rtruediv__': 'm', + '__str__': 'm', + '__sub__': 'm', + '__truediv__': 'm', + 'conjugate': 'm', + 'imag': 'd', + 'real': 'd'}], + [20, + 1, + (16,), + {'__and__': 'm', + '__doc__': 14, + '__new__': 'n', + '__or__': 'm', + '__rand__': 'm', + '__repr__': 'm', + '__ror__': 'm', + '__rxor__': 'm', + '__str__': 'm', + '__xor__': 'm'}], + [21, + 1, + (0,), + {'__doc__': 14, + '__get__': 'm', + '__getattribute__': 'm', + '__init__': 'm', + '__new__': 'n'}], + [22, + 1, + (0,), + {'__call__': 'm', + '__delattr__': 'm', + '__dict__': 'd', + '__doc__': 'd', + '__get__': 'm', + '__getattribute__': 'm', + '__module__': 'd', + '__name__': 'd', + '__new__': 'n', + '__repr__': 'm', + '__setattr__': 'm', + 'func_closure': 'd', + 'func_code': 'd', + 'func_defaults': 'd', + 'func_dict': 'd', + 'func_doc': 'd', + 'func_globals': 'd', + 'func_name': 'd'}], + [23, + 1, + (0,), + {'__call__': 'm', + '__cmp__': 'm', + '__delattr__': 'm', + '__doc__': 14, + '__get__': 'm', + '__getattribute__': 'm', + '__hash__': 'm', + '__new__': 'n', + '__repr__': 'm', + '__setattr__': 'm', + 'im_class': 'd', + 'im_func': 'd', + 'im_self': 'd'}], + [24, + 1, + (0,), + {'__cmp__': 'm', + '__doc__': 14, + '__getattribute__': 'm', + '__hash__': 'm', + '__new__': 'n', + '__repr__': 'm', + 'co_argcount': 'd', + 'co_cellvars': 'd', + 'co_code': 'd', + 'co_consts': 'd', + 'co_filename': 'd', + 'co_firstlineno': 'd', + 'co_flags': 'd', + 'co_freevars': 'd', + 'co_lnotab': 'd', + 'co_name': 'd', + 'co_names': 'd', + 'co_nlocals': 'd', + 'co_stacksize': 'd', + 'co_varnames': 'd'}], + [25, + 1, + (0,), + {'__delattr__': 'm', + '__doc__': '-', + '__getattribute__': 'm', + '__setattr__': 'm', + 'f_back': 'd', + 'f_builtins': 'd', + 'f_code': 'd', + 'f_exc_traceback': 'd', + 'f_exc_type': 'd', + 'f_exc_value': 'd', + 'f_globals': 'd', + 'f_lasti': 'd', + 'f_lineno': 'd', + 'f_locals': 'd', + 'f_restricted': 'd', + 'f_trace': 'd'}], + [26, 1, (0,), {'__doc__': '-'}], + [1, + 1, + (0,), + {'__base__': 'd', + '__bases__': 'd', + '__basicsize__': 'd', + '__call__': 'm', + '__cmp__': 'm', + '__delattr__': 'm', + '__dict__': 'd', + '__dictoffset__': 'd', + '__doc__': 'd', + '__flags__': 'd', + '__getattribute__': 'm', + '__hash__': 'm', + '__itemsize__': 'd', + '__module__': 'd', + '__mro__': 'd', + '__name__': 'd', + '__new__': 'n', + '__repr__': 'm', + '__setattr__': 'm', + '__subclasses__': 'm', + '__weakrefoffset__': 'd', + 'mro': 'm'}]] +print 'comparing with information from 2.3.5' +import make_checker +make_checker.do_check(names, checks) Copied: branches/2.3/Misc/make_checker.py (from rev 3041, trunk/jython/Misc/make_checker.py) =================================================================== --- branches/2.3/Misc/make_checker.py (rev 0) +++ branches/2.3/Misc/make_checker.py 2007-02-22 05:29:40 UTC (rev 3116) @@ -0,0 +1,188 @@ +import __builtin__ + +import sys +import __builtin__ + +opt = lambda n: getattr(__builtin__, n, None) + +def f(): pass +try: + raise Exception +except: + _, _, tb = sys.exc_info() + +class C: + f = f + +m = C.f + +types_list = [ +object, +type, +unicode, +dict, +list, +slice, +super, +staticmethod, +float, +opt('enumerate'), +open, +opt('basestring'), +long, +tuple, +str, +property, +int, +xrange, +file, +complex, +opt('bool'), +classmethod, +#buffer, +# + +type(f), +type(m), +type(f.func_code), +type(sys._getframe()), +type(tb), +type(slice), +] + +del f, tb +if 0: + for n, x in __builtin__.__dict__.items(): + if isinstance(x, type): + if x not in types: + print "%s," % n + +i = 0 +types = {} +for t in types_list: + if t is not None: + types.setdefault(t, i) + i += 1 + +extra = { + type(dict.__dict__.get('fromkeys')): types[classmethod], # xxx hack + type(list.__dict__['append']): 'm', + type(int.__dict__['__add__']): 'm', + type(int.__dict__['__new__']): 'n', + type(object.__dict__['__class__']): 'd', + type(super.__dict__['__thisclass__']): 'd', + type(None): '-', +} + +def which(t): + try: + return types[t] + except KeyError: + return extra[t] + +def do_check(names, checks): + def swhich(t): + try: + return which(t) + except KeyError: + return "%s?" % t.__name__ + def n(fnd): + if isinstance(fnd, tuple): + return tuple(map(n, fnd)) + r = names.get(fnd, fnd) + if isinstance(r, int): + return "%s?" % types_list[fnd].__name__ + return r + for check in checks: + index, expected_type, expected_bases, expected_dict = check + t = types_list[index] + print names[index], t + if t is None: + print " Missing!" + continue + which_type = swhich(type(t)) + err = 0 + if which_type != expected_type: + print " type %s isn't %s" % ( type(t).__name__, n(expected_type)) + err += 1 + elif expected_bases: + which_bases = tuple(map(swhich, t.__bases__)) + if which_bases != expected_bases: + print " bases %s aren't %s" % (n(which_bases), + n(expected_bases)) + err += 1 + d = t.__dict__ + miss = [] + extra = [] + for name in d.keys(): + if name not in expected_dict: + extra.append(name) + if extra: + print " extra %s" % extra + err += len(extra) + for name, expected in expected_dict.items(): + if name not in d: + miss.append(name) + else: + which_type = swhich(type(d[name])) + if which_type != expected: + print "%r type %s isn't %s" % (name, n(which_type), + n(expected)) + err += 1 + if miss: + print " missing %s" % miss + err += len(miss) + + if not err: + print ' OK' + else: + print ' %d problems' % err + + +if __name__ == '__main__': + names = {} + checks = [] + i = -1 + for t in types_list: + i += 1 + if t is None: + continue + names[i] = t.__name__ + check = [] + checks.append(check) + check.append(which(t)) # index + assert type(t) in types, t + check.append(which(type(t))) + if not hasattr(t, '__bases__'): + check.extend([None, None]) + continue + bases = [] + for b in t.__bases__: + assert b in types + bases.append(which(b)) + check.append(tuple(bases)) + membs = {} + for n,x in t.__dict__.items(): + membs[n] = which(type(x)) + check.append(membs) + + + # sanity-check + do_check(names, checks) + + ver = sys.version.split()[0] + simple_ver = ver[:3].replace('.', '') + + import pprint + f = open('checker%s.py' % simple_ver, 'w') + print >>f, "names = ", + pprint.pprint(names, stream=f) + print >>f, "checks = ", + pprint.pprint(checks, stream=f) + print >>f, "print 'comparing with information from %s'" % ver + print >>f, "import make_checker" + print >>f, "make_checker.do_check(names, checks)" + f.close() + + + + Modified: branches/2.3/build.xml =================================================================== --- branches/2.3/build.xml 2007-02-22 05:23:37 UTC (rev 3115) +++ branches/2.3/build.xml 2007-02-22 05:29:40 UTC (rev 3116) @@ -20,7 +20,7 @@ - call target 'full-build' This build will create a working directory named full_build_${svn.tag} at the same level as your local directories jython, sandbox and installer. -It will contain a big jython_${svn.tag}.jar file suitable for installation. +It will contain a big jython_installer_${svn.tag}.jar file suitable for installation. Please be aware: To build older releases, it may be necessary to use an older build.xml, too (with the corresponding tag). @@ -654,7 +654,7 @@ <fileset dir="${install.src.dir}" includes="**/*.png" excludes="bin/**" /> </copy> <echo>building installer .jar file</echo> - <jar destfile="${work.dir}/jython_${svn.revision}.jar" basedir="${dist.dir}" update="true"> + <jar destfile="${work.dir}/jython_installer_${svn.revision}.jar" basedir="${dist.dir}" update="true"> <manifest> <attribute name="Main-Class" value="org.python.util.install.Installation" /> <attribute name="Built-By" value="${user.name}" /> Modified: branches/2.3/src/org/python/core/Options.java =================================================================== --- branches/2.3/src/org/python/core/Options.java 2007-02-22 05:23:37 UTC (rev 3115) +++ branches/2.3/src/org/python/core/Options.java 2007-02-22 05:29:40 UTC (rev 3116) @@ -73,7 +73,7 @@ /** * If true, Jython will use the first module found on sys.path where java * File.isFile() returns true. Setting this to true have no effect on - * unix-type filesystems. On Windows/HPS+ systems setting it to true will + * unix-type filesystems. On Windows/HFS+ systems setting it to true will * enable Jython-2.0 behaviour. */ public static boolean caseok = false; Modified: branches/2.3/src/org/python/core/PyString.java =================================================================== --- branches/2.3/src/org/python/core/PyString.java 2007-02-22 05:23:37 UTC (rev 3115) +++ branches/2.3/src/org/python/core/PyString.java 2007-02-22 05:29:40 UTC (rev 3116) @@ -3296,13 +3296,21 @@ } private byte[] getBytes() { - byte[] buf = new byte[string.length()]; - string.getBytes(0, string.length(), buf, 0); - return buf; - //XXX: would rather not use above getBytes since it is deprecated, - // but that breaks zlib.py -- need to figure out why and fix. - //return string.getBytes(); + return to_bytes(string); } + + public static byte[] to_bytes(String s){ + byte[] bytes = new byte[s.length()]; + for(int i = 0; i < bytes.length; i++) { + char c = s.charAt(i); + if(c < 256){ + bytes[i] = (byte)c; + }else{ + throw Py.ValueError("Strings added to sha hashes must not contain characters with value > 255"); + } + } + return bytes; + } public Object __tojava__(Class c) { if (c.isAssignableFrom(String.class)) { Modified: branches/2.3/src/org/python/core/PySystemState.java =================================================================== --- branches/2.3/src/org/python/core/PySystemState.java 2007-02-22 05:23:37 UTC (rev 3115) +++ branches/2.3/src/org/python/core/PySystemState.java 2007-02-22 05:29:40 UTC (rev 3116) @@ -9,7 +9,9 @@ import java.io.FilterInputStream; import java.io.IOException; import java.io.InputStream; +import java.io.UnsupportedEncodingException; import java.net.URL; +import java.net.URLDecoder; import java.security.AccessControlException; import java.util.Enumeration; import java.util.Hashtable; @@ -34,7 +36,6 @@ private static final String JAR_URL_PREFIX = "jar:file:"; private static final String JAR_SEPARATOR = "!"; - private static final String URL_BLANK_REPLACEMENT = "%20"; /** * The current version of Jython. @@ -673,14 +674,14 @@ URL url = thisClass.getResource(className + ".class"); // we expect an URL like jar:file:/install_dir/jython.jar!/org/python/core/PySystemState.class if (url != null) { - String urlString = url.toString(); - int jarSeparatorIndex = urlString.indexOf(JAR_SEPARATOR); - if (urlString.startsWith(JAR_URL_PREFIX) && jarSeparatorIndex > 0) { - jarFileName = urlString.substring(JAR_URL_PREFIX.length(), jarSeparatorIndex); - // handle directories containing blanks - if (jarFileName.indexOf(URL_BLANK_REPLACEMENT) >= 0) { - jarFileName = jarFileName.replaceAll(URL_BLANK_REPLACEMENT, " "); + try { + String urlString = URLDecoder.decode(url.toString(), "UTF-8"); + int jarSeparatorIndex = urlString.indexOf(JAR_SEPARATOR); + if (urlString.startsWith(JAR_URL_PREFIX) && jarSeparatorIndex > 0) { + jarFileName = urlString.substring(JAR_URL_PREFIX.length(), jarSeparatorIndex); } + } catch (UnsupportedEncodingException e) { + // this is VERY unlikely - forget about standalone if it happens } } return jarFileName; Modified: branches/2.3/src/org/python/core/PyType.java =================================================================== --- branches/2.3/src/org/python/core/PyType.java 2007-02-22 05:23:37 UTC (rev 3115) +++ branches/2.3/src/org/python/core/PyType.java 2007-02-22 05:29:40 UTC (rev 3116) @@ -1320,9 +1320,12 @@ if (exposed_methods == null) exposed_methods = EMPTY; } - PyType newtype = c == PyType.class ? new PyType(true) : new PyType(); - class_to_type.put(c, newtype); - fillFromClass(newtype, name, c, base, newstyle, setup, exposed_methods); + PyType newtype = (PyType)class_to_type.get(c); + if (newtype == null) { + newtype = c == PyType.class ? new PyType(true) : new PyType(); + class_to_type.put(c, newtype); + fillFromClass(newtype, name, c, base, newstyle, setup, exposed_methods); + } return newtype; } Modified: branches/2.3/src/org/python/core/PyTypeDerived.java =================================================================== --- branches/2.3/src/org/python/core/PyTypeDerived.java 2007-02-22 05:23:37 UTC (rev 3115) +++ branches/2.3/src/org/python/core/PyTypeDerived.java 2007-02-22 05:29:40 UTC (rev 3116) @@ -12,33 +12,9 @@ private PyObject[]slots; - private PyObject dict; - - public PyObject fastGetDict() { - return dict; - } - - public PyObject getDict() { - return dict; - } - - public void setDict(PyObject newDict) { - if (newDict instanceof PyStringMap||newDict instanceof PyDictionary) { - dict=newDict; - } else { - throw Py.TypeError("__dict__ must be set to a Dictionary "+newDict.getClass().getName()); - } - } - - public void delDict() { - // deleting an object's instance dict makes it grow a new one - dict=new PyStringMap(); - } - public PyTypeDerived(PyType subtype) { super(subtype); slots=new PyObject[subtype.getNumSlots()]; - dict=subtype.instDict(); } public PyString __str__() { Modified: branches/2.3/src/org/python/modules/MD5Object.java =================================================================== --- branches/2.3/src/org/python/modules/MD5Object.java 2007-02-22 05:23:37 UTC (rev 3115) +++ branches/2.3/src/org/python/modules/MD5Object.java 2007-02-22 05:29:40 UTC (rev 3116) @@ -9,6 +9,8 @@ { private String data; + public int digest_size = 16; + public MD5Object(String s) { data = s; } Modified: branches/2.3/src/org/python/modules/SHA1.java =================================================================== --- branches/2.3/src/org/python/modules/SHA1.java 2007-02-22 05:23:37 UTC (rev 3115) +++ branches/2.3/src/org/python/modules/SHA1.java 2007-02-22 05:29:40 UTC (rev 3116) @@ -43,7 +43,8 @@ package org.python.modules; -import org.python.core.PyString; +import java.io.UnsupportedEncodingException; +import org.python.core.*; /** * This class implements the SHA-1 message digest algorithm. @@ -89,9 +90,9 @@ */ private long count; + public int digest_size = 20; - /** * <b>SPI</b>: Updates the message digest with a byte of new data. * @@ -162,9 +163,6 @@ private byte[] tmp; private int[] w; - private byte[] digestBits; - - /** * Constructs a SHA-1 message digest. */ @@ -242,14 +240,14 @@ protected byte[] engineDigest(byte[] in, int length) { byte b[] = java_digest(in, length); - engineReset(); return b; } private byte[] java_digest(byte[] in, int pos) { + int[] digest_save = (int[]) digest.clone(); if (pos != 0) System.arraycopy(in, 0, tmp, 0, pos); - + tmp[pos++] = (byte)0x80; if (pos > DATA_LENGTH - 8) @@ -287,6 +285,7 @@ buf[off++] = (byte) (d>>>8); buf[off++] = (byte) d; } + digest = digest_save; return buf; } @@ -471,8 +470,7 @@ * to the test vectors. */ public String hexdigest() { - if (digestBits == null) - digestBits = engineDigest(); + byte[] digestBits = engineDigest(); StringBuffer sb = new StringBuffer(); for (int i = 0; i < 20; i++) { @@ -494,9 +492,12 @@ ); public String digest() { - if (digestBits == null) - digestBits = engineDigest(); - return new String(digestBits); + byte[] digestBits = engineDigest(); + try { + return new String(digestBits, "ISO-8859-1"); + } catch (UnsupportedEncodingException exc) { + throw Py.ValueError("encoding not supported"); + } } // XXX should become PyObject and use Py.idstr? Modified: branches/2.3/src/org/python/modules/sha.java =================================================================== --- branches/2.3/src/org/python/modules/sha.java 2007-02-22 05:23:37 UTC (rev 3115) +++ branches/2.3/src/org/python/modules/sha.java 2007-02-22 05:29:40 UTC (rev 3116) @@ -2,13 +2,10 @@ package org.python.modules; +import java.io.UnsupportedEncodingException; import org.python.core.*; -public class sha { - public int blocksize = 1; - public int digestsize = 20; - public int digest_size = digestsize; - +public class sha implements ClassDictInit { public static String __doc__ = "* Cryptix General License\n" + "* Copyright (c) 1995, 1996, 1997, 1998, 1999, 2000 The Cryptix"+ @@ -45,10 +42,10 @@ public static SHA1 new$(PyObject[] args, String[] kws) { ArgParser ap = new ArgParser("sha", args, kws, "string"); String cp = ap.getString(0, null); - SHA1 n = new SHA1(); - if (cp != null) - n.update(cp.getBytes()); + if(cp != null) { + n.update(PyString.to_bytes(cp)); + } return n; } @@ -56,4 +53,11 @@ public static SHA1 sha$(PyObject[] args, String[] kws) { return new$(args, kws); } + + public static void classDictInit(PyObject dict) { + dict.__setitem__("digest_size", Py.newInteger(20)); + dict.__setitem__("digestsize", Py.newInteger(20)); + dict.__setitem__("blocksize", Py.newInteger(1)); + dict.__setitem__("classDictInit", null); + } } Modified: branches/2.3/src/templates/type.derived =================================================================== --- branches/2.3/src/templates/type.derived 2007-02-22 05:23:37 UTC (rev 3115) +++ branches/2.3/src/templates/type.derived 2007-02-22 05:29:40 UTC (rev 3116) @@ -1,4 +1,4 @@ base_class: PyType -want_dict: true +want_dict: false ctr: incl: object This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <cg...@us...> - 2007-02-22 05:40:27
|
Revision: 3117 http://svn.sourceforge.net/jython/?rev=3117&view=rev Author: cgroves Date: 2007-02-21 21:40:25 -0800 (Wed, 21 Feb 2007) Log Message: ----------- merge -r 3048:3083 https://jython.svn.sourceforge.net/svnroot/jython/trunk/jython Modified Paths: -------------- branches/2.3/Lib/javaos.py branches/2.3/Lib/javapath.py branches/2.3/Lib/site.py branches/2.3/Lib/test/output/test_extcall branches/2.3/Lib/test/regrtest.py branches/2.3/Lib/test/test_mhlib.py branches/2.3/Lib/test/test_sax.py branches/2.3/Lib/test/test_support.py branches/2.3/Misc/checker22.py branches/2.3/Misc/checker23.py branches/2.3/Misc/make_checker.py branches/2.3/NEWS branches/2.3/build.xml branches/2.3/src/org/python/core/PyBuiltinFunctionNarrow.java branches/2.3/src/org/python/core/PyBuiltinFunctionWide.java branches/2.3/src/org/python/core/PyMethod.java branches/2.3/src/org/python/core/PyObject.java branches/2.3/src/org/python/core/PyString.java branches/2.3/src/org/python/core/PySystemState.java branches/2.3/src/org/python/core/PyUnicode.java branches/2.3/src/templates/str.expose Added Paths: ----------- branches/2.3/Misc/jython_checker.py branches/2.3/bugtests/test393m.py Removed Paths: ------------- branches/2.3/src/org/apache/ branches/2.3/src/org/python/modules/MatchObject.java branches/2.3/src/org/python/modules/RegexObject.java branches/2.3/src/org/python/modules/re.java Property Changed: ---------------- branches/2.3/bugtests/ branches/2.3/bugtests/classes/ branches/2.3/bugtests/classes/test092m/ branches/2.3/bugtests/classes/test121p/ branches/2.3/bugtests/classes/test217p/ branches/2.3/bugtests/classes/test232p/ branches/2.3/bugtests/classes/test246p/ branches/2.3/bugtests/classes/test301p/ branches/2.3/bugtests/classes/test336p/ branches/2.3/bugtests/classes/test336p/data/ branches/2.3/bugtests/test049p/ branches/2.3/bugtests/test088p/ branches/2.3/bugtests/test122p/ branches/2.3/bugtests/test154p/ branches/2.3/bugtests/test168p/ branches/2.3/bugtests/test170p/ branches/2.3/bugtests/test171p/ branches/2.3/bugtests/test173p/ branches/2.3/bugtests/test194m/ branches/2.3/bugtests/test209p/ branches/2.3/bugtests/test209p/foo/ branches/2.3/bugtests/test235p/ branches/2.3/bugtests/test238p/ branches/2.3/bugtests/test240p/ branches/2.3/bugtests/test241p/ branches/2.3/bugtests/test243p/ branches/2.3/bugtests/test244p/ branches/2.3/bugtests/test261p/ branches/2.3/bugtests/test261p/ccs/ branches/2.3/bugtests/test261p/ccs/util/ branches/2.3/bugtests/test262p/ branches/2.3/bugtests/test262p/p1/ branches/2.3/bugtests/test269p/ branches/2.3/bugtests/test270p/ branches/2.3/bugtests/test273p/ branches/2.3/bugtests/test273p/com/ branches/2.3/bugtests/test277p/ branches/2.3/bugtests/test278p/ branches/2.3/bugtests/test293p/ branches/2.3/bugtests/test296p/ branches/2.3/bugtests/test308d/ branches/2.3/bugtests/test342p/ branches/2.3/bugtests/test364p/ branches/2.3/bugtests/test387p/ branches/2.3/bugtests/test394jar/ Modified: branches/2.3/Lib/javaos.py =================================================================== --- branches/2.3/Lib/javaos.py 2007-02-22 05:29:40 UTC (rev 3116) +++ branches/2.3/Lib/javaos.py 2007-02-22 05:40:25 UTC (rev 3117) @@ -88,6 +88,13 @@ extsep = '/' else: extsep = '.' +path.curdir = curdir +path.pardir = pardir +path.sep = sep +path.altsep = altsep +path.pathsep = pathsep +path.defpath = defpath +path.extsep = extsep def _exit(n=0): java.lang.System.exit(n) Modified: branches/2.3/Lib/javapath.py =================================================================== --- branches/2.3/Lib/javapath.py 2007-02-22 05:29:40 UTC (rev 3116) +++ branches/2.3/Lib/javapath.py 2007-02-22 05:40:25 UTC (rev 3117) @@ -20,11 +20,12 @@ from java.lang import System import os + def _tostr(s, method): - if isinstance(s, "".__class__): + if isinstance(s, basestring): return s import org - raise TypeError, "%s() argument must be a string object, not %s" % ( + raise TypeError, "%s() argument must be a str or unicode object, not %s" % ( method, org.python.core.Py.safeRepr(s)) def dirname(path): @@ -236,8 +237,11 @@ # Return an absolute path. def abspath(path): path = _tostr(path, "abspath") - return File(path).getAbsolutePath() + return File(path).getCanonicalPath() +def realpath(path): + path = _tostr(path, "realpath") + return File(path).getCanonicalPath() def getsize(path): path = _tostr(path, "getsize") Modified: branches/2.3/Lib/site.py =================================================================== --- branches/2.3/Lib/site.py 2007-02-22 05:29:40 UTC (rev 3116) +++ branches/2.3/Lib/site.py 2007-02-22 05:40:25 UTC (rev 3117) @@ -61,6 +61,8 @@ def makepath(*paths): dir = os.path.join(*paths) + if dir == '__classpath__': + return dir return os.path.normcase(os.path.abspath(dir)) L = sys.modules.values() Modified: branches/2.3/Lib/test/output/test_extcall =================================================================== --- branches/2.3/Lib/test/output/test_extcall 2007-02-22 05:29:40 UTC (rev 3116) +++ branches/2.3/Lib/test/output/test_extcall 2007-02-22 05:40:25 UTC (rev 3117) @@ -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: branches/2.3/Lib/test/regrtest.py =================================================================== --- branches/2.3/Lib/test/regrtest.py 2007-02-22 05:29:40 UTC (rev 3116) +++ branches/2.3/Lib/test/regrtest.py 2007-02-22 05:40:25 UTC (rev 3117) @@ -407,14 +407,13 @@ if verbose: print "CAUTION: stdout isn't compared in verbose mode: a test" print "that passes in verbose mode may fail without it." + surprises = 0 if skipped and not quiet: print count(len(skipped), "test"), "skipped:" - printlist(skipped) - printsurprises(_Expected(_skips), skipped, 'skip') + surprises += countsurprises(_Expected(_skips), skipped, 'skip') if bad: print count(len(bad), "test"), "failed:" - printlist(bad) - printsurprises(_Expected(_failures), bad, 'fail') + surprises += countsurprises(_Expected(_failures), bad, 'fail') ## if single: ## alltests = findtests(testdir, stdtests, nottests) ## for i in range(len(alltests)): @@ -432,7 +431,7 @@ if memo: savememo(memo,good,bad,skipped) - return len(bad) > 0 + return surprises > 0 STDTESTS = [ @@ -631,17 +630,21 @@ if len(line) > indent: print line -def printsurprises(e, actual, name): - plat = sys.platform - if e.isvalid(): - surprise = _Set(actual) - e.getexpected() +def countsurprises(expected, actual, name): + """returns the number of items in actual that aren't in expected.""" + + printlist(actual) + if expected.isvalid(): + surprise = _Set(actual) - expected.getexpected() if surprise: print count(len(surprise), name), \ - "unexpected on", plat + ":" + "unexpected on", sys.platform + ":" printlist(surprise) + return len(surprise) else: print "Ask someone to teach regrtest.py about which tests are" - print "expected to %s on %s." % (name, plat) + print "expected to %s on %s." % (name, sys.platform) + return 1#Surprising not to know what to expect.... class _Set: def __init__(self, seq=[]): @@ -1040,6 +1043,8 @@ test_winsound """ } +if test_support.is_jython and test_support.underlying_system.startswith('win'): + _skips['java'] += 'test_mhlib' _failures = { 'java': Modified: branches/2.3/Lib/test/test_mhlib.py =================================================================== --- branches/2.3/Lib/test/test_mhlib.py 2007-02-22 05:29:40 UTC (rev 3116) +++ branches/2.3/Lib/test/test_mhlib.py 2007-02-22 05:40:25 UTC (rev 3117) @@ -7,13 +7,15 @@ ### mhlib. It should. import unittest -from test.test_support import run_unittest, TESTFN, TestSkipped +from test.test_support import run_unittest, TESTFN, TestSkipped, underlying_system import os, StringIO import sys import mhlib -if (sys.platform.startswith("win") or sys.platform=="riscos" or - sys.platform.startswith("atheos")): + + +if (underlying_system.startswith("win") or underlying_system=="riscos" or + underlying_system.startswith("atheos")): # mhlib.updateline() renames a file to the name of a file that already # exists. That causes a reasonable OS <wink> to complain in test_sequence # here, like the "OSError: [Errno 17] File exists" raised on Windows. @@ -21,7 +23,7 @@ # link counts, and that causes test_listfolders() here to get back # an empty list from its call of listallfolders(). # The other tests here pass on Windows. - raise TestSkipped("skipped on %s -- " % sys.platform + + raise TestSkipped("skipped on %s -- " % underlying_system + "too many Unix assumptions") _mhroot = TESTFN+"_MH" Modified: branches/2.3/Lib/test/test_sax.py =================================================================== --- branches/2.3/Lib/test/test_sax.py 2007-02-22 05:29:40 UTC (rev 3116) +++ branches/2.3/Lib/test/test_sax.py 2007-02-22 05:40:25 UTC (rev 3117) @@ -449,9 +449,9 @@ XMLGenerator.__init__(self, out, encoding) self.location = None - def endDocument(self): - XMLGenerator.endDocument(self) - self.location = Location(self._locator) + def setDocumentLocator(self, locator): + XMLGenerator.setDocumentLocator(self, locator) + self.location = Location(self._locator) def test_expat_locator_noinfo(): result = StringIO() Modified: branches/2.3/Lib/test/test_support.py =================================================================== --- branches/2.3/Lib/test/test_support.py 2007-02-22 05:29:40 UTC (rev 3116) +++ branches/2.3/Lib/test/test_support.py 2007-02-22 05:40:25 UTC (rev 3117) @@ -113,6 +113,11 @@ is_jython = sys.platform.startswith('java') +underlying_system = sys.platform +if is_jython: + import java.lang.System + underlying_system = java.lang.System.getProperty('os.name').lower() + import os # Filename used for testing if os.name == 'java': Modified: branches/2.3/Misc/checker22.py =================================================================== --- branches/2.3/Misc/checker22.py 2007-02-22 05:29:40 UTC (rev 3116) +++ branches/2.3/Misc/checker22.py 2007-02-22 05:40:25 UTC (rev 3117) @@ -627,6 +627,8 @@ '__name__': 'd', '__repr__': 'm', '__self__': 'd'}]] -print 'comparing with information from 2.2.3+' -import make_checker -make_checker.do_check(names, checks) +source_version = '2.2.3' +if __name__ == '__main__': + print 'comparing with information from %s' % source_version + import make_checker + make_checker.report(*make_checker.do_check(names, checks)) Modified: branches/2.3/Misc/checker23.py =================================================================== --- branches/2.3/Misc/checker23.py 2007-02-22 05:29:40 UTC (rev 3116) +++ branches/2.3/Misc/checker23.py 2007-02-22 05:40:25 UTC (rev 3117) @@ -715,6 +715,8 @@ '__subclasses__': 'm', '__weakrefoffset__': 'd', 'mro': 'm'}]] -print 'comparing with information from 2.3.5' -import make_checker -make_checker.do_check(names, checks) +source_version = '2.3.5' +if __name__ == '__main__': + print 'comparing with information from %s' % source_version + import make_checker + make_checker.report(*make_checker.do_check(names, checks)) Copied: branches/2.3/Misc/jython_checker.py (from rev 3083, trunk/jython/Misc/jython_checker.py) =================================================================== --- branches/2.3/Misc/jython_checker.py (rev 0) +++ branches/2.3/Misc/jython_checker.py 2007-02-22 05:40:25 UTC (rev 3117) @@ -0,0 +1,45 @@ +import sys +def usage(): + print 'Usage: jython jython_checker.py <module name created by make_checker>' + sys.exit(1) + +if not len(sys.argv) == 2: + usage() +checker_name = sys.argv[1].split('.')[0]#pop off the .py if needed +try: + checker = __import__(checker_name) +except: + print 'No module "%s" found' % checker_name + usage() + +import make_checker + +ignored_types = ['frame', + 'code', + 'traceback'] +checks = [] +for check in checker.checks: + index, expected_type, expected_bases, expected_dict = check + if checker.names[index] in ignored_types: + print 'Skipping', checker.names[index] + continue + checks.append(check) + + +ignored_members = ['__getattribute__', '__doc__'] + +ok, missing, bad_type, different = make_checker.do_check(checker.names, checks) + +def strip_ignored(differences, key, ignored): + if not key in differences: + return + problems = differences[key] + for member in ignored_members: + if member in problems: + problems.remove(member) + +for t, name, differences in different: + strip_ignored(differences, 'missing', ignored_members) + strip_ignored(differences, 'extras', ignored_members) + +make_checker.report(ok, missing, bad_type, different) Modified: branches/2.3/Misc/make_checker.py =================================================================== --- branches/2.3/Misc/make_checker.py 2007-02-22 05:29:40 UTC (rev 3116) +++ branches/2.3/Misc/make_checker.py 2007-02-22 05:40:25 UTC (rev 3117) @@ -57,6 +57,7 @@ print "%s," % n i = 0 +#Make types a mapping from an item in types_list to its index types = {} for t in types_list: if t is not None: @@ -74,6 +75,7 @@ } def which(t): + '''Get the index of t in types_list or its str value in extra if it's not in types_list''' try: return types[t] except KeyError: @@ -86,58 +88,76 @@ except KeyError: return "%s?" % t.__name__ def n(fnd): + '''Gets the name of fnd if it's a single item, or its names if it's a tuple''' if isinstance(fnd, tuple): return tuple(map(n, fnd)) r = names.get(fnd, fnd) if isinstance(r, int): return "%s?" % types_list[fnd].__name__ return r + missing = [] + bad_type = [] + different = [] + ok = [] for check in checks: index, expected_type, expected_bases, expected_dict = check t = types_list[index] - print names[index], t if t is None: - print " Missing!" + missing.append(t) continue which_type = swhich(type(t)) - err = 0 if which_type != expected_type: - print " type %s isn't %s" % ( type(t).__name__, n(expected_type)) - err += 1 + bad_type.append((t, names[index], n(expected_type))) elif expected_bases: + differences = {} which_bases = tuple(map(swhich, t.__bases__)) if which_bases != expected_bases: - print " bases %s aren't %s" % (n(which_bases), - n(expected_bases)) - err += 1 + differences['bases'] = ['had %s but expected %s' % (n(which_bases), n(expected_bases))] d = t.__dict__ + bad_types = [] miss = [] extra = [] for name in d.keys(): if name not in expected_dict: extra.append(name) if extra: - print " extra %s" % extra - err += len(extra) + differences['extra'] = extra for name, expected in expected_dict.items(): if name not in d: miss.append(name) else: which_type = swhich(type(d[name])) if which_type != expected: - print "%r type %s isn't %s" % (name, n(which_type), - n(expected)) - err += 1 + bad_types.append("%r type %s isn't %s" % (name, n(which_type), n(expected))) if miss: - print " missing %s" % miss - err += len(miss) - - if not err: - print ' OK' - else: - print ' %d problems' % err - + differences['missing'] = miss + if bad_types: + differences['bad_types'] = bad_types + if differences: + different.append((t, names[index], differences)) + else: + ok.append(names[index]) + return ok, missing, bad_type, different +def report(ok, missing, bad_type, different): + if ok: + print 'OK: %s' % ', '.join(ok) + if missing: + print 'Missing: %s' % ', '.join(missing) + if bad_type: + print 'Bad Type:' + for t, name, expected_type in bad_type: + print " ", name, t, "type isn't", expected_type + if different: + print 'Different:' + for t, name, differences in different: + print ' ', name, t + for k, v in differences.items(): + if not v: continue + print ' ', k + for val in v: + print ' ', val + if __name__ == '__main__': names = {} checks = [] @@ -167,7 +187,7 @@ # sanity-check - do_check(names, checks) + report(*do_check(names, checks)) ver = sys.version.split()[0] simple_ver = ver[:3].replace('.', '') @@ -178,9 +198,11 @@ pprint.pprint(names, stream=f) print >>f, "checks = ", pprint.pprint(checks, stream=f) - print >>f, "print 'comparing with information from %s'" % ver - print >>f, "import make_checker" - print >>f, "make_checker.do_check(names, checks)" + print >>f, '''source_version = '%s' +if __name__ == '__main__': + print 'comparing with information from %%s' %% source_version + import make_checker + make_checker.report(*make_checker.do_check(names, checks))''' % ver f.close() Modified: branches/2.3/NEWS =================================================================== --- branches/2.3/NEWS 2007-02-22 05:29:40 UTC (rev 3116) +++ branches/2.3/NEWS 2007-02-22 05:40:25 UTC (rev 3117) @@ -1,35 +1,64 @@ Jython NEWS -Jython 2.2 tip +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) - added datetime support using the pure python datetime.py from cpython non-dist. - Bug fixes. - - applied patch 906256: Follow spec for read modes of open() - - applied patch 868514: yield in finally block -- yield in nested try:except: - - fixed bug 1243049: Can't subclass str in 2.2a1 + - new-style classes and their instances are Java serializable + - most new-style builtin types can be pickleds + - __slots__ for new-style classes + - xml modules from pyxml readded + - comparison operations between subclasses of + builtin types tries the subclass first even if it's on the right side + Bugs fixed. + - Modules that throw exceptions while being imported aren't left + in sys.modules + - Don't allow sys.recursionlimit to be set below 0 + - [ 1533624 ] NPE thrown building traceback for a call that jumps + threads + - [ 1531644 ] import * makes java exception uncatchable + - [1243049, 1218089] Can't subclass builtin types in 2.2a1 + - [1256506] Importing directory module with 12+ char name fails + - [1512745] Allow arbitrary precision for formatted strings, + but only 250 chars for decimal, integer and long + - [1506749] Instance __dict__ are unassignable + - [1599004] several fixes to get the sha module up to speed + - [1616493] unicode objects can't be passed to os.path + methods + - [ 979157 ] Stack traces untrimmed + - [ 1299032 ] os.getenv out of sync with cpython + - [ 738951 ] jython slice behavior differs from python in __getattr__ + - [ 610576 ] Impl of abstract method not found + - [ 1374088 ] keyword args to dict() constructor ignored + - [ 730082 ] new can't create unbound methods + - [ 1382581 ] double(s) read inaccurately from database + - [ 1603312 ] subclasses of int raise a TypeError when given large + value + - [1465476] bad parenthesis nesting terminates interpreter + - [ 1227282 ] Deadlock between PythonTraceFunction.safeCall() and + imp.import + - [ 1421812 ] Jython 2.2a and 2.1 imports directories as modules + - [ 480017 ] Proxy super classes are loaded from syspath, not the + proxy's classpath + - [ 628315 ] problem with Java synchronized lists + - [ 1284344 ] __file__ compiled into .py.class file + - [ 610576 ] Impl of abstract method not found + Patches applied. + - [906256] Follow spec for read modes of open() + - [868514] yield in finally block -- yield in nested try:except: + - [1542997] Only evaluate the second expression in an assert + if the first expression is false + - [1612711]: add iterkeys, itervalues and iteritems to + PyStringMap + - [ 1267425 ] make cStringIO work with gzip.py + - [ 1361317 ] __set__ failing on PyProperty + -xx-jul-2005 Jython 2.2 alpha1 continued +17-jul-2005 Jython 2.2 alpha1 New features - - finished long/int unification -- PyObject.__int__() now returns a - PyObject (which could be a PyInteger or a PyLong). - - dict and list conform to CPython 2.3 behaviors (such as the 3 arg - list.index()). - - new-style conversion of tuple, float, file and str. - - Preliminary work on a unicode type. - - Imported tempfile.py and userlist.py from CPython 2.3 and applied some - small adjustments to get tests to pass. - - Reworked message construction for TypeError exceptions - (such as the exceptions generated from operations like [] + ""). - - Bug fixes. - -xx-xxx-2003 Jython 2.2 alpha1 - - New features - Integrated patch (by Aleks Totic) that allows to use the Python parser outside of Jython. PythonGrammar grows two constructors, one of which _must_ be used: @@ -41,9 +70,17 @@ - New-style classes - PEP 302 implementation - Java collections integration + - finished long/int unification -- PyObject.__int__() now returns a + PyObject (which could be a PyInteger or a PyLong). + - dict and list conform to CPython 2.3 behaviors (such as the 3 arg + list.index()). + - new-style conversion of tuple, float, file and str. + - Preliminary work on a unicode type. + - Imported tempfile.py and userlist.py from CPython 2.3 and applied some + small adjustments to get tests to pass. + - Reworked message construction for TypeError exceptions + (such as the exceptions generated from operations like [] + ""). - Bug fixes. - 31-jul-2003 Jython 2.2 alpha0 New features Property changes on: branches/2.3/bugtests ___________________________________________________________________ Name: svn:ignore - *.jar *.class *.out *.tmp *.ser *.pyc *.err jpywork cachedir support_config.py *.zip *.diff .classpath .project .ipr .iws .iml test385jar test385javapackage + *.jar *.class *.out *.tmp *.ser *.pyc *.err jpywork cachedir support_config.py *.zip *.diff .classpath .project .ipr .iws .iml test246p test302s.py test339p test385jar test385javapackage Property changes on: branches/2.3/bugtests/classes ___________________________________________________________________ Name: svn:ignore + *.class Property changes on: branches/2.3/bugtests/classes/test092m ___________________________________________________________________ Name: svn:ignore + *.class Property changes on: branches/2.3/bugtests/classes/test121p ___________________________________________________________________ Name: svn:ignore + *.class Property changes on: branches/2.3/bugtests/classes/test217p ___________________________________________________________________ Name: svn:ignore + *.class Property changes on: branches/2.3/bugtests/classes/test232p ___________________________________________________________________ Name: svn:ignore + *.class Property changes on: branches/2.3/bugtests/classes/test246p ___________________________________________________________________ Name: svn:ignore + *.class Property changes on: branches/2.3/bugtests/classes/test301p ___________________________________________________________________ Name: svn:ignore + *.class Property changes on: branches/2.3/bugtests/classes/test336p ___________________________________________________________________ Name: svn:ignore + *.class Property changes on: branches/2.3/bugtests/classes/test336p/data ___________________________________________________________________ Name: svn:ignore + *.class Property changes on: branches/2.3/bugtests/test049p ___________________________________________________________________ Name: svn:ignore + *.class Property changes on: branches/2.3/bugtests/test088p ___________________________________________________________________ Name: svn:ignore + *.class Property changes on: branches/2.3/bugtests/test122p ___________________________________________________________________ Name: svn:ignore + *.class Property changes on: branches/2.3/bugtests/test154p ___________________________________________________________________ Name: svn:ignore + *.class Property changes on: branches/2.3/bugtests/test168p ___________________________________________________________________ Name: svn:ignore + *.class Property changes on: branches/2.3/bugtests/test170p ___________________________________________________________________ Name: svn:ignore + *.class Property changes on: branches/2.3/bugtests/test171p ___________________________________________________________________ Name: svn:ignore + *.class Property changes on: branches/2.3/bugtests/test173p ___________________________________________________________________ Name: svn:ignore + *.class Property changes on: branches/2.3/bugtests/test194m ___________________________________________________________________ Name: svn:ignore + *.class Property changes on: branches/2.3/bugtests/test209p ___________________________________________________________________ Name: svn:ignore + *.class Property changes on: branches/2.3/bugtests/test209p/foo ___________________________________________________________________ Name: svn:ignore + *.class Property changes on: branches/2.3/bugtests/test235p ___________________________________________________________________ Name: svn:ignore + *.class Property changes on: branches/2.3/bugtests/test238p ___________________________________________________________________ Name: svn:ignore + *.class Property changes on: branches/2.3/bugtests/test240p ___________________________________________________________________ Name: svn:ignore + *.class Property changes on: branches/2.3/bugtests/test241p ___________________________________________________________________ Name: svn:ignore + *.class Property changes on: branches/2.3/bugtests/test243p ___________________________________________________________________ Name: svn:ignore + *.class Property changes on: branches/2.3/bugtests/test244p ___________________________________________________________________ Name: svn:ignore + *.class Property changes on: branches/2.3/bugtests/test261p ___________________________________________________________________ Name: svn:ignore + *.class Property changes on: branches/2.3/bugtests/test261p/ccs ___________________________________________________________________ Name: svn:ignore + *.class Property changes on: branches/2.3/bugtests/test261p/ccs/util ___________________________________________________________________ Name: svn:ignore + *.class Property changes on: branches/2.3/bugtests/test262p ___________________________________________________________________ Name: svn:ignore + *.class Property changes on: branches/2.3/bugtests/test262p/p1 ___________________________________________________________________ Name: svn:ignore + *.class Property changes on: branches/2.3/bugtests/test269p ___________________________________________________________________ Name: svn:ignore + *.class Property changes on: branches/2.3/bugtests/test270p ___________________________________________________________________ Name: svn:ignore + *.class Property changes on: branches/2.3/bugtests/test273p ___________________________________________________________________ Name: svn:ignore + *.class Property changes on: branches/2.3/bugtests/test273p/com ___________________________________________________________________ Name: svn:ignore + *.class Property changes on: branches/2.3/bugtests/test277p ___________________________________________________________________ Name: svn:ignore + *.class Property changes on: branches/2.3/bugtests/test278p ___________________________________________________________________ Name: svn:ignore + *.class Property changes on: branches/2.3/bugtests/test293p ___________________________________________________________________ Name: svn:ignore + *.class Property changes on: branches/2.3/bugtests/test296p ___________________________________________________________________ Name: svn:ignore + *.class Property changes on: branches/2.3/bugtests/test308d ___________________________________________________________________ Name: svn:ignore + *.class Property changes on: branches/2.3/bugtests/test342p ___________________________________________________________________ Name: svn:ignore + *.class Property changes on: branches/2.3/bugtests/test364p ___________________________________________________________________ Name: svn:ignore + *.class Property changes on: branches/2.3/bugtests/test387p ___________________________________________________________________ Name: svn:ignore + *.class Copied: branches/2.3/bugtests/test393m.py (from rev 3083, trunk/jython/bugtests/test393m.py) =================================================================== --- branches/2.3/bugtests/test393m.py (rev 0) +++ branches/2.3/bugtests/test393m.py 2007-02-22 05:40:25 UTC (rev 3117) @@ -0,0 +1 @@ +assert __file__ == "test393m.py" Property changes on: branches/2.3/bugtests/test394jar ___________________________________________________________________ Name: svn:ignore - run.jar jython.jar + *.class run.jar jython.jar Modified: branches/2.3/build.xml =================================================================== --- branches/2.3/build.xml 2007-02-22 05:29:40 UTC (rev 3116) +++ branches/2.3/build.xml 2007-02-22 05:40:25 UTC (rev 3117) @@ -67,9 +67,10 @@ 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. check in all the changes - 8. apply the new tag to the jython svn (all projects) - 9. call target 'full-build' + 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' @@ -359,6 +360,11 @@ <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" /> </svn> + + <!-- checkout cpython license from the correct python maintenance branch --> + <svn javahl="${javahl.dir}" > + <checkout url="http://svn.python.org/projects/python/branches/release22-maint/" destPath="${svn.checkout.dir}/python" recurse="false" /> + </svn> </target> @@ -564,9 +570,8 @@ </copy> <!-- copy the CPython license --> - <echo>copy CPython LICENSE from ${python.home} to ${dist.dir}/LICENSE_CPython.txt</echo> - <!-- +++ TODO: checkout the CPython LICENSE (not: .txt) and copy from there --> - <copy file="${python.home}/LICENSE.txt" tofile="${dist.dir}/LICENSE_CPython.txt" preservelastmodified="true" /> + <echo>copy CPython LICENSE from ${svn.checkout.dir}/python</echo> + <copy file="${svn.checkout.dir}/python/LICENSE" tofile="${dist.dir}/LICENSE_CPython.txt" preservelastmodified="true" /> <!-- sources: todir has to correspond with installer/**/JarInstaller.java --> <echo>copy sources from ${jython.base.dir}</echo> Modified: branches/2.3/src/org/python/core/PyBuiltinFunctionNarrow.java =================================================================== --- branches/2.3/src/org/python/core/PyBuiltinFunctionNarrow.java 2007-02-22 05:29:40 UTC (rev 3116) +++ branches/2.3/src/org/python/core/PyBuiltinFunctionNarrow.java 2007-02-22 05:40:25 UTC (rev 3117) @@ -1,6 +1,8 @@ package org.python.core; public abstract class PyBuiltinFunctionNarrow extends PyBuiltinFunction { + + public static final Class exposed_as = PyBuiltinFunction.class; public PyBuiltinFunctionNarrow(Info info) { super(info); Modified: branches/2.3/src/org/python/core/PyBuiltinFunctionWide.java =================================================================== --- branches/2.3/src/org/python/core/PyBuiltinFunctionWide.java 2007-02-22 05:29:40 UTC (rev 3116) +++ branches/2.3/src/org/python/core/PyBuiltinFunctionWide.java 2007-02-22 05:40:25 UTC (rev 3117) @@ -2,6 +2,8 @@ public abstract class PyBuiltinFunctionWide extends PyBuiltinFunction { + public static final Class exposed_as = PyBuiltinFunction.class; + public PyBuiltinFunctionWide(Info info) { super(info); } Modified: branches/2.3/src/org/python/core/PyMethod.java =================================================================== --- branches/2.3/src/org/python/core/PyMethod.java 2007-02-22 05:29:40 UTC (rev 3116) +++ branches/2.3/src/org/python/core/PyMethod.java 2007-02-22 05:40:25 UTC (rev 3117) @@ -78,18 +78,21 @@ public PyObject _doget(PyObject container, PyObject wherefound) { /* Only if classes are compatible */ - if (container == null) + if(container == null || im_self != null) { return this; - if (__builtin__.issubclass(container.fastGetClass(), im_class)) - if (im_func instanceof PyFunction) - return new PyMethod(container, (PyFunction)im_func, - im_class); - else if (im_func instanceof PyReflectedFunction) - return new PyMethod(container, (PyReflectedFunction)im_func, - im_class); - else - return new PyMethod(container, im_func, im_class); - return this; + } else if(__builtin__.issubclass(container.fastGetClass(), im_class)) { + if(im_func instanceof PyFunction) { + return new PyMethod(container, (PyFunction)im_func, im_class); + } else if(im_func instanceof PyReflectedFunction) { + return new PyMethod(container, + (PyReflectedFunction)im_func, + im_class); + } else { + return new PyMethod(container, im_func, im_class); + } + } else { + return this; + } } Modified: branches/2.3/src/org/python/core/PyObject.java =================================================================== --- branches/2.3/src/org/python/core/PyObject.java 2007-02-22 05:29:40 UTC (rev 3116) +++ branches/2.3/src/org/python/core/PyObject.java 2007-02-22 05:40:25 UTC (rev 3117) @@ -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 @@ -761,14 +764,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) { @@ -778,9 +779,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( @@ -791,49 +792,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) { Modified: branches/2.3/src/org/python/core/PyString.java =================================================================== --- branches/2.3/src/org/python/core/PyString.java 2007-02-22 05:29:40 UTC (rev 3116) +++ branches/2.3/src/org/python/core/PyString.java 2007-02-22 05:40:25 UTC (rev 3117) @@ -237,6 +237,34 @@ } dict.__setitem__("__add__",new PyMethodDescr("__add__",PyString.class,1,1,new exposed___add__(null,null))); + class exposed___mod__ extends PyBuiltinFunctionNarrow { + + private PyString self; + + public PyObject getSelf() { + return self; + } + + exposed___mod__(PyString self,PyBuiltinFunction.Info info) { + super(info); + this.self=self; + } + + public PyBuiltinFunction makeBound(PyObject self) { + return new exposed___mod__((PyString)self,info); + } + + public PyObject __call__(PyObject arg0) { + return self.str___mod__(arg0); + } + + public PyObject inst_call(PyObject gself,PyObject arg0) { + PyString self=(PyString)gself; + return self.str___mod__(arg0); + } + + } + dict.__setitem__("__mod__",new PyMethodDescr("__mod__",PyString.class,1,1,new exposed___mod__(null,null))); class exposed___mul__ extends PyBuiltinFunctionNarrow { private PyString self; @@ -2794,8 +2822,11 @@ PyObject[] args, String[] keywords) { ArgParser ap = new ArgParser("str", args, keywords, new String[] { "object" }, 0); PyObject S = ap.getPyObject(0, null); - if (new_.for_type == subtype) { - return returnString(S); + if(new_.for_type == subtype) { + if(S == null) { + return new PyString(""); + } + return S.__str__(); } else { if (S == null) { return new PyStringDerived(subtype, ""); @@ -2804,18 +2835,6 @@ } } - private static PyString returnString(PyObject S) { - if (S == null) { - return new PyString(""); - } - if (S instanceof PyStringDerived || S instanceof PyUnicode) { - return new PyString(S.toString()); - } if (S instanceof PyString) { - return (PyString)S; - } - return S.__str__(); - } - /** <i>Internal use only. Do not call this method explicit.</i> */ public static void classDictInit(PyObject dict) throws PyIgnoreMethodTag {} @@ -2828,7 +2847,7 @@ } final PyString str___str__() { - return returnString(this); + return this; } public PyUnicode __unicode__() { @@ -3419,6 +3438,10 @@ } public PyObject __mod__(PyObject other) { + return str___mod__(other); + } + + public PyObject str___mod__(PyObject other){ StringFormatter fmt = new StringFormatter(string); return createInstance(fmt.format(other)); } Modified: branches/2.3/src/org/python/core/PySystemState.java =================================================================== --- branches/2.3/src/org/python/core/PySystemState.java 2007-02-22 05:29:40 UTC (rev 3116) +++ branches/2.3/src/org/python/core/PySystemState.java 2007-02-22 05:40:25 UTC (rev 3117) @@ -9,7 +9,6 @@ import java.io.FilterInputStream; import java.io.IOException; import java.io.InputStream; -import java.io.UnsupportedEncodingException; import java.net.URL; import java.net.URLDecoder; import java.security.AccessControlException; @@ -675,13 +674,12 @@ // we expect an URL like jar:file:/install_dir/jython.jar!/org/python/core/PySystemState.class if (url != null) { try { - String urlString = URLDecoder.decode(url.toString(), "UTF-8"); + String urlString = URLDecoder.decode(url.toString()); int jarSeparatorIndex = urlString.indexOf(JAR_SEPARATOR); if (urlString.startsWith(JAR_URL_PREFIX) && jarSeparatorIndex > 0) { jarFileName = urlString.substring(JAR_URL_PREFIX.length(), jarSeparatorIndex); } - } catch (UnsupportedEncodingException e) { - // this is VERY unlikely - forget about standalone if it happens + } catch (Exception e) { } } return jarFileName; Modified: branches/2.3/src/org/python/core/PyUnicode.java =================================================================== --- branches/2.3/src/org/python/core/PyUnicode.java 2007-02-22 05:29:40 UTC (rev 3116) +++ branches/2.3/src/org/python/core/PyUnicode.java 2007-02-22 05:40:25 UTC (rev 3117) @@ -2775,7 +2775,7 @@ } public PyString unicode___str__() { - return str___str__(); + return new PyString(toString()); } final int unicode___len__() { Deleted: branches/2.3/src/org/python/modules/MatchObject.java =================================================================== --- branches/2.3/src/org/python/modules/MatchObject.java 2007-02-22 05:29:40 UTC (rev 3116) +++ branches/2.3/src/org/python/modules/MatchObject.java 2007-02-22 05:40:25 UTC (rev 3117) @@ -1,153 +0,0 @@ -// Copyright (c) Corporation for National Research Initiatives -package org.python.modules; - -import org.python.core.*; -import org.apache.oro.text.regex.*; - -public class MatchObject extends PyObject -{ - public String string; - public int pos, endpos; - public RegexObject re; - private MatchResult match; - - public MatchObject(RegexObject re, String string, - int pos, int endpos, MatchResult match) - { - this.string = string; - this.pos = pos; - this.endpos = endpos; - this.re = re; - this.match = match; - } - - public int start(int g) { - return match.beginOffset(g); - } - - public int start() { - return start(0); - } - - public int start(PyString s) { - return start(getindex(s)); - } - - public int end(int g) { - return match.endOffset(g); - } - - public int end() { - return end(0); - } - - public int end(PyString s) { - return end(getindex(s)); - } - - public PyTuple span(int g) { - return new PyTuple( - new PyObject[] { - new PyInteger(start(g)), - new PyInteger(end(g)) - }); - } - - public PyTuple span() { - return span(0); - } - - public PyTuple span(PyString s) { - return span(getindex(s)); - } - - public PyTuple groups(PyObject defalt) { - int n = match.groups()-1; - PyObject[] ret = new PyObject[n]; - for(int i=0; i<n; i++) { - String tmp = match.group(i+1); - if (tmp == null) { - ret[i] = defalt; - } else { - ret[i] = new PyString(tmp); - } - } - return new PyTuple(ret); - } - - public PyTuple groups() { - return groups(Py.None); - } - - private int getindex(PyString s) { - PyInteger v = (PyInteger)re.groupindex.__finditem__(s); - if (v == null) - throw Py.IndexError("group '"+s+"' is undefined"); - return v.getValue(); - } - - private String group(int i) { - if (i >= match.groups()) { - throw Py.IndexError("group "+i+" is undefined"); - } - return match.group(i); - } - - private String group(PyString s) { - return group(getindex(s)); - } - - private PyObject group(PyObject o) { - String s; - - if (o instanceof PyInteger) { - s = group(((PyInteger)o).getValue()); - } else if (o instanceof PyString) { - s = group((PyString)o); - } else { - throw org.python.modules.re.ReError( - "group index must be a string or integer"); - } - if (s == null) - return Py.None; - else - return new PyString(s); - } - - public PyObject group(PyObject[] args) { - int n = args.length; - - if (n == 0) - return new PyString(group(0)); - if (n == 1) - return group(args[0]); - - PyObject[] res = new PyObject[n]; - for(int i=0; i < n; i++) { - res[i] = group(args[i]); - } - return new PyTuple(res); - } - - public PyObject groupdict() { - return groupdict(Py.None); - } - - public PyObject groupdict(PyObject defalt) { - PyDictionary dict = new PyDictionary(); - PyList items = re.groupindex.items(); - - for (int i=0; i < items.__len__(); i++) { - PyTuple t = (PyTuple)items.__getitem__(i); - PyString name = (PyString)t.__getitem__(0); - PyInteger index = (PyInteger)t.__getitem__(1); - - String s = group(index.getValue()); - if (s == null) - dict.__setitem__(name, defalt); - else - dict.__setitem__(name, new PyString(s)); - } - return dict; - } -} Deleted: branches/2.3/src/org/python/modules/RegexObject.java =================================================================== --- branches/2.3/src/org/python/modules/RegexObject.java 2007-02-22 05:29:40 UTC (rev 3116) +++ branches/2.3/src/org/python/modules/RegexObject.java 2007-02-22 05:40:25 UTC (rev 3117) @@ -1,526 +0,0 @@ -// Copyright (c) Corporation for National Research Initiatives -package org.python.modules; - -import org.python.core.*; -import org.apache.oro.text.regex.*; - - -public class RegexObject extends PyObject -{ - private static Perl5Compiler compiler = new Perl5Compiler(); - - private static synchronized Pattern compile(String pattern, int flags) { - try { - return compiler.compile(pattern, flags); - } - catch (MalformedPatternException e) { - throw re.ReError(e.getMessage()); - } - } - - private static synchronized Perl5Matcher getMatcher() { - Perl5Matcher matcher = new Perl5Matcher(); - //matcher.setMultiline(false); - return matcher; - } - - public String pattern; - public int flags; - public PyDictionary groupindex; - private Pattern code; - - public RegexObject(String pattern, int flags) { - this.pattern = pattern; - this.flags = flags; - groupindex = new PyDictionary(); - code = compile(fixPattern(pattern), flags); - } - - public MatchObject match(String string) { - MatchResult result = doMatch(string); - if (result == null) - return null; - return new MatchObject(this, string, 0, string.length(), result); - } - - public MatchObject match(String s, int pos) { - return match(s, pos, s.length()); - } - - public MatchObject match(String string, int pos, int endpos) { - if (endpos > string.length()) - endpos = string.length(); - if (endpos < pos) - endpos = pos; - - MatchResult result = - doMatch(new PatternMatcherInput(string, pos, endpos-pos)); - if (result == null) - return null; - return new MatchObject(this, string, pos, endpos, result); - } - - private MatchResult doMatch(Object input) { - Perl5Matcher matcher = getMatcher(); - if (input instanceof String) { - if (!matcher.matchesPrefix((String)input, code)) - return null; - } - else { - if (!matcher.matchesPrefix((PatternMatcherInput)input, code)) - return null; - } - return matcher.getMatch(); - } - - public MatchObject search(String string) { - MatchResult result = doSearch(string); - if (result == null) - return null; - return new MatchObject(this, string, 0, string.length(), result); - } - - public MatchObject search(String s, int pos) { - return search(s, pos, s.length()); - } - - public MatchObject search(String string, int pos, int endpos) { - if (endpos > string.length()) - endpos = string.length(); - if (endpos < pos) - endpos = pos; - - MatchResult result = - doSearch(new PatternMatcherInput(string, pos, endpos-pos)); - if (result == null) - return null; - return new MatchObject(this, string, pos, endpos, result); - } - - private MatchResult doSearch(Object input) { - Perl5Matcher matcher = getMatcher(); - - if (input instanceof String) { - if (!matcher.contains((String)input, code)) - return null; - } - else { - if (!matcher.contains((PatternMatcherInput)input, code)) - return null; - } - return matcher.getMatch(); - } - - public PyString sub(PyObject repl, String string) { - return sub(repl, string, 0); - } - - public PyString sub(PyObject repl, String string, int count) { - return (PyString)subn(repl, string, count).__getitem__(0); - } - - public PyTuple subn(PyObject repl, String string) { - return subn(repl, string, 0); - } - - public PyTuple subn(PyObject repl, String string, int count) { - // Real work is done here - String srepl = null; - boolean expand = false; - if (repl instanceof PyString) { - srepl = repl.toString(); - expand = (srepl.indexOf('\\') != -1); - } - if (count < 0) { - throw re.ReError("negative substitution count"); - } - if (count == 0) { - count = Integer.MAX_VALUE; - } - - // How to handle repl as String vs. callable? - int n=0; - StringBuffer buf = new StringBuffer(); - Perl5Matcher matcher = getMatcher(); - PatternMatcherInput match = new PatternMatcherInput(string); - int lastmatch = 0; - - while (n < count && !match.endOfInput()) { - if (!matcher.contains(match, code)) - break; - n++; - int offset = match.getMatchBeginOffset(); - //System.err.println("off: "+offset+", "+lastmatch); - if (offset > lastmatch) { - buf.append(match.substring(lastmatch, offset)); - } - if (srepl == null) { - MatchObject m = new MatchObject(this, string, lastmatch, - string.length(), - matcher.getMatch()); - PyObject ret = repl.__call__(m); - buf.append(ret.toString()); - } - else { - if (expand) - buf.append(expandMatch(matcher.getMatch(), srepl)); - else - buf.append(srepl); - } - lastmatch = match.getMatchEndOffset(); - } - if (lastmatch < match.getEndOffset()) { - buf.append(match.substring(lastmatch, match.getEndOffset())); - } - return new PyTuple( - new PyObject[] { - new PyString(buf.toString()), - new PyInteger(n) - }); - } - - public PyList split(String string) { - return split(string, 0); - } - - public PyList split(String string, int maxsplit) { - if (maxsplit < 0) { - throw re.ReError("maxsplit < 0"); - } - if (maxsplit == 0) { - maxsplit = Integer.MAX_VALUE; - } - - int n=0; - Perl5Matcher matcher = getMatcher(); - PatternMatcherInput match = new PatternMatcherInput(string); - int lastmatch = 0; - PyList results = new PyList(); - - while (n < maxsplit && !match.endOfInput()) { - if (!matcher.contains(match, code)) - break; - n++; - - int begin = match.getMatchBeginOffset(); - int end = match.getMatchEndOffset(); - - if (begin == end) { - // More needed? - continue; - } - - results.append(new PyString(match.substring(lastmatch, begin))); - - MatchResult m = matcher.getMatch(); - int ngroups = m.groups(); - if (ngroups > 1) { - for (int j=1; j<ngroups; j++) { - String tmp = m.group(j); - if (tmp == null) { - results.append(Py.None); - } - else { - results.append(new PyString(tmp)); - } - } - } - lastmatch = end; - } - results.append( - new PyString(match.substring(lastmatch, match.getEndOffset()))); - return results; - } - - private int getindex(PyString s) { - PyInteger v = (PyInteger)groupindex.__finditem__(s); - if (v == null) { - try { - v = (PyInteger)s.__int__(); - } - catch (PyException exc) { - if (!isname(s.toString())) - throw re.ReError("illegal character in group name"); - else - throw Py.IndexError("group "+s.__repr__() + - " is undefined"); - } - } - return v.getValue(); - } - - private boolean isdigit(char c) { - return '0' <= c && c <= '9'; - } - - private boolean isident(char c) { - return ('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z') || (c == '_'); - } - - private boolean isname(String name) { - int n = name.length(); - if (n <= 0 || !isident(name.charAt(0))) - return false; - for (int i = 1; i < n; i++) { - char c = name.charAt(i); - if (!isident(c) && !isdigit(c)) - return false; - } - return true; - } - - private String fixPattern(String pattern) { - char[] chars = pattern.toCharArray(); - - int index=0; - int group=1; - int lasti=0; - int n = chars.length; - - StringBuffer buf = new StringBuffer(); - - while (index < n) { - if (chars[index++] == '(') { - // Ignore \( because these are literal parens - if (index > 2 && chars[index-2] == '\\') - continue; - - if (index < n && chars[index] == '?') { - index++; - if (index < n && chars[index] == 'P') { - index++; - if (index == n) - break; - char c = chars[index++]; - int start = index; - if (c == '<') { - while (index < n && chars[index] != '>') - index++; - if (index == n) - throw re.ReError("unmatched <"); - String name = - new String(chars, start, index-start); - // name must be a valid Python identifier - if (!isname(name)) - throw re.ReError("illegal character in " + - "group name"); - groupindex.__setitem__(new PyString(name), - new PyInteger(group)); - buf.append(chars, lasti, start-3-lasti); - index++; - lasti = index; - group++; - continue; - } - ... [truncated message content] |
From: <cg...@us...> - 2007-02-23 18:07:03
|
Revision: 3119 http://svn.sourceforge.net/jython/?rev=3119&view=rev Author: cgroves Date: 2007-02-23 10:06:54 -0800 (Fri, 23 Feb 2007) Log Message: ----------- merge -r 3090:HEAD https://jython.svn.sourceforge.net/svnroot/jython/trunk/jython Modified Paths: -------------- branches/2.3/LICENSE.txt branches/2.3/Lib/test/test_jbasic.py branches/2.3/Lib/test/test_sax.py branches/2.3/Lib/test/test_types.py branches/2.3/build.Lib.include.properties branches/2.3/build.xml branches/2.3/src/org/python/core/Py.java branches/2.3/src/org/python/core/PyDictionary.java branches/2.3/src/org/python/core/PyMethodDescr.java branches/2.3/src/org/python/core/PySystemState.java branches/2.3/src/org/python/util/InteractiveConsole.java branches/2.3/src/org/python/util/TemplateAntTask.java branches/2.3/src/templates/dict.expose branches/2.3/src/templates/gderived.py branches/2.3/src/templates/gexpose-defs branches/2.3/src/templates/gexpose.py branches/2.3/src/templates/mappings Added Paths: ----------- branches/2.3/src/org/python/core/PyClassMethodDescr.java Modified: branches/2.3/LICENSE.txt =================================================================== --- branches/2.3/LICENSE.txt 2007-02-22 05:44:02 UTC (rev 3118) +++ branches/2.3/LICENSE.txt 2007-02-23 18:06:54 UTC (rev 3119) @@ -1,25 +1,56 @@ -A. HISTORY OF THE SOFTWARE -======================= -JPython was created in late 1997 by Jim Hugunin. Jim was also the -primary developer while he was at CNRI. In February 1999 Barry Warsaw -took over as primary developer and released JPython version 1.1. +A. TERMS AND CONDITIONS FOR ACCESSING OR OTHERWISE USING JYTHON +======================================================= -In October 2000 Barry helped move the software to SourceForge -where it was renamed to Jython. Jython 2.0 and on are licensed under -the Jython specific license below. +PYTHON SOFTWARE FOUNDATION LICENSE VERSION 2 +-------------------------------------------- -The standard library is covered by the Python Software Foundation -license. See the LICENSE_CPython.txt file for details. +1. This LICENSE AGREEMENT is between the Python Software Foundation +("PSF"), and the Individual or Organization ("Licensee") accessing and +otherwise using this software ("Jython") in source or binary form and +its associated documentation. -The zxJDBC package was written by Brian Zimmer and originally licensed -under the GNU Public License. The package is now covered by the Jython -Software License. +2. Subject to the terms and conditions of this License Agreement, PSF +hereby grants Licensee a nonexclusive, royalty-free, world-wide +license to reproduce, analyze, test, perform and/or display publicly, +prepare derivative works, distribute, and otherwise use Jython alone +or in any derivative version, provided, however, that PSF's License +Agreement and PSF's notice of copyright, i.e., "Copyright (c) 2007 +Python Software Foundation; All Rights Reserved" are retained in +Jython alone or in any derivative version prepared by Licensee. -The command line interpreter is covered by the Apache Software -License. See the LICENSE_Apache.txt file for details. +3. In the event Licensee prepares a derivative work that is based on +or incorporates Jython or any part thereof, and wants to make +the derivative work available to others as provided herein, then +Licensee hereby agrees to include in any such work a brief summary of +the changes made to Jython. + +4. PSF is making Jython available to Licensee on an "AS IS" +basis. PSF MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR +IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, PSF MAKES NO AND +DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS +FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF JYTHON WILL NOT +INFRINGE ANY THIRD PARTY RIGHTS. + +5. PSF SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF JYTHON +FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS +A RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING JYTHON, +OR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF. + +6. This License Agreement will automatically terminate upon a material +breach of its terms and conditions. + +7. Nothing in this License Agreement shall be deemed to create any +relationship of agency, partnership, or joint venture between PSF and +Licensee. This License Agreement does not grant permission to use PSF +trademarks or trade name in a trademark sense to endorse or promote +products or services of Licensee, or any third party. + +8. By copying, installing or otherwise using Jython, Licensee +agrees to be bound by the terms and conditions of this License +Agreement. -B. TERMS AND CONDITIONS FOR ACCESSING OR OTHERWISE USING JYTHON +Jython 2.0, 2.1 License ================================ Copyright (c) 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007 Jython Developers @@ -142,3 +173,28 @@ [ACCEPT BUTTON] +B. HISTORY OF THE SOFTWARE +======================================================= + +JPython was created in late 1997 by Jim Hugunin. Jim was also the +primary developer while he was at CNRI. In February 1999 Barry Warsaw +took over as primary developer and released JPython version 1.1. + +In October 2000 Barry helped move the software to SourceForge +where it was renamed to Jython. Jython 2.0 and 2.1 were developed +under the Jython specific license below. + +From the 2.2 release on, Jython contributors have signed +Python Software Foundation contributor agreements and releases are +covered under the Python Software Foundation license version 2. + +The standard library is covered by the Python Software Foundation +license as well. See the Lib/LICENSE file for details. + +The zxJDBC package was written by Brian Zimmer and originally licensed +under the GNU Public License. The package is now covered by the Jython +Software License. + +The command line interpreter is covered by the Apache Software +License. See the org/apache/LICENSE file for details. + Modified: branches/2.3/Lib/test/test_jbasic.py =================================================================== --- branches/2.3/Lib/test/test_jbasic.py 2007-02-22 05:44:02 UTC (rev 3118) +++ branches/2.3/Lib/test/test_jbasic.py 2007-02-23 18:06:54 UTC (rev 3119) @@ -78,9 +78,10 @@ print_test('get/set bean properties') -b1 = awt.Button() +from javax import swing +b1 = swing.JButton() b1.label = 'foo' -b2 = awt.Button(label='foo') +b2 = swing.JButton(label='foo') assert b1.label == b2.label == 'foo', 'Button label bean property' print_test('bean event properties') @@ -94,17 +95,17 @@ b1.actionPerformed = testAction flag = 0 -b1.dispatchEvent(doit) -assert flag == 1, 'one action per event' +b1.doClick() +assert flag == 1, 'expected one action per event but got %s' % flag b1.actionPerformed.append(testAction) flag = 0 -b1.dispatchEvent(doit) +b1.doClick() assert flag == 2, 'two actions per event' b1.actionPerformed = testAction flag = 0 -b1.dispatchEvent(doit) +b1.doClick() assert flag == 1, 'one actions per event - again' # TBD: JPython does not properly exit after this code! Modified: branches/2.3/Lib/test/test_sax.py =================================================================== --- branches/2.3/Lib/test/test_sax.py 2007-02-22 05:44:02 UTC (rev 3118) +++ branches/2.3/Lib/test/test_sax.py 2007-02-23 18:06:54 UTC (rev 3119) @@ -707,9 +707,16 @@ outf.write(result.getvalue()) outf.close() +import sys +java_14 = sys.platform.startswith("java1.4") +del sys + items = locals().items() items.sort() for (name, value) in items: + if name.startswith('test_expat') and java_14: + #skip expat tests on java14 since the crimson parser is so crappy + continue if name[:5] == "test_": confirm(value(), name) Modified: branches/2.3/Lib/test/test_types.py =================================================================== --- branches/2.3/Lib/test/test_types.py 2007-02-22 05:44:02 UTC (rev 3118) +++ branches/2.3/Lib/test/test_types.py 2007-02-23 18:06:54 UTC (rev 3119) @@ -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__' Modified: branches/2.3/build.Lib.include.properties =================================================================== --- branches/2.3/build.Lib.include.properties 2007-02-22 05:44:02 UTC (rev 3118) +++ branches/2.3/build.Lib.include.properties 2007-02-23 18:06:54 UTC (rev 3119) @@ -111,6 +111,7 @@ symbol.py telnetlib.py tempfile.py +this.py threading.py textwrap.py token.py Modified: branches/2.3/build.xml =================================================================== --- branches/2.3/build.xml 2007-02-22 05:44:02 UTC (rev 3118) +++ branches/2.3/build.xml 2007-02-23 18:06:54 UTC (rev 3119) @@ -15,12 +15,12 @@ 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 level as your local directories jython, sandbox and installer. -It will contain a big jython_installer_${svn.tag}.jar file suitable for installation. +It will contain a big jython_installer-${jython.version}.jar file suitable for installation. Please be aware: To build older releases, it may be necessary to use an older build.xml, too (with the corresponding tag). @@ -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,7 +102,7 @@ # - 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 @@ -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" /> @@ -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" /> @@ -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> @@ -213,11 +214,8 @@ <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}" /> - <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" /> @@ -228,11 +226,14 @@ <condition property="do.checkout" value="true"> <istrue value="${has.repositories.connection}" /> </condition> - <condition property="do.snapshot.build" value="true"> - <not> - <equals arg1="${svn.revision}" arg2="${svn.tag}" /> - </not> + <condition property="do.snapshot.build"> + <isset property="svn.revision" /> </condition> + <condition property="jython.version" value="${svn.revision}"> + <isset property="svn.revision" /> + </condition> + <property name="jython.version" value="2.2b1" /> + <property name="svn.revision" value="HEAD"/> <!-- classpath for svn ant task --> <path id="svn.classpath"> @@ -364,13 +365,13 @@ </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 --> + <!-- checkout cpython license from the correct python maintenance branch --> <svn javahl="${javahl.dir}" > - <checkout url="http://svn.python.org/projects/python/branches/release22-maint/" destPath="${svn.checkout.dir}/python" recurse="false" /> + <checkout url="http://svn.python.org/projects/python/branches/release22-maint/" destPath="${svn.checkout.dir}/python" recurse="false" /> </svn> </target> @@ -378,8 +379,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 = 0x0A" 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}" /> @@ -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> @@ -506,7 +495,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.revision}" /> + <attribute name="version" value="${jython.version}" /> <attribute name="svn-build" value="${do.checkout}" /> <attribute name="threadlocal" value="${threadlocal.present}" /> <attribute name="secureclassloader" value="${secureclassloader.present}" /> @@ -667,13 +656,13 @@ <fileset dir="${install.src.dir}" includes="**/*.png" excludes="bin/**" /> </copy> <echo>building installer .jar file</echo> - <jar destfile="${work.dir}/jython_installer_${svn.revision}.jar" basedir="${dist.dir}" update="true"> + <jar destfile="${work.dir}/jython_installer-${jython.version}.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.revision}" /> + <attribute name="version" value="${jython.version}" /> <attribute name="exclude-dirs" value="org;META-INF" /> </section> <!-- info section. ATTN: no blanks, no '.' in the names --> Modified: branches/2.3/src/org/python/core/Py.java =================================================================== --- branches/2.3/src/org/python/core/Py.java 2007-02-22 05:44:02 UTC (rev 3118) +++ branches/2.3/src/org/python/core/Py.java 2007-02-23 18:06:54 UTC (rev 3119) @@ -405,29 +405,18 @@ public static PyObject JavaError; public static PyException JavaError(Throwable t) { -// System.err.println("t: "+t); - if (t instanceof PyException) { + if(t instanceof PyException) { return (PyException)t; - } - else if (t instanceof InvocationTargetException) { - return JavaError( - ((InvocationTargetException)t).getTargetException()); - } -// Remove this automatic coercion, people want to see the real -// exceptions! -// else if (t instanceof java.io.IOException) { -// return IOError((java.io.IOException)t); -// } -// see corresponding logic in matchException - else if (t instanceof OutOfMemoryError) { + } else if(t instanceof InvocationTargetException) { + return JavaError(((InvocationTargetException)t).getTargetException()); + } else if(t instanceof OutOfMemoryError) { memory_error((OutOfMemoryError)t); } - PyJavaInstance exc = (PyJavaInstance)Py.java2py(t); + PyJavaInstance exc = new PyJavaInstance(t); return new PyException(exc.instclass, exc); - } - // Don't allow any constructors. Class only provides static methods. + // Don't allow any constructors. Class only provides static methods. private Py() { ; } /** @deprecated **/ @@ -680,7 +669,12 @@ SyntaxWarning = initExc("SyntaxWarning", exc, dict); OverflowWarning = initExc("OverflowWarning", exc, dict); RuntimeWarning = initExc("RuntimeWarning", exc, dict); - FutureWarning = initExc("FutureWarning", exc, dict); + FutureWarning = initExc("FutureWarning", exc, dict); + + // Pre-initialize the PyJavaClass for OutOfMemoryError so when we need + // it it creating the pieces for it won't cause an additional out of + // memory error. Fix for bug #1654484 + PyJavaClass.lookup(java.lang.OutOfMemoryError.class); } public static PySystemState defaultSystemState; @@ -1132,7 +1126,6 @@ /* Helpers to implement except clauses */ public static PyException setException(Throwable t, PyFrame frame) { - //System.out.println("Py.setException"); PyException pye = Py.JavaError(t); pye.instantiate(); @@ -1155,44 +1148,28 @@ // A special case for IOError's to allow them to also match // java.io.IOExceptions. This is a hack for 1.0.x until I can do // it right in 1.1 - if (e == Py.IOError) { - if (__builtin__.isinstance( - pye.value, - PyJavaClass.lookup(java.io.IOException.class))) - { + if(e == Py.IOError) { + if(__builtin__.isinstance(pye.value, + PyJavaClass.lookup(java.io.IOException.class))) { return true; } } // FIXME too, same approach for OutOfMemoryError - if (e == Py.MemoryError) { - if (__builtin__.isinstance( - pye.value, - PyJavaClass.lookup(java.lang.OutOfMemoryError.class))) - { + if(e == Py.MemoryError) { + if(__builtin__.isinstance(pye.value, + PyJavaClass.lookup(java.lang.OutOfMemoryError.class))) { return true; } - } - if (e == Py.IOError) { - if (__builtin__.isinstance( - pye.value, - PyJavaClass.lookup(java.io.IOException.class))) - { - return true; - } } - // same approach for OutOfMemoryError - - if (e instanceof PyClass) { + if(e instanceof PyClass) { return __builtin__.isinstance(pye.value, (PyClass)e); - } - else { - if (e == pye.type) + } else { + if(e == pye.type) return true; - - if (e instanceof PyTuple) { + if(e instanceof PyTuple) { PyObject[] l = ((PyTuple)e).getArray(); - for (int i=0; i<l.length; i++) { - if (matchException(pye, l[i])) + for(int i = 0; i < l.length; i++) { + if(matchException(pye, l[i])) return true; } } Added: branches/2.3/src/org/python/core/PyClassMethodDescr.java =================================================================== --- branches/2.3/src/org/python/core/PyClassMethodDescr.java (rev 0) +++ branches/2.3/src/org/python/core/PyClassMethodDescr.java 2007-02-23 18:06:54 UTC (rev 3119) @@ -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: branches/2.3/src/org/python/core/PyDictionary.java =================================================================== --- branches/2.3/src/org/python/core/PyDictionary.java 2007-02-22 05:44:02 UTC (rev 3118) +++ branches/2.3/src/org/python/core/PyDictionary.java 2007-02-23 18:06:54 UTC (rev 3119) @@ -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: branches/2.3/src/org/python/core/PyMethodDescr.java =================================================================== --- branches/2.3/src/org/python/core/PyMethodDescr.java 2007-02-22 05:44:02 UTC (rev 3118) +++ branches/2.3/src/org/python/core/PyMethodDescr.java 2007-02-23 18:06:54 UTC (rev 3119) @@ -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: branches/2.3/src/org/python/core/PySystemState.java =================================================================== --- branches/2.3/src/org/python/core/PySystemState.java 2007-02-22 05:44:02 UTC (rev 3118) +++ branches/2.3/src/org/python/core/PySystemState.java 2007-02-23 18:06:54 UTC (rev 3119) @@ -67,7 +67,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" + @@ -617,7 +617,7 @@ private static PyList initPath(Properties props, boolean standalone, String jarFileName) { PyList path = new PyList(); if (!Py.frozen) { - addPaths(path, props.getProperty("python.prepath", ".")); + addPaths(path, props.getProperty("python.prepath", "")); if (prefix != null) { String libpath = new File(prefix, "Lib").toString(); Modified: branches/2.3/src/org/python/util/InteractiveConsole.java =================================================================== --- branches/2.3/src/org/python/util/InteractiveConsole.java 2007-02-22 05:44:02 UTC (rev 3118) +++ branches/2.3/src/org/python/util/InteractiveConsole.java 2007-02-23 18:06:54 UTC (rev 3119) @@ -32,11 +32,8 @@ } public static String getDefaultBanner() { - String compiler = System.getProperty("java.compiler"); - - return "Jython " + PySystemState.version + " on " + - PySystemState.platform + " (JIT: " + - ((compiler == null) ? "null" : compiler) + ")"; + return "Jython " + PySystemState.version + " on " + + PySystemState.platform; } public void interact(String banner) { Modified: branches/2.3/src/org/python/util/TemplateAntTask.java =================================================================== --- branches/2.3/src/org/python/util/TemplateAntTask.java 2007-02-22 05:44:02 UTC (rev 3118) +++ branches/2.3/src/org/python/util/TemplateAntTask.java 2007-02-23 18:06:54 UTC (rev 3119) @@ -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: branches/2.3/src/templates/dict.expose =================================================================== --- branches/2.3/src/templates/dict.expose 2007-02-22 05:44:02 UTC (rev 3118) +++ branches/2.3/src/templates/dict.expose 2007-02-23 18:06:54 UTC (rev 3119) @@ -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: branches/2.3/src/templates/gderived.py =================================================================== --- branches/2.3/src/templates/gderived.py 2007-02-22 05:44:02 UTC (rev 3118) +++ branches/2.3/src/templates/gderived.py 2007-02-23 18:06:54 UTC (rev 3119) @@ -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: branches/2.3/src/templates/gexpose-defs =================================================================== --- branches/2.3/src/templates/gexpose-defs 2007-02-22 05:44:02 UTC (rev 3118) +++ branches/2.3/src/templates/gexpose-defs 2007-02-23 18:06:54 UTC (rev 3119) @@ -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: branches/2.3/src/templates/gexpose.py =================================================================== --- branches/2.3/src/templates/gexpose.py 2007-02-22 05:44:02 UTC (rev 3118) +++ branches/2.3/src/templates/gexpose.py 2007-02-23 18:06:54 UTC (rev 3119) @@ -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) Modified: branches/2.3/src/templates/mappings =================================================================== --- branches/2.3/src/templates/mappings 2007-02-22 05:44:02 UTC (rev 3118) +++ branches/2.3/src/templates/mappings 2007-02-23 18:06:54 UTC (rev 3119) @@ -22,7 +22,7 @@ #file.e... [truncated message content] |
From: <cg...@us...> - 2007-04-17 08:21:26
|
Revision: 3161 http://svn.sourceforge.net/jython/?rev=3161&view=rev Author: cgroves Date: 2007-04-17 01:21:25 -0700 (Tue, 17 Apr 2007) Log Message: ----------- merge -r 3145:HEAD https://jython.svn.sourceforge.net/svnroot/jython/trunk/jython Modified Paths: -------------- branches/2.3/Lib/test/output/test_extcall branches/2.3/Lib/test/regrtest.py branches/2.3/Lib/test/test_descr.py branches/2.3/Lib/test/test_descrtut.py branches/2.3/Lib/test/test_unicode.py branches/2.3/Lib/xml/sax/_exceptions.py branches/2.3/NEWS branches/2.3/src/org/python/core/PyArray.java branches/2.3/src/org/python/core/PyComplex.java branches/2.3/src/org/python/core/PyDictionary.java branches/2.3/src/org/python/core/PyFile.java branches/2.3/src/org/python/core/PyFloat.java branches/2.3/src/org/python/core/PyInteger.java branches/2.3/src/org/python/core/PyList.java branches/2.3/src/org/python/core/PyLong.java branches/2.3/src/org/python/core/PyModule.java branches/2.3/src/org/python/core/PySequence.java branches/2.3/src/org/python/core/PyString.java branches/2.3/src/org/python/core/PySystemState.java branches/2.3/src/org/python/core/PyTuple.java branches/2.3/src/org/python/core/PyUnicode.java branches/2.3/src/org/python/core/__builtin__.java branches/2.3/src/org/python/util/TemplateAntTask.java branches/2.3/src/templates/complex.expose branches/2.3/src/templates/dict.expose branches/2.3/src/templates/float.expose branches/2.3/src/templates/int.expose branches/2.3/src/templates/long.expose branches/2.3/src/templates/mappings branches/2.3/src/templates/sequence.expose branches/2.3/src/templates/str.expose branches/2.3/src/templates/tuple.expose branches/2.3/src/templates/unicode.expose Added Paths: ----------- branches/2.3/Lib/test/test_module.py branches/2.3/src/org/python/core/PyModuleDerived.java Modified: branches/2.3/Lib/test/output/test_extcall =================================================================== --- branches/2.3/Lib/test/output/test_extcall 2007-04-17 08:16:17 UTC (rev 3160) +++ branches/2.3/Lib/test/output/test_extcall 2007-04-17 08:21:25 UTC (rev 3161) @@ -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: branches/2.3/Lib/test/regrtest.py =================================================================== --- branches/2.3/Lib/test/regrtest.py 2007-04-17 08:16:17 UTC (rev 3160) +++ branches/2.3/Lib/test/regrtest.py 2007-04-17 08:21:25 UTC (rev 3161) @@ -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: branches/2.3/Lib/test/test_descr.py =================================================================== --- branches/2.3/Lib/test/test_descr.py 2007-04-17 08:16:17 UTC (rev 3160) +++ branches/2.3/Lib/test/test_descr.py 2007-04-17 08:21:25 UTC (rev 3161) @@ -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 @@ -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..." @@ -749,8 +761,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) Modified: branches/2.3/Lib/test/test_descrtut.py =================================================================== --- branches/2.3/Lib/test/test_descrtut.py 2007-04-17 08:16:17 UTC (rev 3160) +++ branches/2.3/Lib/test/test_descrtut.py 2007-04-17 08:21:25 UTC (rev 3161) @@ -189,14 +189,18 @@ '__delslice__', '__doc__', '__eq__', + '__ge__', '__getattribute__', '__getitem__', '__getslice__', + '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', + '__le__', '__len__', + '__lt__', '__mul__', '__ne__', '__new__', Copied: branches/2.3/Lib/test/test_module.py (from rev 3159, trunk/jython/Lib/test/test_module.py) =================================================================== --- branches/2.3/Lib/test/test_module.py (rev 0) +++ branches/2.3/Lib/test/test_module.py 2007-04-17 08:21:25 UTC (rev 3161) @@ -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: branches/2.3/Lib/test/test_unicode.py =================================================================== --- branches/2.3/Lib/test/test_unicode.py 2007-04-17 08:16:17 UTC (rev 3160) +++ branches/2.3/Lib/test/test_unicode.py 2007-04-17 08:21:25 UTC (rev 3161) @@ -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: branches/2.3/Lib/xml/sax/_exceptions.py =================================================================== --- branches/2.3/Lib/xml/sax/_exceptions.py 2007-04-17 08:16:17 UTC (rev 3160) +++ branches/2.3/Lib/xml/sax/_exceptions.py 2007-04-17 08:21:25 UTC (rev 3161) @@ -1,8 +1,4 @@ """Different kinds of SAX Exceptions""" -import sys -if sys.platform[:4] == "java": - from java.lang import Exception -del sys # ===== SAXEXCEPTION ===== Modified: branches/2.3/NEWS =================================================================== --- branches/2.3/NEWS 2007-04-17 08:16:17 UTC (rev 3160) +++ branches/2.3/NEWS 2007-04-17 08:21:25 UTC (rev 3161) @@ -1,7 +1,35 @@ Jython NEWS +Jython 2.2 beta2 + New features + - All functions in __builtin__ are new style functions instead of reflected + functions + - Classmethods added to newstyle classes + - array is a newstyle class + + Bugs fixed + - [ 1599012 ] current directory is prepended to entries in sys.path + - [ 1654484 ] Initializing PyJavaClass for java.lang.OutOfMemory causes a further OutOfMemory problem + - [ 1661679 ] types.UnicodeType is str + - [ 1659819 ] Joining unicode items with string doesn't create unicode + - [ 1603253 ] Thread's setDaemon setting does not work + - types module uses newstyle classes + - [ 1671134 ] '%s' % u'x' returns str object + - [ 1672800 ] __import__('module', None) raises AttributeError + - [ 1576036 ] Fix: SyspathJavaLoader file reader causes importerror + - [ 1605847 ] co_filename set in bytecode doesn't match __file__ + - [ 1603312 ] subclasses of int raise a TypeError when given large value + - [ 1603315 ] str missing object keyword arg + - [ 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 + Patches applied + - [ 1681774 ] str.decode, unicode.encode and str(u'') fixes + - [ 1682423 ] Convert PyModule to a new-style class + - [ 1682498 ] Fix int(None) raising an AttributeError + 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: branches/2.3/src/org/python/core/PyArray.java =================================================================== --- branches/2.3/src/org/python/core/PyArray.java 2007-04-17 08:16:17 UTC (rev 3160) +++ branches/2.3/src/org/python/core/PyArray.java 2007-04-17 08:21:25 UTC (rev 3161) @@ -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: branches/2.3/src/org/python/core/PyComplex.java =================================================================== --- branches/2.3/src/org/python/core/PyComplex.java 2007-04-17 08:16:17 UTC (rev 3160) +++ branches/2.3/src/org/python/core/PyComplex.java 2007-04-17 08:21:25 UTC (rev 3161) @@ -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: branches/2.3/src/org/python/core/PyDictionary.java =================================================================== --- branches/2.3/src/org/python/core/PyDictionary.java 2007-04-17 08:16:17 UTC (rev 3160) +++ branches/2.3/src/org/python/core/PyDictionary.java 2007-04-17 08:21:25 UTC (rev 3161) @@ -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: branches/2.3/src/org/python/core/PyFile.java =================================================================== --- branches/2.3/src/org/python/core/PyFile.java 2007-04-17 08:16:17 UTC (rev 3160) +++ branches/2.3/src/org/python/core/PyFile.java 2007-04-17 08:21:25 UTC (rev 3161) @@ -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: branches/2.3/src/org/python/core/PyFloat.java =================================================================== --- branches/2.3/src/org/python/core/PyFloat.java 2007-04-17 08:16:17 UTC (rev 3160) +++ branches/2.3/src/org/python/core/PyFloat.java 2007-04-17 08:21:25 UTC (rev 3161) @@ -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) { @@ -882,7 +920,11 @@ ); } + final PyObject float___rdivmod__(PyObject left) { + return __rdivmod__(left); + } + public PyObject __pow__(PyObject right, PyObject modulo) { return float___pow__(right, modulo); } @@ -898,7 +940,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: branches/2.3/src/org/python/core/PyInteger.java =================================================================== --- branches/2.3/src/org/python/core/PyInteger.java 2007-04-17 08:16:17 UTC (rev 3160) +++ branches/2.3/src/org/python/core/PyInteger.java 2007-04-17 08:21:25 UTC (rev 3161) @@ -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) { @@ -683,30 +816,27 @@ if (x == null) { return Py.Zero; } - if (base == -909) { + if (base == -909) { if (x instanceof PyBoolean) { return (coerce(x) == 0) ? Py.Zero : Py.One; } - return x.__int__(); - } - if (!(x instanceof PyString)) { - throw Py - .TypeError("int: can't convert non-string with explicit base"); - } + 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 @@ -715,6 +845,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); @@ -1040,7 +1184,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); } @@ -1064,6 +1221,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) { @@ -1147,7 +1308,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); } @@ -1165,6 +1340,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); } @@ -1174,6 +1362,10 @@ return null; return Py.newInteger(getValue() & coerce(right)); } + + final PyObject int___rand__(PyObject left){ + return int___and__(left); + } public PyObject __xor__(PyObject right) { return int___xor__(right); @@ -1188,7 +1380,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); } @@ -1202,6 +1404,10 @@ return Py.newInteger(getValue() | rightv); } + + final PyObject int___ror__(PyObject left){ + return int___or__(left); + } public PyObject __neg__() { return int___neg__(); Modified: branches/2.3/src/org/python/core/PyList.java =================================================================== --- branches/2.3/src/org/python/core/PyList.java 2007-04-17 08:16:17 UTC (rev 3160) +++ branches/2.3/src/org/python/core/PyList.java 2007-04-17 08:21:25 UTC (rev 3161) @@ -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: branches/2.3/src/org/python/core/PyLong.java =================================================================== --- branches/2.3/src/org/python/core/PyLong.java 2007-04-17 08:16:17 UTC (rev 3160) +++ branches/2.3/src/org/python/core/PyLong.java 2007-04-17 08:21:25 UTC (rev 3161) @@ -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) { @@ -763,6 +912,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) { @@ -1205,6 +1358,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); } @@ -1218,6 +1379,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: branches/2.3/src/org/python/core/PyModule.java =================================================================== --- branches/2.3/src/org/python/core/PyModule.java 2007-04-17 08:16:17 UTC (rev 3160) +++ branches/2.3/src/org/python/core/PyModule.java 2007-04-17 08:21:25 UTC (rev 3161) @@ -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__")... [truncated message content] |
From: <cg...@us...> - 2007-04-24 05:41:20
|
Revision: 3185 http://svn.sourceforge.net/jython/?rev=3185&view=rev Author: cgroves Date: 2007-04-23 22:41:14 -0700 (Mon, 23 Apr 2007) Log Message: ----------- merge -r 3164:3176 https://jython.svn.sourceforge.net/svnroot/jython/trunk/jython Modified Paths: -------------- branches/2.3/Lib/test/regrtest.py branches/2.3/NEWS branches/2.3/bugtests/driver.py branches/2.3/bugtests/support.py branches/2.3/bugtests/test054.py branches/2.3/bugtests/test086.py branches/2.3/build.xml branches/2.3/src/org/python/compiler/CodeCompiler.java branches/2.3/src/org/python/core/CompilerFlags.java branches/2.3/src/org/python/core/Py.java branches/2.3/src/org/python/core/PyInteger.java branches/2.3/src/org/python/core/imp.java branches/2.3/src/org/python/modules/py_compile.java branches/2.3/src/org/python/util/InteractiveConsole.java branches/2.3/src/org/python/util/ReadlineConsole.java Added Paths: ----------- branches/2.3/bugtests/classes/test395j1.java branches/2.3/bugtests/classes/test395j2.java branches/2.3/bugtests/classes/test396j.java branches/2.3/bugtests/test395.py branches/2.3/bugtests/test396.py branches/2.3/src/org/python/util/JLineConsole.java Property Changed: ---------------- branches/2.3/bugtests/ Modified: branches/2.3/Lib/test/regrtest.py =================================================================== --- branches/2.3/Lib/test/regrtest.py 2007-04-23 15:50:47 UTC (rev 3184) +++ branches/2.3/Lib/test/regrtest.py 2007-04-24 05:41:14 UTC (rev 3185) @@ -1050,6 +1050,7 @@ 'java': ''' test_atexit + test_class test_cpickle test_descr test_descrtut Modified: branches/2.3/NEWS =================================================================== --- branches/2.3/NEWS 2007-04-23 15:50:47 UTC (rev 3184) +++ branches/2.3/NEWS 2007-04-24 05:41:14 UTC (rev 3185) @@ -6,6 +6,8 @@ functions - Classmethods added to newstyle classes - array is a newstyle class + - org.python.util.JLineConsole provides readline-like functionality with + JLine without requiring native readline Bugs fixed - [ 1599012 ] current directory is prepended to entries in sys.path @@ -24,10 +26,15 @@ - [ 1619040 ] dict.fromkeys() should take iterable - [ 1658647 ] type(x) calls x.__class__.__init__ - [ 1699556 ] SAXException descends from Java's Exception instead of Python's + - [ 1603686 ] Unmarshaling long-error + - [ 1230674 ] eval with from future does not work through import + - [ 663592 ] Problems calling an overriden class in the constructor Patches applied - [ 1681774 ] str.decode, unicode.encode and str(u'') fixes - [ 1682423 ] Convert PyModule to a new-style class - [ 1682498 ] Fix int(None) raising an AttributeError + - [ 1684172 ] Changes to make compileall work + Jython 2.2 beta1 New features Property changes on: branches/2.3/bugtests ___________________________________________________________________ Name: svn:ignore - *.jar *.class *.out *.tmp *.ser *.pyc *.err jpywork cachedir support_config.py *.zip *.diff .classpath .project .ipr .iws .iml test246p test302s.py test339p test385jar test385javapackage + *.jar *.class *.out *.tmp *.ser *.pyc *.err jpywork cachedir support_config.py *.zip *.diff .classpath .project .ipr .iws .iml test246p test257s1.py test260s1.py test302s.py test339p test385jar test385javapackage Copied: branches/2.3/bugtests/classes/test395j1.java (from rev 3176, trunk/jython/bugtests/classes/test395j1.java) =================================================================== --- branches/2.3/bugtests/classes/test395j1.java (rev 0) +++ branches/2.3/bugtests/classes/test395j1.java 2007-04-24 05:41:14 UTC (rev 3185) @@ -0,0 +1,4 @@ +public class test395j1 { + protected test395j1() { + } +} Copied: branches/2.3/bugtests/classes/test395j2.java (from rev 3176, trunk/jython/bugtests/classes/test395j2.java) =================================================================== --- branches/2.3/bugtests/classes/test395j2.java (rev 0) +++ branches/2.3/bugtests/classes/test395j2.java 2007-04-24 05:41:14 UTC (rev 3185) @@ -0,0 +1,5 @@ +public class test395j2 extends test395j1 { + private test395j2() { + super(); + } +} Copied: branches/2.3/bugtests/classes/test396j.java (from rev 3176, trunk/jython/bugtests/classes/test396j.java) =================================================================== --- branches/2.3/bugtests/classes/test396j.java (rev 0) +++ branches/2.3/bugtests/classes/test396j.java 2007-04-24 05:41:14 UTC (rev 3185) @@ -0,0 +1,8 @@ +public abstract class test396j { + public test396j() { + abstractMethod(); + } + + public abstract void abstractMethod(); + +} Modified: branches/2.3/bugtests/driver.py =================================================================== --- branches/2.3/bugtests/driver.py 2007-04-23 15:50:47 UTC (rev 3184) +++ branches/2.3/bugtests/driver.py 2007-04-24 05:41:14 UTC (rev 3185) @@ -3,6 +3,7 @@ failures = {} warnings = {} +skipped = {} def runTests(seq): @@ -29,12 +30,15 @@ except support.TestWarning: sys.stdout = stdout report("Warning", warnings, loud=loud_warnings) + except support.TestSkip: + report("Skipped", skipped, loud=0) except: sys.stdout = stdout report("Failed", failures) summarize(failures, "failures") summarize(warnings, "warnings") + summarize(skipped, "skipped") def summarize(errors_dict, description): t = errors_dict.keys() @@ -43,11 +47,14 @@ print t if __name__ == '__main__': - opts, args = getopt.getopt(sys.argv[1:], 'w') + opts, args = getopt.getopt(sys.argv[1:], 'wc', 'skipjythonc') loud_warnings = ('-w',"") in opts + support.test_jythonc = not ('--skipjythonc', '') in opts if loud_warnings: print "LOUD warnings" + if not support.test_jythonc: + print 'Skipping jythonc tests' sys.path[:0] = ['classes'] Modified: branches/2.3/bugtests/support.py =================================================================== --- branches/2.3/bugtests/support.py 2007-04-23 15:50:47 UTC (rev 3184) +++ branches/2.3/bugtests/support.py 2007-04-24 05:41:14 UTC (rev 3185) @@ -14,6 +14,7 @@ UNIX = os.pathsep == ":" WIN = os.pathsep == ";" +test_jythonc = 1 if not UNIX ^ WIN: raise TestError("Unknown platform") @@ -26,6 +27,10 @@ def __init__(self, args): exceptions.Exception.__init__(self, args) +class TestSkip(exceptions.Exception): + def __init__(self, args): + exceptions.Exception.__init__(self, args) + def compare(s, pattern): m = re.search(pattern, str(s)) if m is None: @@ -67,6 +72,9 @@ return ret def compileJava(src, **kw): + classfile = src.replace('.java', '.class') + if os.path.exists(classfile) and os.stat(src).st_mtime < os.stat(classfile).st_mtime: + return 0 classpath = cfg.classpath if "classpath" in kw: classpath = os.pathsep.join([cfg.classpath, kw["classpath"]]) @@ -110,6 +118,8 @@ return execCmd(cmd, kw) def compileJPythonc(*files, **kw): + if not test_jythonc: + raise TestSkip('Skipping pythonc') if os.path.isdir("jpywork") and not kw.has_key("keep"): shutil.rmtree("jpywork", 1) Modified: branches/2.3/bugtests/test054.py =================================================================== --- branches/2.3/bugtests/test054.py 2007-04-23 15:50:47 UTC (rev 3184) +++ branches/2.3/bugtests/test054.py 2007-04-24 05:41:14 UTC (rev 3185) @@ -9,7 +9,7 @@ class Foo: def __repr__(self): - time.sleep(2.0) + time.sleep(0.5) return 'Foo instance' foo = Foo() Modified: branches/2.3/bugtests/test086.py =================================================================== --- branches/2.3/bugtests/test086.py 2007-04-23 15:50:47 UTC (rev 3184) +++ branches/2.3/bugtests/test086.py 2007-04-24 05:41:14 UTC (rev 3185) @@ -15,5 +15,4 @@ mythread().start() mythread("pipo 1").start() mythread("pipo 2").start() -java.lang.Thread.sleep(15000) Copied: branches/2.3/bugtests/test395.py (from rev 3176, trunk/jython/bugtests/test395.py) =================================================================== --- branches/2.3/bugtests/test395.py (rev 0) +++ branches/2.3/bugtests/test395.py 2007-04-24 05:41:14 UTC (rev 3185) @@ -0,0 +1,20 @@ +""" +Classes with greater a protected constructor can be subclassed and instantiated +Tests bug #649582 +""" + +import support + +support.compileJava("classes/test395j1.java") +support.compileJava("classes/test395j2.java") + +import test395j2 + +class Subclass(test395j2): + def __init__(self): + test395j2.__init__(self) + +try: + Subclass() +except AttributeError: + raise support.TestWarning('Unable to access protected superclass constructor') Copied: branches/2.3/bugtests/test396.py (from rev 3176, trunk/jython/bugtests/test396.py) =================================================================== --- branches/2.3/bugtests/test396.py (rev 0) +++ branches/2.3/bugtests/test396.py 2007-04-24 05:41:14 UTC (rev 3185) @@ -0,0 +1,19 @@ +''' +Checks for bug 663592. Used to be that if an abstract Java class called an +abstract method implemented by a Python subclass in its constructor, an +AttributeError would be thrown. +''' +import support + +support.compileJava("classes/test396j.java") + +import test396j + +class Subclass(test396j): + def __init__(self): + test396j.__init__(self) + + def abstractMethod(self): + pass + +x = Subclass() Modified: branches/2.3/build.xml =================================================================== --- branches/2.3/build.xml 2007-04-23 15:50:47 UTC (rev 3184) +++ branches/2.3/build.xml 2007-04-24 05:41:14 UTC (rev 3185) @@ -91,7 +91,10 @@ # - org.gnu.readline readline.jar=${basedir}/../externals/external-jars/readline.jar +# - jline +jline.jar=${basedir}/../externals/external-jars/jline-0.9.91.jar + # - zxJDBC # (for mysql, see www.mysql.com/downloads/api-jdbc-stable.html) # (for postgres, see http://jdbc.postgresql.org/) @@ -172,6 +175,7 @@ <!-- classpaths --> <path id="main.classpath"> <pathelement path="${readline.jar}" /> + <pathelement path="${jline.jar}" /> <pathelement path="${servlet.jar}" /> <pathelement path="${informix.jar}" /> <pathelement path="${oracle.jar}" /> @@ -186,6 +190,7 @@ <available property="secureclassloader.present" classname="java.security.SecureClassLoader" /> <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="jline.present" classname="jline.Terminal" classpath="${jline.jar}" /> <available property="informix.present" classname="com.informix.jdbc.IfxDriver" classpath="${informix.jar}" /> <available property="mysql.present" classname="org.gjt.mm.mysql.Driver" classpath="${mysql.jar}" /> <available property="postgresql.present" classname="org.postgresql.Driver" classpath="${postgresql.jar}" /> @@ -247,6 +252,7 @@ <taskdef name="svn" classname="org.tigris.subversion.svnant.SvnTask" classpathref="svn.classpath" /> <!-- Require all of the optional jars for a full build --> <fail unless="readline.present" message="readline jar not present" /> + <fail unless="jline.present" message="jline jar not present" /> <fail unless="servlet.present" message="servlet jar not present" /> <fail unless="informix.present" message="informix jar not present" /> <fail unless="mysql.present" message="mysql jar not present" /> @@ -268,6 +274,7 @@ <echo>secureclassloader = '${secureclassloader.present}'</echo> <echo>servlet = '${servlet.present}'</echo> <echo>readline = '${readline.present}'</echo> + <echo>jline = '${jline.present}'</echo> <echo>oracle = '${oracle.present}'</echo> <echo>informix = '${informix.present}'</echo> <echo>mysql = '${mysql.present}'</echo> @@ -436,6 +443,7 @@ <exclude name="org/python/parser/python.java" /> <exclude name="**/PyServlet.java" unless="servlet.present" /> <exclude name="**/ReadlineConsole.java" unless="readline.present" /> + <exclude name="**/JLineConsole.java" unless="jline.present" /> <exclude name="**/handler/InformixDataHandler.java" unless="informix.present" /> <exclude name="**/handler/MySQLDataHandler.java" unless="mysql.present" /> <exclude name="**/handler/OracleDataHandler.java" unless="oracle.present" /> @@ -503,6 +511,7 @@ <attribute name="secureclassloader" value="${secureclassloader.present}" /> <attribute name="servlet" value="${servlet.present}" /> <attribute name="readline" value="${readline.present}" /> + <attribute name="jline" value="${jline.present}" /> <attribute name="oracle" value="${oracle.present}" /> <attribute name="informix" value="${informix.present}" /> <attribute name="mysql" value="${mysql.present}" /> @@ -674,6 +683,7 @@ <attribute name="secureclassloader" value="${secureclassloader.present}" /> <attribute name="servlet" value="${servlet.present}" /> <attribute name="readline" value="${readline.present}" /> + <attribute name="jline" value="${jline.present}" /> <attribute name="oracle" value="${oracle.present}" /> <attribute name="informix" value="${informix.present}" /> <attribute name="mysql" value="${mysql.present}" /> Modified: branches/2.3/src/org/python/compiler/CodeCompiler.java =================================================================== --- branches/2.3/src/org/python/compiler/CodeCompiler.java 2007-04-23 15:50:47 UTC (rev 3184) +++ branches/2.3/src/org/python/compiler/CodeCompiler.java 2007-04-24 05:41:14 UTC (rev 3185) @@ -6,6 +6,7 @@ import java.util.Hashtable; import java.util.Stack; import java.util.Vector; + import org.python.core.CompilerFlags; import org.python.core.PyComplex; import org.python.core.PyFloat; @@ -2102,7 +2103,7 @@ scope.setup_closure(); scope.dump(); module.PyCode(retSuite, name, true, className, - false, false, node.beginLine, scope).get(code); + false, false, node.beginLine, scope, cflags).get(code); if (!makeClosure(scope)) { if (mrefs.PyFunction_init1 == 0) { @@ -2168,7 +2169,7 @@ scope.dump(); //Make code object out of suite module.PyCode(new Suite(node.body, node), name, false, name, - true, false, node.beginLine, scope).get(code); + true, false, node.beginLine, scope, cflags).get(code); //Get doc string (if there) getDocString(node.body); Modified: branches/2.3/src/org/python/core/CompilerFlags.java =================================================================== --- branches/2.3/src/org/python/core/CompilerFlags.java 2007-04-23 15:50:47 UTC (rev 3184) +++ branches/2.3/src/org/python/core/CompilerFlags.java 2007-04-24 05:41:14 UTC (rev 3185) @@ -1,10 +1,10 @@ package org.python.core; -public class CompilerFlags extends Object { +public class CompilerFlags { + + public CompilerFlags(){} - public CompilerFlags() {} - public CompilerFlags(int co_flags) { if ((co_flags & org.python.core.PyTableCode.CO_NESTED) != 0) { this.nested_scopes = true; @@ -16,6 +16,13 @@ this.generator_allowed = true; } } + + public String toString() { + return "CompilerFlags[division=" + division + " nested_scopes=" + nested_scopes + " generators=" + + generator_allowed + "]"; + } + + public boolean nested_scopes = true; public boolean division; Modified: branches/2.3/src/org/python/core/Py.java =================================================================== --- branches/2.3/src/org/python/core/Py.java 2007-04-23 15:50:47 UTC (rev 3184) +++ branches/2.3/src/org/python/core/Py.java 2007-04-24 05:41:14 UTC (rev 3185) @@ -449,38 +449,39 @@ /* Helper functions for PyProxy's */ - /** @deprecated **/ - public static PyObject jfindattr(PyProxy proxy, String name) { - PyInstance o = proxy._getPyInstance(); - if (o == null) { - proxy.__initProxy__(new Object[0]); - o = proxy._getPyInstance(); - } - PyObject ret = o.__jfindattr__(name); - if (ret == null) - return null; + /** @deprecated * */ + public static PyObject jfindattr(PyProxy proxy, String name) { + PyInstance o = proxy._getPyInstance(); + if (o == null) { + proxy.__initProxy__(new Object[0]); + o = proxy._getPyInstance(); + } + PyObject ret = o.__jfindattr__(name); + if (ret == null) + return null; - // Set the current system state to match proxy -- usually - // this is a waste of time :-( - Py.setSystemState(proxy._getPySystemState()); - return ret; - } - /** @deprecated **/ - public static PyObject jgetattr(PyProxy proxy, String name) { - PyInstance o = proxy._getPyInstance(); - PyObject ret = null; - if (o != null) { - ret = o.__jfindattr__(name); - } - if (ret == null) - throw Py.AttributeError("abstract method \""+name+ - "\" not implemented"); - // Set the current system state to match proxy -- usually this is a - // waste of time :-( - Py.setSystemState(proxy._getPySystemState()); - return ret; - } + // Set the current system state to match proxy -- usually + // this is a waste of time :-( + Py.setSystemState(proxy._getPySystemState()); + return ret; + } + /** @deprecated * */ + public static PyObject jgetattr(PyProxy proxy, String name) { + PyInstance o = proxy._getPyInstance(); + if (o == null) { + proxy.__initProxy__(new Object[0]); + o = proxy._getPyInstance(); + } + PyObject ret = o.__jfindattr__(name); + if (ret == null) + throw Py.AttributeError("abstract method \"" + name + "\" not implemented"); + // Set the current system state to match proxy -- usually this is a + // waste of time :-( + Py.setSystemState(proxy._getPySystemState()); + return ret; + } + /* Convenience methods to create new constants without using "new" */ private static PyInteger[] integerCache = null; Modified: branches/2.3/src/org/python/core/PyInteger.java =================================================================== --- branches/2.3/src/org/python/core/PyInteger.java 2007-04-23 15:50:47 UTC (rev 3184) +++ branches/2.3/src/org/python/core/PyInteger.java 2007-04-24 05:41:14 UTC (rev 3185) @@ -1127,7 +1127,10 @@ final PyObject int___truediv__(PyObject right) { if (right instanceof PyInteger) return __float__().__truediv__(right); - return null; + else if(right instanceof PyLong) + return int___long__().__truediv__(right); + else + return null; } public PyObject __rtruediv__(PyObject left) { @@ -1137,7 +1140,10 @@ final PyObject int___rtruediv__(PyObject left) { if (left instanceof PyInteger) return left.__float__().__truediv__(this); - return null; + else if(left instanceof PyLong) + return left.__truediv__(int___long__()); + else + return null; } private static int modulo(int x, int y, int xdivy) { @@ -1296,11 +1302,13 @@ } final PyObject int___lshift__(PyObject right) { - int rightv; - if (right instanceof PyInteger) - rightv = ((PyInteger)right).getValue(); - else - return null; + int rightv; + if (right instanceof PyInteger) + rightv = ((PyInteger) right).getValue(); + else if (right instanceof PyLong) + return int___long__().__lshift__(right); + else + return null; if (rightv > 31) return Py.newInteger(0); @@ -1309,12 +1317,14 @@ return Py.newInteger(getValue() << rightv); } - final PyObject int___rlshift__(PyObject left){ - int leftv; - if (left instanceof PyInteger) - leftv = ((PyInteger)left).getValue(); - else - return null; + final PyObject int___rlshift__(PyObject left) { + int leftv; + if (left instanceof PyInteger) + leftv = ((PyInteger) left).getValue(); + else if (left instanceof PyLong) + return left.__rlshift__(int___long__()); + else + return null; if (getValue() > 31) return Py.newInteger(0); @@ -1327,23 +1337,27 @@ return int___rshift__(right); } - final PyObject int___rshift__(PyObject right) { - int rightv; - if (right instanceof PyInteger) - rightv = ((PyInteger)right).getValue(); - else - return null; + final PyObject int___rshift__(PyObject right) { + int rightv; + if (right instanceof PyInteger) + rightv = ((PyInteger) right).getValue(); + else if (right instanceof PyLong) + return int___long__().__rshift__(right); + else + return null; - if(rightv < 0) - throw Py.ValueError("negative shift count"); + if (rightv < 0) + throw Py.ValueError("negative shift count"); - return Py.newInteger(getValue() >> rightv); - } + return Py.newInteger(getValue() >> rightv); + } final PyObject int___rrshift__(PyObject left) { int leftv; if (left instanceof PyInteger) leftv = ((PyInteger)left).getValue(); + else if(left instanceof PyLong) + return left.__rshift__(int___long__()); else return null; @@ -1358,9 +1372,15 @@ } final PyObject int___and__(PyObject right) { - if (!canCoerce(right)) - return null; - return Py.newInteger(getValue() & coerce(right)); + int rightv; + if (right instanceof PyInteger) + rightv = ((PyInteger) right).getValue(); + else if (right instanceof PyLong) + return int___long__().__and__(right); + else + return null; + + return Py.newInteger(getValue() & rightv); } final PyObject int___rand__(PyObject left){ @@ -1371,20 +1391,24 @@ return int___xor__(right); } - final PyObject int___xor__(PyObject right) { - int rightv; - if (right instanceof PyInteger) - rightv = ((PyInteger)right).getValue(); - else - return null; + final PyObject int___xor__(PyObject right) { + int rightv; + if (right instanceof PyInteger) + rightv = ((PyInteger) right).getValue(); + else if (right instanceof PyLong) + return int___long__().__xor__(right); + else + return null; - return Py.newInteger(getValue() ^ rightv); + return Py.newInteger(getValue() ^ rightv); } final PyObject int___rxor__(PyObject left){ int leftv; if (left instanceof PyInteger) leftv = ((PyInteger)left).getValue(); + else if(left instanceof PyLong) + return left.__rxor__(int___long__()); else return null; @@ -1395,14 +1419,16 @@ return int___or__(right); } - final PyObject int___or__(PyObject right) { - int rightv; - if (right instanceof PyInteger) - rightv = ((PyInteger)right).getValue(); - else - return null; + final PyObject int___or__(PyObject right) { + int rightv; + if (right instanceof PyInteger) + rightv = ((PyInteger) right).getValue(); + else if (right instanceof PyLong) + return int___long__().__or__(right); + else + return null; - return Py.newInteger(getValue() | rightv); + return Py.newInteger(getValue() | rightv); } final PyObject int___ror__(PyObject left){ Modified: branches/2.3/src/org/python/core/imp.java =================================================================== --- branches/2.3/src/org/python/core/imp.java 2007-04-23 15:50:47 UTC (rev 3184) +++ branches/2.3/src/org/python/core/imp.java 2007-04-24 05:41:14 UTC (rev 3185) @@ -133,7 +133,7 @@ * compiledFilename couldn't be determined of if an error was thrown * while writing to the cache file. */ - private static String cacheCompiledSource(String sourceFilename, + public static String cacheCompiledSource(String sourceFilename, String compiledFilename, byte[] compiledSource) { if(compiledFilename == null){ @@ -176,7 +176,7 @@ } org.python.parser.ast.modType node; try { - node = parser.parse(fp, "exec", filename, null); + node = parser.parse(fp, "exec", filename, Py.getCompilerFlags()); } finally { fp.close(); } @@ -187,7 +187,7 @@ true, false, true, - null); + Py.getCompilerFlags()); return ofp.toByteArray(); } catch(Throwable t) { throw parser.fixParseError(null, t, filename); Modified: branches/2.3/src/org/python/modules/py_compile.java =================================================================== --- branches/2.3/src/org/python/modules/py_compile.java 2007-04-23 15:50:47 UTC (rev 3184) +++ branches/2.3/src/org/python/modules/py_compile.java 2007-04-24 05:41:14 UTC (rev 3185) @@ -1,30 +1,32 @@ // Copyright (c) Corporation for National Research Initiatives package org.python.modules; -import org.python.core.*; import java.io.File; +import org.python.core.PyList; +import org.python.core.PyString; + public class py_compile { - public static PyList __all__ = new PyList(new PyString[] { - new PyString("compile") - }); + public static PyList __all__ = new PyList(new PyString[] { new PyString("compile") }); - - public static void compile(String filename, String cfile) { - compile(filename, cfile, null); + public static boolean compile(String filename, String cfile) { + return compile(filename, cfile, null); } - public static void compile(String filename) { - compile(filename, null, null); + public static boolean compile(String filename) { + return compile(filename, null, null); } - public static void compile(String filename, String cfile, String dfile) { + public static boolean compile(String filename, String cfile, String dfile) { File file = new File(filename); String name = file.getName(); int dot = name.lastIndexOf('.'); if (dot != -1) { name = name.substring(0, dot); } - org.python.core.imp.compileSource(name, file, dfile, cfile); + byte[] bytes = org.python.core.imp.compileSource(name, file, dfile, cfile); + org.python.core.imp.cacheCompiledSource(filename, null, bytes); + + return bytes.length > 0; } } Modified: branches/2.3/src/org/python/util/InteractiveConsole.java =================================================================== --- branches/2.3/src/org/python/util/InteractiveConsole.java 2007-04-23 15:50:47 UTC (rev 3184) +++ branches/2.3/src/org/python/util/InteractiveConsole.java 2007-04-24 05:41:14 UTC (rev 3185) @@ -1,57 +1,85 @@ // Copyright (c) Corporation for National Research Initiatives package org.python.util; -import org.python.core.*; +import org.python.core.Py; +import org.python.core.PyBuiltinFunctionSet; +import org.python.core.PyException; +import org.python.core.PyObject; +import org.python.core.PySystemState; +import org.python.core.__builtin__; + // Based on CPython-1.5.2's code module +public class InteractiveConsole extends InteractiveInterpreter { -public class InteractiveConsole extends InteractiveInterpreter { + public static final String CONSOLE_FILENAME = "<console>"; + public String filename; public InteractiveConsole() { - this(null, "<console>"); + this(null, CONSOLE_FILENAME); } + public InteractiveConsole(PyObject locals) { - this(locals, "<console>"); + this(locals, CONSOLE_FILENAME); } + public InteractiveConsole(PyObject locals, String filename) { + this(locals, filename, false); + } + + /** + * @param replaceRawInput - + * if true, we hook this Class's raw_input into the builtins + * table so that clients like cmd.Cmd use it. + */ + public InteractiveConsole(PyObject locals, String filename, boolean replaceRawInput) { super(locals); this.filename = filename; + if(replaceRawInput) { + PyObject newRawInput = new PyBuiltinFunctionSet("raw_input", 0, 0, 1) { + + public PyObject __call__() { + return __call__(Py.EmptyString); + } + + public PyObject __call__(PyObject prompt) { + return Py.newString(raw_input(prompt)); + } + }; + Py.getSystemState().builtins.__setitem__("raw_input", newRawInput); + } } /** * Closely emulate the interactive Python console. - * - * The optional banner argument specifies the banner to print before - * the first interaction; by default it prints a banner similar to the - * one printed by the real Python interpreter, followed by the current - * class name in parentheses (so as not to confuse this with the real - * interpreter -- since it's so close!). - **/ + * + * The optional banner argument specifies the banner to print before the + * first interaction; by default it prints "Jython <version> on <platform>". + */ public void interact() { interact(getDefaultBanner()); } public static String getDefaultBanner() { - return "Jython " + PySystemState.version + " on " - + PySystemState.platform; + return "Jython " + PySystemState.version + " on " + PySystemState.platform; } public void interact(String banner) { - if (banner != null) { + if(banner != null) { write(banner); write("\n"); } // Dummy exec in order to speed up response on first command exec("2"); - //System.err.println("interp2"); + // System.err.println("interp2"); boolean more = false; - while (true) { + while(true) { PyObject prompt = more ? systemState.ps2 : systemState.ps1; String line; try { line = raw_input(prompt); - } catch (PyException exc) { - if (!Py.matchException(exc, Py.EOFError)) + } catch(PyException exc) { + if(!Py.matchException(exc, Py.EOFError)) throw exc; write("\n"); break; @@ -62,36 +90,35 @@ /** * Push a line to the interpreter. - * + * * The line should not have a trailing newline; it may have internal - * newlines. The line is appended to a buffer and the interpreter's - * runsource() method is called with the concatenated contents of the - * buffer as source. If this indicates that the command was executed - * or invalid, the buffer is reset; otherwise, the command is - * incomplete, and the buffer is left as it was after the line was - * appended. The return value is 1 if more input is required, 0 if the - * line was dealt with in some way (this is the same as runsource()). - **/ - + * newlines. The line is appended to a buffer and the interpreter's + * runsource() method is called with the concatenated contents of the buffer + * as source. If this indicates that the command was executed or invalid, + * the buffer is reset; otherwise, the command is incomplete, and the buffer + * is left as it was after the line was appended. The return value is 1 if + * more input is required, 0 if the line was dealt with in some way (this is + * the same as runsource()). + */ public boolean push(String line) { - if (buffer.length() > 0) + if(buffer.length() > 0) buffer.append("\n"); buffer.append(line); boolean more = runsource(buffer.toString(), filename); - if (!more) + if(!more) resetbuffer(); return more; } /** * Write a prompt and read a line. - * - * The returned line does not include the trailing newline. When the - * user enters the EOF key sequence, EOFError is raised. - * + * + * The returned line does not include the trailing newline. When the user + * enters the EOF key sequence, EOFError is raised. + * * The base implementation uses the built-in function raw_input(); a * subclass may replace this with a different implementation. - **/ + */ public String raw_input(PyObject prompt) { return __builtin__.raw_input(prompt); } Copied: branches/2.3/src/org/python/util/JLineConsole.java (from rev 3176, trunk/jython/src/org/python/util/JLineConsole.java) =================================================================== --- branches/2.3/src/org/python/util/JLineConsole.java (rev 0) +++ branches/2.3/src/org/python/util/JLineConsole.java 2007-04-24 05:41:14 UTC (rev 3185) @@ -0,0 +1,48 @@ +package org.python.util; + +import java.io.IOException; +import jline.ConsoleReader; +import jline.Terminal; +import org.python.core.Py; +import org.python.core.PyObject; + +/** + * This class uses <a href="http://jline.sourceforge.net/">JLine</a> to provide + * readline like functionality to its console without requiring native readline + * support. + */ +public class JLineConsole extends InteractiveConsole { + + public JLineConsole() { + this(null); + } + + public JLineConsole(PyObject locals) { + this(locals, CONSOLE_FILENAME); + } + + public JLineConsole(PyObject locals, String filename) { + super(locals, filename, true); + Terminal.setupTerminal(); + try { + reader = new ConsoleReader(); + } catch(IOException e) { + throw new RuntimeException(e); + } + } + + public String raw_input(PyObject prompt) { + String line = null; + try { + line = reader.readLine(prompt.toString()); + } catch(IOException io) { + throw Py.IOError(io); + } + if(line == null) { + throw Py.EOFError("Ctrl-D exit"); + } + return line.endsWith("\n") ? line.substring(0, line.length() - 1) : line; + } + + private ConsoleReader reader; +} Modified: branches/2.3/src/org/python/util/ReadlineConsole.java =================================================================== --- branches/2.3/src/org/python/util/ReadlineConsole.java 2007-04-23 15:50:47 UTC (rev 3184) +++ branches/2.3/src/org/python/util/ReadlineConsole.java 2007-04-24 05:41:14 UTC (rev 3185) @@ -3,81 +3,57 @@ import org.gnu.readline.Readline; import org.gnu.readline.ReadlineLibrary; -import org.python.core.ArgParser; import org.python.core.Py; import org.python.core.PyException; import org.python.core.PyObject; -import org.python.core.PyString; import org.python.core.PySystemState; /** - * Uses: - * <a href="http://java-readline.sourceforge.net/">Java Readline</a> - * <p/> - * + * Uses: <a href="http://java-readline.sourceforge.net/">Java Readline</a> <p/> + * * Based on CPython-1.5.2's code module - * + * */ public class ReadlineConsole extends InteractiveConsole { + public String filename; public ReadlineConsole() { - this(null, "<console>"); + this(null, CONSOLE_FILENAME); } + public ReadlineConsole(PyObject locals) { - this(locals, "<console>"); + this(locals, CONSOLE_FILENAME); } + public ReadlineConsole(PyObject locals, String filename) { - super(locals,filename); - String backingLib = PySystemState.registry.getProperty( - "python.console.readlinelib", "Editline"); + super(locals, filename, true); + String backingLib = PySystemState.registry.getProperty("python.console.readlinelib", + "Editline"); try { Readline.load(ReadlineLibrary.byName(backingLib)); - } catch (RuntimeException e) { + } catch(RuntimeException e) { // Silently ignore errors during load of the native library. // Will use a pure java fallback. } - - // hook into the builtins table so that clients like cmd.Cmd can - // also use readline. - Py.getSystemState().builtins.__setitem__("raw_input", - Py.newJavaFunc(this.getClass(), "_raw_input")); - Readline.initReadline("jython"); } - /** * Write a prompt and read a line. - * - * The returned line does not include the trailing newline. When the - * user enters the EOF key sequence, EOFError is raised. - * + * + * The returned line does not include the trailing newline. When the user + * enters the EOF key sequence, EOFError is raised. + * * This subclass implements the functionality using JavaReadline. - **/ + */ public String raw_input(PyObject prompt) { - return _raw_input(new PyObject[] { prompt }, new String[0]); - } - - /** - * Central point of dispatch to Readline library for all clients, - * whether the console itself or others like cmd.Cmd interpreters. - * Both of these uses come through here. - * - * @param args should contain a single prompt - * @param kws keywords - * @return the user input - **/ - public static String _raw_input(PyObject args[], String kws[]) { - ArgParser ap = new ArgParser("raw_input", args, kws, "prompt"); - PyObject prompt = ap.getPyObject(0, new PyString("")); try { - String line = Readline.readline( - prompt==null ? "" : prompt.toString()); + String line = Readline.readline(prompt == null ? "" : prompt.toString()); return (line == null ? "" : line); - } catch (java.io.EOFException eofe) { + } catch(java.io.EOFException eofe) { throw new PyException(Py.EOFError); - } catch (java.io.IOException e) { + } catch(java.io.IOException e) { throw new PyException(Py.IOError); } } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <cg...@us...> - 2007-04-24 05:42:44
|
Revision: 3186 http://svn.sourceforge.net/jython/?rev=3186&view=rev Author: cgroves Date: 2007-04-23 22:42:42 -0700 (Mon, 23 Apr 2007) Log Message: ----------- merge -r 3177:HEAD https://jython.svn.sourceforge.net/svnroot/jython/trunk/jython Modified Paths: -------------- branches/2.3/Lib/test/regrtest.py branches/2.3/Lib/test/test_datetime.py branches/2.3/NEWS branches/2.3/build.Lib.include.properties branches/2.3/src/org/python/core/PathPackageManager.java branches/2.3/src/org/python/core/PyFile.java branches/2.3/src/org/python/modules/time/Time.java Added Paths: ----------- branches/2.3/Lib/test/test_SimpleXMLRPCServer.py branches/2.3/bugtests/test397.py branches/2.3/bugtests/test397m.py Modified: branches/2.3/Lib/test/regrtest.py =================================================================== --- branches/2.3/Lib/test/regrtest.py 2007-04-24 05:41:14 UTC (rev 3185) +++ branches/2.3/Lib/test/regrtest.py 2007-04-24 05:42:42 UTC (rev 3186) @@ -1056,7 +1056,6 @@ test_descrtut test_doctest2 test_frozen - test_long_future test_marshal test_new test_pickle Copied: branches/2.3/Lib/test/test_SimpleXMLRPCServer.py (from rev 3185, trunk/jython/Lib/test/test_SimpleXMLRPCServer.py) =================================================================== --- branches/2.3/Lib/test/test_SimpleXMLRPCServer.py (rev 0) +++ branches/2.3/Lib/test/test_SimpleXMLRPCServer.py 2007-04-24 05:42:42 UTC (rev 3186) @@ -0,0 +1,88 @@ +# +# Matt Shelton <ma...@ma...> +# + +from SimpleXMLRPCServer import SimpleXMLRPCServer +import threading, xmlrpclib, unittest + +HOST = "127.0.0.1" +PORT = 7218 + +def multiply(x, y): + return x * y + +class MyService: + """This test class is going to be used to test an entire class being + exposed via XML-RPC.""" + + def _dispatch(self, method, params): + """This method is called whenever a call is made to the + service.""" + func = getattr(self, 'expose_' + method) + return func(*params) + + def expose_squared(self, x): + """Square""" + return x * x + +class ServerThread(threading.Thread): + """A test harness for launching a SimpleXMLRPCServer instance in the + background.""" + def __init__(self, server): + threading.Thread.__init__(self) + self.server = server + + def run(self): + self.server.socket.settimeout(5) + self.server.allow_reuse_address = 1 + self.server.handle_request() + self.server.server_close() + +class SimpleXMLRPCServerTestCase(unittest.TestCase): + """Test case for the Python SimpleXMLRPCServer module.""" + def test_exposeLambda(self): + """Expose a lambda function via XML-RPC.""" + # Create a server instance. + server = SimpleXMLRPCServer((HOST, PORT)) + server.register_function(lambda x,y: x+y, 'add') + ServerThread(server).start() + + # Access the exposed service. + client = xmlrpclib.ServerProxy("http://%s:%d" % (HOST, PORT)) + self.assertEqual(client.add(10, 20), 30) + + def test_exposeFunction1(self): + """Expose a function via XML-RPC.""" + server = SimpleXMLRPCServer((HOST, PORT + 1)) + server.register_function(multiply) + ServerThread(server).start() + + # Access the exposed service. + client = xmlrpclib.ServerProxy("http://%s:%d" % (HOST, PORT + 1)) + self.assertEqual(client.multiply(5, 10), 50) + + def test_exposeFunction2(self): + """Expose a function using a different name via XML-RPC.""" + server = SimpleXMLRPCServer((HOST, PORT + 2)) + server.register_function(multiply, "mult") + ServerThread(server).start() + + # Access the exposed service. + client = xmlrpclib.ServerProxy("http://%s:%d" % (HOST, PORT + 2)) + self.assertEqual(client.mult(7, 11), 77) + + def test_exposeClass(self): + """Expose an entire class and test the _dispatch method.""" + server = SimpleXMLRPCServer((HOST, PORT + 3)) + server.register_instance(MyService()) + ServerThread(server).start() + + # Access the exposed service. + client = xmlrpclib.ServerProxy("http://%s:%d" % (HOST, PORT + 3)) + self.assertEqual(client.squared(10), 100) + + +if __name__ == "__main__": + unittest.main() + +# vim:et:ts=4:sw=4: Modified: branches/2.3/Lib/test/test_datetime.py =================================================================== --- branches/2.3/Lib/test/test_datetime.py 2007-04-24 05:41:14 UTC (rev 3185) +++ branches/2.3/Lib/test/test_datetime.py 2007-04-24 05:42:42 UTC (rev 3186) @@ -13,6 +13,7 @@ from datetime import tzinfo from datetime import time from datetime import date, datetime +from test import test_support # Before Python 2.3, proto=2 was taken as a synonym for proto=1. # cPickle not updated in Jython so commenting out. @@ -2934,11 +2935,10 @@ #import gc import sys - r = unittest.TextTestRunner() s = test_suite() lastrc = None while True: - r.run(s) + test_support.run_suite(s) if 1: # change to 0, under a debug build, for some leak detection break gc.collect() Modified: branches/2.3/NEWS =================================================================== --- branches/2.3/NEWS 2007-04-24 05:41:14 UTC (rev 3185) +++ branches/2.3/NEWS 2007-04-24 05:42:42 UTC (rev 3186) @@ -29,6 +29,8 @@ - [ 1603686 ] Unmarshaling long-error - [ 1230674 ] eval with from future does not work through import - [ 663592 ] Problems calling an overriden class in the constructor + - [ 448398 ] open('test.txt', 'w').write('test') fails + - [ 1671373 ] A "$_PyInner.class" file in a package causes import to fail Patches applied - [ 1681774 ] str.decode, unicode.encode and str(u'') fixes - [ 1682423 ] Convert PyModule to a new-style class Copied: branches/2.3/bugtests/test397.py (from rev 3185, trunk/jython/bugtests/test397.py) =================================================================== --- branches/2.3/bugtests/test397.py (rev 0) +++ branches/2.3/bugtests/test397.py 2007-04-24 05:42:42 UTC (rev 3186) @@ -0,0 +1,41 @@ +''' +Checks that files are closed in three situations: +1. Garbage collection/finalization close +2. Regular close +3. Shutdown time, close out open PyFiles +''' + +import os +import support + +from java.io import File +from java.lang import System, Thread + +def check(fn='test.txt'): + f = File(fn) + if not f.exists(): + raise support.TestError('"%s" should exist' % fn) + if not f.length(): + raise support.TestError('"%s" should have contents' % fn) + os.remove(fn) + + +open("garbagecollected", "w").write("test") + +#Wait up to 2 seconds for garbage collected to disappear +System.gc() +for i in range(10): + if not os.path.exists('garbagecollected'): + break + Thread.sleep(200) + +check("garbagecollected") + +f = open("normalclose", "w") +f.write("test") +f.close() +check("normalclose") + +#test397m writes to "shutdown" and exits +support.runJython('test397m.py') +check('shutdown') Copied: branches/2.3/bugtests/test397m.py (from rev 3185, trunk/jython/bugtests/test397m.py) =================================================================== --- branches/2.3/bugtests/test397m.py (rev 0) +++ branches/2.3/bugtests/test397m.py 2007-04-24 05:42:42 UTC (rev 3186) @@ -0,0 +1 @@ +open("shutdown", "w").write('exiting') Modified: branches/2.3/build.Lib.include.properties =================================================================== --- branches/2.3/build.Lib.include.properties 2007-04-24 05:41:14 UTC (rev 3185) +++ branches/2.3/build.Lib.include.properties 2007-04-24 05:42:42 UTC (rev 3186) @@ -101,6 +101,7 @@ shlex.py shutil.py SimpleHTTPServer.py +SimpleXMLRPCServer.py site.py smtplib.py sndhdr.py Modified: branches/2.3/src/org/python/core/PathPackageManager.java =================================================================== --- branches/2.3/src/org/python/core/PathPackageManager.java 2007-04-24 05:41:14 UTC (rev 3185) +++ branches/2.3/src/org/python/core/PathPackageManager.java 2007-04-24 05:42:42 UTC (rev 3186) @@ -59,10 +59,10 @@ private boolean python; public boolean accept(File dir, String name) { - if (name.endsWith(".py") || name.endsWith("$py.class")) { - this.python = true; - } else if (name.endsWith(".class")) { - this.java = true; + if(name.endsWith(".py") || name.endsWith("$py.class") || name.endsWith("$_PyInner.class")) { + python = true; + }else if (name.endsWith(".class")) { + java = true; } return false; } Modified: branches/2.3/src/org/python/core/PyFile.java =================================================================== --- branches/2.3/src/org/python/core/PyFile.java 2007-04-24 05:41:14 UTC (rev 3185) +++ branches/2.3/src/org/python/core/PyFile.java 2007-04-24 05:42:42 UTC (rev 3186) @@ -1,7 +1,12 @@ // Copyright (c) Corporation for National Research Initiatives package org.python.core; -import java.io.*; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.util.LinkedList; // To do: // - readinto(array) @@ -13,7 +18,6 @@ /** * A python file wrapper around a java stream, reader/writer or file. */ - public class PyFile extends PyObject { @@ -1094,18 +1098,7 @@ String nameArg = ap.getString(0, null); String modeArg = ap.getString(1, "r"); int buffArg = ap.getInt(2, 0); - FileWrapper fw = _setup(nameArg, modeArg, buffArg); - - //xxx: c&p'ed from one of the constructors. - fw.setMode(modeArg); - this.name = nameArg; - this.mode = modeArg; - this.softspace = false; - this.closed = false; - if (modeArg.indexOf('b') < 0) - this.file = new TextWrapper(fw); - else - this.file = fw; + file_init(_setup(nameArg, modeArg, buffArg), nameArg, modeArg); } public PyFile() { @@ -1117,15 +1110,21 @@ } public PyFile(FileWrapper file, String name, String mode) { + file_init(file, name, mode); + } + + private void file_init(FileWrapper file, String name, String mode){ file.setMode(mode); this.name = name; this.mode = mode; this.softspace = false; this.closed = false; - if (mode.indexOf('b') < 0) + if (mode.indexOf('b') < 0){ this.file = new TextWrapper(file); - else + }else{ this.file = file; + } + closer = new Closer(this.file); } public PyFile(java.io.InputStream istream, java.io.OutputStream ostream, @@ -1483,10 +1482,9 @@ } final void file_close() { - try { - file.close(); - } catch (java.io.IOException e) { - throw Py.IOError(e); + if(closer != null){ + closer.close(); + closer = null; } closed = true; file = new FileWrapper(); @@ -1570,4 +1568,86 @@ public boolean getClosed() { return closed; } + + protected void finalize() throws Throwable { + super.finalize(); + if(closer != null) { + closer.close(); + } + } + + /** + * A mechanism to make sure PyFiles are closed on exit. On creation Closer + * adds itself to a list of Closers that will be run by PyFileCloser on JVM + * shutdown. When a PyFile's close or finalize methods are called, PyFile calls + * its Closer.close which clears Closer out of the shutdown queue. + * + * We use a regular object here rather than WeakReferences and their + * ilk as they may be collected before the shutdown hook runs. There's no + * guarantee that finalize will be called during shutdown, so we can't use + * it. It's vital that this Closer has no reference to the PyFile it's + * closing so the PyFile remains garbage collectable. + */ + private static class Closer { + + public Closer(FileWrapper fw){ + this.fw = fw; + //Add ourselves to the queue of Closers to be run on shutdown + synchronized(closers) { + closers.add(this); + } + } + + public void close() { + synchronized(closers) { + if(!closers.remove(this)){ + return; + } + } + _close(); + } + + public void _close(){ + try { + fw.close(); + } catch(java.io.IOException e) { + throw Py.IOError(e); + } finally { + fw = null; + } + } + + private FileWrapper fw; + } + + + private Closer closer; + + private static LinkedList closers = new LinkedList(); + static { + try { + Runtime.getRuntime().addShutdownHook(new PyFileCloser()); + } catch(SecurityException e) { + Py.writeDebug("PyFile", "Can't register file closer hook"); + } + } + + private static class PyFileCloser extends Thread { + + public PyFileCloser() { + super("Jython Shutdown File Closer"); + } + + public void run() { + synchronized(closers) { + while(closers.size() > 0) { + try { + ((Closer)closers.removeFirst())._close(); + } catch(PyException e) {} + } + } + } + } + + } Modified: branches/2.3/src/org/python/modules/time/Time.java =================================================================== --- branches/2.3/src/org/python/modules/time/Time.java 2007-04-24 05:41:14 UTC (rev 3185) +++ branches/2.3/src/org/python/modules/time/Time.java 2007-04-24 05:42:42 UTC (rev 3186) @@ -290,6 +290,27 @@ protected static String[] shortdays = null; protected static String[] shortmonths = null; + private static String[] enshortdays = new String[] {"Mon", + "Tue", + "Wed", + "Thu", + "Fri", + "Sat", + "Sun"}; + + private static String[] enshortmonths = new String[] {"Jan", + "Feb", + "Mar", + "Apr", + "May", + "Jun", + "Jul", + "Aug", + "Sep", + "Oct", + "Nov", + "Dec"}; + private static String _shortday(int dow) { // we need to hand craft shortdays[] because Java and Python have // different specifications. Java (undocumented) appears to be @@ -357,6 +378,21 @@ } public static String asctime(PyTuple tup) { + StringBuffer buf = new StringBuffer(25); + buf.append(enshortdays[item(tup, 6)]).append(' '); + buf.append(enshortmonths[item(tup, 1)]).append(' '); + int dayOfMonth = item(tup, 2); + if(dayOfMonth < 10){ + buf.append(' '); + } + buf.append(dayOfMonth).append(' '); + buf.append(_twodigit(item(tup, 3))).append(':'); + buf.append(_twodigit(item(tup, 4))).append(':'); + buf.append(_twodigit(item(tup, 5))).append(' '); + return buf.append(item(tup, 0)).toString(); + } + + public static String locale_asctime(PyTuple tup) { checkLocale(); int day = item(tup, 6); int mon = item(tup, 1); @@ -444,8 +480,7 @@ s = s + syms[j]; break; case 'c': - // locale's date and time repr (essentially asctime()?) - s = s + asctime(tup); + s = s + locale_asctime(tup); break; case 'd': // day of month (01-31) This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <cg...@us...> - 2007-05-16 06:54:59
|
Revision: 3229 http://svn.sourceforge.net/jython/?rev=3229&view=rev Author: cgroves Date: 2007-05-15 23:54:58 -0700 (Tue, 15 May 2007) Log Message: ----------- merge -r 3227:3228 https://jython.svn.sourceforge.net/svnroot/jython/trunk/jython . Modified Paths: -------------- branches/2.3/build.xml branches/2.3/src/org/python/core/Options.java branches/2.3/src/org/python/modules/thread.java Modified: branches/2.3/build.xml =================================================================== --- branches/2.3/build.xml 2007-05-16 06:51:58 UTC (rev 3228) +++ branches/2.3/build.xml 2007-05-16 06:54:58 UTC (rev 3229) @@ -626,6 +626,7 @@ <patternset> <includesfile name="${jython.base.dir}/build.Lib.include.properties" /> <exclude name="test/output/test_sax"/> + <exclude name="test/test_cpickle.py"/> </patternset> </fileset> </copy> Modified: branches/2.3/src/org/python/core/Options.java =================================================================== --- branches/2.3/src/org/python/core/Options.java 2007-05-16 06:51:58 UTC (rev 3228) +++ branches/2.3/src/org/python/core/Options.java 2007-05-16 06:54:58 UTC (rev 3229) @@ -14,7 +14,7 @@ * when an exception occurs in Java code, and it is not caught, should the * interpreter print out the Java exception in the traceback? */ - public static boolean showJavaExceptions = false; + public static boolean showJavaExceptions = true; /** * When true, python exception raised in overriden methods will be shown on Modified: branches/2.3/src/org/python/modules/thread.java =================================================================== --- branches/2.3/src/org/python/modules/thread.java 2007-05-16 06:51:58 UTC (rev 3228) +++ branches/2.3/src/org/python/modules/thread.java 2007-05-16 06:54:58 UTC (rev 3229) @@ -42,11 +42,17 @@ public static void start_new_thread(PyObject func, PyTuple args) { Thread pt = new FunctionThread(func, args.getArray()); PyObject currentThread = func.__findattr__("im_self"); - if(currentThread != null) { - PyObject isDaemon = currentThread.__getattr__("isDaemon"); - pt.setDaemon(Py.py2boolean(isDaemon.__call__())); - PyObject getName = currentThread.__getattr__("getName"); - pt.setName(getName.__call__().toString()); + if (currentThread != null) { + PyObject isDaemon = currentThread.__findattr__("isDaemon"); + if (isDaemon != null && isDaemon.isCallable()) { + PyObject po = isDaemon.__call__(); + pt.setDaemon(po.__nonzero__()); + } + PyObject getName = currentThread.__findattr__("getName"); + if (getName != null && getName.isCallable()) { + PyObject pname = getName.__call__(); + pt.setName(String.valueOf(pname)); + } } pt.start(); } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <cg...@us...> - 2007-05-16 06:59:04
|
Revision: 3230 http://svn.sourceforge.net/jython/?rev=3230&view=rev Author: cgroves Date: 2007-05-15 23:59:00 -0700 (Tue, 15 May 2007) Log Message: ----------- Stupid Ctrl-C doesn't kill stupid svn commit under stupid cygwin. Backing out accidental Options and build.xml changes from last commit Modified Paths: -------------- branches/2.3/build.xml branches/2.3/src/org/python/core/Options.java Modified: branches/2.3/build.xml =================================================================== --- branches/2.3/build.xml 2007-05-16 06:54:58 UTC (rev 3229) +++ branches/2.3/build.xml 2007-05-16 06:59:00 UTC (rev 3230) @@ -626,7 +626,6 @@ <patternset> <includesfile name="${jython.base.dir}/build.Lib.include.properties" /> <exclude name="test/output/test_sax"/> - <exclude name="test/test_cpickle.py"/> </patternset> </fileset> </copy> Modified: branches/2.3/src/org/python/core/Options.java =================================================================== --- branches/2.3/src/org/python/core/Options.java 2007-05-16 06:54:58 UTC (rev 3229) +++ branches/2.3/src/org/python/core/Options.java 2007-05-16 06:59:00 UTC (rev 3230) @@ -14,7 +14,7 @@ * when an exception occurs in Java code, and it is not caught, should the * interpreter print out the Java exception in the traceback? */ - public static boolean showJavaExceptions = true; + public static boolean showJavaExceptions = false; /** * When true, python exception raised in overriden methods will be shown on This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <fwi...@us...> - 2007-05-18 00:30:16
|
Revision: 3232 http://svn.sourceforge.net/jython/?rev=3232&view=rev Author: fwierzbicki Date: 2007-05-17 17:30:12 -0700 (Thu, 17 May 2007) Log Message: ----------- moved package cache related classes into their own package. Modified Paths: -------------- branches/2.3/Lib/jxxload_help/PackageManager.java branches/2.3/bugtests/test398.py branches/2.3/src/org/python/core/InternalTables.java branches/2.3/src/org/python/core/PyJavaClass.java branches/2.3/src/org/python/core/PyJavaPackage.java branches/2.3/src/org/python/core/PySystemState.java Added Paths: ----------- branches/2.3/src/org/python/core/packagecache/ branches/2.3/src/org/python/core/packagecache/CachedJarsPackageManager.java branches/2.3/src/org/python/core/packagecache/PackageManager.java branches/2.3/src/org/python/core/packagecache/PathPackageManager.java branches/2.3/src/org/python/core/packagecache/SysPackageManager.java Removed Paths: ------------- branches/2.3/src/org/python/core/CachedJarsPackageManager.java branches/2.3/src/org/python/core/PackageManager.java branches/2.3/src/org/python/core/PathPackageManager.java branches/2.3/src/org/python/core/SysPackageManager.java Modified: branches/2.3/Lib/jxxload_help/PackageManager.java =================================================================== --- branches/2.3/Lib/jxxload_help/PackageManager.java 2007-05-16 19:47:04 UTC (rev 3231) +++ branches/2.3/Lib/jxxload_help/PackageManager.java 2007-05-18 00:30:12 UTC (rev 3232) @@ -2,7 +2,7 @@ package jxxload_help; -public class PackageManager extends org.python.core.PathPackageManager { +public class PackageManager extends org.python.core.packagecache.PathPackageManager { private JavaLoaderFactory factory; private ClassLoader loader; Modified: branches/2.3/bugtests/test398.py =================================================================== --- branches/2.3/bugtests/test398.py 2007-05-16 19:47:04 UTC (rev 3231) +++ branches/2.3/bugtests/test398.py 2007-05-18 00:30:12 UTC (rev 3232) @@ -16,7 +16,7 @@ from java.io import File from java.lang import String from java.util import Properties -from org.python.core import SysPackageManager +from org.python.core.packagecache import SysPackageManager PACKAGE = "test398javapackage" CACHEDIR = "test398cache" Deleted: branches/2.3/src/org/python/core/CachedJarsPackageManager.java =================================================================== --- branches/2.3/src/org/python/core/CachedJarsPackageManager.java 2007-05-16 19:47:04 UTC (rev 3231) +++ branches/2.3/src/org/python/core/CachedJarsPackageManager.java 2007-05-18 00:30:12 UTC (rev 3232) @@ -1,595 +0,0 @@ -// Copyright (c) Corporation for National Research Initiatives -// Copyright 2000 Samuele Pedroni - -package org.python.core; - -import java.io.BufferedInputStream; -import java.io.BufferedOutputStream; -import java.io.DataInputStream; -import java.io.DataOutputStream; -import java.io.EOFException; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.lang.reflect.Modifier; -import java.net.URL; -import java.net.URLConnection; -import java.security.AccessControlException; -import java.util.Enumeration; -import java.util.Hashtable; -import java.util.Vector; -import java.util.zip.ZipEntry; -import java.util.zip.ZipInputStream; - -/** - * Abstract package manager that gathers info about statically known classes - * from a set of jars. This info can be eventually cached. Off-the-shelf this - * class offers a local file-system based cache impl. - */ -public abstract class CachedJarsPackageManager extends PackageManager { - - /** - * Message log method - hook. This default impl does nothing. - * - * @param msg message text - */ - protected void message(String msg) { - } - - /** - * Warning log method - hook. This default impl does nothing. - * - * @param warn warning text - */ - protected void warning(String warn) { - } - - /** - * Comment log method - hook. This default impl does nothing. - * - * @param msg message text - */ - protected void comment(String msg) { - } - - /** - * Debug log method - hook. This default impl does nothing. - * - * @param msg message text - */ - protected void debug(String msg) { - } - - /** - * Filter class/pkg by name helper method - hook. The default impl. is used - * by {@link #addJarToPackages} in order to filter out classes whose name - * contains '$' (e.g. inner classes,...). Should be used or overriden by - * derived classes too. Also to be used in {@link #doDir}. - * - * @param name class/pkg name - * @param pkg if true, name refers to a pkg - * @return true if name must be filtered out - */ - protected boolean filterByName(String name, boolean pkg) { - return name.indexOf('$') != -1; - } - - /** - * Filter class by access perms helper method - hook. The default impl. is - * used by {@link #addJarToPackages} in order to filter out non-public - * classes. Should be used or overriden by derived classes too. Also to be - * used in {@link #doDir}. Access perms can be read with - * {@link #checkAccess}. - * - * @param name class name - * @param acc class access permissions as int - * @return true if name must be filtered out - */ - protected boolean filterByAccess(String name, int acc) { - return (acc & Modifier.PUBLIC) != Modifier.PUBLIC; - } - - private boolean indexModified; - - private Hashtable jarfiles; - - private static String vectorToString(Vector vec) { - int n = vec.size(); - StringBuffer ret = new StringBuffer(); - for (int i = 0; i < n; i++) { - ret.append((String) vec.elementAt(i)); - if (i < n - 1) { - ret.append(","); - } - } - return ret.toString(); - } - - // Add a single class from zipFile to zipPackages - // Only add valid, public classes - private void addZipEntry(Hashtable zipPackages, ZipEntry entry, - ZipInputStream zip) throws IOException { - String name = entry.getName(); - // System.err.println("entry: "+name); - if (!name.endsWith(".class")) { - return; - } - - char sep = '/'; - int breakPoint = name.lastIndexOf(sep); - if (breakPoint == -1) { - breakPoint = name.lastIndexOf('\\'); - sep = '\\'; - } - - String packageName; - if (breakPoint == -1) { - packageName = ""; - } else { - packageName = name.substring(0, breakPoint).replace(sep, '.'); - } - - String className = name.substring(breakPoint + 1, name.length() - 6); - - if (filterByName(className, false)) { - return; - } - - Vector[] vec = (Vector[]) zipPackages.get(packageName); - if (vec == null) { - vec = new Vector[] { new Vector(), new Vector() }; - zipPackages.put(packageName, vec); - } - int access = checkAccess(zip); - if ((access != -1) && !filterByAccess(name, access)) { - vec[0].addElement(className); - } else { - vec[1].addElement(className); - } - } - - // Extract all of the packages in a single jarfile - private Hashtable getZipPackages(InputStream jarin) throws IOException { - Hashtable zipPackages = new Hashtable(); - - ZipInputStream zip = new ZipInputStream(jarin); - - ZipEntry entry; - while ((entry = zip.getNextEntry()) != null) { - addZipEntry(zipPackages, entry, zip); - zip.closeEntry(); - } - - // Turn each vector into a comma-separated String - for (Enumeration e = zipPackages.keys(); e.hasMoreElements();) { - Object key = e.nextElement(); - Vector[] vec = (Vector[]) zipPackages.get(key); - String classes = vectorToString(vec[0]); - if (vec[1].size() > 0) { - classes += '@' + vectorToString(vec[1]); - } - zipPackages.put(key, classes); - } - - return zipPackages; - } - - /** - * Gathers classes info from jar specified by jarurl URL. Eventually just - * using previously cached info. Eventually updated info is not cached. - * Persistent cache storage access goes through inOpenCacheFile() and - * outCreateCacheFile(). - */ - public void addJarToPackages(java.net.URL jarurl) { - addJarToPackages(jarurl, null, false); - } - - /** - * Gathers classes info from jar specified by jarurl URL. Eventually just - * using previously cached info. Eventually updated info is (re-)cached if - * param cache is true. Persistent cache storage access goes through - * inOpenCacheFile() and outCreateCacheFile(). - */ - public void addJarToPackages(URL jarurl, boolean cache) { - addJarToPackages(jarurl, null, cache); - } - - /** - * Gathers classes info from jar specified by File jarfile. Eventually just - * using previously cached info. Eventually updated info is not cached. - * Persistent cache storage access goes through inOpenCacheFile() and - * outCreateCacheFile(). - */ - public void addJarToPackages(File jarfile) { - addJarToPackages(null, jarfile, false); - } - - /** - * Gathers classes info from jar specified by File jarfile. Eventually just - * using previously cached info. Eventually updated info is (re-)cached if - * param cache is true. Persistent cache storage access goes through - * inOpenCacheFile() and outCreateCacheFile(). - */ - public void addJarToPackages(File jarfile, boolean cache) { - addJarToPackages(null, jarfile, cache); - } - - private void addJarToPackages(URL jarurl, File jarfile, boolean cache) { - try { - boolean caching = this.jarfiles != null; - - URLConnection jarconn = null; - boolean localfile = true; - - if (jarfile == null) { - jarconn = jarurl.openConnection(); - // This is necessary because 'file:' url-connections - // return always 0 through getLastModified (bug?). - // And in order to handle localfiles (from urls too) - // uniformly. - if (jarconn.getURL().getProtocol().equals("file")) { - // ??pending: need to use java2 URLDecoder.decode? - String jarfilename = jarurl.getFile(); - jarfilename = jarfilename.replace('/', File.separatorChar); - jarfile = new File(jarfilename); - } else { - localfile = false; - } - } - - if (localfile && !jarfile.exists()) { - return; - } - - Hashtable zipPackages = null; - - long mtime = 0; - String jarcanon = null; - JarXEntry entry = null; - boolean brandNew = false; - - if (caching) { - - if (localfile) { - mtime = jarfile.lastModified(); - jarcanon = jarfile.getCanonicalPath(); - } else { - mtime = jarconn.getLastModified(); - jarcanon = jarurl.toString(); - } - - entry = (JarXEntry) this.jarfiles.get(jarcanon); - - if ((entry == null || !(new File(entry.cachefile).exists())) - && cache) { - message("processing new jar, '" + jarcanon + "'"); - - String jarname; - if (localfile) { - jarname = jarfile.getName(); - } else { - jarname = jarurl.getFile(); - int slash = jarname.lastIndexOf('/'); - if (slash != -1) - jarname = jarname.substring(slash + 1); - } - jarname = jarname.substring(0, jarname.length() - 4); - - entry = new JarXEntry(jarname); - this.jarfiles.put(jarcanon, entry); - - brandNew = true; - } - - if (mtime != 0 && entry != null && entry.mtime == mtime) { - zipPackages = readCacheFile(entry, jarcanon); - } - - } - - if (zipPackages == null) { - caching = caching && cache; - - if (caching) { - this.indexModified = true; - if (entry.mtime != 0) { - message("processing modified jar, '" + jarcanon + "'"); - } - entry.mtime = mtime; - } - - InputStream jarin; - if (jarconn == null) { - jarin = new BufferedInputStream( - new FileInputStream(jarfile)); - } else { - jarin = jarconn.getInputStream(); - } - - zipPackages = getZipPackages(jarin); - - if (caching) { - writeCacheFile(entry, jarcanon, zipPackages, brandNew); - } - } - - addPackages(zipPackages, jarcanon); - } catch (IOException ioe) { - // silently skip any bad directories - warning("skipping bad jar, '" - + (jarfile != null ? jarfile.toString() : jarurl.toString()) - + "'"); - } - - } - - private void addPackages(Hashtable zipPackages, String jarfile) { - for (Enumeration e = zipPackages.keys(); e.hasMoreElements();) { - String pkg = (String) e.nextElement(); - String classes = (String) zipPackages.get(pkg); - - int idx = classes.indexOf('@'); - if (idx >= 0 && Options.respectJavaAccessibility) { - classes = classes.substring(0, idx); - } - - makeJavaPackage(pkg, classes, jarfile); - } - } - - // Read in cache file storing package info for a single .jar - // Return null and delete this cachefile if it is invalid - private Hashtable readCacheFile(JarXEntry entry, String jarcanon) { - String cachefile = entry.cachefile; - long mtime = entry.mtime; - - debug("reading cache, '" + jarcanon + "'"); - - try { - DataInputStream istream = inOpenCacheFile(cachefile); - String old_jarcanon = istream.readUTF(); - long old_mtime = istream.readLong(); - if ((!old_jarcanon.equals(jarcanon)) || (old_mtime != mtime)) { - comment("invalid cache file: " + cachefile + ", " + jarcanon - + ":" + old_jarcanon + ", " + mtime + ":" + old_mtime); - deleteCacheFile(cachefile); - return null; - } - Hashtable packs = new Hashtable(); - try { - while (true) { - String packageName = istream.readUTF(); - String classes = istream.readUTF(); - packs.put(packageName, classes); - } - } catch (EOFException eof) { - ; - } - istream.close(); - - return packs; - } catch (IOException ioe) { - // if (cachefile.exists()) cachefile.delete(); - return null; - } - } - - // Write a cache file storing package info for a single .jar - private void writeCacheFile(JarXEntry entry, String jarcanon, - Hashtable zipPackages, boolean brandNew) { - try { - DataOutputStream ostream = outCreateCacheFile(entry, brandNew); - ostream.writeUTF(jarcanon); - ostream.writeLong(entry.mtime); - comment("rewriting cachefile for '" + jarcanon + "'"); - - for (Enumeration e = zipPackages.keys(); e.hasMoreElements();) { - String packageName = (String) e.nextElement(); - String classes = (String) zipPackages.get(packageName); - ostream.writeUTF(packageName); - ostream.writeUTF(classes); - } - ostream.close(); - } catch (IOException ioe) { - warning("can't write cache file for '" + jarcanon + "'"); - } - } - - /** - * Initializes cache. Eventually reads back cache index. Index persistent - * storage is accessed through inOpenIndex(). - */ - protected void initCache() { - this.indexModified = false; - this.jarfiles = new Hashtable(); - - try { - DataInputStream istream = inOpenIndex(); - if (istream == null) { - return; - } - - try { - while (true) { - String jarcanon = istream.readUTF(); - String cachefile = istream.readUTF(); - long mtime = istream.readLong(); - this.jarfiles - .put(jarcanon, new JarXEntry(cachefile, mtime)); - } - } catch (EOFException eof) { - ; - } - istream.close(); - } catch (IOException ioe) { - warning("invalid index file"); - } - - } - - /** - * Write back cache index. Index persistent storage is accessed through - * outOpenIndex(). - */ - public void saveCache() { - if (this.jarfiles == null || !this.indexModified) { - return; - } - - this.indexModified = false; - - comment("writing modified index file"); - - try { - DataOutputStream ostream = outOpenIndex(); - for (Enumeration e = this.jarfiles.keys(); e.hasMoreElements();) { - String jarcanon = (String) e.nextElement(); - JarXEntry entry = (JarXEntry) this.jarfiles.get(jarcanon); - ostream.writeUTF(jarcanon); - ostream.writeUTF(entry.cachefile); - ostream.writeLong(entry.mtime); - } - ostream.close(); - } catch (IOException ioe) { - warning("can't write index file"); - } - } - - // hooks for changing cache storage - - /** - * To pass a cachefile id by ref. And for internal use. See - * outCreateCacheFile - */ - public static class JarXEntry extends Object { - /** cachefile id */ - public String cachefile; - - public long mtime; - - public JarXEntry(String cachefile) { - this.cachefile = cachefile; - } - - public JarXEntry(String cachefile, long mtime) { - this.cachefile = cachefile; - this.mtime = mtime; - } - - } - - /** - * Open cache index for reading from persistent storage - hook. Must Return - * null if this is absent. This default impl is part of the off-the-shelf - * local file-system cache impl. Can be overriden. - */ - protected DataInputStream inOpenIndex() throws IOException { - File indexFile = new File(this.cachedir, "packages.idx"); - - if (!indexFile.exists()) { - return null; - } - - DataInputStream istream = new DataInputStream(new BufferedInputStream( - new FileInputStream(indexFile))); - - return istream; - } - - /** - * Open cache index for writing back to persistent storage - hook. This - * default impl is part of the off-the-shelf local file-system cache impl. - * Can be overriden. - */ - protected DataOutputStream outOpenIndex() throws IOException { - File indexFile = new File(this.cachedir, "packages.idx"); - - return new DataOutputStream(new BufferedOutputStream( - new FileOutputStream(indexFile))); - } - - /** - * Open cache file for reading from persistent storage - hook. This default - * impl is part of the off-the-shelf local file-system cache impl. Can be - * overriden. - */ - protected DataInputStream inOpenCacheFile(String cachefile) - throws IOException { - return new DataInputStream(new BufferedInputStream(new FileInputStream( - cachefile))); - } - - /** - * Delete (invalidated) cache file from persistent storage - hook. This - * default impl is part of the off-the-shelf local file-system cache impl. - * Can be overriden. - */ - protected void deleteCacheFile(String cachefile) { - new File(cachefile).delete(); - } - - /** - * Create/open cache file for rewriting back to persistent storage - hook. - * If create is false, cache file is supposed to exist and must be opened - * for rewriting, entry.cachefile is a valid cachefile id. If create is - * true, cache file must be created. entry.cachefile is a flat jarname to be - * used to produce a valid cachefile id (to be put back in entry.cachefile - * on exit). This default impl is part of the off-the-shelf local - * file-system cache impl. Can be overriden. - */ - protected DataOutputStream outCreateCacheFile(JarXEntry entry, - boolean create) throws IOException { - File cachefile = null; - - if (create) { - int index = 1; - String suffix = ""; - String jarname = entry.cachefile; - while (true) { - cachefile = new File(this.cachedir, jarname + suffix + ".pkc"); - // System.err.println("try cachefile: "+cachefile); - if (!cachefile.exists()) { - break; - } - suffix = "$" + index; - index += 1; - } - entry.cachefile = cachefile.getCanonicalPath(); - } else - cachefile = new File(entry.cachefile); - - return new DataOutputStream(new BufferedOutputStream( - new FileOutputStream(cachefile))); - } - - // for default cache (local fs based) impl - - private File cachedir; - - /** - * Initialize off-the-shelf (default) local file-system cache impl. Must be - * called before {@link #initCache}. cachedir is the cache repository - * directory, this is eventually created. Returns true if dir works. - */ - protected boolean useCacheDir(File aCachedir1) { - if (aCachedir1 == null) { - return false; - } - try { - if(!aCachedir1.isDirectory() && aCachedir1.mkdirs() == false) { - warning("can't create package cache dir, '" + aCachedir1 + "'"); - return false; - } - } catch(AccessControlException ace) { - warning("The java security manager isn't allowing access to the package cache dir, '" + aCachedir1 + "'"); - return false; - } - - this.cachedir = aCachedir1; - - return true; - } - -} Modified: branches/2.3/src/org/python/core/InternalTables.java =================================================================== --- branches/2.3/src/org/python/core/InternalTables.java 2007-05-16 19:47:04 UTC (rev 3231) +++ branches/2.3/src/org/python/core/InternalTables.java 2007-05-18 00:30:12 UTC (rev 3232) @@ -2,6 +2,8 @@ package org.python.core; +import org.python.core.packagecache.PackageManager; + import java.util.StringTokenizer; public abstract class InternalTables { @@ -134,4 +136,4 @@ } } -} \ No newline at end of file +} Deleted: branches/2.3/src/org/python/core/PackageManager.java =================================================================== --- branches/2.3/src/org/python/core/PackageManager.java 2007-05-16 19:47:04 UTC (rev 3231) +++ branches/2.3/src/org/python/core/PackageManager.java 2007-05-18 00:30:12 UTC (rev 3232) @@ -1,227 +0,0 @@ -// Copyright (c) Corporation for National Research Initiatives -// Copyright 2000 Samuele Pedroni - -package org.python.core; - -/** - * Abstract package manager. - */ -public abstract class PackageManager extends Object { - - public PyJavaPackage topLevelPackage; - - public PackageManager() { - this.topLevelPackage = new PyJavaPackage("", this); - } - - abstract public Class findClass(String pkg, String name, String reason); - - public Class findClass(String pkg, String name) { - return findClass(pkg, name, "java class"); - } - - public void notifyPackageImport(String pkg, String name) { - } - - /** - * Dynamically check if pkg.name exists as java pkg in the controlled - * hierarchy. Should be overriden. - * - * @param pkg parent pkg name - * @param name candidate name - * @return true if pkg exists - */ - public abstract boolean packageExists(String pkg, String name); - - /** - * Reports the specified package content names. Should be overriden. Used by - * {@link PyJavaPackage#__dir__} and {@link PyJavaPackage#fillDir}. - * - * @return resulting list of names (PyList of PyString) - * @param jpkg queried package - * @param instantiate if true then instatiate reported names in package dict - * @param exclpkgs exclude packages (just when instantiate is false) - */ - public abstract PyList doDir(PyJavaPackage jpkg, boolean instantiate, - boolean exclpkgs); - - /** - * Append a directory to the list of directories searched for java packages - * and java classes. - * - * @param dir A directory. - */ - public abstract void addDirectory(java.io.File dir); - - /** - * Append a directory to the list of directories searched for java packages - * and java classes. - * - * @param dir A directory name. - */ - public abstract void addJarDir(String dir, boolean cache); - - /** - * Append a jar file to the list of locations searched for java packages and - * java classes. - * - * @param jarfile A directory name. - */ - public abstract void addJar(String jarfile, boolean cache); - - /** - * Basic helper implementation of {@link #doDir}. It merges information - * from jpkg {@link PyJavaPackage#clsSet} and {@link PyJavaPackage#__dict__}. - */ - protected PyList basicDoDir(PyJavaPackage jpkg, boolean instantiate, - boolean exclpkgs) { - PyStringMap dict = jpkg.__dict__; - PyStringMap cls = jpkg.clsSet; - - if (!instantiate) { - PyList ret = cls.keys(); - - PyList dictKeys = dict.keys(); - - for (int i = 0; i < dictKeys.__len__(); i++) { - PyObject name = dictKeys.pyget(i); - if (!cls.has_key(name)) { - if (exclpkgs && dict.get(name) instanceof PyJavaPackage) - continue; - ret.append(name); - } - } - - return ret; - } - - PyList clsNames = cls.keys(); - - for (int i = 0; i < clsNames.__len__(); i++) { - PyObject name = clsNames.pyget(i); - if (!dict.has_key(name)) - jpkg.addLazyClass(name.toString()); - } - - return dict.keys(); - } - - /** - * Helper merging list2 into list1. Returns list1. - */ - protected PyList merge(PyList list1, PyList list2) { - for (int i = 0; i < list2.__len__(); i++) { - PyObject name = list2.pyget(i); - list1.append(name); - } - - return list1; - } - - public PyObject lookupName(String name) { - PyObject top = this.topLevelPackage; - do { - int dot = name.indexOf('.'); - String firstName = name; - String lastName = null; - if (dot != -1) { - firstName = name.substring(0, dot); - lastName = name.substring(dot + 1, name.length()); - } - firstName = firstName.intern(); - top = top.__findattr__(firstName); - if (top == null) - return null; - // ??pending: test for jpkg/jclass? - name = lastName; - } while (name != null); - return top; - } - - /** - * Creates package/updates statically known classes info. Uses - * {@link PyJavaPackage#addPackage(java.lang.String, java.lang.String) }, - * {@link PyJavaPackage#addPlaceholders}. - * - * @param name package name - * @param classes comma-separated string - * @param jarfile involved jarfile; can be null - * @return created/updated package - */ - public PyJavaPackage makeJavaPackage(String name, String classes, - String jarfile) { - PyJavaPackage p = this.topLevelPackage; - if (name.length() != 0) - p = p.addPackage(name, jarfile); - - if (classes != null) - p.addPlaceholders(classes); - - return p; - } - - /** - * Check that a given stream is a valid Java .class file. And return its - * access permissions as an int. - */ - static protected int checkAccess(java.io.InputStream cstream) - throws java.io.IOException { - java.io.DataInputStream istream = new java.io.DataInputStream(cstream); - - int magic = istream.readInt(); - - //int minor = - istream.readShort(); - //int major = - istream.readShort(); - - if (magic != 0xcafebabe) - return -1; - // Check versions??? - // System.out.println("magic: "+magic+", "+major+", "+minor); - int nconstants = istream.readShort(); - for (int i = 1; i < nconstants; i++) { - int cid = istream.readByte(); - // System.out.println(""+i+" : "+cid); - switch (cid) { - case 7: - istream.skipBytes(2); - break; - case 9: - case 10: - case 11: - istream.skipBytes(4); - break; - case 8: - istream.skipBytes(2); - break; - case 3: - case 4: - istream.skipBytes(4); - break; - case 5: - case 6: - istream.skipBytes(8); - i++; - break; - case 12: - istream.skipBytes(4); - break; - case 1: - // System.out.println("utf: "+istream.readUTF()+";"); - int slength = istream.readUnsignedShort(); - istream.skipBytes(slength); - break; - default: - // System.err.println("unexpected cid: "+cid+", "+i+", "+ - // nconstants); - // for (int j=0; j<10; j++) - // System.err.print(", "+istream.readByte()); - // System.err.println(); - return -1; - } - } - return istream.readShort(); - } - -} Deleted: branches/2.3/src/org/python/core/PathPackageManager.java =================================================================== --- branches/2.3/src/org/python/core/PathPackageManager.java 2007-05-16 19:47:04 UTC (rev 3231) +++ branches/2.3/src/org/python/core/PathPackageManager.java 2007-05-18 00:30:12 UTC (rev 3232) @@ -1,230 +0,0 @@ -// Copyright (c) Corporation for National Research Initiatives -// Copyright 2000 Samuele Pedroni - -package org.python.core; - -import java.io.BufferedInputStream; -import java.io.File; -import java.io.FileInputStream; -import java.io.FilenameFilter; -import java.io.IOException; - -/** - * Path package manager. Gathering classes info dynamically from a set of - * directories in path {@link #searchPath}, and statically from a set of jars, - * like {@link CachedJarsPackageManager}. - */ -public abstract class PathPackageManager extends CachedJarsPackageManager { - - public PyList searchPath; - - public PathPackageManager() { - this.searchPath = new PyList(); - } - - /** - * Helper for {@link #packageExists(java.lang.String,java.lang.String)}. - * Scans for package pkg.name the directories in path. - */ - protected boolean packageExists(PyList path, String pkg, String name) { - String child = pkg.replace('.', File.separatorChar) + File.separator - + name; - - for (int i = 0; i < path.__len__(); i++) { - String dir = imp.defaultEmptyPathDirectory(path.pyget(i).__str__().toString()); - - File f = new File(dir, child); - if (f.isDirectory() && imp.caseok(f, name, name.length())) { - /* - * Figure out if we have a directory a mixture of python and - * java or just an empty directory (which means Java) or a - * directory with only Python source (which means Python). - */ - PackageExistsFileFilter m = new PackageExistsFileFilter(); - f.listFiles(m); - boolean exists = m.packageExists(); - if (exists) { - Py.writeComment("import", "java package as '" - + f.getAbsolutePath() + "'"); - } - return exists; - } - } - return false; - } - - class PackageExistsFileFilter implements FilenameFilter { - private boolean java; - - private boolean python; - - public boolean accept(File dir, String name) { - if(name.endsWith(".py") || name.endsWith("$py.class") || name.endsWith("$_PyInner.class")) { - python = true; - }else if (name.endsWith(".class")) { - java = true; - } - return false; - } - - public boolean packageExists() { - if (this.python && !this.java) { - return false; - } - return true; - } - } - - /** - * Helper for {@link #doDir(PyJavaPackage,boolean,boolean)}. Scans for - * package jpkg content over the directories in path. Add to ret the founded - * classes/pkgs. Filter out classes using {@link #filterByName},{@link #filterByAccess}. - */ - protected void doDir(PyList path, PyList ret, PyJavaPackage jpkg, - boolean instantiate, boolean exclpkgs) { - String child = jpkg.__name__.replace('.', File.separatorChar); - - for (int i = 0; i < path.__len__(); i++) { - String dir = path.pyget(i).__str__().toString(); - if (dir.length() == 0) { - dir = null; - } - - File childFile = new File(dir, child); - - String[] list = childFile.list(); - if (list == null) { - continue; - } - - doList: for (int j = 0; j < list.length; j++) { - String jname = list[j]; - - File cand = new File(childFile, jname); - - int jlen = jname.length(); - - boolean pkgCand = false; - - if (cand.isDirectory()) { - if (!instantiate && exclpkgs) { - continue; - } - pkgCand = true; - } else { - if (!jname.endsWith(".class")) { - continue; - } - jlen -= 6; - } - - jname = jname.substring(0, jlen); - PyString name = new PyString(jname); - - if (filterByName(jname, pkgCand)) { - continue; - } - - // for opt maybe we should some hash-set for ret - if (jpkg.__dict__.has_key(name) || jpkg.clsSet.has_key(name) - || ret.__contains__(name)) { - continue; - } - - if (!Character.isJavaIdentifierStart(jname.charAt(0))) { - continue; - } - - for (int k = 1; k < jlen; k++) { - if (!Character.isJavaIdentifierPart(jname.charAt(k))) { - continue doList; - } - } - - if (!pkgCand) { - try { - int acc = checkAccess(new BufferedInputStream( - new FileInputStream(cand))); - if ((acc == -1) || filterByAccess(jname, acc)) { - continue; - } - } catch (IOException e) { - continue; - } - } - - if (instantiate) { - if (pkgCand) { - jpkg.addPackage(jname); - } else { - jpkg.addLazyClass(jname); - } - } - - ret.append(name); - - } - } - - } - - /** - * Add directory dir (if exists) to {@link #searchPath}. - */ - public void addDirectory(File dir) { - try { - if (dir.getPath().length() == 0) { - this.searchPath.append(Py.EmptyString); - } else { - this.searchPath.append(new PyString(dir.getCanonicalPath())); - } - } catch (IOException e) { - warning("skipping bad directory, '" + dir + "'"); - } - } - - // ??pending: - // Uses simply split and not a StringTokenizer+trim to adhere to - // sun jvm parsing of classpath. - // E.g. "a;" is parsed by sun jvm as a, ""; the latter is interpreted - // as cwd. jview trims and cwd is per default in classpath. - // The logic here should work for both(...). Need to distinguish? - // This code does not avoid duplicates in searchPath. - // Should cause no problem (?). - - /** - * Adds "classpath" entry. Calls {@link #addDirectory} if path refers to a - * dir, {@link #addJarToPackages(java.io.File, boolean)} with param cache - * true if path refers to a jar. - */ - public void addClassPath(String path) { - PyList paths = new PyString(path).split(java.io.File.pathSeparator); - - for (int i = 0; i < paths.__len__(); i++) { - String entry = paths.pyget(i).toString(); - if (entry.endsWith(".jar") || entry.endsWith(".zip")) { - addJarToPackages(new File(entry), true); - } else { - File dir = new File(entry); - if (entry.length() == 0 || dir.isDirectory()) { - addDirectory(dir); - } - } - } - } - - public PyList doDir(PyJavaPackage jpkg, boolean instantiate, - boolean exclpkgs) { - PyList basic = basicDoDir(jpkg, instantiate, exclpkgs); - PyList ret = new PyList(); - - doDir(this.searchPath, ret, jpkg, instantiate, exclpkgs); - - return merge(basic, ret); - } - - public boolean packageExists(String pkg, String name) { - return packageExists(this.searchPath, pkg, name); - } - -} Modified: branches/2.3/src/org/python/core/PyJavaClass.java =================================================================== --- branches/2.3/src/org/python/core/PyJavaClass.java 2007-05-16 19:47:04 UTC (rev 3231) +++ branches/2.3/src/org/python/core/PyJavaClass.java 2007-05-18 00:30:12 UTC (rev 3232) @@ -1,6 +1,8 @@ // Copyright (c) Corporation for National Research Initiatives package org.python.core; +import org.python.core.packagecache.PackageManager; + import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.Method; Modified: branches/2.3/src/org/python/core/PyJavaPackage.java =================================================================== --- branches/2.3/src/org/python/core/PyJavaPackage.java 2007-05-16 19:47:04 UTC (rev 3231) +++ branches/2.3/src/org/python/core/PyJavaPackage.java 2007-05-18 00:30:12 UTC (rev 3232) @@ -3,6 +3,8 @@ package org.python.core; +import org.python.core.packagecache.PackageManager; + import java.util.StringTokenizer; /** Modified: branches/2.3/src/org/python/core/PySystemState.java =================================================================== --- branches/2.3/src/org/python/core/PySystemState.java 2007-05-16 19:47:04 UTC (rev 3231) +++ branches/2.3/src/org/python/core/PySystemState.java 2007-05-18 00:30:12 UTC (rev 3232) @@ -4,6 +4,9 @@ package org.python.core; +import org.python.core.packagecache.PackageManager; +import org.python.core.packagecache.SysPackageManager; + import java.io.File; import java.io.FileInputStream; import java.io.FilterInputStream; Deleted: branches/2.3/src/org/python/core/SysPackageManager.java =================================================================== --- branches/2.3/src/org/python/core/SysPackageManager.java 2007-05-16 19:47:04 UTC (rev 3231) +++ branches/2.3/src/org/python/core/SysPackageManager.java 2007-05-18 00:30:12 UTC (rev 3232) @@ -1,162 +0,0 @@ -// Copyright (c) Corporation for National Research Initiatives -// Copyright 2000 Samuele Pedroni - -package org.python.core; - -import java.util.Properties; -import java.util.StringTokenizer; -import java.io.*; - -/** - * System package manager. Used by org.python.core.PySystemState. - */ -public class SysPackageManager extends PathPackageManager { - - protected void message(String msg) { - Py.writeMessage("*sys-package-mgr*", msg); - } - - protected void warning(String warn) { - Py.writeWarning("*sys-package-mgr*", warn); - } - - protected void comment(String msg) { - Py.writeComment("*sys-package-mgr*", msg); - } - - protected void debug(String msg) { - Py.writeDebug("*sys-package-mgr*", msg); - } - - public SysPackageManager(File cachedir, Properties registry) { - if (useCacheDir(cachedir)) { - initCache(); - findAllPackages(registry); - saveCache(); - } - } - - public void addJar(String jarfile, boolean cache) { - addJarToPackages(new File(jarfile), cache); - if (cache) { - saveCache(); - } - } - - public void addJarDir(String jdir, boolean cache) { - addJarDir(jdir, cache, cache); - } - - private void addJarDir(String jdir, boolean cache, boolean saveCache) { - File file = new File(jdir); - if (!file.isDirectory()) { - return; - } - String[] files = file.list(); - for (int i = 0; i < files.length; i++) { - String entry = files[i]; - if (entry.endsWith(".jar") || entry.endsWith(".zip")) { - addJarToPackages(new File(jdir, entry), cache); - } - } - if (saveCache) { - saveCache(); - } - } - - private void addJarPath(String path) { - StringTokenizer tok = new StringTokenizer(path, - java.io.File.pathSeparator); - while (tok.hasMoreTokens()) { - // ??pending: do jvms trim? how is interpreted entry=""? - String entry = tok.nextToken(); - addJarDir(entry, true, false); - } - } - - private void findAllPackages(Properties registry) { - String paths = registry.getProperty("python.packages.paths", - "java.class.path,sun.boot.class.path"); - String directories = registry.getProperty( - "python.packages.directories", "java.ext.dirs"); - String fakepath = registry - .getProperty("python.packages.fakepath", null); - StringTokenizer tok = new StringTokenizer(paths, ","); - while (tok.hasMoreTokens()) { - String entry = tok.nextToken().trim(); - String tmp = registry.getProperty(entry); - if (tmp == null) { - continue; - } - addClassPath(tmp); - } - - tok = new StringTokenizer(directories, ","); - while (tok.hasMoreTokens()) { - String entry = tok.nextToken().trim(); - String tmp = registry.getProperty(entry); - if (tmp == null) { - continue; - } - addJarPath(tmp); - } - - if (fakepath != null) { - addClassPath(fakepath); - } - } - - public void notifyPackageImport(String pkg, String name) { - if (pkg != null && pkg.length() > 0) { - name = pkg + '.' + name; - } - Py.writeComment("import", "'" + name + "' as java package"); - } - - public Class findClass(String pkg, String name) { - Class c = super.findClass(pkg, name); - if (c != null) { - Py.writeComment("import", "'" + name + "' as java class"); - } - return c; - } - - public Class findClass(String pkg, String name, String reason) { - if (pkg != null && pkg.length() > 0) { - name = pkg + '.' + name; - } - return Py.findClassEx(name, reason); - } - - public PyList doDir(PyJavaPackage jpkg, boolean instantiate, - boolean exclpkgs) { - PyList basic = basicDoDir(jpkg, instantiate, exclpkgs); - PyList ret = new PyList(); - - doDir(this.searchPath, ret, jpkg, instantiate, exclpkgs); - - PySystemState system = Py.getSystemState(); - - if (system.getClassLoader() == null) { - doDir(system.path, ret, jpkg, instantiate, exclpkgs); - } - - return merge(basic, ret); - } - - public boolean packageExists(String pkg, String name) { - if (packageExists(this.searchPath, pkg, name)) { - return true; - } - - PySystemState system = Py.getSystemState(); - - if (system.getClassLoader() == null - && packageExists(Py.getSystemState().path, pkg, name)) { - return true; - } - - return false; - } - -} Copied: branches/2.3/src/org/python/core/packagecache/CachedJarsPackageManager.java (from rev 3231, branches/2.3/src/org/python/core/CachedJarsPackageManager.java) =================================================================== --- branches/2.3/src/org/python/core/packagecache/CachedJarsPackageManager.java (rev 0) +++ branches/2.3/src/org/python/core/packagecache/CachedJarsPackageManager.java 2007-05-18 00:30:12 UTC (rev 3232) @@ -0,0 +1,597 @@ +// Copyright (c) Corporation for National Research Initiatives +// Copyright 2000 Samuele Pedroni + +package org.python.core.packagecache; + +import org.python.core.Options; + +import java.io.BufferedInputStream; +import java.io.BufferedOutputStream; +import java.io.DataInputStream; +import java.io.DataOutputStream; +import java.io.EOFException; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.lang.reflect.Modifier; +import java.net.URL; +import java.net.URLConnection; +import java.security.AccessControlException; +import java.util.Enumeration; +import java.util.Hashtable; +import java.util.Vector; +import java.util.zip.ZipEntry; +import java.util.zip.ZipInputStream; + +/** + * Abstract package manager that gathers info about statically known classes + * from a set of jars. This info can be eventually cached. Off-the-shelf this + * class offers a local file-system based cache impl. + */ +public abstract class CachedJarsPackageManager extends PackageManager { + + /** + * Message log method - hook. This default impl does nothing. + * + * @param msg message text + */ + protected void message(String msg) { + } + + /** + * Warning log method - hook. This default impl does nothing. + * + * @param warn warning text + */ + protected void warning(String warn) { + } + + /** + * Comment log method - hook. This default impl does nothing. + * + * @param msg message text + */ + protected void comment(String msg) { + } + + /** + * Debug log method - hook. This default impl does nothing. + * + * @param msg message text + */ + protected void debug(String msg) { + } + + /** + * Filter class/pkg by name helper method - hook. The default impl. is used + * by {@link #addJarToPackages} in order to filter out classes whose name + * contains '$' (e.g. inner classes,...). Should be used or overriden by + * derived classes too. Also to be used in {@link #doDir}. + * + * @param name class/pkg name + * @param pkg if true, name refers to a pkg + * @return true if name must be filtered out + */ + protected boolean filterByName(String name, boolean pkg) { + return name.indexOf('$') != -1; + } + + /** + * Filter class by access perms helper method - hook. The default impl. is + * used by {@link #addJarToPackages} in order to filter out non-public + * classes. Should be used or overriden by derived classes too. Also to be + * used in {@link #doDir}. Access perms can be read with + * {@link #checkAccess}. + * + * @param name class name + * @param acc class access permissions as int + * @return true if name must be filtered out + */ + protected boolean filterByAccess(String name, int acc) { + return (acc & Modifier.PUBLIC) != Modifier.PUBLIC; + } + + private boolean indexModified; + + private Hashtable jarfiles; + + private static String vectorToString(Vector vec) { + int n = vec.size(); + StringBuffer ret = new StringBuffer(); + for (int i = 0; i < n; i++) { + ret.append((String) vec.elementAt(i)); + if (i < n - 1) { + ret.append(","); + } + } + return ret.toString(); + } + + // Add a single class from zipFile to zipPackages + // Only add valid, public classes + private void addZipEntry(Hashtable zipPackages, ZipEntry entry, + ZipInputStream zip) throws IOException { + String name = entry.getName(); + // System.err.println("entry: "+name); + if (!name.endsWith(".class")) { + return; + } + + char sep = '/'; + int breakPoint = name.lastIndexOf(sep); + if (breakPoint == -1) { + breakPoint = name.lastIndexOf('\\'); + sep = '\\'; + } + + String packageName; + if (breakPoint == -1) { + packageName = ""; + } else { + packageName = name.substring(0, breakPoint).replace(sep, '.'); + } + + String className = name.substring(breakPoint + 1, name.length() - 6); + + if (filterByName(className, false)) { + return; + } + + Vector[] vec = (Vector[]) zipPackages.get(packageName); + if (vec == null) { + vec = new Vector[] { new Vector(), new Vector() }; + zipPackages.put(packageName, vec); + } + int access = checkAccess(zip); + if ((access != -1) && !filterByAccess(name, access)) { + vec[0].addElement(className); + } else { + vec[1].addElement(className); + } + } + + // Extract all of the packages in a single jarfile + private Hashtable getZipPackages(InputStream jarin) throws IOException { + Hashtable zipPackages = new Hashtable(); + + ZipInputStream zip = new ZipInputStream(jarin); + + ZipEntry entry; + while ((entry = zip.getNextEntry()) != null) { + addZipEntry(zipPackages, entry, zip); + zip.closeEntry(); + } + + // Turn each vector into a comma-separated String + for (Enumeration e = zipPackages.keys(); e.hasMoreElements();) { + Object key = e.nextElement(); + Vector[] vec = (Vector[]) zipPackages.get(key); + String classes = vectorToString(vec[0]); + if (vec[1].size() > 0) { + classes += '@' + vectorToString(vec[1]); + } + zipPackages.put(key, classes); + } + + return zipPackages; + } + + /** + * Gathers classes info from jar specified by jarurl URL. Eventually just + * using previously cached info. Eventually updated info is not cached. + * Persistent cache storage access goes through inOpenCacheFile() and + * outCreateCacheFile(). + */ + public void addJarToPackages(java.net.URL jarurl) { + addJarToPackages(jarurl, null, false); + } + + /** + * Gathers classes info from jar specified by jarurl URL. Eventually just + * using previously cached info. Eventually updated info is (re-)cached if + * param cache is true. Persistent cache storage access goes through + * inOpenCacheFile() and outCreateCacheFile(). + */ + public void addJarToPackages(URL jarurl, boolean cache) { + addJarToPackages(jarurl, null, cache); + } + + /** + * Gathers classes info from jar specified by File jarfile. Eventually just + * using previously cached info. Eventually updated info is not cached. + * Persistent cache storage access goes through inOpenCacheFile() and + * outCreateCacheFile(). + */ + public void addJarToPackages(File jarfile) { + addJarToPackages(null, jarfile, false); + } + + /** + * Gathers classes info from jar specified by File jarfile. Eventually just + * using previously cached info. Eventually updated info is (re-)cached if + * param cache is true. Persistent cache storage access goes through + * inOpenCacheFile() and outCreateCacheFile(). + */ + public void addJarToPackages(File jarfile, boolean cache) { + addJarToPackages(null, jarfile, cache); + } + + private void addJarToPackages(URL jarurl, File jarfile, boolean cache) { + try { + boolean caching = this.jarfiles != null; + + URLConnection jarconn = null; + boolean localfile = true; + + if (jarfile == null) { + jarconn = jarurl.openConnection(); + // This is necessary because 'file:' url-connections + // return always 0 through getLastModified (bug?). + // And in order to handle localfiles (from urls too) + // uniformly. + if (jarconn.getURL().getProtocol().equals("file")) { + // ??pending: need to use java2 URLDecoder.decode? + String jarfilename = jarurl.getFile(); + jarfilename = jarfilename.replace('/', File.separatorChar); + jarfile = new File(jarfilename); + } else { + localfile = false; + } + } + + if (localfile && !jarfile.exists()) { + return; + } + + Hashtable zipPackages = null; + + long mtime = 0; + String jarcanon = null; + JarXEntry entry = null; + boolean brandNew = false; + + if (caching) { + + if (localfile) { + mtime = jarfile.lastModified(); + jarcanon = jarfile.getCanonicalPath(); + } else { + mtime = jarconn.getLastModified(); + jarcanon = jarurl.toString(); + } + + entry = (JarXEntry) this.jarfiles.get(jarcanon); + + if ((entry == null || !(new File(entry.cachefile).exists())) + && cache) { + message("processing new jar, '" + jarcanon + "'"); + + String jarname; + if (localfile) { + jarname = jarfile.getName(); + } else { + jarname = jarurl.getFile(); + int slash = jarname.lastIndexOf('/'); + if (slash != -1) + jarname = jarname.substring(slash + 1); + } + jarname = jarname.substring(0, jarname.length() - 4); + + entry = new JarXEntry(jarname); + this.jarfiles.put(jarcanon, entry); + + brandNew = true; + } + + if (mtime != 0 && entry != null && entry.mtime == mtime) { + zipPackages = readCacheFile(entry, jarcanon); + } + + } + + if (zipPackages == null) { + caching = caching && cache; + + if (caching) { + this.indexModified = true; + if (entry.mtime != 0) { + message("processing modified jar, '" + jarcanon + "'"); + } + entry.mtime = mtime; + } + + InputStream jarin; + if (jarconn == null) { + jarin = new BufferedInputStream( + new FileInputStream(jarfile)); + } else { + jarin = jarconn.getInputStream(); + } + + zipPackages = getZipPackages(jarin); + + if (caching) { + writeCacheFile(entry, jarcanon, zipPackages, brandNew); + } + } + + addPackages(zipPackages, jarcanon); + } catch (IOException ioe) { + // silently skip any bad directories + warning("skipping bad jar, '" + + (jarfile != null ? jarfile.toString() : jarurl.toString()) + + "'"); + } + + } + + private void addPackages(Hashtable zipPackages, String jarfile) { + for (Enumeration e = zipPackages.keys(); e.hasMoreElements();) { + String pkg = (String) e.nextElement(); + String classes = (String) zipPackages.get(pkg); + + int idx = classes.indexOf('@'); + if (idx >= 0 && Options.respectJavaAccessibility) { + classes = classes.substring(0, idx); + } + + makeJavaPackage(pkg, classes, jarfile); + } + } + + // Read in cache file storing package info for a single .jar + // Return null and delete this cachefile if it is invalid + private Hashtable readCacheFile(JarXEntry entry, String jarcanon) { + String cachefile = entry.cachefile; + long mtime = entry.mtime; + + debug("reading cache, '" + jarcanon + "'"); + + try { + DataInputStream istream = inOpenCacheFile(cachefile); + String old_jarcanon = istream.readUTF(); + long old_mtime = istream.readLong(); + if ((!old_jarcanon.equals(jarcanon)) || (old_mtime != mtime)) { + comment("invalid cache file: " + cachefile + ", " + jarcanon + + ":" + old_jarcanon + ", " + mtime + ":" + old_mtime); + deleteCacheFile(cachefile); + return null; + } + Hashtable packs = new Hashtable(); + try { + while (true) { + String packageName = istream.readUTF(); + String classes = istream.readUTF(); + packs.put(packageName, classes); + } + } catch (EOFException eof) { + ; + } + istream.close(); + + return packs; + } catch (IOException ioe) { + // if (cachefile.exists()) cachefile.delete(); + return null; + } + } + + // Write a cache file storing package info for a single .jar + private void writeCacheFile(JarXEntry entry, String jarcanon, + Hashtable zipPackages, boolean brandNew) { + try { + DataOutputStream ostream = outCreateCacheFile(entry, brandNew); + ostream.writeUTF(jarcanon); + ostream.writeLong(entry.mtime); + comment("rewriting cachefile for '" + jarcanon + "'"); + + for (Enumeration e = zipPackages.keys(); e.hasMoreElements();) { + String packageName = (String) e.nextElem... [truncated message content] |
From: <fwi...@us...> - 2007-06-06 18:28:50
|
Revision: 3249 http://svn.sourceforge.net/jython/?rev=3249&view=rev Author: fwierzbicki Date: 2007-06-06 11:28:48 -0700 (Wed, 06 Jun 2007) Log Message: ----------- svn merge -r 3188:3202 https://jython.svn.sourceforge.net/svnroot/jython/trunk/jython Modified Paths: -------------- branches/2.3/Lib/test/regrtest.py branches/2.3/NEWS branches/2.3/build.xml branches/2.3/src/org/python/compiler/Module.java branches/2.3/src/org/python/core/CollectionIter.java branches/2.3/src/org/python/core/CollectionIter2.java branches/2.3/src/org/python/core/Py.java branches/2.3/src/org/python/core/PyObject.java branches/2.3/src/org/python/core/PySystemState.java branches/2.3/src/org/python/core/__builtin__.java branches/2.3/src/org/python/modules/py_compile.java branches/2.3/src/org/python/util/JLineConsole.java branches/2.3/src/org/python/util/PyServlet.java branches/2.3/src/org/python/util/PythonInterpreter.java Modified: branches/2.3/Lib/test/regrtest.py =================================================================== --- branches/2.3/Lib/test/regrtest.py 2007-05-30 05:19:19 UTC (rev 3248) +++ branches/2.3/Lib/test/regrtest.py 2007-06-06 18:28:48 UTC (rev 3249) @@ -1054,7 +1054,6 @@ test_cpickle test_descr test_descrtut - test_doctest2 test_frozen test_marshal test_new @@ -1066,7 +1065,6 @@ test_threaded_import test_trace test_weakref - test_zlib ''', } Modified: branches/2.3/NEWS =================================================================== --- branches/2.3/NEWS 2007-05-30 05:19:19 UTC (rev 3248) +++ branches/2.3/NEWS 2007-06-06 18:28:48 UTC (rev 3249) @@ -31,6 +31,7 @@ - [ 663592 ] Problems calling an overriden class in the constructor - [ 448398 ] open('test.txt', 'w').write('test') fails - [ 1671373 ] A "$_PyInner.class" file in a package causes import to fail + - [ 1671431 ] dir function does not work with database connection object Patches applied - [ 1681774 ] str.decode, unicode.encode and str(u'') fixes - [ 1682423 ] Convert PyModule to a new-style class Modified: branches/2.3/build.xml =================================================================== --- branches/2.3/build.xml 2007-05-30 05:19:19 UTC (rev 3248) +++ branches/2.3/build.xml 2007-06-06 18:28:48 UTC (rev 3249) @@ -626,6 +626,7 @@ <patternset> <includesfile name="${jython.base.dir}/build.Lib.include.properties" /> <exclude name="test/output/test_sax"/> + <exclude name="test/output/test_zlib"/> </patternset> </fileset> </copy> Modified: branches/2.3/src/org/python/compiler/Module.java =================================================================== --- branches/2.3/src/org/python/compiler/Module.java 2007-05-30 05:19:19 UTC (rev 3248) +++ branches/2.3/src/org/python/compiler/Module.java 2007-06-06 18:28:48 UTC (rev 3249) @@ -555,19 +555,15 @@ } public void addMain() throws IOException { - Code c = classfile.addMethod("main", "(" + $str + ")V", - ClassFile.PUBLIC | ClassFile.STATIC); - - - int mref_self = c.pool.Fieldref(classfile.name, - "self", - "L"+classfile.name+";"); - c.getstatic(mref_self); + Code c = classfile.addMethod("main", "(" + $strArr + ")V", + ClassFile.PUBLIC | ClassFile.STATIC); + c.new_(c.pool.Class(classfile.name)); + c.dup(); + c.ldc(classfile.name); + c.invokespecial(c.pool.Methodref(classfile.name, "<init>", "(" + $str + ")V")); c.aload(0); - c.invokestatic(c.pool.Methodref( - "org/python/core/Py", - "do_main", - "(" + $pyRunnable + $strArr + ")V")); + c.invokestatic(c.pool.Methodref("org/python/core/Py", "runMain", "(" + + $pyRunnable + $strArr + ")V")); c.return_(); } @@ -632,7 +628,7 @@ public void write(OutputStream stream) throws IOException { addInit(); addRunnable(); - //addMain(); + addMain(); addFunctions(); Modified: branches/2.3/src/org/python/core/CollectionIter.java =================================================================== --- branches/2.3/src/org/python/core/CollectionIter.java 2007-05-30 05:19:19 UTC (rev 3248) +++ branches/2.3/src/org/python/core/CollectionIter.java 2007-06-06 18:28:48 UTC (rev 3249) @@ -2,7 +2,9 @@ package org.python.core; -import java.util.*; +import java.util.Dictionary; +import java.util.Enumeration; +import java.util.Vector; class CollectionIter extends PyObject { PyObject findCollection(Object object) { Modified: branches/2.3/src/org/python/core/CollectionIter2.java =================================================================== --- branches/2.3/src/org/python/core/CollectionIter2.java 2007-05-30 05:19:19 UTC (rev 3248) +++ branches/2.3/src/org/python/core/CollectionIter2.java 2007-06-06 18:28:48 UTC (rev 3249) @@ -2,7 +2,10 @@ package org.python.core; -import java.util.*; +import java.lang.reflect.Method; +import java.util.Collection; +import java.util.Iterator; +import java.util.Map; class CollectionIter2 extends CollectionIter { CollectionIter2() throws Exception { @@ -19,7 +22,18 @@ if (object instanceof Iterator) { return new IteratorIter(((Iterator) object)); } - + try { + // TODO - Once we depend on Java 5 we can replace this with a check + // for the Iterable interface + Method m = object.getClass().getMethod("iterator", new Class[0]); + if (Iterator.class.isAssignableFrom(m.getReturnType())) { + return new IteratorIter((Iterator) m.invoke(object, + new Object[0])); + } + } catch (Exception e) { + // Looks like one of the many reflection based exceptions ocurred so + // we won't get an Iterator this way + } return null; } } Modified: branches/2.3/src/org/python/core/Py.java =================================================================== --- branches/2.3/src/org/python/core/Py.java 2007-05-30 05:19:19 UTC (rev 3248) +++ branches/2.3/src/org/python/core/Py.java 2007-06-06 18:28:48 UTC (rev 3249) @@ -1,10 +1,21 @@ // Copyright (c) Corporation for National Research Initiatives package org.python.core; -import org.python.parser.ast.modType; +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileOutputStream; +import java.io.InputStream; +import java.io.ObjectStreamException; +import java.io.OutputStream; +import java.io.PrintStream; +import java.io.Serializable; +import java.io.StreamCorruptedException; +import java.io.Writer; import java.lang.reflect.InvocationTargetException; -import java.io.*; +import org.python.compiler.Module; +import org.python.parser.ast.modType; + public final class Py { static boolean frozen; @@ -927,6 +938,27 @@ Py.runCode(code, dict, dict); } + /** + * Initializes a default PythonInterpreter and runs the code from + * {@link PyRunnable#getMain} as __main__ + * + * Called by the code generated in {@link Module#addMain()} + */ + public static void runMain(PyRunnable main, String[] args) throws Exception + { + initProperties(args, null, null, null, null, main.getClass() + .getClassLoader()); + try { + imp.createFromCode("__main__", main.getMain()); + } catch (PyException e) { + Py.getSystemState().callExitFunc(); + if (Py.matchException(e, Py.SystemExit)) + return; + throw e; + } + Py.getSystemState().callExitFunc(); + } + public static void runMain(Class mainClass, String[] args, String[] packages, String[] props, @@ -1719,9 +1751,8 @@ { try { ByteArrayOutputStream ostream = new ByteArrayOutputStream(); - org.python.compiler.Module.compile(node, ostream, name, filename, - linenumbers, printResults, - false,cflags); + Module.compile(node, ostream, name, filename, linenumbers, + printResults, false, cflags); saveClassFile(name, ostream); @@ -1753,8 +1784,8 @@ public static PyObject compile_command_flags(String string, String filename, String kind, CompilerFlags cflags,boolean stdprompt) { - org.python.parser.ast.modType node = - parser.partialParse(string+"\n", kind, filename, cflags, stdprompt); + modType node = parser.partialParse(string + "\n", kind, filename, + cflags, stdprompt); if (node == null) return Py.None; Modified: branches/2.3/src/org/python/core/PyObject.java =================================================================== --- branches/2.3/src/org/python/core/PyObject.java 2007-05-30 05:19:19 UTC (rev 3248) +++ branches/2.3/src/org/python/core/PyObject.java 2007-06-06 18:28:48 UTC (rev 3249) @@ -1119,8 +1119,9 @@ for (; (name = lst_iter.__iternext__())!= null; ) { accum.__setitem__(name, Py.None); } + } else { + accum.update(obj); } - accum.update(obj); } protected void __rawdir__(PyDictionary accum) { Modified: branches/2.3/src/org/python/core/PySystemState.java =================================================================== --- branches/2.3/src/org/python/core/PySystemState.java 2007-05-30 05:19:19 UTC (rev 3248) +++ branches/2.3/src/org/python/core/PySystemState.java 2007-06-06 18:28:48 UTC (rev 3249) @@ -110,9 +110,9 @@ exit(Py.None); } - public PyObject modules; // = new PyStringMap(); + public PyObject modules; public PyList path; - public PyObject builtins; + public static PyObject builtins; public PyList meta_path; public PyList path_hooks; @@ -279,8 +279,6 @@ if(builtins == null){ builtins = new PyStringMap(); __builtin__.fillWithBuiltins(builtins); - }else{ - builtins = Py.defaultSystemState.builtins; } PyModule __builtin__ = new PyModule("__builtin__", builtins); modules.__setitem__("__builtin__", __builtin__); @@ -477,7 +475,7 @@ if (classLoader != null) Py.defaultSystemState.setClassLoader(classLoader); - Py.initClassExceptions(Py.defaultSystemState.builtins); + Py.initClassExceptions(PySystemState.builtins); // Make sure that Exception classes have been loaded new PySyntaxError("", 1,1,"", ""); } Modified: branches/2.3/src/org/python/core/__builtin__.java =================================================================== --- branches/2.3/src/org/python/core/__builtin__.java 2007-05-30 05:19:19 UTC (rev 3248) +++ branches/2.3/src/org/python/core/__builtin__.java 2007-06-06 18:28:48 UTC (rev 3249) @@ -305,7 +305,6 @@ public class __builtin__ { public static void fillWithBuiltins(PyObject dict) { /* newstyle */ - dict.__setitem__("object", PyType.fromClass(PyObject.class)); dict.__setitem__("type", PyType.fromClass(PyType.class)); dict.__setitem__("bool", PyType.fromClass(PyBoolean.class)); Modified: branches/2.3/src/org/python/modules/py_compile.java =================================================================== --- branches/2.3/src/org/python/modules/py_compile.java 2007-05-30 05:19:19 UTC (rev 3248) +++ branches/2.3/src/org/python/modules/py_compile.java 2007-06-06 18:28:48 UTC (rev 3249) @@ -24,9 +24,20 @@ if (dot != -1) { name = name.substring(0, dot); } + // Make the compiled classfile's name the fully qualified with a package by + // walking up the directory tree looking for __init__.py files. Don't + // check for __init__$py.class since we're compiling source here and the + // existence of a class file without corresponding source probably doesn't + // indicate a package. + File dir = file.getParentFile(); + while (dir != null && (new File(dir, "__init__.py").exists())) { + name = dir.getName() + "." + name; + dir = dir.getParentFile(); + } byte[] bytes = org.python.core.imp.compileSource(name, file, dfile, cfile); - org.python.core.imp.cacheCompiledSource(filename, null, bytes); + org.python.core.imp.cacheCompiledSource(filename, cfile, bytes); return bytes.length > 0; } + } Modified: branches/2.3/src/org/python/util/JLineConsole.java =================================================================== --- branches/2.3/src/org/python/util/JLineConsole.java 2007-05-30 05:19:19 UTC (rev 3248) +++ branches/2.3/src/org/python/util/JLineConsole.java 2007-06-06 18:28:48 UTC (rev 3249) @@ -44,5 +44,5 @@ return line.endsWith("\n") ? line.substring(0, line.length() - 1) : line; } - private ConsoleReader reader; + protected ConsoleReader reader; } Modified: branches/2.3/src/org/python/util/PyServlet.java =================================================================== --- branches/2.3/src/org/python/util/PyServlet.java 2007-05-30 05:19:19 UTC (rev 3248) +++ branches/2.3/src/org/python/util/PyServlet.java 2007-06-06 18:28:48 UTC (rev 3249) @@ -94,20 +94,17 @@ File.separator + "lib"); } - PythonInterpreter.initialize(baseProps, props, - new String[0]); + PySystemState.initialize(baseProps, props, new String[0]); reset(); - PySystemState sys = Py.getSystemState(); - sys.add_package("javax.servlet"); - sys.add_package("javax.servlet.http"); - sys.add_package("javax.servlet.jsp"); - sys.add_package("javax.servlet.jsp.tagext"); + PySystemState.add_package("javax.servlet"); + PySystemState.add_package("javax.servlet.http"); + PySystemState.add_package("javax.servlet.jsp"); + PySystemState.add_package("javax.servlet.jsp.tagext"); - sys.add_classdir(rootPath + "WEB-INF" + - File.separator + "classes"); + PySystemState.add_classdir(rootPath + "WEB-INF" + File.separator + "classes"); - sys.add_extdir(rootPath + "WEB-INF" + File.separator + "lib", true); + PySystemState.add_extdir(rootPath + "WEB-INF" + File.separator + "lib", true); } /** @@ -122,8 +119,7 @@ { req.setAttribute("pyservlet", this); - String spath = (String)req.getAttribute( - "javax.servlet.include.servlet_path"); + String spath = (String) req.getAttribute("javax.servlet.include.servlet_path"); if (spath == null) { spath = ((HttpServletRequest) req).getServletPath(); if (spath == null || spath.length() == 0) { @@ -147,11 +143,11 @@ destroyCache(); interp = new PythonInterpreter(null, new PySystemState()); cache.clear(); + PySystemState sys = Py.getSystemState(); sys.path.append(new PyString(rootPath)); - String modulesDir = rootPath + "WEB-INF" + - File.separator + "jython"; + String modulesDir = rootPath + "WEB-INF" + File.separator + "jython"; sys.path.append(new PyString(modulesDir)); } @@ -187,21 +183,20 @@ try { interp.execfile(path); PyObject cls = interp.get(name); - if (cls == null) - throw new ServletException("No callable (class or function) "+ - "named " + name + " in " + path); - + if (cls == null) { + throw new ServletException("No callable (class or function) named " + name + " in " + + path); + } PyObject pyServlet = cls.__call__(); Object o = pyServlet.__tojava__(HttpServlet.class); - if (o == Py.NoConversion) - throw new ServletException("The value from " + name + - "must extend HttpServlet"); + if (o == Py.NoConversion) { + throw new ServletException("The value from " + name + " must extend HttpServlet"); + } servlet = (HttpServlet)o; servlet.init(getServletConfig()); } catch (PyException e) { - throw new ServletException("Could not create "+ - "Jython servlet" + e.toString()); + throw new ServletException(e); } CacheEntry entry = new CacheEntry(servlet, file.lastModified()); cache.put(path, entry); Modified: branches/2.3/src/org/python/util/PythonInterpreter.java =================================================================== --- branches/2.3/src/org/python/util/PythonInterpreter.java 2007-05-30 05:19:19 UTC (rev 3248) +++ branches/2.3/src/org/python/util/PythonInterpreter.java 2007-06-06 18:28:48 UTC (rev 3249) @@ -19,20 +19,19 @@ protected CompilerFlags cflags = null; /** - * Initialize the jython runtime. This method should only be - * called once, and should be call before any other python objects - * are created (included a PythonInterpreter). - * - * @param preProperties A set of properties. Typically - * System.getProperties() is used. - * @param postProperties An other set of properties. Values like - * python.home, python.path and all other - * values from the registry files can be - * added to this property set. PostProperties - * will override system properties and - * registry properties. - * @param argv Command line argument. These values will - * assigned to sys.argv. + * Initializes the jython runtime. This should only be called once, and + * should be called before any other python objects are created (including a + * PythonInterpreter). + * + * @param preProperties + * A set of properties. Typically System.getProperties() is used. + * @param postProperties + * An other set of properties. Values like python.home, + * python.path and all other values from the registry files can + * be added to this property set. PostProperties will override + * system properties and registry properties. + * @param argv + * Command line argument. These values will assigned to sys.argv. */ public static void initialize(Properties preProperties, Properties postProperties, @@ -60,7 +59,6 @@ } public PythonInterpreter(PyObject dict, PySystemState systemState) { - PySystemState.initialize(); if (dict == null) dict = new PyStringMap(); if (systemState == null) { This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <fwi...@us...> - 2007-06-07 02:35:44
|
Revision: 3250 http://svn.sourceforge.net/jython/?rev=3250&view=rev Author: fwierzbicki Date: 2007-06-06 19:35:42 -0700 (Wed, 06 Jun 2007) Log Message: ----------- svn merge -r 3206:3212 https://jython.svn.sourceforge.net/svnroot/jython/trunk/jython Modified Paths: -------------- branches/2.3/Lib/javashell.py branches/2.3/NEWS branches/2.3/src/org/python/core/Py.java branches/2.3/src/org/python/core/PyGetSetDescr.java branches/2.3/src/org/python/core/PySystemState.java branches/2.3/src/org/python/util/JLineConsole.java Added Paths: ----------- branches/2.3/src/org/python/core/adapter/ branches/2.3/src/org/python/core/adapter/ClassAdapter.java branches/2.3/src/org/python/core/adapter/ClassicPyObjectAdapter.java branches/2.3/src/org/python/core/adapter/ExtensiblePyObjectAdapter.java branches/2.3/src/org/python/core/adapter/PyObjectAdapter.java Removed Paths: ------------- branches/2.3/src/org/python/core/adapter/ClassAdapter.java branches/2.3/src/org/python/core/adapter/ClassicPyObjectAdapter.java branches/2.3/src/org/python/core/adapter/ExtensiblePyObjectAdapter.java branches/2.3/src/org/python/core/adapter/PyObjectAdapter.java Modified: branches/2.3/Lib/javashell.py =================================================================== --- branches/2.3/Lib/javashell.py 2007-06-06 18:28:48 UTC (rev 3249) +++ branches/2.3/Lib/javashell.py 2007-06-07 02:35:42 UTC (rev 3250) @@ -138,7 +138,8 @@ _osTypeMap = ( ( "nt", ( 'nt', 'Windows NT', 'Windows NT 4.0', 'WindowsNT', - 'Windows 2000', 'Windows 2003', 'Windows XP', 'Windows CE' )), + 'Windows 2000', 'Windows 2003', 'Windows XP', 'Windows CE', + 'Windows Vista' )), ( "dos", ( 'dos', 'Windows 95', 'Windows 98', 'Windows ME' )), ( "mac", ( 'mac', 'MacOS', 'Darwin' )), ( "None", ( 'None', )), Modified: branches/2.3/NEWS =================================================================== --- branches/2.3/NEWS 2007-06-06 18:28:48 UTC (rev 3249) +++ branches/2.3/NEWS 2007-06-07 02:35:42 UTC (rev 3250) @@ -32,6 +32,7 @@ - [ 448398 ] open('test.txt', 'w').write('test') fails - [ 1671373 ] A "$_PyInner.class" file in a package causes import to fail - [ 1671431 ] dir function does not work with database connection object + - [ 1713513 ] os.environ fails in Windows Vista JDK 1.6_01 Patches applied - [ 1681774 ] str.decode, unicode.encode and str(u'') fixes - [ 1682423 ] Convert PyModule to a new-style class Modified: branches/2.3/src/org/python/core/Py.java =================================================================== --- branches/2.3/src/org/python/core/Py.java 2007-06-06 18:28:48 UTC (rev 3249) +++ branches/2.3/src/org/python/core/Py.java 2007-06-07 02:35:42 UTC (rev 3250) @@ -14,6 +14,8 @@ import java.lang.reflect.InvocationTargetException; import org.python.compiler.Module; +import org.python.core.adapter.ClassicPyObjectAdapter; +import org.python.core.adapter.ExtensiblePyObjectAdapter; import org.python.parser.ast.modType; public final class Py @@ -1527,7 +1529,7 @@ private static PyString[] letters=null; - static final PyString makeCharacter(Character o) { + public static final PyString makeCharacter(Character o) { return makeCharacter(o.charValue()); } @@ -1547,49 +1549,27 @@ } return letters[c]; } - - // Needs rewriting for efficiency and extensibility - public static PyObject java2py(Object o) { - if (o instanceof PyObject) - return (PyObject)o; - - if (o instanceof PyProxy) - return ((PyProxy)o)._getPyInstance(); - - if (o instanceof Number) { - if (o instanceof Double || o instanceof Float) { - return new PyFloat(((Number)o).doubleValue()); - } - else if (o instanceof Long) { - return new PyLong(((Number)o).longValue()); - } - else if (o instanceof Integer || - o instanceof Byte || - o instanceof Short) - { - return new PyInteger(((Number)o).intValue()); - } - } - if (o instanceof Boolean) { - return ((Boolean)o).booleanValue() ? Py.True : Py.False; - } - if (o == null) return Py.None; - if (o instanceof String) return new PyString((String)o); - if (o instanceof Character) return makeCharacter((Character)o); - if (o instanceof Class) { - Class cls = (Class)o; - if (PyObject.class.isAssignableFrom(cls)) { - return PyType.fromClass(cls); - } - return PyJavaClass.lookup(cls); - } - - Class c = o.getClass(); - if (c.isArray()) { - return new PyArray(c.getComponentType(), o); - } - return new PyJavaInstance(o); + + /** + * Uses the PyObjectAdapter passed to {@link PySystemState#initialize} to turn o into a PyObject. + * + * @see ClassicPyObjectAdapter - default PyObjectAdapter type + */ + public static PyObject java2py(Object o) { + return adapter.adapt(o); + } + + /** + * @return the ExtensiblePyObjectAdapter used by java2py. + */ + public static ExtensiblePyObjectAdapter getAdapter(){ + return adapter; } + + /** + * Handles wrapping Java objects in PyObject to expose them to jython. + */ + protected static ExtensiblePyObjectAdapter adapter; public static PyObject makeClass(String name, PyObject[] bases, PyCode code, PyObject doc) Modified: branches/2.3/src/org/python/core/PyGetSetDescr.java =================================================================== --- branches/2.3/src/org/python/core/PyGetSetDescr.java 2007-06-06 18:28:48 UTC (rev 3249) +++ branches/2.3/src/org/python/core/PyGetSetDescr.java 2007-06-07 02:35:42 UTC (rev 3250) @@ -36,28 +36,28 @@ try { get_meth = c.getMethod(get, new Class[] {}); } catch(NoSuchMethodException e) { - throw Py.SystemError("bogus getset spec"); + throw Py.SystemError("method "+get+" doesn't exist: "+c.getName()); } if(Modifier.isStatic(get_meth.getModifiers())) - throw Py.SystemError("static getset not supported"); + throw Py.SystemError("static "+get+" not supported: "+c.getName()); getset_type = get_meth.getReturnType(); if(set != null) { try { set_meth = c.getMethod(set, new Class[] {getset_type}); } catch(NoSuchMethodException e) { - throw Py.SystemError("bogus getset spec"); + throw Py.SystemError("method "+set+" doesn't exist: "+c.getName()); } if(Modifier.isStatic(set_meth.getModifiers())) - throw Py.SystemError("static getset not supported"); + throw Py.SystemError("static "+set+" not supported: "+c.getName()); } if(del != null) { try { del_meth = c.getMethod(del, new Class[] {}); } catch(NoSuchMethodException e) { - throw Py.SystemError("bogus getset spec"); + throw Py.SystemError("method "+set+" doesn't exist: "+c.getName()); } if(Modifier.isStatic(del_meth.getModifiers())) - throw Py.SystemError("static getset not supported"); + throw Py.SystemError("static "+del+" not supported: "+c.getName()); } } Modified: branches/2.3/src/org/python/core/PySystemState.java =================================================================== --- branches/2.3/src/org/python/core/PySystemState.java 2007-06-06 18:28:48 UTC (rev 3249) +++ branches/2.3/src/org/python/core/PySystemState.java 2007-06-07 02:35:42 UTC (rev 3250) @@ -21,6 +21,8 @@ import java.util.StringTokenizer; import java.util.jar.JarEntry; import java.util.jar.JarFile; +import org.python.core.adapter.ClassicPyObjectAdapter; +import org.python.core.adapter.ExtensiblePyObjectAdapter; import org.python.modules.Setup; /** @@ -435,6 +437,14 @@ String[] argv, ClassLoader classLoader) { + initialize(preProperties, postProperties, argv, classLoader, new ClassicPyObjectAdapter()); + } + public static synchronized void initialize(Properties preProperties, + Properties postProperties, + String[] argv, + ClassLoader classLoader, + ExtensiblePyObjectAdapter adapter) + { //System.err.println("initializing system state"); //Thread.currentThread().dumpStack(); @@ -449,6 +459,7 @@ } initialized = true; + Py.adapter = adapter; boolean standalone = false; String jarFileName = getJarFileName(); if (jarFileName != null) { Copied: branches/2.3/src/org/python/core/adapter (from rev 3212, trunk/jython/src/org/python/core/adapter) Deleted: branches/2.3/src/org/python/core/adapter/ClassAdapter.java =================================================================== --- trunk/jython/src/org/python/core/adapter/ClassAdapter.java 2007-05-06 06:44:44 UTC (rev 3212) +++ branches/2.3/src/org/python/core/adapter/ClassAdapter.java 2007-06-07 02:35:42 UTC (rev 3250) @@ -1,19 +0,0 @@ -package org.python.core.adapter; - -public abstract class ClassAdapter implements PyObjectAdapter { - - public ClassAdapter(Class adaptedClass) { - this.adaptedClass = adaptedClass; - } - - public Class getAdaptedClass() { - return adaptedClass; - } - - public boolean canAdapt(Object o) { - return adaptedClass.getClass().equals(adaptedClass); - } - - private Class adaptedClass; - -} Copied: branches/2.3/src/org/python/core/adapter/ClassAdapter.java (from rev 3212, trunk/jython/src/org/python/core/adapter/ClassAdapter.java) =================================================================== --- branches/2.3/src/org/python/core/adapter/ClassAdapter.java (rev 0) +++ branches/2.3/src/org/python/core/adapter/ClassAdapter.java 2007-06-07 02:35:42 UTC (rev 3250) @@ -0,0 +1,19 @@ +package org.python.core.adapter; + +public abstract class ClassAdapter implements PyObjectAdapter { + + public ClassAdapter(Class adaptedClass) { + this.adaptedClass = adaptedClass; + } + + public Class getAdaptedClass() { + return adaptedClass; + } + + public boolean canAdapt(Object o) { + return adaptedClass.getClass().equals(adaptedClass); + } + + private Class adaptedClass; + +} Deleted: branches/2.3/src/org/python/core/adapter/ClassicPyObjectAdapter.java =================================================================== --- trunk/jython/src/org/python/core/adapter/ClassicPyObjectAdapter.java 2007-05-06 06:44:44 UTC (rev 3212) +++ branches/2.3/src/org/python/core/adapter/ClassicPyObjectAdapter.java 2007-06-07 02:35:42 UTC (rev 3250) @@ -1,154 +0,0 @@ -package org.python.core.adapter; - -import org.python.core.Py; -import org.python.core.PyArray; -import org.python.core.PyFloat; -import org.python.core.PyInteger; -import org.python.core.PyJavaClass; -import org.python.core.PyJavaInstance; -import org.python.core.PyLong; -import org.python.core.PyObject; -import org.python.core.PyProxy; -import org.python.core.PyString; -import org.python.core.PyType; - -/** - * Implements the algorithm originally used in {@link Py#java2py} to adapt objects. - * - * Pre-class adapters are added to handle instances of PyObject, PyProxy and - * null values. Class adapters are added to handle builtin Java classes: String, - * Integer, Float, Double, Byte, Long, Short, Character, Class and Boolean. An - * adapter is added to the post-class adapters to handle wrapping arrays - * properly. Finally, if all of the added adapters can handle an object, it's - * wrapped in a PyJavaInstance. - * - */ -public class ClassicPyObjectAdapter extends ExtensiblePyObjectAdapter { - - public ClassicPyObjectAdapter() { - addPreClass(new PyObjectAdapter() { - - public PyObject adapt(Object o) { - return (PyObject) o; - } - - public boolean canAdapt(Object o) { - return o instanceof PyObject; - } - }); - addPreClass(new PyObjectAdapter() { - - public PyObject adapt(Object o) { - return ((PyProxy) o)._getPyInstance(); - } - - public boolean canAdapt(Object o) { - return o instanceof PyProxy; - } - }); - addPreClass(new PyObjectAdapter() { - - public boolean canAdapt(Object o) { - return o == null; - } - - public PyObject adapt(Object o) { - return Py.None; - } - }); - - add(new ClassAdapter(String.class) { - - public PyObject adapt(Object o) { - return new PyString((String) o); - } - - }); - add(new ClassAdapter(Character.class) { - - public PyObject adapt(Object o) { - return Py.makeCharacter((Character) o); - } - - }); - add(new ClassAdapter(Class.class) { - - public PyObject adapt(Object o) { - Class cls = (Class) o; - if (PyObject.class.isAssignableFrom(cls)) { - return PyType.fromClass(cls); - } - return PyJavaClass.lookup(cls); - } - - }); - add(new NumberToPyFloat(Double.class)); - add(new NumberToPyFloat(Float.class)); - add(new NumberToPyInteger(Integer.class)); - add(new NumberToPyInteger(Byte.class)); - add(new NumberToPyInteger(Short.class)); - add(new ClassAdapter(Long.class) { - - public PyObject adapt(Object o) { - return new PyLong(((Number) o).longValue()); - } - - }); - add(new ClassAdapter(Boolean.class) { - - public PyObject adapt(Object o) { - return ((Boolean) o).booleanValue() ? Py.One : Py.Zero; - } - - }); - addPostClass(new PyObjectAdapter() { - - public PyObject adapt(Object o) { - return new PyArray(o.getClass().getComponentType(), o); - } - - public boolean canAdapt(Object o) { - return o.getClass().isArray(); - } - }); - } - - /** - * Always returns true as we just return new PyJavaInstance(o) if the - * adapters added to the superclass can't handle o. - */ - public boolean canAdapt(Object o) { - return true; - } - - public PyObject adapt(Object o) { - PyObject result = super.adapt(o); - if (result != null) { - return result; - } - return new PyJavaInstance(o); - } - - private static class NumberToPyInteger extends ClassAdapter { - - public NumberToPyInteger(Class c) { - super(c); - } - - public PyObject adapt(Object o) { - return new PyInteger(((Number) o).intValue()); - } - - } - - private static class NumberToPyFloat extends ClassAdapter { - public NumberToPyFloat(Class c) { - super(c); - } - - public PyObject adapt(Object o) { - return new PyFloat(((Number) o).doubleValue()); - } - - } -} Copied: branches/2.3/src/org/python/core/adapter/ClassicPyObjectAdapter.java (from rev 3212, trunk/jython/src/org/python/core/adapter/ClassicPyObjectAdapter.java) =================================================================== --- branches/2.3/src/org/python/core/adapter/ClassicPyObjectAdapter.java (rev 0) +++ branches/2.3/src/org/python/core/adapter/ClassicPyObjectAdapter.java 2007-06-07 02:35:42 UTC (rev 3250) @@ -0,0 +1,154 @@ +package org.python.core.adapter; + +import org.python.core.Py; +import org.python.core.PyArray; +import org.python.core.PyFloat; +import org.python.core.PyInteger; +import org.python.core.PyJavaClass; +import org.python.core.PyJavaInstance; +import org.python.core.PyLong; +import org.python.core.PyObject; +import org.python.core.PyProxy; +import org.python.core.PyString; +import org.python.core.PyType; + +/** + * Implements the algorithm originally used in {@link Py#java2py} to adapt objects. + * + * Pre-class adapters are added to handle instances of PyObject, PyProxy and + * null values. Class adapters are added to handle builtin Java classes: String, + * Integer, Float, Double, Byte, Long, Short, Character, Class and Boolean. An + * adapter is added to the post-class adapters to handle wrapping arrays + * properly. Finally, if all of the added adapters can handle an object, it's + * wrapped in a PyJavaInstance. + * + */ +public class ClassicPyObjectAdapter extends ExtensiblePyObjectAdapter { + + public ClassicPyObjectAdapter() { + addPreClass(new PyObjectAdapter() { + + public PyObject adapt(Object o) { + return (PyObject) o; + } + + public boolean canAdapt(Object o) { + return o instanceof PyObject; + } + }); + addPreClass(new PyObjectAdapter() { + + public PyObject adapt(Object o) { + return ((PyProxy) o)._getPyInstance(); + } + + public boolean canAdapt(Object o) { + return o instanceof PyProxy; + } + }); + addPreClass(new PyObjectAdapter() { + + public boolean canAdapt(Object o) { + return o == null; + } + + public PyObject adapt(Object o) { + return Py.None; + } + }); + + add(new ClassAdapter(String.class) { + + public PyObject adapt(Object o) { + return new PyString((String) o); + } + + }); + add(new ClassAdapter(Character.class) { + + public PyObject adapt(Object o) { + return Py.makeCharacter((Character) o); + } + + }); + add(new ClassAdapter(Class.class) { + + public PyObject adapt(Object o) { + Class cls = (Class) o; + if (PyObject.class.isAssignableFrom(cls)) { + return PyType.fromClass(cls); + } + return PyJavaClass.lookup(cls); + } + + }); + add(new NumberToPyFloat(Double.class)); + add(new NumberToPyFloat(Float.class)); + add(new NumberToPyInteger(Integer.class)); + add(new NumberToPyInteger(Byte.class)); + add(new NumberToPyInteger(Short.class)); + add(new ClassAdapter(Long.class) { + + public PyObject adapt(Object o) { + return new PyLong(((Number) o).longValue()); + } + + }); + add(new ClassAdapter(Boolean.class) { + + public PyObject adapt(Object o) { + return ((Boolean) o).booleanValue() ? Py.One : Py.Zero; + } + + }); + addPostClass(new PyObjectAdapter() { + + public PyObject adapt(Object o) { + return new PyArray(o.getClass().getComponentType(), o); + } + + public boolean canAdapt(Object o) { + return o.getClass().isArray(); + } + }); + } + + /** + * Always returns true as we just return new PyJavaInstance(o) if the + * adapters added to the superclass can't handle o. + */ + public boolean canAdapt(Object o) { + return true; + } + + public PyObject adapt(Object o) { + PyObject result = super.adapt(o); + if (result != null) { + return result; + } + return new PyJavaInstance(o); + } + + private static class NumberToPyInteger extends ClassAdapter { + + public NumberToPyInteger(Class c) { + super(c); + } + + public PyObject adapt(Object o) { + return new PyInteger(((Number) o).intValue()); + } + + } + + private static class NumberToPyFloat extends ClassAdapter { + public NumberToPyFloat(Class c) { + super(c); + } + + public PyObject adapt(Object o) { + return new PyFloat(((Number) o).doubleValue()); + } + + } +} Deleted: branches/2.3/src/org/python/core/adapter/ExtensiblePyObjectAdapter.java =================================================================== --- trunk/jython/src/org/python/core/adapter/ExtensiblePyObjectAdapter.java 2007-05-06 06:44:44 UTC (rev 3212) +++ branches/2.3/src/org/python/core/adapter/ExtensiblePyObjectAdapter.java 2007-06-07 02:35:42 UTC (rev 3250) @@ -1,94 +0,0 @@ -package org.python.core.adapter; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; - -import org.python.core.PyObject; - -/** - * A PyObjectAdapter attempts to adapt a Java Object with three user fillable - * groups of adapters: preClass, class and postClass. - * - */ -public class ExtensiblePyObjectAdapter implements PyObjectAdapter { - - /** - * @return true if a preClass, postClass or class adapter can handle this - */ - public boolean canAdapt(Object o) { - return findAdapter(preClassAdapters, o) != null || classAdapters.containsKey(o.getClass()) - || findAdapter(postClassAdapters, o) != null; - } - - /** - * Attempts to adapt o using the preClass, class and postClass adapters. - * - * First each of the preClass adapters is asked in the order of addition if - * they can adapt o. If so, they adapt it. Otherwise, if o.getClass() is - * equal to one of the classes from the added ClassAdapters, that class - * adapter is used. Finally, each of the post class adapters are asked in - * turn if they can adapt o. If so, that adapter handles it. If none can, - * null is returned. - */ - public PyObject adapt(Object o) { - PyObjectAdapter adapter = findAdapter(preClassAdapters, o); - if (adapter != null) { - return adapter.adapt(o); - } - - adapter = (PyObjectAdapter) classAdapters.get(o.getClass()); - if (adapter != null) { - return adapter.adapt(o); - } - - adapter = findAdapter(postClassAdapters, o); - if (adapter != null) { - return adapter.adapt(o); - } - return null; - } - - /** - * Adds an adapter to the list of adapters to be tried before the - * ClassAdapters. - */ - public void addPreClass(PyObjectAdapter adapter) { - preClassAdapters.add(adapter); - } - - /** - * Adds a Class handling adapter that will adapt any objects of its Class if - * that object hasn't already been handled by one of the pre class adapters. - */ - public void add(ClassAdapter adapter) { - classAdapters.put(adapter.getAdaptedClass(), adapter); - } - - /** - * Adds an adapter to the list of adapters to be tried after the - * ClassAdapters. - */ - public void addPostClass(PyObjectAdapter converter) { - postClassAdapters.add(converter); - } - - private static PyObjectAdapter findAdapter(List l, Object o) { - for (Iterator iter = l.iterator(); iter.hasNext();) { - PyObjectAdapter adapter = (PyObjectAdapter) iter.next(); - if (adapter.canAdapt(o)) { - return adapter; - } - } - return null; - } - - private List preClassAdapters = new ArrayList(); - - private List postClassAdapters = new ArrayList(); - - private Map classAdapters = new HashMap(); - -} Copied: branches/2.3/src/org/python/core/adapter/ExtensiblePyObjectAdapter.java (from rev 3212, trunk/jython/src/org/python/core/adapter/ExtensiblePyObjectAdapter.java) =================================================================== --- branches/2.3/src/org/python/core/adapter/ExtensiblePyObjectAdapter.java (rev 0) +++ branches/2.3/src/org/python/core/adapter/ExtensiblePyObjectAdapter.java 2007-06-07 02:35:42 UTC (rev 3250) @@ -0,0 +1,94 @@ +package org.python.core.adapter; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; + +import org.python.core.PyObject; + +/** + * A PyObjectAdapter attempts to adapt a Java Object with three user fillable + * groups of adapters: preClass, class and postClass. + * + */ +public class ExtensiblePyObjectAdapter implements PyObjectAdapter { + + /** + * @return true if a preClass, postClass or class adapter can handle this + */ + public boolean canAdapt(Object o) { + return findAdapter(preClassAdapters, o) != null || classAdapters.containsKey(o.getClass()) + || findAdapter(postClassAdapters, o) != null; + } + + /** + * Attempts to adapt o using the preClass, class and postClass adapters. + * + * First each of the preClass adapters is asked in the order of addition if + * they can adapt o. If so, they adapt it. Otherwise, if o.getClass() is + * equal to one of the classes from the added ClassAdapters, that class + * adapter is used. Finally, each of the post class adapters are asked in + * turn if they can adapt o. If so, that adapter handles it. If none can, + * null is returned. + */ + public PyObject adapt(Object o) { + PyObjectAdapter adapter = findAdapter(preClassAdapters, o); + if (adapter != null) { + return adapter.adapt(o); + } + + adapter = (PyObjectAdapter) classAdapters.get(o.getClass()); + if (adapter != null) { + return adapter.adapt(o); + } + + adapter = findAdapter(postClassAdapters, o); + if (adapter != null) { + return adapter.adapt(o); + } + return null; + } + + /** + * Adds an adapter to the list of adapters to be tried before the + * ClassAdapters. + */ + public void addPreClass(PyObjectAdapter adapter) { + preClassAdapters.add(adapter); + } + + /** + * Adds a Class handling adapter that will adapt any objects of its Class if + * that object hasn't already been handled by one of the pre class adapters. + */ + public void add(ClassAdapter adapter) { + classAdapters.put(adapter.getAdaptedClass(), adapter); + } + + /** + * Adds an adapter to the list of adapters to be tried after the + * ClassAdapters. + */ + public void addPostClass(PyObjectAdapter converter) { + postClassAdapters.add(converter); + } + + private static PyObjectAdapter findAdapter(List l, Object o) { + for (Iterator iter = l.iterator(); iter.hasNext();) { + PyObjectAdapter adapter = (PyObjectAdapter) iter.next(); + if (adapter.canAdapt(o)) { + return adapter; + } + } + return null; + } + + private List preClassAdapters = new ArrayList(); + + private List postClassAdapters = new ArrayList(); + + private Map classAdapters = new HashMap(); + +} Deleted: branches/2.3/src/org/python/core/adapter/PyObjectAdapter.java =================================================================== --- trunk/jython/src/org/python/core/adapter/PyObjectAdapter.java 2007-05-06 06:44:44 UTC (rev 3212) +++ branches/2.3/src/org/python/core/adapter/PyObjectAdapter.java 2007-06-07 02:35:42 UTC (rev 3250) @@ -1,20 +0,0 @@ -package org.python.core.adapter; - -import org.python.core.PyObject; - -/** - * PyObjectAdapters turn Java Objects into PyObjects. - */ -public interface PyObjectAdapter { - - /** - * @return true if o can be adapted by this adapter. - */ - public abstract boolean canAdapt(Object o); - - /** - * @return the PyObject version of o or null if canAdapt(o) returns false. - */ - public abstract PyObject adapt(Object o); - -} \ No newline at end of file Copied: branches/2.3/src/org/python/core/adapter/PyObjectAdapter.java (from rev 3212, trunk/jython/src/org/python/core/adapter/PyObjectAdapter.java) =================================================================== --- branches/2.3/src/org/python/core/adapter/PyObjectAdapter.java (rev 0) +++ branches/2.3/src/org/python/core/adapter/PyObjectAdapter.java 2007-06-07 02:35:42 UTC (rev 3250) @@ -0,0 +1,20 @@ +package org.python.core.adapter; + +import org.python.core.PyObject; + +/** + * PyObjectAdapters turn Java Objects into PyObjects. + */ +public interface PyObjectAdapter { + + /** + * @return true if o can be adapted by this adapter. + */ + public abstract boolean canAdapt(Object o); + + /** + * @return the PyObject version of o or null if canAdapt(o) returns false. + */ + public abstract PyObject adapt(Object o); + +} \ No newline at end of file Modified: branches/2.3/src/org/python/util/JLineConsole.java =================================================================== --- branches/2.3/src/org/python/util/JLineConsole.java 2007-06-06 18:28:48 UTC (rev 3249) +++ branches/2.3/src/org/python/util/JLineConsole.java 2007-06-07 02:35:42 UTC (rev 3250) @@ -1,5 +1,6 @@ package org.python.util; +import java.io.File; import java.io.IOException; import jline.ConsoleReader; import jline.Terminal; @@ -19,6 +20,13 @@ public JLineConsole(PyObject locals) { this(locals, CONSOLE_FILENAME); + try { + File historyFile = new File(System.getProperty("user.home"), + ".jline-jython.history"); + reader.getHistory().setHistoryFile(historyFile); + } catch(IOException e) { + // oh well, no history from file + } } public JLineConsole(PyObject locals, String filename) { This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <fwi...@us...> - 2007-06-20 15:42:24
|
Revision: 3261 http://svn.sourceforge.net/jython/?rev=3261&view=rev Author: fwierzbicki Date: 2007-06-20 08:42:21 -0700 (Wed, 20 Jun 2007) Log Message: ----------- svn merge -r 3207:3260 https://jython.svn.sourceforge.net/svnroot/jython/trunk/jython and conflict cleanup. Modified Paths: -------------- branches/2.3/Lib/isql.py branches/2.3/Lib/javaos.py branches/2.3/Lib/javapath.py branches/2.3/Lib/popen2.py branches/2.3/Lib/test/test_jbasic.py branches/2.3/Lib/zlib.py branches/2.3/NEWS branches/2.3/README.txt branches/2.3/Tools/jythonc/main.py branches/2.3/bugtests/support.py branches/2.3/bugtests/test386jar/test386called.py branches/2.3/build.xml branches/2.3/src/com/ziclix/python/sql/PyConnection.java branches/2.3/src/com/ziclix/python/sql/PyCursor.java branches/2.3/src/com/ziclix/python/sql/PyExtendedCursor.java branches/2.3/src/com/ziclix/python/sql/util/BCP.java branches/2.3/src/org/python/core/JavaImportHelper.java branches/2.3/src/org/python/core/PyArray.java branches/2.3/src/org/python/core/PyBuiltinMethodSet.java branches/2.3/src/org/python/core/PyObject.java branches/2.3/src/org/python/core/PyString.java branches/2.3/src/org/python/modules/_weakref.java branches/2.3/src/org/python/parser/TreeBuilder.java Added Paths: ----------- branches/2.3/Lib/select.py branches/2.3/Lib/socket.py branches/2.3/Lib/test/test_select.py branches/2.3/Lib/test/test_select_new.py branches/2.3/Lib/test/test_socket.py Removed Paths: ------------- branches/2.3/Lib/socket.py branches/2.3/Lib/test/test_socket.py Modified: branches/2.3/Lib/isql.py =================================================================== --- branches/2.3/Lib/isql.py 2007-06-19 07:36:26 UTC (rev 3260) +++ branches/2.3/Lib/isql.py 2007-06-20 15:42:21 UTC (rev 3261) @@ -28,7 +28,7 @@ return prompt if os.name == 'java': def __tojava__(self, cls): - import java + import java.lang.String if cls == java.lang.String: return self.__str__() return False Modified: branches/2.3/Lib/javaos.py =================================================================== --- branches/2.3/Lib/javaos.py 2007-06-19 07:36:26 UTC (rev 3260) +++ branches/2.3/Lib/javaos.py 2007-06-20 15:42:21 UTC (rev 3261) @@ -26,8 +26,8 @@ "popen", "popen2", "popen3", "popen4", "getlogin" ] -import java from java.io import File +import java.lang.System import javapath as path from UserDict import UserDict Modified: branches/2.3/Lib/javapath.py =================================================================== --- branches/2.3/Lib/javapath.py 2007-06-19 07:36:26 UTC (rev 3260) +++ branches/2.3/Lib/javapath.py 2007-06-20 15:42:21 UTC (rev 3261) @@ -8,15 +8,14 @@ # Incompletely implemented: # islink -- How? # ismount -- How? -# splitdrive -- How? # normcase -- How? # Missing: # sameopenfile -- Java doesn't have fstat nor file descriptors? # samestat -- How? -import java from java.io import File +import java.io.IOException from java.lang import System import os @@ -72,13 +71,15 @@ return (path[:n], path[n:]) def splitdrive(path): - """Split a pathname into drive and path. + """Split a pathname into drive and path specifiers. - On JDK, drive is always empty. - XXX This isn't correct for JDK on DOS/Windows! - + Returns a 2-tuple "(drive,path)"; either part may be empty. """ - return ("", path) + # Algorithm based on CPython's ntpath.splitdrive and ntpath.isabs. + if path[1:2] == ':' and path[0].lower() in 'abcdefghijklmnopqrstuvwxyz' \ + and (path[2:] == '' or path[2] in '/\\'): + return path[:2], path[2:] + return '', path def exists(path): """Test whether a path exists. @@ -150,9 +151,7 @@ """Test whether two pathnames reference the same actual file""" path = _tostr(path, "samefile") path2 = _tostr(path2, "samefile") - f = File(path) - f2 = File(path2) - return f.getCanonicalPath() == f2.getCanonicalPath() + return _realpath(path) == _realpath(path2) def ismount(path): """Test whether a path is a mount point. @@ -162,7 +161,6 @@ """ return 0 - def walk(top, func, arg): """Walk a directory tree. @@ -234,14 +232,26 @@ comps.append(curdir) return slashes + string.joinfields(comps, sep) -# Return an absolute path. def abspath(path): + """Return an absolute path normalized but symbolic links not eliminated""" path = _tostr(path, "abspath") - return File(path).getCanonicalPath() + return _abspath(path) +def _abspath(path): + # Must use normpath separately because getAbsolutePath doesn't normalize + # and getCanonicalPath would eliminate symlinks. + return normpath(File(path).getAbsolutePath()) + def realpath(path): + """Return an absolute path normalized and symbolic links eliminated""" path = _tostr(path, "realpath") - return File(path).getCanonicalPath() + return _realpath(path) + +def _realpath(path): + try: + return File(path).getCanonicalPath() + except java.io.IOException: + return _abspath(path) def getsize(path): path = _tostr(path, "getsize") Modified: branches/2.3/Lib/popen2.py =================================================================== --- branches/2.3/Lib/popen2.py 2007-06-19 07:36:26 UTC (rev 3260) +++ branches/2.3/Lib/popen2.py 2007-06-20 15:42:21 UTC (rev 3261) @@ -22,8 +22,11 @@ import jarray from java.lang import System -from java.util import * -from java.io import * +from java.util import Vector +from java.io import BufferedOutputStream +from java.io import BufferedInputStream +from java.io import PipedOutputStream +from java.io import PipedInputStream from org.python.core import PyFile from javashell import shellexecute Copied: branches/2.3/Lib/select.py (from rev 3260, trunk/jython/Lib/select.py) =================================================================== --- branches/2.3/Lib/select.py (rev 0) +++ branches/2.3/Lib/select.py 2007-06-20 15:42:21 UTC (rev 3261) @@ -0,0 +1,157 @@ +""" +AMAK: 20070515: New select implementation that uses java.nio +""" + +import java.nio.channels.SelectableChannel +import java.nio.channels.SelectionKey +import java.nio.channels.Selector +from java.nio.channels.SelectionKey import OP_ACCEPT, OP_CONNECT, OP_WRITE, OP_READ + +import socket + +class error(Exception): pass + +POLLIN = 1 +POLLOUT = 2 + +# The following event types are completely ignored on jython +# Java does not support them, AFAICT +# They are declared only to support code compatibility with cpython + +POLLPRI = 4 +POLLERR = 8 +POLLHUP = 16 +POLLNVAL = 32 + +class poll: + + def __init__(self): + self.selector = java.nio.channels.Selector.open() + self.chanmap = {} + self.unconnected_sockets = [] + + def _getselectable(self, socket_object): + for st in socket.SocketTypes: + if isinstance(socket_object, st): + try: + return socket_object.getchannel() + except: + return None + raise error("Object '%s' is not watchable" % socket_object, 10038) + + def _register_channel(self, socket_object, channel, mask): + jmask = 0 + if mask & POLLIN: + # Note that OP_READ is NOT a valid event on server socket channels. + if channel.validOps() & OP_ACCEPT: + jmask = OP_ACCEPT + else: + jmask = OP_READ + if mask & POLLOUT: + jmask |= OP_WRITE + if channel.validOps() & OP_CONNECT: + jmask |= OP_CONNECT + selectionkey = channel.register(self.selector, jmask) + self.chanmap[channel] = (socket_object, selectionkey) + + def _check_unconnected_sockets(self): + temp_list = [] + for socket_object, mask in self.unconnected_sockets: + channel = self._getselectable(socket_object) + if channel is not None: + self._register_channel(socket_object, channel, mask) + else: + temp_list.append( (socket_object, mask) ) + self.unconnected_sockets = temp_list + + def register(self, socket_object, mask = POLLIN|POLLOUT|POLLPRI): + channel = self._getselectable(socket_object) + if channel is None: + # The socket is not yet connected, and thus has no channel + # Add it to a pending list, and return + self.unconnected_sockets.append( (socket_object, mask) ) + return + self._register_channel(socket_object, channel, mask) + + def unregister(self, socket_object): + channel = self._getselectable(socket_object) + self.chanmap[channel][1].cancel() + del self.chanmap[channel] + + def _dopoll(self, timeout=None): + if timeout is None or timeout < 0: + self.selector.select() + elif timeout == 0: + self.selector.selectNow() + else: + # No multiplication required: both cpython and java use millisecond timeouts + self.selector.select(timeout) + # The returned selectedKeys cannot be used from multiple threads! + return self.selector.selectedKeys() + + def poll(self, timeout=None): + self._check_unconnected_sockets() + selectedkeys = self._dopoll(timeout) + results = [] + for k in selectedkeys.iterator(): + jmask = k.readyOps() + pymask = 0 + if jmask & OP_READ: pymask |= POLLIN + if jmask & OP_WRITE: pymask |= POLLOUT + if jmask & OP_ACCEPT: pymask |= POLLIN + if jmask & OP_CONNECT: pymask |= POLLOUT + # Now return the original userobject, and the return event mask + results.append( (self.chanmap[k.channel()][0], pymask) ) + return results + + def close(self): + for k in self.selector.keys(): + k.cancel() + self.selector.close() + +def _calcselecttimeoutvalue(value): + if value is None: + return None + try: + floatvalue = float(value) + except Exception, x: + raise TypeError("Select timeout value must be a number or None") + if value < 0: + raise error("Select timeout value cannot be negative", 10022) + if floatvalue < 0.000001: + return 0 + return int(floatvalue * 1000) # Convert to milliseconds + +def select ( read_fd_list, write_fd_list, outofband_fd_list, timeout=None): + timeout = _calcselecttimeoutvalue(timeout) + # First create a poll object to do the actual watching. + pobj = poll() + already_registered = {} + # Check the read list + try: + # AMAK: Need to remove all this list searching, change to a dictionary? + for fd in read_fd_list: + mask = POLLIN + if fd in write_fd_list: + mask |= POLLOUT + pobj.register(fd, mask) + already_registered[fd] = 1 + # And now the write list + for fd in write_fd_list: + if not already_registered.has_key(fd): + pobj.register(fd, POLLOUT) + results = pobj.poll(timeout) + except AttributeError, ax: + if str(ax) == "__getitem__": + raise TypeError(ax) + raise ax + # Now start preparing the results + read_ready_list, write_ready_list, oob_ready_list = [], [], [] + for fd, mask in results: + if mask & POLLIN: + read_ready_list.append(fd) + if mask & POLLOUT: + write_ready_list.append(fd) + pobj.close() + return read_ready_list, write_ready_list, oob_ready_list + Deleted: branches/2.3/Lib/socket.py =================================================================== --- branches/2.3/Lib/socket.py 2007-06-19 07:36:26 UTC (rev 3260) +++ branches/2.3/Lib/socket.py 2007-06-20 15:42:21 UTC (rev 3261) @@ -1,428 +0,0 @@ -"""Preliminary socket module. - -XXX Restrictions: - -- Only INET sockets -- No asynchronous behavior -- No socket options -- Can't do a very good gethostbyaddr() right... -- 20050527: updated by Alan Kennedy to support socket timeouts. -""" - -import java.io -import java.net -import org.python.core -import jarray -import string - -__all__ = [ 'AF_INET', 'SO_REUSEADDR', 'SOCK_DGRAM', 'SOCK_RAW', - 'SOCK_RDM', 'SOCK_SEQPACKET', 'SOCK_STREAM', 'SOL_SOCKET', - 'SocketType', 'error', 'getfqdn', 'gethostbyaddr', - 'gethostbyname', 'gethostname', 'socket', 'getaddrinfo'] - -error = IOError -class timeout(error): pass - -AF_INET = 2 - -SOCK_DGRAM = 1 -SOCK_STREAM = 2 -SOCK_RAW = 3 # not supported -SOCK_RDM = 4 # not supported -SOCK_SEQPACKET = 5 # not supported -SOL_SOCKET = 0xFFFF -SO_REUSEADDR = 4 - -def _gethostbyaddr(name): - # This is as close as I can get; at least the types are correct... - addresses = java.net.InetAddress.getAllByName(gethostbyname(name)) - names = [] - addrs = [] - for addr in addresses: - names.append(addr.getHostName()) - addrs.append(addr.getHostAddress()) - return (names, addrs) - -def getfqdn(name=None): - """ - Return a fully qualified domain name for name. If name is omitted or empty - it is interpreted as the local host. To find the fully qualified name, - the hostname returned by gethostbyaddr() is checked, then aliases for the - host, if available. The first name which includes a period is selected. - In case no fully qualified domain name is available, the hostname is retur - New in version 2.0. - """ - if not name: - name = gethostname() - names, addrs = _gethostbyaddr(name) - for a in names: - if a.find(".") >= 0: - return a - return name - -def gethostname(): - return java.net.InetAddress.getLocalHost().getHostName() - -def gethostbyname(name): - return java.net.InetAddress.getByName(name).getHostAddress() - -def gethostbyaddr(name): - names, addrs = _gethostbyaddr(name) - return (names[0], names, addrs) - -def socket(family = AF_INET, type = SOCK_STREAM, flags=0): - assert family == AF_INET - assert type in (SOCK_DGRAM, SOCK_STREAM) - assert flags == 0 - if type == SOCK_STREAM: - return _tcpsocket() - else: - return _udpsocket() - -def getaddrinfo(host, port, family=0, socktype=SOCK_STREAM, proto=0, flags=0): - return ( (AF_INET, socktype, 0, "", (gethostbyname(host), port)), ) - -_defaulttimeout = None - -def getdefaulttimeout(): - return _defaulttimeout - -def _get_timeout_value(value): - if value is None: - return None - try: - floatval = float(value) - except ValueError: - raise TypeError('A float is required') - if floatval < 0: - raise ValueError('Timeout value out of range') - if floatval < 0.001: # 1 millisecond - # java interprets a zero timeout as an infinite timeout - # python interprets a zero timeout as equivalent to non-blocking - # we cannot represent python semantics for a zero timeout on - # java (if we want it to work on pre 1.4 JVMs) - # so we use the shortest timeout possible, 1.1 millisecond - return 0.0011 - return floatval - -def setdefaulttimeout(timeout): - try: - global _defaulttimeout - _defaulttimeout = _get_timeout_value(timeout) - finally: - _tcpsocket.timeout = _defaulttimeout - -class _tcpsocket: - - sock = None - istream = None - ostream = None - addr = None - server = 0 - file_count = 0 - reuse_addr = 0 - - def __init__(self): - self.timeout = _defaulttimeout - - def bind(self, addr, port=None): - if port is not None: - addr = (addr, port) - assert not self.sock - assert not self.addr - host, port = addr # format check - self.addr = addr - - def listen(self, backlog=50): - "This signifies a server socket" - assert not self.sock - self.server = 1 - if self.addr: - host, port = self.addr - else: - host, port = "", 0 - if host: - a = java.net.InetAddress.getByName(host) - self.sock = java.net.ServerSocket(port, backlog, a) - else: - self.sock = java.net.ServerSocket(port, backlog) - if hasattr(self.sock, "setReuseAddress"): - self.sock.setReuseAddress(self.reuse_addr) - - def accept(self): - "This signifies a server socket" - if not self.sock: - self.listen() - assert self.server - if self.timeout: - self.sock.setSoTimeout(int(self.timeout*1000)) - try: - sock = self.sock.accept() - except java.net.SocketTimeoutException, jnste: - raise timeout('timed out') - host = sock.getInetAddress().getHostName() - port = sock.getPort() - conn = _tcpsocket() - conn._setup(sock) - return conn, (host, port) - - def connect(self, addr, port=None): - "This signifies a client socket" - if port is not None: - addr = (addr, port) - assert not self.sock - host, port = addr - if host == "": - host = java.net.InetAddress.getLocalHost() - try: - cli_sock = java.net.Socket() - addr = java.net.InetSocketAddress(host, port) - if self.timeout: - cli_sock.connect(addr, int(self.timeout*1000)) - else: - cli_sock.connect(addr) - self._setup(cli_sock) - except java.net.SocketTimeoutException, jnste: - raise timeout('timed out') - - def _setup(self, sock): - self.sock = sock - if hasattr(self.sock, "setReuseAddress"): - self.sock.setReuseAddress(self.reuse_addr) - self.istream = sock.getInputStream() - self.ostream = sock.getOutputStream() - - def recv(self, n): - assert self.sock - data = jarray.zeros(n, 'b') - try: - m = self.istream.read(data) - except java.io.InterruptedIOException , jiiie: - raise timeout('timed out') - if m <= 0: - return "" - if m < n: - data = data[:m] - return data.tostring() - - def send(self, s): - assert self.sock - n = len(s) - self.ostream.write(s) - return n - - sendall = send - - def getsockname(self): - if not self.sock: - host, port = self.addr or ("", 0) - host = java.net.InetAddress.getByName(host).getHostAddress() - else: - if self.server: - host = self.sock.getInetAddress().getHostAddress() - else: - host = self.sock.getLocalAddress().getHostAddress() - port = self.sock.getLocalPort() - return (host, port) - - def getpeername(self): - assert self.sock - assert not self.server - host = self.sock.getInetAddress().getHostAddress() - port = self.sock.getPort() - return (host, port) - - def setsockopt(self, level, optname, value): - if optname == SO_REUSEADDR: - self.reuse_addr = value - - def getsockopt(self, level, optname): - if optname == SO_REUSEADDR: - return self.reuse_addr - - def makefile(self, mode="r", bufsize=-1): - file = None - if self.istream: - if self.ostream: - file = org.python.core.PyFile(self.istream, self.ostream, - "<socket>", mode) - else: - file = org.python.core.PyFile(self.istream, "<socket>", mode) - elif self.ostream: - file = org.python.core.PyFile(self.ostream, "<socket>", mode) - else: - raise IOError, "both istream and ostream have been shut down" - if file: - return _tcpsocket.FileWrapper(self, file) - - class FileWrapper: - def __init__(self, socket, file): - self.socket = socket - self.sock = socket.sock - self.istream = socket.istream - self.ostream = socket.ostream - - self.file = file - self.read = file.read - self.readline = file.readline - self.readlines = file.readlines - self.write = file.write - self.writelines = file.writelines - self.flush = file.flush - self.seek = file.seek - self.tell = file.tell - - self.socket.file_count += 1 - - def close(self): - if self.file.closed: - # Already closed - return - - self.socket.file_count -= 1 - self.file.close() - - if self.socket.file_count == 0 and self.socket.sock == 0: - # This is the last file Only close the socket and streams - # if there are no outstanding files left. - if self.sock: - self.sock.close() - if self.istream: - self.istream.close() - if self.ostream: - self.ostream.close() - - def shutdown(self, how): - assert how in (0, 1, 2) - assert self.sock - if how in (0, 2): - self.istream = None - if how in (1, 2): - self.ostream = None - - def close(self): - if not self.sock: - return - sock = self.sock - istream = self.istream - ostream = self.ostream - self.sock = 0 - self.istream = 0 - self.ostream = 0 - # Only close the socket and streams if there are no - # outstanding files left. - if self.file_count == 0: - if istream: - istream.close() - if ostream: - ostream.close() - if sock: - sock.close() - - def gettimeout(self): - return self.timeout - - def settimeout(self, timeout): - self.timeout = _get_timeout_value(timeout) - if self.timeout and self.sock: - self.sock.setSoTimeout(int(self.timeout*1000)) - -class _udpsocket: - - def __init__(self): - self.sock = None - self.addr = None - - def bind(self, addr, port=None): - if port is not None: - addr = (addr, port) - assert not self.sock - host, port = addr - if host == "": - self.sock = java.net.DatagramSocket(port) - else: - a = java.net.InetAddress.getByName(host) - self.sock = java.net.DatagramSocket(port, a) - - def connect(self, addr, port=None): - if port is not None: - addr = (addr, port) - host, port = addr # format check - assert not self.addr - if not self.sock: - self.sock = java.net.DatagramSocket() - self.addr = addr # convert host to InetAddress instance? - - def sendto(self, data, addr): - n = len(data) - if not self.sock: - self.sock = java.net.DatagramSocket() - host, port = addr - bytes = jarray.array(map(ord, data), 'b') - a = java.net.InetAddress.getByName(host) - packet = java.net.DatagramPacket(bytes, n, a, port) - self.sock.send(packet) - return n - - def send(self, data): - assert self.addr - return self.sendto(data, self.addr) - - def recvfrom(self, n): - assert self.sock - bytes = jarray.zeros(n, 'b') - packet = java.net.DatagramPacket(bytes, n) - self.sock.receive(packet) - host = packet.getAddress().getHostName() - port = packet.getPort() - m = packet.getLength() - if m < n: - bytes = bytes[:m] - return bytes.tostring(), (host, port) - - def recv(self, n): - assert self.sock - bytes = jarray.zeros(n, 'b') - packet = java.net.DatagramPacket(bytes, n) - self.sock.receive(packet) - m = packet.getLength() - if m < n: - bytes = bytes[:m] - return bytes.tostring() - - def getsockname(self): - assert self.sock - host = self.sock.getLocalAddress().getHostName() - port = self.sock.getLocalPort() - return (host, port) - - def getpeername(self): - assert self.sock - host = self.sock.getInetAddress().getHostName() - port = self.sock.getPort() - return (host, port) - - def __del__(self): - self.close() - - def close(self): - if not self.sock: - return - sock = self.sock - self.sock = 0 - sock.close() - -SocketType = _tcpsocket - -def test(): - s = socket(AF_INET, SOCK_STREAM) - s.connect(("", 80)) - s.send("GET / HTTP/1.0\r\n\r\n") - while 1: - data = s.recv(2000) - print data - if not data: - break - -if __name__ == '__main__': - test() Copied: branches/2.3/Lib/socket.py (from rev 3260, trunk/jython/Lib/socket.py) =================================================================== --- branches/2.3/Lib/socket.py (rev 0) +++ branches/2.3/Lib/socket.py 2007-06-20 15:42:21 UTC (rev 3261) @@ -0,0 +1,813 @@ +""" +This is an updated socket module for use on JVMs > 1.4; it is derived from the +old jython socket module. +The primary extra it provides is non-blocking support. + +XXX Restrictions: + +- Only INET sockets +- No asynchronous behavior +- No socket options +- Can't do a very good gethostbyaddr() right... +AMAK: 20050527: added socket timeouts +AMAK: 20070515: Added non-blocking (asynchronous) support +AMAK: 20070515: Added client-side SSL support +""" + +_defaulttimeout = None + +import threading +import time +import types +import jarray +import string +import sys + +import java.io.BufferedInputStream +import java.io.BufferedOutputStream +import java.io.InterruptedIOException +import java.lang.Exception +import java.lang.String +import java.net.BindException +import java.net.ConnectException +import java.net.DatagramPacket +import java.net.InetAddress +import java.net.InetSocketAddress +import java.net.Socket +import java.net.SocketTimeoutException +import java.nio.ByteBuffer +import java.nio.channels.DatagramChannel +import java.nio.channels.IllegalBlockingModeException +import java.nio.channels.ServerSocketChannel +import java.nio.channels.SocketChannel +import javax.net.ssl.SSLSocketFactory +import org.python.core.PyFile + +try: + import errno + ERRNO_EWOULDBLOCK = errno.EWOULDBLOCK + ERRNO_EACCES = errno.EACCES + ERRNO_ECONNREFUSED = errno.ECONNREFUSED + ERRNO_EINPROGRESS = errno.EINPROGRESS +except ImportError: + # Support jython 2.1 + ERRNO_EWOULDBLOCK = 11 + ERRNO_EACCES = 13 + ERRNO_ECONNREFUSED = 111 + ERRNO_EINPROGRESS = 115 + +class error(Exception): pass +class herror(error): pass +class gaierror(error): pass +class timeout(error): pass + +ALL = None + +exception_map = { + +# (<javaexception>, <circumstance>) : lambda: <code that raises the python equivalent> + +(java.io.InterruptedIOException, ALL) : lambda exc: timeout('timed out'), +(java.net.BindException, ALL) : lambda exc: error(ERRNO_EACCES, 'Permission denied'), +(java.net.ConnectException, ALL) : lambda exc: error( (ERRNO_ECONNREFUSED, 'Connection refused') ), +(java.net.SocketTimeoutException, ALL) : lambda exc: timeout('timed out'), + +} + +def would_block_error(exc=None): + return error( (ERRNO_EWOULDBLOCK, 'The socket operation could not complete without blocking') ) + +def map_exception(exc, circumstance=ALL): + try: +# print "Mapping exception: %s" % str(exc) + return exception_map[(exc.__class__, circumstance)](exc) + except KeyError: + return error('Unmapped java exception: %s' % exc.toString()) + +exception_map.update({ + (java.nio.channels.IllegalBlockingModeException, ALL) : would_block_error, + }) + +MODE_BLOCKING = 'block' +MODE_NONBLOCKING = 'nonblock' +MODE_TIMEOUT = 'timeout' + +_permitted_modes = (MODE_BLOCKING, MODE_NONBLOCKING, MODE_TIMEOUT) + +class _nio_impl: + + timeout = None + mode = MODE_BLOCKING + + def read(self, buf): + bytebuf = java.nio.ByteBuffer.wrap(buf) + count = self.jchannel.read(bytebuf) + return count + + def write(self, buf): + bytebuf = java.nio.ByteBuffer.wrap(buf) + count = self.jchannel.write(bytebuf) + return count + + def _setreuseaddress(self, flag): + self.jsocket.setReuseAddress(flag) + + def _getreuseaddress(self, flag): + return self.jsocket.getReuseAddress() + + def getpeername(self): + return (self.jsocket.getInetAddress().getHostName(), self.jsocket.getPort() ) + + def config(self, mode, timeout): + self.mode = mode + if self.mode == MODE_BLOCKING: + self.jchannel.configureBlocking(1) + if self.mode == MODE_NONBLOCKING: + self.jchannel.configureBlocking(0) + if self.mode == MODE_TIMEOUT: + # self.channel.configureBlocking(0) + self.jsocket.setSoTimeout(int(timeout*1000)) + + def close1(self): + self.jsocket.close() + + def close2(self): + self.jchannel.close() + + def close3(self): + if not self.jsocket.isClosed(): + self.jsocket.close() + + def close4(self): + if not self.jsocket.isClosed(): + if hasattr(self.jsocket, 'shutdownInput') and not self.jsocket.isInputShutdown(): + self.jsocket.shutdownInput() + if hasattr(self.jsocket, 'shutdownOutput') and not self.jsocket.isOutputShutdown(): + self.jsocket.shutdownOutput() + self.jsocket.close() + + close = close1 +# close = close2 +# close = close3 +# close = close4 + + def getchannel(self): + return self.jchannel + + fileno = getchannel + +class _client_socket_impl(_nio_impl): + + def __init__(self, socket=None): + if socket: + self.jchannel = socket.getChannel() + self.host = socket.getInetAddress().getHostName() + self.port = socket.getPort() + else: + self.jchannel = java.nio.channels.SocketChannel.open() + self.host = None + self.port = None + self.jsocket = self.jchannel.socket() + + def bind(self, host, port): + self.jsocket.bind(java.net.InetSocketAddress(host, port)) + + def connect(self, host, port): + self.host = host + self.port = port + self.jchannel.connect(java.net.InetSocketAddress(self.host, self.port)) + + def finish_connect(self): + return self.jchannel.finishConnect() + + def close(self): + _nio_impl.close(self) + +class _server_socket_impl(_nio_impl): + + def __init__(self, host, port, backlog, reuse_addr): + self.jchannel = java.nio.channels.ServerSocketChannel.open() + self.jsocket = self.jchannel.socket() + if host: + bindaddr = java.net.InetSocketAddress(host, port) + else: + bindaddr = java.net.InetSocketAddress(port) + self._setreuseaddress(reuse_addr) + self.jsocket.bind(bindaddr, backlog) + + def accept(self): + try: + if self.mode in (MODE_BLOCKING, MODE_NONBLOCKING): + new_cli_chan = self.jchannel.accept() + if new_cli_chan != None: + return _client_socket_impl(new_cli_chan.socket()) + else: + return None + else: + # In timeout mode now + new_cli_sock = self.jsocket.accept() + return _client_socket_impl(new_cli_sock) + except java.lang.Exception, jlx: + raise map_exception(jlx) + + def close(self): + _nio_impl.close(self) + +class _datagram_socket_impl(_nio_impl): + + def __init__(self, port=None, address=None, reuse_addr=0): + self.jchannel = java.nio.channels.DatagramChannel.open() + self.jsocket = self.jchannel.socket() + if port: + if address is not None: + local_address = java.net.InetSocketAddress(address, port) + else: + local_address = java.net.InetSocketAddress(port) + self.jsocket.bind(local_address) + self._setreuseaddress(reuse_addr) + + def connect(self, host, port): + self.jchannel.connect(java.net.InetSocketAddress(host, port)) + + def finish_connect(self): + return self.jchannel.finishConnect() + + def receive(self, packet): + self.jsocket.receive(packet) + + def send(self, packet): + self.jsocket.send(packet) + +__all__ = [ 'AF_INET', 'SO_REUSEADDR', 'SOCK_DGRAM', 'SOCK_RAW', + 'SOCK_RDM', 'SOCK_SEQPACKET', 'SOCK_STREAM', 'SOL_SOCKET', + 'SocketType', 'SocketTypes', 'error', 'herror', 'gaierror', 'timeout', + 'getfqdn', 'gethostbyaddr', 'gethostbyname', 'gethostname', + 'socket', 'getaddrinfo', 'getdefaulttimeout', 'setdefaulttimeout', + 'has_ipv6', 'htons', 'htonl', 'ntohs', 'ntohl', + ] + +AF_INET = 2 + +SOCK_DGRAM = 1 +SOCK_STREAM = 2 +SOCK_RAW = 3 # not supported +SOCK_RDM = 4 # not supported +SOCK_SEQPACKET = 5 # not supported +SOL_SOCKET = 0xFFFF +SO_REUSEADDR = 4 + +def _gethostbyaddr(name): + # This is as close as I can get; at least the types are correct... + addresses = java.net.InetAddress.getAllByName(gethostbyname(name)) + names = [] + addrs = [] + for addr in addresses: + names.append(addr.getHostName()) + addrs.append(addr.getHostAddress()) + return (names, addrs) + +def getfqdn(name=None): + """ + Return a fully qualified domain name for name. If name is omitted or empty + it is interpreted as the local host. To find the fully qualified name, + the hostname returned by gethostbyaddr() is checked, then aliases for the + host, if available. The first name which includes a period is selected. + In case no fully qualified domain name is available, the hostname is retur + New in version 2.0. + """ + if not name: + name = gethostname() + names, addrs = _gethostbyaddr(name) + for a in names: + if a.find(".") >= 0: + return a + return name + +def gethostname(): + return java.net.InetAddress.getLocalHost().getHostName() + +def gethostbyname(name): + return java.net.InetAddress.getByName(name).getHostAddress() + +def gethostbyaddr(name): + names, addrs = _gethostbyaddr(name) + return (names[0], names, addrs) + +def getservbyname(servicename, protocolname=None): + # http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4071389 + # How complex is the structure of /etc/services? + raise NotImplementedError("getservbyname not yet supported on jython.") + +def getservbyport(port, protocolname=None): + # Same situation as above + raise NotImplementedError("getservbyport not yet supported on jython.") + +def getprotobyname(protocolname=None): + # Same situation as above + raise NotImplementedError("getprotobyname not yet supported on jython.") + +def socket(family = AF_INET, type = SOCK_STREAM, flags=0): + assert family == AF_INET + assert type in (SOCK_DGRAM, SOCK_STREAM) + assert flags == 0 + if type == SOCK_STREAM: + return _tcpsocket() + else: + return _udpsocket() + +def getaddrinfo(host, port, family=0, socktype=SOCK_STREAM, proto=0, flags=0): + return ( (AF_INET, socktype, 0, "", (gethostbyname(host), port)), ) + +has_ipv6 = 1 + +def getnameinfo(sock_addr, flags): + raise NotImplementedError("getnameinfo not yet supported on jython.") + +def getdefaulttimeout(): + return _defaulttimeout + +def _calctimeoutvalue(value): + if value is None: + return None + try: + floatvalue = float(value) + except: + raise TypeError('Socket timeout value must be a number or None') + if floatvalue < 0: + raise ValueError("Socket timeout value cannot be negative") + if floatvalue < 0.000001: + return 0.0 + return floatvalue + +def setdefaulttimeout(timeout): + global _defaulttimeout + try: + _defaulttimeout = _calctimeoutvalue(timeout) + finally: + _nonblocking_api_mixin.timeout = _defaulttimeout + +def htons(x): return x +def htonl(x): return x +def ntohs(x): return x +def ntohl(x): return x + +class _nonblocking_api_mixin: + + timeout = _defaulttimeout + mode = MODE_BLOCKING + + def gettimeout(self): + return self.timeout + + def settimeout(self, timeout): + self.timeout = _calctimeoutvalue(timeout) + if self.timeout is None: + self.mode = MODE_BLOCKING + elif self.timeout < 0.000001: + self.mode = MODE_NONBLOCKING + else: + self.mode = MODE_TIMEOUT + self._config() + + def setblocking(self, flag): + if flag: + self.mode = MODE_BLOCKING + self.timeout = None + else: + self.mode = MODE_NONBLOCKING + self.timeout = 0.0 + self._config() + + def _config(self): + assert self.mode in _permitted_modes + if self.sock_impl: self.sock_impl.config(self.mode, self.timeout) + + def getchannel(self): + if not self.sock_impl: + return None + return self.sock_impl.getchannel() +# if hasattr(self.sock_impl, 'getchannel'): +# return self.sock_impl.getchannel() +# raise error('Operation not implemented on this JVM') + + fileno = getchannel + + def _get_jsocket(self): + return self.sock_impl.jsocket + +def _unpack_address_tuple(address_tuple): + error_message = "Address must be a tuple of (hostname, port)" + if type(address_tuple) is not type( () ) \ + or type(address_tuple[0]) is not type("") \ + or type(address_tuple[1]) is not type(0): + raise TypeError(error_message) + return address_tuple[0], address_tuple[1] + +class _tcpsocket(_nonblocking_api_mixin): + + sock_impl = None + istream = None + ostream = None + local_addr = None + server = 0 + file_count = 0 + #reuse_addr = 1 + reuse_addr = 0 + + def bind(self, addr): + assert not self.sock_impl + assert not self.local_addr + # Do the address format check + host, port = _unpack_address_tuple(addr) + self.local_addr = addr + + def listen(self, backlog=50): + "This signifies a server socket" + try: + assert not self.sock_impl + self.server = 1 + if self.local_addr: + host, port = self.local_addr + else: + host, port = "", 0 + self.sock_impl = _server_socket_impl(host, port, backlog, self.reuse_addr) + self._config() + except java.lang.Exception, jlx: + raise map_exception(jlx) + +# +# The following has information on a java.lang.NullPointerException problem I'm having +# +# http://developer.java.sun.com/developer/bugParade/bugs/4801882.html + + def accept(self): + "This signifies a server socket" + try: + if not self.sock_impl: + self.listen() + assert self.server + new_sock = self.sock_impl.accept() + if not new_sock: + raise would_block_error() + cliconn = _tcpsocket() + cliconn._setup(new_sock) + return cliconn, new_sock.getpeername() + except java.lang.Exception, jlx: + raise map_exception(jlx) + + def _get_host_port(self, addr): + host, port = _unpack_address_tuple(addr) + if host == "": + host = java.net.InetAddress.getLocalHost() + return host, port + + def _do_connect(self, addr): + try: + assert not self.sock_impl + host, port = self._get_host_port(addr) + self.sock_impl = _client_socket_impl() + if self.local_addr: # Has the socket been bound to a local address? + bind_host, bind_port = self.local_addr + self.sock_impl.bind(bind_host, bind_port) + self._config() # Configure timeouts, etc, now that the socket exists + self.sock_impl.connect(host, port) + self._setup(self.sock_impl) + except java.lang.Exception, jlx: + raise map_exception(jlx) + + def connect(self, addr): + "This signifies a client socket" + self._do_connect(addr) + self._setup(self.sock_impl) + + def connect_ex(self, addr): + "This signifies a client socket" + self._do_connect(addr) + if self.sock_impl.finish_connect(): + self._setup(self.sock_impl) + return 0 + return ERRNO_EINPROGRESS + + def _setup(self, sock): + self.sock_impl = sock + self.sock_impl._setreuseaddress(self.reuse_addr) + if self.mode != MODE_NONBLOCKING: + self.istream = self.sock_impl.jsocket.getInputStream() + self.ostream = self.sock_impl.jsocket.getOutputStream() + + def recv(self, n): + try: + if not self.sock_impl: raise error('Socket not open') + if self.sock_impl.jchannel.isConnectionPending(): + self.sock_impl.jchannel.finishConnect() + data = jarray.zeros(n, 'b') + m = self.sock_impl.read(data) + if m <= 0: + if self.mode == MODE_NONBLOCKING: + raise would_block_error() + return "" + if m < n: + data = data[:m] + return data.tostring() + except java.lang.Exception, jlx: + raise map_exception(jlx) + + def recvfrom(self, n): + return self.recv(n), None + + def send(self, s): + if not self.sock_impl: raise error('Socket not open') + if self.sock_impl.jchannel.isConnectionPending(): + self.sock_impl.jchannel.finishConnect() + #n = len(s) + numwritten = self.sock_impl.write(s) + return numwritten + + sendall = send + + def getsockname(self): + if not self.sock_impl: + host, port = self.local_addr or ("", 0) + host = java.net.InetAddress.getByName(host).getHostAddress() + else: + if self.server: + host = self.sock_impl.jsocket.getInetAddress().getHostAddress() + else: + host = self.sock_impl.jsocket.getLocalAddress().getHostAddress() + port = self.sock_impl.jsocket.getLocalPort() + return (host, port) + + def getpeername(self): + assert self.sock_impl + assert not self.server + host = self.sock_impl.jsocket.getInetAddress().getHostAddress() + port = self.sock_impl.jsocket.getPort() + return (host, port) + + def setsockopt(self, level, optname, value): + if optname == SO_REUSEADDR: + self.reuse_addr = value + + def getsockopt(self, level, optname): + if optname == SO_REUSEADDR: + return self.reuse_addr + + def makefile(self, mode="r", bufsize=-1): + file = None + if self.istream: + if self.ostream: + file = org.python.core.PyFile(self.istream, self.ostream, + "<socket>", mode) + else: + file = org.python.core.PyFile(self.istream, "<socket>", mode) + elif self.ostream: + file = org.python.core.PyFile(self.ostream, "<socket>", mode) + else: + raise IOError, "both istream and ostream have been shut down" + if file: + return _tcpsocket.FileWrapper(self, file) + + class FileWrapper: + def __init__(self, socket, file): + self.socket = socket + self.sock = socket.sock_impl + self.istream = socket.istream + self.ostream = socket.ostream + + self.file = file + self.read = file.read + self.readline = file.readline + self.readlines = file.readlines + self.write = file.write + self.writelines = file.writelines + self.flush = file.flush + self.seek = file.seek + self.tell = file.tell + self.closed = file.closed + + self.socket.file_count += 1 + + def close(self): + if self.file.closed: + # Already closed + return + + self.socket.file_count -= 1 + self.file.close() + self.closed = self.file.closed + + if self.socket.file_count == 0 and self.socket.sock_impl == 0: + # This is the last file Only close the socket and streams + # if there are no outstanding files left. + if self.sock: + self.sock.close() + if self.istream: + self.istream.close() + if self.ostream: + self.ostream.close() + + def shutdown(self, how): + assert how in (0, 1, 2) + assert self.sock_impl + if how in (0, 2): + self.istream = None + if how in (1, 2): + self.ostream = None + + def close(self): + if not self.sock_impl: + return + sock = self.sock_impl + istream = self.istream + ostream = self.ostream + self.sock_impl = 0 + self.istream = 0 + self.ostream = 0 + # Only close the socket and streams if there are no + # outstanding files left. + if self.file_count == 0: + if istream: + istream.close() + if ostream: + ostream.close() + if sock: + sock.close() + +class _udpsocket(_nonblocking_api_mixin): + + def __init__(self): + self.sock_impl = None + self.addr = None + self.reuse_addr = 0 + + def bind(self, addr): + assert not self.sock_impl + host, port = _unpack_address_tuple(addr) + host_address = java.net.InetAddress.getByName(host) + self.sock_impl = _datagram_socket_impl(port, host_address, reuse_addr = self.reuse_addr) + self._config() + + def connect(self, addr): + host, port = _unpack_address_tuple(addr) + assert not self.addr + if not self.sock_impl: + self.sock_impl = _datagram_socket_impl() + self._config() + self.sock_impl.connect(host, port) + self.addr = addr # convert host to InetAddress instance? + + def connect_ex(self, addr): + host, port = _unpack_address_tuple(addr) + assert not self.addr + self.addr = addr + if not self.sock_impl: + self.sock_impl = _datagram_socket_impl() + self._config() + self.sock_impl.connect(host, port) + if self.sock_impl.finish_connect(): + return 0 + return ERRNO_EINPROGRESS + + def sendto(self, data, p1, p2=None): + if not p2: + flags, addr = 0, p1 + else: + flags, addr = 0, p2 + n = len(data) + if not self.sock_impl: + self.sock_impl = _datagram_socket_impl() + host, port = addr + bytes = java.lang.String(data).getBytes('iso-8859-1') + a = java.net.InetAddress.getByName(host) + packet = java.net.DatagramPacket(bytes, n, a, port) + self.sock_impl.send(packet) + return n + + def send(self, data): + assert self.addr + return self.sendto(data, self.addr) + + def recvfrom(self, n): + try: + assert self.sock_impl + bytes = jarray.zeros(n, 'b') + packet = java.net.DatagramPacket(bytes, n) + self.sock_impl.receive(packet) + host = None + if packet.getAddress(): + host = packet.getAddress().getHostName() + port = packet.getPort() + m = packet.getLength() + if m < n: + bytes = bytes[:m] + return bytes.tostring(), (host, port) + except java.lang.Exception, jlx: + raise map_exception(jlx) + + def recv(self, n): + try: + assert self.sock_impl + bytes = jarray.zeros(n, 'b') + packet = java.net.DatagramPacket(bytes, n) + self.sock_impl.receive(packet) + m = packet.getLength() + if m < n: + bytes = bytes[:m] + return bytes.tostring() + except java.lang.Exception, jlx: + raise map_exception(jlx) + + def getsockname(self): + assert self.sock_impl + host = self.sock_impl.jsocket.getLocalAddress().getHostName() + port = self.sock_impl.jsocket.getLocalPort() + return (host, port) + + def getpeername(self): + assert self.sock + host = self.sock_impl.jsocket.getInetAddress().getHostName() + port = self.sock_impl.jsocket.getPort() + return (host, port) + + def __del__(self): + self.close() + + def close(self): + if not self.sock_impl: + return + sock = self.sock_impl + self.sock_impl = None + sock.close() + + def setsockopt(self, level, optname, value): + if optname == SO_REUSEADDR: + self.reuse_addr = value +# self.sock._setreuseaddress(value) + + def getsockopt(self, level, optname): + if optname == SO_REUSEADDR: + return self.sock_impl._getreuseaddress() + else: + return None + +SocketType = _tcpsocket +SocketTypes = [_tcpsocket, _udpsocket] + +# Define the SSL support + +class ssl: + + def __init__(self, plain_sock, keyfile=None, certfile=None): + self.ssl_sock = self.make_ssl_socket(plain_sock) + + def make_ssl_socket(self, plain_socket, auto_close=0): + java_net_socket = plain_socket._get_jsocket() + assert isinstance(java_net_socket, java.net.Socket) + host = java_net_socket.getInetAddress().getHostName() + port = java_net_socket.getPort() + factory = javax.net.ssl.SSLSocketFactory.getDefault(); + ssl_socket = factory.createSocket(java_net_socket, host, port, auto_close) + ssl_socket.setEnabledCipherSuites(ssl_socket.getSupportedCipherSuites()) + ssl_socket.startHandshake() + return ssl_socket + + def read(self, n=4096): + # Probably needs some work on efficency + in_buf = java.io.BufferedInputStream(self.ssl_sock.getInputStream()) + data = jarray.zeros(n, 'b') + m = in_buf.read(data, 0, n) + if m <= 0: + return "" + if m < n: + data = data[:m] + return data.tostring() + + def write(self, s): + # Probably needs some work on efficency + out = java.io.BufferedOutputStream(self.ssl_sock.getOutputStream()) + out.write(s) + out.flush() + + def _get_server_cert(self): + return self.ssl_sock.getSession().getPeerCertificates()[0] + + def server(self): + cert = self._get_server_cert() + return cert.getSubjectDN().toString() + + def issuer(self): + cert = self._get_server_cert() + return cert.getIssuerDN().toString() + +def test(): + s = socket(AF_INET, SOCK_STREAM) + s.connect(("", 80)) + s.send("GET / HTTP/1.0\r\n\r\n") + while 1: + data = s.recv(2000) + print data + if not data: + break + +if __name__ == '__main__': + test() Modified: branches/2.3/Lib/test/test_jbasic.py =================================================================== --- branches/2.3/Lib/test/test_jbasic.py 2007-06-19 07:36:26 UTC (rev 3260) +++ branches/2.3/Lib/test/test_jbasic.py 2007-06-20 15:42:21 UTC (rev 3261) @@ -60,10 +60,10 @@ assert s.regionMatches(1, 1, 'eLl', 0, 3), 'method call ignore case' assert not s.regionMatches(1, 'eLl', 0, 3), 'should ignore case' -from java import awt +from java.awt import Dimension print_test('get/set fields') -d = awt.Dimension(3,9) +d = Dimension(3,9) assert d.width == 3 and d.height == 9, 'getting fields' d.width = 42 assert d.width == 42 and d.height == 9, 'setting fields' @@ -91,8 +91,10 @@ global flag flag = flag + 1 -doit = awt.event.ActionEvent(b1, awt.event.ActionEvent.ACTION_PERFORMED, "") +from java.awt.event import ActionEvent +doit = ActionEvent(b1, ActionEvent.ACTION_PERFORMED, "") + b1.actionPerformed = testAction flag = 0 b1.doClick() Copied: branches/2.3/Lib/test/test_select.py (from rev 3260, trunk/jython/Lib/test/test_select.py) =================================================================== --- branches/2.3/Lib/test/test_select.py (rev 0) +++ branches/2.3/Lib/test/test_select.py 2007-06-20 15:42:21 UTC (rev 3261) @@ -0,0 +1,214 @@ +""" +AMAK: 20050515: This module is the test_select.py from cpython 2.4, ported to jython + unittest +""" + +try: + object +except NameError: + class object: pass + +import socket, select + +import os +import sys +import unittest + +class SelectWrapper: + + def __init__(self): + self.read_fds = [] + self.write_fds = [] + self.oob_fds = [] + self.timeout = None + + def add_read_fd(self, fd): + self.read_fds.append(fd) + + def add_write_fd(self, fd): + self.write_fds.append(fd) + + def add_oob_fd(self, fd): + self.oob_fds.append(fd) + + def set_timeout(self, timeout): + self.timeout = timeout + +class PollWrapper: + + def __init__(self): + self.timeout = None + self.poll_object = select.poll() + + def add_read_fd(self, fd): + self.poll_object.register(fd, select.POLL_IN) + + def add_write_fd(self, fd): + self.poll_object.register(fd, select.POLL_OUT) + + def add_oob_fd(self, fd): + self.poll_object.register(fd, select.POLL_PRI) + +class TestSelectInvalidParameters(unittest.TestCase): + + def testBadSelectSetTypes(self): + # Test some known error conditions + for bad_select_set in [None, 1,]: + for pos in range(2): # OOB not supported on Java + args = [[], [], []] + args[pos] = bad_select_set + try: + timeout = 0 # Can't wait forever + rfd, wfd, xfd = select.select(args[0], args[1], args[2], timeout) + except TypeError: + pass + else: + self.fail("Selecting on '%s' should have raised TypeError" % str(bad_select_set)) + + def testBadSelectableTypes(self): + class Nope: pass + + class Almost1: + def fileno(self): + return 'fileno' + + class Almost2: + def fileno(self): + return 'fileno' + + # Test some known error conditions + for bad_selectable in [None, 1, object(), Nope(), Almost1(), Almost2()]: + try: + timeout = 0 # Can't wait forever + rfd, wfd, xfd = select.select([bad_selectable], [], [], timeout) + except (TypeError, select.error), x: + pass + else: + self.fail("Selecting on '%s' should have raised TypeError or select.error" % str(bad_selectable)) + + def testInvalidTimeoutTypes(self): + for invalid_timeout in ['not a number']: + try: + rfd, wfd, xfd = select.select([], [], [], invalid_timeout) + except TypeError: + pass + else: + self.fail("Invalid timeout value '%s' should have raised TypeError" % invalid_timeout) + + def testInvalidTimeoutValues(self): + for invalid_timeout in [-1]: + try: + rfd, wfd, xfd = select.select([], [], [], invalid_timeout) + except (ValueError, select.error): + pass + else: + self.fail("Invalid timeout value '%s' should have raised ValueError or select.error" % invalid_timeout) + +class TestSelectClientSocket(unittest.TestCase): + + def testUnconnectedSocket(self): + sockets = [socket.socket(socket.AF_INET, socket.SOCK_STREAM) for x in range(5)] + for pos in range(2): # OOB not supported on Java + args = [[], [], []] + args[pos] = sockets + timeout = 0 # Can't wait forever + rfd, wfd, xfd = select.select(args[0], args[1], args[2], timeout) + for s in sockets: + self.failIf(s in rfd) + self.failIf(s in wfd) + +def check_server_running_on_localhost_port(port_number): + s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + try: + s.connect( ('localhost', port_number) ) + s.close() + except: + return 0 + return 1 + +class TestPollClientSocket(unittest.TestCase): + + def testEventConstants(self): + for event_name in ['IN', 'OUT', 'PRI', 'ERR', 'HUP', 'NVAL', ]: + self.failUnless(hasattr(select, 'POLL%s' % event_name)) + + def testSocketRegisteredBeforeConnected(self): + # You MUST be running a server on port 80 for this one to work + if not check_server_running_on_localhost_port(80): + print "Unable to run testSocketRegisteredBeforeConnected: no server on port 80" + return + sockets = [socket.socket(socket.AF_INET, socket.SOCK_STREAM) for x in range(5)] + timeout = 1 # Can't wait forever + poll_object = select.poll() + for s in sockets: + # Register the sockets before they are connected + poll_object.register(s, select.POLLOUT) + result_list = poll_object.poll(timeout) + result_sockets = [r[0] for r in result_list] + for s in sockets: + self.failIf(s in result_sockets) + # Now connect the sockets, but DO NOT register them again + for s in sockets: + s.setblocking(0) + s.connect( ('localhost', 80) ) + # Now poll again, to see if the poll object has recognised that the sockets are now connected + result_list = poll_object.poll(timeout) + result_sockets = [r[0] for r in result_list] + for s in sockets: + self.failUnless(s in result_sockets) + + def testUnregisterRaisesKeyError(self): + s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + poll_object = select.poll() + try: + poll_object.unregister(s) + except KeyError: + pass + else: + self.fail("Unregistering socket that is not registered should have raised KeyError") + +class TestPipes(unittest.TestCase): + + verbose = 1 + + def test(self): + import sys + from test.test_support import verbose + if sys.platform[:3] in ('win', 'mac', 'os2', 'riscos'): + if verbose: + print "Can't test select easily on", sys.platform + return + cmd = 'for i in 0 1 2 3 4 5 6 7 8 9; do echo testing...; sleep 1; done' + p = os.popen(cmd, 'r') + for tout in (0, 1, 2, 4, 8, 16) + (None,)*10: + if verbose: + print 'timeout =', tout + rfd, wfd, xfd = select.select([p], [], [], tout) + if (rfd, wfd, xfd) == ([], [], []): + continue + if (rfd, wfd, xfd) == ([p], [], []): + line = p.readline() + if verbose: + print repr(line) + if not line: + if verbose: + print 'EOF' + break + continue + self.fail('Unexpected return values from select(): %s' % str(rfd, wfd, xfd)) + p.close() + +def test_main(): + tests = [ + TestSelectInvalidParameters, + TestSelectClientSocket, + TestPollClientSocket, + ] + if sys.platform[:4] != 'java': + tests.append(TestPipes) + suites = [unittest.makeSuite(klass, 'test') for klass in tests] + main_suite = unittest.TestSuite(suites) + runner = unittest.TextTestRunner(verbosity=100) + runner.run(main_suite) + +if __name__ == "__main__": + test_main() Copied: branches/2.3/Lib/test/test_select_new.py (from rev 3... [truncated message content] |
From: <cg...@us...> - 2007-07-15 05:10:02
|
Revision: 3298 http://svn.sourceforge.net/jython/?rev=3298&view=rev Author: cgroves Date: 2007-07-14 22:09:58 -0700 (Sat, 14 Jul 2007) Log Message: ----------- merge -r 3261:3284 and merge -r 3285:HEAD sans version changes to build.xml and PySystemState.java Modified Paths: -------------- branches/2.3/Lib/select.py branches/2.3/Lib/socket.py branches/2.3/Lib/test/output/test_socket branches/2.3/Lib/test/test_select.py branches/2.3/Lib/test/test_socket.py branches/2.3/NEWS branches/2.3/README.txt branches/2.3/bugtests/test001.py branches/2.3/bugtests/test258.py branches/2.3/src/org/python/core/Py.java branches/2.3/src/org/python/core/PySystemState.java branches/2.3/src/org/python/core/imp.java branches/2.3/src/org/python/modules/errno.java branches/2.3/src/org/python/parser/TreeBuilder.java branches/2.3/src/org/python/util/jython.java Added Paths: ----------- branches/2.3/Lib/test/test_poll.py branches/2.3/bugtests/test400/ branches/2.3/bugtests/test400/x/ branches/2.3/bugtests/test400/x/__init__.py branches/2.3/bugtests/test400.py Removed Paths: ------------- branches/2.3/bugtests/test400/x/ branches/2.3/bugtests/test400/x/__init__.py Modified: branches/2.3/Lib/select.py =================================================================== --- branches/2.3/Lib/select.py 2007-07-14 03:23:56 UTC (rev 3297) +++ branches/2.3/Lib/select.py 2007-07-15 05:09:58 UTC (rev 3298) @@ -9,8 +9,33 @@ import socket +try: + import errno + ERRNO_EINVAL = errno.EINVAL + ERRNO_ENOTSOCK = errno.ENOTSOCK + ERRNO_ESOCKISBLOCKING = errno.ESOCKISBLOCKING +except ImportError: + ERRNO_EINVAL = 22 + ERRNO_ENOTSOCK = 88 + ERRNO_ESOCKISBLOCKING = 20000 + class error(Exception): pass +ALL = None + +_exception_map = { + +# (<javaexception>, <circumstance>) : lambda: <code that raises the python equivalent> + +(java.nio.channels.IllegalBlockingModeException, ALL) : lambda exc: error(ERRNO_ESOCKISBLOCKING, 'socket must be in non-blocking mode'), +} + +def _map_exception(exc, circumstance=ALL): + try: + return _exception_map[(exc.__class__, circumstance)](exc) + except KeyError: + return error(-1, 'Unmapped java exception: %s' % exc.toString()) + POLLIN = 1 POLLOUT = 2 @@ -37,7 +62,7 @@ return socket_object.getchannel() except: return None - raise error("Object '%s' is not watchable" % socket_object, 10038) + raise error("Object '%s' is not watchable" % socket_object, ERRNO_ENOTSOCK) def _register_channel(self, socket_object, channel, mask): jmask = 0 @@ -65,49 +90,66 @@ self.unconnected_sockets = temp_list def register(self, socket_object, mask = POLLIN|POLLOUT|POLLPRI): - channel = self._getselectable(socket_object) - if channel is None: - # The socket is not yet connected, and thus has no channel - # Add it to a pending list, and return - self.unconnected_sockets.append( (socket_object, mask) ) - return - self._register_channel(socket_object, channel, mask) + try: + channel = self._getselectable(socket_object) + if channel is None: + # The socket is not yet connected, and thus has no channel + # Add it to a pending list, and return + self.unconnected_sockets.append( (socket_object, mask) ) + return + self._register_channel(socket_object, channel, mask) + except java.lang.Exception, jlx: + raise _map_exception(jlx) def unregister(self, socket_object): - channel = self._getselectable(socket_object) - self.chanmap[channel][1].cancel() - del self.chanmap[channel] + try: + channel = self._getselectable(socket_object) + self.chanmap[channel][1].cancel() + del self.chanmap[channel] + except java.lang.Exception, jlx: + raise _map_exception(jlx) - def _dopoll(self, timeout=None): + def _dopoll(self, timeout): if timeout is None or timeout < 0: self.selector.select() - elif timeout == 0: - self.selector.selectNow() else: - # No multiplication required: both cpython and java use millisecond timeouts - self.selector.select(timeout) + try: + timeout = int(timeout) + if timeout == 0: + self.selector.selectNow() + else: + # No multiplication required: both cpython and java use millisecond timeouts + self.selector.select(timeout) + except ValueError, vx: + raise error("poll timeout must be a number of milliseconds or None", ERRNO_EINVAL) # The returned selectedKeys cannot be used from multiple threads! return self.selector.selectedKeys() def poll(self, timeout=None): - self._check_unconnected_sockets() - selectedkeys = self._dopoll(timeout) - results = [] - for k in selectedkeys.iterator(): - jmask = k.readyOps() - pymask = 0 - if jmask & OP_READ: pymask |= POLLIN - if jmask & OP_WRITE: pymask |= POLLOUT - if jmask & OP_ACCEPT: pymask |= POLLIN - if jmask & OP_CONNECT: pymask |= POLLOUT - # Now return the original userobject, and the return event mask - results.append( (self.chanmap[k.channel()][0], pymask) ) - return results + try: + self._check_unconnected_sockets() + selectedkeys = self._dopoll(timeout) + results = [] + for k in selectedkeys.iterator(): + jmask = k.readyOps() + pymask = 0 + if jmask & OP_READ: pymask |= POLLIN + if jmask & OP_WRITE: pymask |= POLLOUT + if jmask & OP_ACCEPT: pymask |= POLLIN + if jmask & OP_CONNECT: pymask |= POLLOUT + # Now return the original userobject, and the return event mask + results.append( (self.chanmap[k.channel()][0], pymask) ) + return results + except java.lang.Exception, jlx: + raise _map_exception(jlx) def close(self): - for k in self.selector.keys(): - k.cancel() - self.selector.close() + try: + for k in self.selector.keys(): + k.cancel() + self.selector.close() + except java.lang.Exception, jlx: + raise _map_exception(jlx) def _calcselecttimeoutvalue(value): if value is None: @@ -117,7 +159,7 @@ except Exception, x: raise TypeError("Select timeout value must be a number or None") if value < 0: - raise error("Select timeout value cannot be negative", 10022) + raise error("Select timeout value cannot be negative", ERRNO_EINVAL) if floatvalue < 0.000001: return 0 return int(floatvalue * 1000) # Convert to milliseconds Modified: branches/2.3/Lib/socket.py =================================================================== --- branches/2.3/Lib/socket.py 2007-07-14 03:23:56 UTC (rev 3297) +++ branches/2.3/Lib/socket.py 2007-07-15 05:09:58 UTC (rev 3298) @@ -35,26 +35,30 @@ import java.net.InetSocketAddress import java.net.Socket import java.net.SocketTimeoutException +import java.net.UnknownHostException import java.nio.ByteBuffer import java.nio.channels.DatagramChannel import java.nio.channels.IllegalBlockingModeException import java.nio.channels.ServerSocketChannel import java.nio.channels.SocketChannel +import java.nio.channels.UnresolvedAddressException import javax.net.ssl.SSLSocketFactory import org.python.core.PyFile try: import errno - ERRNO_EWOULDBLOCK = errno.EWOULDBLOCK - ERRNO_EACCES = errno.EACCES - ERRNO_ECONNREFUSED = errno.ECONNREFUSED - ERRNO_EINPROGRESS = errno.EINPROGRESS + ERRNO_EWOULDBLOCK = errno.EWOULDBLOCK + ERRNO_EACCES = errno.EACCES + ERRNO_ECONNREFUSED = errno.ECONNREFUSED + ERRNO_EINPROGRESS = errno.EINPROGRESS + ERRNO_EGETADDRINFOFAILED = errno.EGETADDRINFOFAILED except ImportError: # Support jython 2.1 - ERRNO_EWOULDBLOCK = 11 - ERRNO_EACCES = 13 - ERRNO_ECONNREFUSED = 111 - ERRNO_EINPROGRESS = 115 + ERRNO_EWOULDBLOCK = 11 + ERRNO_EACCES = 13 + ERRNO_ECONNREFUSED = 111 + ERRNO_EINPROGRESS = 115 + ERRNO_EGETADDRINFOFAILED = 20001 class error(Exception): pass class herror(error): pass @@ -63,31 +67,28 @@ ALL = None -exception_map = { +_exception_map = { # (<javaexception>, <circumstance>) : lambda: <code that raises the python equivalent> (java.io.InterruptedIOException, ALL) : lambda exc: timeout('timed out'), (java.net.BindException, ALL) : lambda exc: error(ERRNO_EACCES, 'Permission denied'), -(java.net.ConnectException, ALL) : lambda exc: error( (ERRNO_ECONNREFUSED, 'Connection refused') ), +(java.net.ConnectException, ALL) : lambda exc: error(ERRNO_ECONNREFUSED, 'Connection refused'), (java.net.SocketTimeoutException, ALL) : lambda exc: timeout('timed out'), +(java.net.UnknownHostException, ALL) : lambda exc: gaierror(ERRNO_EGETADDRINFOFAILED, 'getaddrinfo failed'), +(java.nio.channels.UnresolvedAddressException, ALL) : lambda exc: gaierror(ERRNO_EGETADDRINFOFAILED, 'getaddrinfo failed'), } def would_block_error(exc=None): return error( (ERRNO_EWOULDBLOCK, 'The socket operation could not complete without blocking') ) -def map_exception(exc, circumstance=ALL): +def _map_exception(exc, circumstance=ALL): try: -# print "Mapping exception: %s" % str(exc) - return exception_map[(exc.__class__, circumstance)](exc) + return _exception_map[(exc.__class__, circumstance)](exc) except KeyError: - return error('Unmapped java exception: %s' % exc.toString()) + return error(-1, 'Unmapped java exception: %s' % exc.toString()) -exception_map.update({ - (java.nio.channels.IllegalBlockingModeException, ALL) : would_block_error, - }) - MODE_BLOCKING = 'block' MODE_NONBLOCKING = 'nonblock' MODE_TIMEOUT = 'timeout' @@ -125,8 +126,8 @@ if self.mode == MODE_NONBLOCKING: self.jchannel.configureBlocking(0) if self.mode == MODE_TIMEOUT: - # self.channel.configureBlocking(0) - self.jsocket.setSoTimeout(int(timeout*1000)) + self._timeout_millis = int(timeout*1000) + self.jsocket.setSoTimeout(self._timeout_millis) def close1(self): self.jsocket.close() @@ -175,7 +176,10 @@ def connect(self, host, port): self.host = host self.port = port - self.jchannel.connect(java.net.InetSocketAddress(self.host, self.port)) + if self.mode == MODE_TIMEOUT: + self.jsocket.connect(java.net.InetSocketAddress(self.host, self.port), self._timeout_millis) + else: + self.jchannel.connect(java.net.InetSocketAddress(self.host, self.port)) def finish_connect(self): return self.jchannel.finishConnect() @@ -208,7 +212,7 @@ new_cli_sock = self.jsocket.accept() return _client_socket_impl(new_cli_sock) except java.lang.Exception, jlx: - raise map_exception(jlx) + raise _map_exception(jlx) def close(self): _nio_impl.close(self) @@ -284,10 +288,16 @@ return name def gethostname(): - return java.net.InetAddress.getLocalHost().getHostName() + try: + return java.net.InetAddress.getLocalHost().getHostName() + except java.lang.Exception, jlx: + raise _map_exception(jlx) def gethostbyname(name): - return java.net.InetAddress.getByName(name).getHostAddress() + try: + return java.net.InetAddress.getByName(name).getHostAddress() + except java.lang.Exception, jlx: + raise _map_exception(jlx) def gethostbyaddr(name): names, addrs = _gethostbyaddr(name) @@ -433,7 +443,7 @@ self.sock_impl = _server_socket_impl(host, port, backlog, self.reuse_addr) self._config() except java.lang.Exception, jlx: - raise map_exception(jlx) + raise _map_exception(jlx) # # The following has information on a java.lang.NullPointerException problem I'm having @@ -453,7 +463,7 @@ cliconn._setup(new_sock) return cliconn, new_sock.getpeername() except java.lang.Exception, jlx: - raise map_exception(jlx) + raise _map_exception(jlx) def _get_host_port(self, addr): host, port = _unpack_address_tuple(addr) @@ -471,9 +481,8 @@ self.sock_impl.bind(bind_host, bind_port) self._config() # Configure timeouts, etc, now that the socket exists self.sock_impl.connect(host, port) - self._setup(self.sock_impl) except java.lang.Exception, jlx: - raise map_exception(jlx) + raise _map_exception(jlx) def connect(self, addr): "This signifies a client socket" @@ -510,7 +519,7 @@ data = data[:m] return data.tostring() except java.lang.Exception, jlx: - raise map_exception(jlx) + raise _map_exception(jlx) def recvfrom(self, n): return self.recv(n), None @@ -702,7 +711,7 @@ bytes = bytes[:m] return bytes.tostring(), (host, port) except java.lang.Exception, jlx: - raise map_exception(jlx) + raise _map_exception(jlx) def recv(self, n): try: @@ -715,7 +724,7 @@ bytes = bytes[:m] return bytes.tostring() except java.lang.Exception, jlx: - raise map_exception(jlx) + raise _map_exception(jlx) def getsockname(self): assert self.sock_impl Modified: branches/2.3/Lib/test/output/test_socket =================================================================== --- branches/2.3/Lib/test/output/test_socket 2007-07-14 03:23:56 UTC (rev 3297) +++ branches/2.3/Lib/test/output/test_socket 2007-07-15 05:09:58 UTC (rev 3298) @@ -1,2 +1 @@ test_socket -socket.error Copied: branches/2.3/Lib/test/test_poll.py (from rev 3264, trunk/jython/Lib/test/test_poll.py) =================================================================== --- branches/2.3/Lib/test/test_poll.py (rev 0) +++ branches/2.3/Lib/test/test_poll.py 2007-07-15 05:09:58 UTC (rev 3298) @@ -0,0 +1,3 @@ +from test_support import TestSkipped + +raise TestSkipped, 'test_poll currently not supported in Jython' Modified: branches/2.3/Lib/test/test_select.py =================================================================== --- branches/2.3/Lib/test/test_select.py 2007-07-14 03:23:56 UTC (rev 3297) +++ branches/2.3/Lib/test/test_select.py 2007-07-15 05:09:58 UTC (rev 3298) @@ -7,7 +7,9 @@ except NameError: class object: pass -import socket, select +import errno +import select +import socket import os import sys @@ -116,55 +118,65 @@ self.failIf(s in rfd) self.failIf(s in wfd) -def check_server_running_on_localhost_port(port_number): - s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) - try: - s.connect( ('localhost', port_number) ) - s.close() - except: - return 0 - return 1 - class TestPollClientSocket(unittest.TestCase): def testEventConstants(self): for event_name in ['IN', 'OUT', 'PRI', 'ERR', 'HUP', 'NVAL', ]: self.failUnless(hasattr(select, 'POLL%s' % event_name)) + def testUnregisterRaisesKeyError(self): + s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + poll_object = select.poll() + try: + poll_object.unregister(s) + except KeyError: + pass + else: + self.fail("Unregistering socket that is not registered should have raised KeyError") + +# +# using the test_socket thread based server/client management, for convenience. +# + +import test_socket + +class ThreadedPollClientSocket(test_socket.ThreadedTCPSocketTest): + def testSocketRegisteredBeforeConnected(self): - # You MUST be running a server on port 80 for this one to work - if not check_server_running_on_localhost_port(80): - print "Unable to run testSocketRegisteredBeforeConnected: no server on port 80" - return - sockets = [socket.socket(socket.AF_INET, socket.SOCK_STREAM) for x in range(5)] - timeout = 1 # Can't wait forever + self.cli_conn = self.serv.accept() + + def _testSocketRegisteredBeforeConnected(self): + timeout = 1000 # milliseconds poll_object = select.poll() - for s in sockets: - # Register the sockets before they are connected - poll_object.register(s, select.POLLOUT) + # Register the socket before it is connected + poll_object.register(self.cli, select.POLLOUT) result_list = poll_object.poll(timeout) result_sockets = [r[0] for r in result_list] - for s in sockets: - self.failIf(s in result_sockets) - # Now connect the sockets, but DO NOT register them again - for s in sockets: - s.setblocking(0) - s.connect( ('localhost', 80) ) - # Now poll again, to see if the poll object has recognised that the sockets are now connected + self.failIf(self.cli in result_sockets, "Unconnected client socket should not have been selectable") + # Now connect the socket, but DO NOT register it again + self.cli.setblocking(0) + self.cli.connect( (test_socket.HOST, test_socket.PORT) ) + # Now poll again, to check that the poll object has recognised that the socket is now connected result_list = poll_object.poll(timeout) result_sockets = [r[0] for r in result_list] - for s in sockets: - self.failUnless(s in result_sockets) + self.failUnless(self.cli in result_sockets, "Connected client socket should have been selectable") - def testUnregisterRaisesKeyError(self): - s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + def testSocketMustBeNonBlocking(self): + self.cli_conn = self.serv.accept() + + def _testSocketMustBeNonBlocking(self): + self.cli.setblocking(1) + self.cli.connect( (test_socket.HOST, test_socket.PORT) ) + timeout = 1000 # milliseconds poll_object = select.poll() try: - poll_object.unregister(s) - except KeyError: - pass + poll_object.register(self.cli) + except select.error, se: + self.failUnlessEqual(se[0], errno.ESOCKISBLOCKING) + except Exception, x: + self.fail("Registering blocking socket should have raised select.error, not %s" % str(x)) else: - self.fail("Unregistering socket that is not registered should have raised KeyError") + self.fail("Registering blocking socket should have raised select.error") class TestPipes(unittest.TestCase): @@ -202,6 +214,7 @@ TestSelectInvalidParameters, TestSelectClientSocket, TestPollClientSocket, + ThreadedPollClientSocket, ] if sys.platform[:4] != 'java': tests.append(TestPipes) Modified: branches/2.3/Lib/test/test_socket.py =================================================================== --- branches/2.3/Lib/test/test_socket.py 2007-07-14 03:23:56 UTC (rev 3297) +++ branches/2.3/Lib/test/test_socket.py 2007-07-15 05:09:58 UTC (rev 3298) @@ -7,6 +7,7 @@ import unittest #from test import test_support +import errno import socket import select import time @@ -710,7 +711,7 @@ def _testConnectWithLocalBind(self): # Testing blocking connect with local bind - self.cli.settimeout(10) + self.cli.settimeout(1) self.cli.bind( (HOST, PORT-1) ) self.cli.connect((HOST, PORT)) bound_host, bound_port = self.cli.getsockname() @@ -885,6 +886,22 @@ if not ok: self.fail("accept() returned success when we did not expect it") +class TCPClientTimeoutTest(ThreadedTCPSocketTest): + + def testTCPClientTimeout(self): + pass # i.e. do not accept + + def _testTCPClientTimeout(self): + try: + self.cli.settimeout(0.1) + self.cli.connect( (HOST, PORT) ) + except socket.timeout, st: + pass + except Exception, x: + self.fail("Client socket timeout should have raised socket.timeout, not %s" % str(x)) + else: + self.fail("Client socket timeout should have raised socket.timeout") + # # AMAK: 20070307 # Corrected the superclass of UDPTimeoutTest @@ -921,6 +938,59 @@ self.assert_(issubclass(socket.gaierror, socket.error)) self.assert_(issubclass(socket.timeout, socket.error)) +class TestJythonExceptions(unittest.TestCase): + + def testHostNotFound(self): + try: + socket.gethostbyname("doesnotexist") + except socket.gaierror, gaix: + self.failUnlessEqual(gaix[0], errno.EGETADDRINFOFAILED) + except Exception, x: + self.fail("Get host name for non-existent host raised wrong exception: %s" % x) + + def testConnectionRefused(self): + try: + s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + # This port should not be open at this time + s.connect( (HOST, PORT) ) + except socket.error, se: + self.failUnlessEqual(se[0], errno.ECONNREFUSED) + except Exception, x: + self.fail("Connection to non-existent host/port raised wrong exception: %s" % x) + else: + self.fail("Socket (%s,%s) should not have been listening at this time" % (HOST, PORT)) + + def testBindException(self): + # First bind to the target port + s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + s.bind( (HOST, PORT) ) + s.listen() + try: + try: + # And then try to bind again + t = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + t.bind( (HOST, PORT) ) + t.listen() + except socket.error, se: + self.failUnlessEqual(se[0], errno.EACCES) + except Exception, x: + self.fail("Binding to already bound host/port raised wrong exception: %s" % x) + else: + self.fail("Binding to already bound host/port should have raised exception") + finally: + s.close() + + def testUnresolvedAddress(self): + try: + s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + s.connect( ('non.existent.server', PORT) ) + except socket.gaierror, gaix: + self.failUnlessEqual(gaix[0], errno.EGETADDRINFOFAILED) + except Exception, x: + self.fail("Get host name for non-existent host raised wrong exception: %s" % x) + else: + self.fail("Get host name for non-existent host should have raised exception") + class TestAddressParameters: def testBindNonTupleEndpointRaisesTypeError(self): @@ -962,6 +1032,7 @@ GeneralModuleTests, BasicTCPTest, TCPTimeoutTest, + TCPClientTimeoutTest, TestExceptions, TestTCPAddressParameters, TestUDPAddressParameters, @@ -976,6 +1047,8 @@ ] if hasattr(socket, "socketpair"): tests.append(BasicSocketPairTest) + if sys.platform[:4] == 'java': + tests.append(TestJythonExceptions) suites = [unittest.makeSuite(klass, 'test') for klass in tests] main_suite = unittest.TestSuite(suites) runner = unittest.TextTestRunner(verbosity=100) Modified: branches/2.3/NEWS =================================================================== --- branches/2.3/NEWS 2007-07-14 03:23:56 UTC (rev 3297) +++ branches/2.3/NEWS 2007-07-15 05:09:58 UTC (rev 3298) @@ -1,11 +1,34 @@ Jython NEWS +Jython 2.2 rc2 + Bugs fixed + - [ 931129 ] jython -jar some-path/test.jar fails + - [ 1719528 ] -c doesn't put the empty string in sys.path + - [ 1746957 ] Weird 'uu' prefix for unicode + - [ 1747092 ] Failed imports should not be "cached" + - [ 1742770 ] urllib.urlopen('http://inv') -> UnknownHostException + - [ 1745068 ] select gives confusing message when given blocking sockets + - [ 1744775 ] umlauts displayed incorrectly in installer + - timeouts on socket client connects were not being honoured + - a float could not be passed as milliseconds to select.poll.poll + Jython 2.2 rc1 + New features + - Completely rewritten socket module and new select module using java.nio + which allows the use of SSL and non-blocking sockets. + - Explicit imports of Java classes like 'from java.net import URL' or + 'import java.net.URL' work with package scanning disabled. Bugs fixed - [ 1708080 ] float("1d") -> 1.0 (not ValueError as expected) - [ 1661700 ] os.path.abspath raises IOException if drive not accessible - [ 1662689 ] os.path.abspath eliminates symlinks - [ 1717498 ] os.path.splitdrive does nothing for Windows drives + - [ 1622207 ] _weakref.ref(o) only works if the argument is hasheable + - [ 1735864 ] Parser not threadsafe + - [ 1722306 ] OverflowError in UDP Socket Implementation + - [ 1348645 ] socket.py send() requires too many arguments + - [ 998602 ] urllib : https request does not work + - [ 621180 ] module socket _udpsocket close bug Jython 2.2 beta2 New features Modified: branches/2.3/README.txt =================================================================== --- branches/2.3/README.txt 2007-07-14 03:23:56 UTC (rev 3297) +++ branches/2.3/README.txt 2007-07-15 05:09:58 UTC (rev 3298) @@ -1,7 +1,7 @@ -Welcome to Jython 2.2b2 +Welcome to Jython 2.2rc2 ======================= -This is the second beta release towards the 2.2 version of Jython. It +This is the second release candidate of the 2.2 version of Jython. It contains all of the new features for the 2.2 release: - new-style classes - Java List integration @@ -11,18 +11,20 @@ - __future__ division - support for running on modern JVMs - a new installer + - ssl and non-blocking support for socket -In addition to these major features, many bugs have been fixed from 2.2b1. See -the NEWS file for a more complete list of changes. +In addition to these major features, several bugs have been fixed from 2.2rc1. +See the NEWS file for a more complete list of changes. -The release was compiled on Windows XP with JDK 6 but it should run on +The release was compiled on Mac OS X with JDK 5 but it should run on 1.4.2+. -This release exists to solicit feedback about any bugs or missing -features; if you can provide it, it is greatly appreciated. Bug -reports can be created at http://jython.org/bugs whereas more general -questions can be sent to the Jython-dev mailing list, -jy...@li.... +This release is intended to find any major bugs before releasing 2.2. If none +are found, this will become the 2.2 release. If you can run this and check for +bugs, it will be greatly appreciated. Bug reports can be created at +http://jython.org/bugs whereas more general questions can be sent to the +Jython-users mailing list, jyt...@li.... -The current plan calls for a release candiate in a few weeks, and if it proves -stable, the final release of 2.2 a few weeks after that. +If this release proves stable, the final release of 2.2 will be in a couple +weeks. If not, successive release candidates will be made until all the major +bugs are ironed out. Modified: branches/2.3/bugtests/test001.py =================================================================== --- branches/2.3/bugtests/test001.py 2007-07-14 03:23:56 UTC (rev 3297) +++ branches/2.3/bugtests/test001.py 2007-07-15 05:09:58 UTC (rev 3298) @@ -11,5 +11,5 @@ support.compare(str(v.size), "<java function size") -if type(v.size) != BuiltinFunctionType: - raise support.TestError('Wrong type for v.size' + `type(v.size)`) +if not callable(v.size): + raise support.TestError('v.size should be callable') Modified: branches/2.3/bugtests/test258.py =================================================================== --- branches/2.3/bugtests/test258.py 2007-07-14 03:23:56 UTC (rev 3297) +++ branches/2.3/bugtests/test258.py 2007-07-15 05:09:58 UTC (rev 3298) @@ -8,7 +8,7 @@ import sys -if not sys.modules.has_key('test258m1'): - raise support.TestError, "Module should exists in sys.modules" +if sys.modules.has_key('test258m1'): + raise support.TestError, "Module should not exist in sys.modules" Copied: branches/2.3/bugtests/test400 (from rev 3297, trunk/jython/bugtests/test400) Copied: branches/2.3/bugtests/test400/x (from rev 3297, trunk/jython/bugtests/test400/x) Deleted: branches/2.3/bugtests/test400/x/__init__.py =================================================================== Copied: branches/2.3/bugtests/test400/x/__init__.py (from rev 3297, trunk/jython/bugtests/test400/x/__init__.py) =================================================================== Copied: branches/2.3/bugtests/test400.py (from rev 3297, trunk/jython/bugtests/test400.py) =================================================================== --- branches/2.3/bugtests/test400.py (rev 0) +++ branches/2.3/bugtests/test400.py 2007-07-15 05:09:58 UTC (rev 3298) @@ -0,0 +1,10 @@ +import support + +try: + import x + raise support.TestError, "x shouldn't be on sys.path until after this" +except: + pass +import sys +sys.path.append('test400') +import x Modified: branches/2.3/src/org/python/core/Py.java =================================================================== --- branches/2.3/src/org/python/core/Py.java 2007-07-14 03:23:56 UTC (rev 3297) +++ branches/2.3/src/org/python/core/Py.java 2007-07-15 05:09:58 UTC (rev 3298) @@ -1556,20 +1556,32 @@ * @see ClassicPyObjectAdapter - default PyObjectAdapter type */ public static PyObject java2py(Object o) { - return adapter.adapt(o); + return getAdapter().adapt(o); } /** * @return the ExtensiblePyObjectAdapter used by java2py. */ public static ExtensiblePyObjectAdapter getAdapter(){ + if(adapter == null) { + adapter = new ClassicPyObjectAdapter(); + } return adapter; } + /** + * Set the ExtensiblePyObjectAdapter used by java2py. + * + * @param adapter The new ExtensiblePyObjectAdapter + */ + protected static void setAdapter(ExtensiblePyObjectAdapter adapter) { + Py.adapter = adapter; + } + /** * Handles wrapping Java objects in PyObject to expose them to jython. */ - protected static ExtensiblePyObjectAdapter adapter; + private static ExtensiblePyObjectAdapter adapter; public static PyObject makeClass(String name, PyObject[] bases, PyCode code, PyObject doc) Modified: branches/2.3/src/org/python/core/PySystemState.java =================================================================== --- branches/2.3/src/org/python/core/PySystemState.java 2007-07-14 03:23:56 UTC (rev 3297) +++ branches/2.3/src/org/python/core/PySystemState.java 2007-07-15 05:09:58 UTC (rev 3298) @@ -459,7 +459,7 @@ } initialized = true; - Py.adapter = adapter; + Py.setAdapter(adapter); boolean standalone = false; String jarFileName = getJarFileName(); if (jarFileName != null) { Modified: branches/2.3/src/org/python/core/imp.java =================================================================== --- branches/2.3/src/org/python/core/imp.java 2007-07-14 03:23:56 UTC (rev 3297) +++ branches/2.3/src/org/python/core/imp.java 2007-07-15 05:09:58 UTC (rev 3298) @@ -233,8 +233,13 @@ if (c instanceof PyTableCode) { code = (PyTableCode) c; } - PyFrame f = new PyFrame(code, module.__dict__, module.__dict__, null); - code.call(f); + try { + PyFrame f = new PyFrame(code, module.__dict__, module.__dict__, null); + code.call(f); + } catch (RuntimeException t) { + Py.getSystemState().modules.__delitem__(name.intern()); + throw t; + } if(moduleLocation != null) { module.__setattr__("__file__", new PyString(moduleLocation)); @@ -651,13 +656,14 @@ } else { firstName = name.substring(0, dot); } - StringBuffer parentNameBuffer = new StringBuffer( - pkgMod != null ? pkgName : ""); + StringBuffer parentNameBuffer = new StringBuffer(pkgMod != null ? pkgName : ""); PyObject topMod = import_next(pkgMod, parentNameBuffer, firstName, name, fromlist); if (topMod == Py.None || topMod == null) { - if (topMod == null) { - modules.__setitem__(parentNameBuffer.toString().intern(), - Py.None); + // Add None to sys.modules for submodule or subpackage names that aren't found, but + // leave top-level entries out. This allows them to be tried again if another + // import attempt is made after they've been added to sys.path. + if (topMod == null && pkgMod != null) { + modules.__setitem__(parentNameBuffer.toString().intern(), Py.None); } parentNameBuffer = new StringBuffer(""); // could throw ImportError Modified: branches/2.3/src/org/python/modules/errno.java =================================================================== --- branches/2.3/src/org/python/modules/errno.java 2007-07-14 03:23:56 UTC (rev 3297) +++ branches/2.3/src/org/python/modules/errno.java 2007-07-15 05:09:58 UTC (rev 3298) @@ -137,6 +137,10 @@ public static final int EREMOTEIO = 121; public static final int EDQUOT = 122; + // AMAK: Starting a new series of jython specific error numbers + public static final int ESOCKISBLOCKING = 20000; + public static final int EGETADDRINFOFAILED = 20001; + public static final PyObject errorcode = new PyDictionary(); private static final PyObject strerror = new PyDictionary(); @@ -264,6 +268,9 @@ addcode(dict, EREMOTEIO, "EREMOTEIO", "Remote I/O error"); addcode(dict, EDQUOT, "EDQUOT", "Disk quota exceeded"); + // AMAK: starting a new series of jython specific errors + addcode(dict, ESOCKISBLOCKING, "ESOCKISBLOCKING", "Socket is in blocking mode"); + addcode(dict, EGETADDRINFOFAILED, "EGETADDRINFOFAILED", "getaddrinfo failed"); } public static PyObject strerror(PyObject error) { Modified: branches/2.3/src/org/python/parser/TreeBuilder.java =================================================================== --- branches/2.3/src/org/python/parser/TreeBuilder.java 2007-07-14 03:23:56 UTC (rev 3297) +++ branches/2.3/src/org/python/parser/TreeBuilder.java 2007-07-15 05:09:58 UTC (rev 3298) @@ -86,7 +86,21 @@ return nodes[id]; } - + /** + * @return the image of the SimpleNode as a String, not throwing a NullPointerException when image is null + * @param n The SimpleNode + */ + public static String getImageAsString(SimpleNode n) { + String imageAsString; + Object image = n.getImage(); + if (image == null) { + imageAsString = "Incomplete node"; + } else { + imageAsString = image.toString(); + } + return imageAsString; + } + public SimpleNode closeNode(SimpleNode n, int arity) throws Exception { exprType value; exprType[] exprs; @@ -102,13 +116,13 @@ return new Expression(makeExpr()); case JJTNAME: - return new Name(n.getImage().toString(), Name.Load); + return new Name(getImageAsString(n), Name.Load); case JJTNUM: return new Num((PyObject) n.getImage()); case JJTSTRING: - return new Str(n.getImage().toString()); + return new Str(getImageAsString(n)); case JJTUNICODE: - return new Unicode(n.getImage().toString()); + return new Unicode(getImageAsString(n)); case JJTSUITE: stmtType[] stmts = new stmtType[arity]; Modified: branches/2.3/src/org/python/util/jython.java =================================================================== --- branches/2.3/src/org/python/util/jython.java 2007-07-14 03:23:56 UTC (rev 3297) +++ branches/2.3/src/org/python/util/jython.java 2007-07-15 05:09:58 UTC (rev 3298) @@ -47,6 +47,15 @@ throw Py.ValueError("jar file missing '__run__.py'"); PyStringMap locals = new PyStringMap(); + + // Stripping the stuff before the last File.separator fixes Bug + // #931129 by keeping illegal characters out of the generated + // proxy class name + int beginIndex; + if ((beginIndex = filename.lastIndexOf(File.separator)) != -1) { + filename = filename.substring(beginIndex + 1); + } + locals.__setitem__("__name__", new PyString(filename)); locals.__setitem__("zipfile", Py.java2py(zip)); @@ -159,14 +168,6 @@ } } - if (opts.command != null) { - try { - interp.exec(opts.command); - } catch (Throwable t) { - Py.printException(t); - } - } - // was there a filename on the command line? if (opts.filename != null) { String path = new java.io.File(opts.filename).getParent(); @@ -204,6 +205,14 @@ // was given, sys.path[0] will have gotten filled in with the // dir of the argument filename. Py.getSystemState().path.insert(0, new PyString("")); + + if (opts.command != null) { + try { + interp.exec(opts.command); + } catch (Throwable t) { + Py.printException(t); + } + } } if (opts.interactive) { This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <cg...@us...> - 2007-07-15 08:30:05
|
Revision: 3307 http://svn.sourceforge.net/jython/?rev=3307&view=rev Author: cgroves Date: 2007-07-15 01:29:58 -0700 (Sun, 15 Jul 2007) Log Message: ----------- Remove support for bytecode loading on ancient JVMs in BytecodeLoader1 and move BytecodeLoader2 into BytecodeLoader as Loader and use it as the default. Don't allow JIT compilation to be turned off since the problem was only noticed on 1.2 JVMs. Modified Paths: -------------- branches/2.3/Lib/jxxload_help/PathVFSJavaLoader.java branches/2.3/src/org/python/core/BytecodeLoader.java branches/2.3/src/org/python/core/Options.java branches/2.3/src/org/python/core/SyspathJavaLoader.java Removed Paths: ------------- branches/2.3/src/org/python/core/BytecodeLoader1.java branches/2.3/src/org/python/core/BytecodeLoader2.java branches/2.3/src/org/python/core/Loader.java Modified: branches/2.3/Lib/jxxload_help/PathVFSJavaLoader.java =================================================================== --- branches/2.3/Lib/jxxload_help/PathVFSJavaLoader.java 2007-07-15 08:27:32 UTC (rev 3306) +++ branches/2.3/Lib/jxxload_help/PathVFSJavaLoader.java 2007-07-15 08:29:58 UTC (rev 3307) @@ -40,9 +40,7 @@ Class c = defineClass(name, data, 0, data.length); resolveClass(c); if (c.isInterface()) interfaces.addElement(c); - if (!org.python.core.Options.skipCompile) { - Compiler.compileClass(c); - } + Compiler.compileClass(c); return c; } Modified: branches/2.3/src/org/python/core/BytecodeLoader.java =================================================================== --- branches/2.3/src/org/python/core/BytecodeLoader.java 2007-07-15 08:27:32 UTC (rev 3306) +++ branches/2.3/src/org/python/core/BytecodeLoader.java 2007-07-15 08:29:58 UTC (rev 3307) @@ -2,6 +2,7 @@ package org.python.core; +import java.security.SecureClassLoader; import java.util.Vector; /** @@ -28,39 +29,12 @@ throw new ClassNotFoundException(name); } - static void compileClass(Class c) { - // This method has caused much trouble. Using it breaks jdk1.2rc1 - // Not using it can make SUN's jdk1.1.6 JIT slightly unhappy. - // Don't use by default, but allow python.options.compileClass to - // override - if (!Options.skipCompile) { - // System.err.println("compile: "+name); - Compiler.compileClass(c); - } + static void compileClass (Class c) { + Compiler.compileClass(c); } - private static Class loaderClass = null; - private static Loader makeLoader() { - if (loaderClass == null) { - synchronized (BytecodeLoader.class) { - String version = System.getProperty("java.version"); - if (version.compareTo("1.2") >= 0) { - try { - loaderClass = Class - .forName("org.python.core.BytecodeLoader2"); - } catch (Throwable e) { - loaderClass = BytecodeLoader1.class; - } - } else - loaderClass = BytecodeLoader1.class; - } - } - try { - return (Loader) loaderClass.newInstance(); - } catch (Exception e) { - return new BytecodeLoader1(); - } + return new Loader(); } /** @@ -105,4 +79,36 @@ throw Py.JavaError(e); } } + + private static class Loader extends SecureClassLoader { + private Vector parents; + + public Loader() { + this.parents = BytecodeLoader.init(); + } + + public void addParent(ClassLoader referent) { + if (!this.parents.contains(referent)) { + this.parents.add(0, referent); + } + } + + // override from abstract base class + protected Class loadClass(String name, boolean resolve) + throws ClassNotFoundException { + Class c = findLoadedClass(name); + if (c != null) { + return c; + } + return BytecodeLoader.findParentClass(this.parents, name); + } + + public Class loadClassFromBytes(String name, byte[] data) { + Class c = defineClass(name, data, 0, data.length, this.getClass() + .getProtectionDomain()); + resolveClass(c); + BytecodeLoader.compileClass(c); + return c; + } + } } Deleted: branches/2.3/src/org/python/core/BytecodeLoader1.java =================================================================== --- branches/2.3/src/org/python/core/BytecodeLoader1.java 2007-07-15 08:27:32 UTC (rev 3306) +++ branches/2.3/src/org/python/core/BytecodeLoader1.java 2007-07-15 08:29:58 UTC (rev 3307) @@ -1,41 +0,0 @@ -// Copyright (c) Corporation for National Research Initiatives - -package org.python.core; - -import java.util.Vector; - -/** - * A java1 classloader for loading compiled python modules. - * - * @deprecated java1 no longer supported. - */ -class BytecodeLoader1 extends ClassLoader implements Loader { - private Vector parents; - - public BytecodeLoader1() { - this.parents = BytecodeLoader.init(); - } - - public void addParent(ClassLoader referent) { - if (!this.parents.contains(referent)) { - this.parents.addElement(referent); - } - } - - // override from abstract base class - protected Class loadClass(String name, boolean resolve) - throws ClassNotFoundException { - Class c = findLoadedClass(name); - if (c != null) { - return c; - } - return BytecodeLoader.findParentClass(this.parents, name); - } - - public Class loadClassFromBytes(String name, byte[] data) { - Class c = defineClass(name, data, 0, data.length); - resolveClass(c); - BytecodeLoader.compileClass(c); - return c; - } -} Deleted: branches/2.3/src/org/python/core/BytecodeLoader2.java =================================================================== --- branches/2.3/src/org/python/core/BytecodeLoader2.java 2007-07-15 08:27:32 UTC (rev 3306) +++ branches/2.3/src/org/python/core/BytecodeLoader2.java 2007-07-15 08:29:58 UTC (rev 3307) @@ -1,42 +0,0 @@ -// Copyright (c) Corporation for National Research Initiatives - -package org.python.core; - -import java.security.SecureClassLoader; -import java.util.Vector; - -/** - * A java2 classloader for loading compiled python modules. - */ -class BytecodeLoader2 extends SecureClassLoader implements Loader { - private Vector parents; - - public BytecodeLoader2() { - this.parents = BytecodeLoader.init(); - } - - public void addParent(ClassLoader referent) { - if (!this.parents.contains(referent)) { - this.parents.add(0, referent); - } - } - - // override from abstract base class - protected Class loadClass(String name, boolean resolve) - throws ClassNotFoundException { - Class c = findLoadedClass(name); - if (c != null) { - return c; - } - return BytecodeLoader.findParentClass(this.parents, name); - } - - public Class loadClassFromBytes(String name, byte[] data) { - Class c = defineClass(name, data, 0, data.length, this.getClass() - .getProtectionDomain()); - resolveClass(c); - BytecodeLoader.compileClass(c); - return c; - } - -} Deleted: branches/2.3/src/org/python/core/Loader.java =================================================================== --- branches/2.3/src/org/python/core/Loader.java 2007-07-15 08:27:32 UTC (rev 3306) +++ branches/2.3/src/org/python/core/Loader.java 2007-07-15 08:29:58 UTC (rev 3307) @@ -1,20 +0,0 @@ -package org.python.core; - -/** - * A common interface for bytecode loaders. Jython 2.0 have two loaders, a - * standard loader and a Java2 SecureClassLoader. Both loader implements this - * interface. - */ - -public interface Loader { - /** - * Turn java byte codes into a class. - */ - public Class loadClassFromBytes(String name, byte[] data); - - /** - * Add another classloader as a parent loader. Dependent classes will - * searched in these loaders. - */ - public void addParent(ClassLoader referent); -} Modified: branches/2.3/src/org/python/core/Options.java =================================================================== --- branches/2.3/src/org/python/core/Options.java 2007-07-15 08:27:32 UTC (rev 3306) +++ branches/2.3/src/org/python/core/Options.java 2007-07-15 08:29:58 UTC (rev 3307) @@ -26,12 +26,6 @@ public static boolean showPythonProxyExceptions = false; /** - * To force JIT compilation of Jython code -- should be unnecessary Setting - * this to true will cause jdk1.2rc1 to core dump on Windows - */ - public static boolean skipCompile = true; - - /** * Setting this to true will cause the console to poll standard in. This * might be helpful on systems without system-level threads. */ @@ -129,9 +123,6 @@ "options.showPythonProxyExceptions", Options.showPythonProxyExceptions); - Options.skipCompile = getBooleanOption("options.skipCompile", - Options.skipCompile); - Options.deprecatedKeywordMangling = getBooleanOption( "deprecated.keywordMangling", Options.deprecatedKeywordMangling); Modified: branches/2.3/src/org/python/core/SyspathJavaLoader.java =================================================================== --- branches/2.3/src/org/python/core/SyspathJavaLoader.java 2007-07-15 08:27:32 UTC (rev 3306) +++ branches/2.3/src/org/python/core/SyspathJavaLoader.java 2007-07-15 08:29:58 UTC (rev 3307) @@ -173,14 +173,7 @@ // System.err.println("loadClassFromBytes("+name+", byte[])"); Class c = defineClass(name, data, 0, data.length); resolveClass(c); - // This method has caused much trouble. Using it breaks jdk1.2rc1 - // Not using it can make SUN's jdk1.1.6 JIT slightly unhappy. - // Don't use by default, but allow python.options.compileClass to - // override - if (!Options.skipCompile) { - // System.err.println("compile: "+name); - Compiler.compileClass(c); - } + Compiler.compileClass(c); return c; } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |